Compare commits
21 Commits
v1.3.56
...
v1.4.12-fix
| Author | SHA1 | Date | |
|---|---|---|---|
| 313c740470 | |||
| d21cb0a98d | |||
| 16bee1eacb | |||
| c8016f076d | |||
| b1a9f94231 | |||
| 42aadcca2c | |||
| a8319d96a6 | |||
| bf878545b3 | |||
| 22cda312cf | |||
| d112ad061e | |||
| be917f8fb7 | |||
| cb48afeb9c | |||
| 2b8ff711ed | |||
| 9a4ccabd1b | |||
| 32728eec37 | |||
| 905ca253d7 | |||
| d89b79a3f8 | |||
| c4dda7e2e5 | |||
| 662f3681a5 | |||
| a56d7188f2 | |||
| 7e1ee6bc04 |
@@ -248,27 +248,60 @@ impl SupabaseClient {
|
||||
}
|
||||
}
|
||||
|
||||
/// Atualiza campos específicos de um fechamento pelo id numérico (pk) ou UUID.
|
||||
pub fn atualizar_fechamento(&self, id: Option<i64>, uuid: &str, updates: &serde_json::Value) -> Result<Value, SupabaseError> {
|
||||
// Se temos id numerico, usa id=eq.; senao usa id=eq.UUID
|
||||
let url = if let Some(num) = id {
|
||||
format!("{}/rest/v1/fechamentos_web?id=eq.{}", self.base_url, num)
|
||||
} else {
|
||||
format!("{}/rest/v1/fechamentos_web?id=eq.{}", self.base_url, uuid)
|
||||
};
|
||||
/// Atualiza campos específicos de um fechamento pelo id_fechamento.
|
||||
pub fn atualizar_fechamento(&self, id_fechamento: &str, updates: &serde_json::Value) -> Result<Value, SupabaseError> {
|
||||
// Campos que o frontend envia mas NÃO existem como colunas na tabela.
|
||||
// Arrays e objetos são guardados no JSONB `dados` — não em colunas escalar.
|
||||
static BLOCKED: &[&str] = &[
|
||||
"id", "uuid", "criado_em", "atualizado_em", "enviado_por",
|
||||
"ip_origem", "user_agent", "id_fechamento",
|
||||
// arrays e objetos que existem dentro do JSONB `dados`
|
||||
"vales", "despesas", "sangrias", "cancelamentos",
|
||||
"pixcnpj", "receber",
|
||||
"cartoes_credito", "cartoes_debito",
|
||||
"cartoes_alimentacao", "cartoes_pix",
|
||||
];
|
||||
|
||||
let map = updates.as_object().cloned().unwrap_or_default();
|
||||
|
||||
// Remove campos bloqueados
|
||||
let filtered: serde_json::Map<String, serde_json::Value> = map
|
||||
.into_iter()
|
||||
.filter(|(k, _)| !BLOCKED.contains(&k.as_str()))
|
||||
.collect();
|
||||
|
||||
if filtered.is_empty() {
|
||||
return Err(SupabaseError::Api("Nenhum campo para atualizar".into()));
|
||||
}
|
||||
|
||||
let url = format!(
|
||||
"{}/rest/v1/fechamentos_web?id_fechamento=eq.{}",
|
||||
self.base_url,
|
||||
urlencoding::encode(id_fechamento)
|
||||
);
|
||||
|
||||
log::info!("[PATCH] url={} body={:#?}", url, filtered);
|
||||
|
||||
let resp = self
|
||||
.http
|
||||
.patch(&url)
|
||||
.headers(self.headers(true))
|
||||
.json(updates)
|
||||
.header("Prefer", "return=representation")
|
||||
.json(&filtered)
|
||||
.send()?;
|
||||
|
||||
if resp.status().is_success() {
|
||||
Ok(serde_json::json!({ "ok": true, "id": id.unwrap_or(0) }))
|
||||
let status = resp.status();
|
||||
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 {
|
||||
let status = resp.status();
|
||||
let body = resp.text().unwrap_or_default();
|
||||
log::error!("[PATCH] HTTP {} body: {}", status.as_u16(), body);
|
||||
Err(SupabaseError::Api(format!(
|
||||
"HTTP {}: {}",
|
||||
status.as_u16(),
|
||||
@@ -504,16 +537,13 @@ pub fn sb_buscar_por_id_fechamento(
|
||||
sb.buscar_por_id_fechamento(&id_fechamento)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[tauri::command(rename_all = "snake_case")]
|
||||
pub fn sb_atualizar_fechamento(
|
||||
sb: State<'_, SupabaseClient>,
|
||||
id: String,
|
||||
id_fechamento: String,
|
||||
updates: serde_json::Value,
|
||||
) -> Result<serde_json::Value, SupabaseError> {
|
||||
// Tenta primeiro como i64 (id numerico), depois como String (UUID)
|
||||
let id_i64 = id.parse::<i64>().ok();
|
||||
let id_str = &id;
|
||||
sb.atualizar_fechamento(id_i64, id_str, &updates)
|
||||
sb.atualizar_fechamento(&id_fechamento, &updates)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
|
||||
+312
-72
@@ -613,7 +613,7 @@ const fmt = v => 'R$ ' + (parseFloat(v) || 0).toLocaleString('pt-BR', { minimumF
|
||||
const parseNum = v => {
|
||||
// Already a number? Return directly (don't treat '.' as thousand separator)
|
||||
if (typeof v === 'number') return isNaN(v) ? 0 : v;
|
||||
const s = String(v || '0').trim();
|
||||
const s = String(v || '0').trim().replace(/^R\$\s*/, ''); // strip currency prefix first
|
||||
if (!s) return 0;
|
||||
// Brazilian format: 1.234,56 → 1234.56
|
||||
// Strategy: if string has comma, treat as BRL (decimal comma)
|
||||
@@ -1486,9 +1486,11 @@ ${data.observacoes ? `<div class="obs">${data.observacoes}</div>` : ''}
|
||||
function buildPrintHTML(data) {
|
||||
const fmt = v => 'R$ ' + (v || 0).toFixed(2).replace('.', ',');
|
||||
const fmtNeg = v => (v < 0 ? '-' : '') + 'R$ ' + Math.abs(v || 0).toFixed(2).replace('.', ',');
|
||||
// Diferença = fechamento - saldo_esperado - cancelamentos
|
||||
const diferenca = data.diferenca !== undefined ? data.diferenca
|
||||
: ((data.fechamento || 0) - (data.saldo_esperado || 0) - (data.cancelamentos || 0));
|
||||
// Diferença = Total Sistema - Saldo Esperado - Cancelamentos
|
||||
const sysTotalCalc = (data.sysTotal || 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 diffColor = diferenca === 0 ? '#2e7d32' : (diferenca > 0 ? '#e65100' : '#c0272d');
|
||||
|
||||
@@ -1869,12 +1871,28 @@ 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'));
|
||||
|
||||
// Lê do DOM — mas se estiver vazio usa estado (registro anterior)
|
||||
const trocoDom = parseNum(val('sys-troco'));
|
||||
const saldoTroco = trocoDom || estado.saldo_troco || 0;
|
||||
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 + voucher pix + pixcnpj + vales + receber
|
||||
const sysTotal = parseNum(val('sys-troco')) + cartCred + cartDeb + cartAli + cartPix + pixCnpjTotal + valesTotal + receberTotal;
|
||||
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,
|
||||
@@ -1883,14 +1901,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,
|
||||
@@ -2162,35 +2180,46 @@ 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);
|
||||
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>
|
||||
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(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>
|
||||
<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>`;
|
||||
}).join('');
|
||||
|
||||
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">
|
||||
<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 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">
|
||||
<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">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: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>
|
||||
@@ -2202,6 +2231,40 @@ function buildConsultaModal(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() {
|
||||
const m = document.getElementById('modal-consulta');
|
||||
if (m) document.body.removeChild(m);
|
||||
@@ -2283,10 +2346,10 @@ function buildRelatorioModal(full) {
|
||||
const totalSangrias = parseFloat(full.total_sangrias || 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 diferenca = parseFloat(full.diferenca || 0);
|
||||
const statusDif = full.status_diferenca || '?';
|
||||
const diferenca = sysTotal - saldoEsperado - totalCancelamentos;
|
||||
const statusDif = diferenca === 0 ? 'ok' : (diferenca > 0 ? 'sobrando' : 'faltando');
|
||||
|
||||
const diffClass = statusDif === 'ok' ? '#2e7d32' : (statusDif === 'sobrando' ? '#e65100' : '#c0272d');
|
||||
const diffLabel = statusDif === 'ok' ? '✓ OK' : (statusDif === 'sobrando' ? '⚠ SOBRANDO' : (statusDif === 'faltando' ? '⚠ FALTANDO' : statusDif));
|
||||
@@ -2495,6 +2558,7 @@ window.toggleEditConsulta = async function() {
|
||||
}
|
||||
|
||||
openEditModal(full);
|
||||
closeRelatorioModal();
|
||||
};
|
||||
|
||||
// Pede senha admin — retorna Promise<boolean>
|
||||
@@ -2631,6 +2695,7 @@ window._recalcEditTotals = function() {
|
||||
const el = id => document.getElementById(id);
|
||||
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-debito')) el('edit-total-debito').textContent = fmtTot(cartDeb_tot);
|
||||
if (el('edit-total-alimentacao')) el('edit-total-alimentacao').textContent = fmtTot(cartAli_tot);
|
||||
@@ -2638,21 +2703,35 @@ window._recalcEditTotals = function() {
|
||||
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-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-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
|
||||
function openEditModal(full) {
|
||||
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 || {};
|
||||
|
||||
// helper para fmt dinheiro
|
||||
const fmtMR = v => {
|
||||
const n = parseFloat(v||0);
|
||||
if (isNaN(n) || n === 0) return '';
|
||||
if (isNaN(n)) return '';
|
||||
if (n === 0) return 'R$ 0,00';
|
||||
return 'R$ ' + n.toLocaleString('pt-BR', { minimumFractionDigits: 2 });
|
||||
};
|
||||
|
||||
@@ -2676,43 +2755,55 @@ function openEditModal(full) {
|
||||
const cartPixHTML = editTableHTML('pix', ['Valor (R$)'], cartPix_rows.length ? cartPix_rows : [['']], [0]);
|
||||
|
||||
// --- 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]);
|
||||
|
||||
// --- 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]);
|
||||
|
||||
// --- 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]);
|
||||
|
||||
// --- 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]);
|
||||
|
||||
// --- 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]);
|
||||
|
||||
// --- 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]);
|
||||
|
||||
// --- 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';
|
||||
@@ -2881,7 +2972,8 @@ function openEditModal(full) {
|
||||
// Formata campo de dinheiro brasileiro
|
||||
function fmtBR(inp) {
|
||||
const v = parseNum(inp.value);
|
||||
if (isNaN(v) || v === 0) return '';
|
||||
if (isNaN(v)) return '';
|
||||
if (v === 0) return 'R$ 0,00';
|
||||
return 'R$ ' + v.toLocaleString('pt-BR', { minimumFractionDigits: 2 });
|
||||
}
|
||||
|
||||
@@ -2892,10 +2984,101 @@ function closeEditModal() {
|
||||
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, '_');
|
||||
}
|
||||
|
||||
// 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);
|
||||
};
|
||||
|
||||
// Salva edições do modal de edição completo
|
||||
window.salvarEdicaoModal = async function() {
|
||||
const full = window._currentConsulta;
|
||||
if (!full) return;
|
||||
console.log('[DEBUG] salvarEdicaoModal called');
|
||||
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 inp = id => { const el = document.getElementById(id); return el ? el.value : ''; };
|
||||
@@ -2934,6 +3117,9 @@ window.salvarEdicaoModal = async function() {
|
||||
const operador = estado.operador || full.operador || '';
|
||||
|
||||
const updates = {
|
||||
// Chave natural — essencial para o Supabase encontrar o registro
|
||||
id_fechamento: inp('edit-loja') + '_' + inp('edit-data') + '_' + inp('edit-operador'),
|
||||
|
||||
// Identificação
|
||||
loja: inp('edit-loja'),
|
||||
data: inp('edit-data'),
|
||||
@@ -2952,29 +3138,77 @@ window.salvarEdicaoModal = async function() {
|
||||
total_cartao_alimentacao: cartAli_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_credito: p(inp('edit-sld-credito')),
|
||||
saldo_debito: p(inp('edit-sld-debito')),
|
||||
saldo_alimentacao: p(inp('edit-sld-alimentacao')),
|
||||
saldo_vales: p(inp('edit-sld-vales')),
|
||||
total_pixcnpj: p(inp('edit-sld-pixcnpj')),
|
||||
saldo_areceber: p(inp('edit-sld-areceber')),
|
||||
saldo_credito: cartCred_tot,
|
||||
saldo_debito: cartDeb_tot,
|
||||
saldo_alimentacao: cartAli_tot,
|
||||
saldo_vales: vales_tot,
|
||||
saldo_areceber: recv_tot,
|
||||
|
||||
// Totais
|
||||
total_vales: vales_tot,
|
||||
total_despesas: desp_tot,
|
||||
total_sangrias: sang_tot,
|
||||
total_areceber: recv_tot,
|
||||
total_pixcnpj: pixcnpj_tot,
|
||||
total_areceber: recv_tot,
|
||||
total_cancelamentos: canc_tot,
|
||||
|
||||
// Lançamentos detalhados
|
||||
vales: vales,
|
||||
despesas: despesas,
|
||||
sangrias: sangrias,
|
||||
cancelamentos: cancelamentos,
|
||||
pixcnpj: pixcnpj,
|
||||
receber: receber,
|
||||
// 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`)
|
||||
// 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,
|
||||
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 };
|
||||
} catch { return base; }
|
||||
}
|
||||
return { ...(existing || {}), ...base };
|
||||
})(),
|
||||
|
||||
// Contadores
|
||||
clientes: parseInt(inp('edit-clientes') || '0'),
|
||||
@@ -2994,12 +3228,16 @@ window.salvarEdicaoModal = async function() {
|
||||
if (!hasTauri) { alert('Tauri não disponível.'); return; }
|
||||
|
||||
try {
|
||||
// Usa uuid (string) — que é o id externo do registro no Supabase
|
||||
const uuid = full.uuid || full.id;
|
||||
if (!uuid) { alert('UUID do registro não encontrado.'); return; }
|
||||
console.log('[DEBUG] salvarEdicaoModal uuid:', uuid, 'updates:', JSON.stringify(updates));
|
||||
// Usa id_fechamento que é a chave natural do registro
|
||||
const id_fechamento = full.id_fechamento || (full.loja && full.data && full.operador
|
||||
? `${full.loja}_${full.data}_${full.operador}`.toLowerCase().replace(/ /g, '_')
|
||||
: 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 });
|
||||
console.log('[DEBUG] invoke result:', result);
|
||||
closeEditModal();
|
||||
closeRelatorioModal();
|
||||
alert('✅ Atualizado com sucesso!');
|
||||
@@ -3035,7 +3273,9 @@ window.salvarEdicaoConsulta = async function() {
|
||||
frango: parseInt(inp('edit-frango') || '0'),
|
||||
vendas: p(inp('edit-vendas')),
|
||||
saldo_esperado: p(inp('edit-esperado')),
|
||||
observacoes: inp('edit-obs')
|
||||
observacoes: inp('edit-obs'),
|
||||
edited_at: new Date().toISOString(),
|
||||
edited_by: full.operador || '',
|
||||
};
|
||||
|
||||
const hasTauri = !!(window.__TAURI__ && window.__TAURI__.core);
|
||||
|
||||
Reference in New Issue
Block a user