Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| de5d5aaafb | |||
| a11db54ffc | |||
| 674caf2b7a | |||
| bdfd54e0cf | |||
| 9c64c06ed9 |
@@ -193,10 +193,10 @@ impl SupabaseClient {
|
||||
}
|
||||
}
|
||||
|
||||
/// Busca um fechamento por UUID (campo "id" do registro).
|
||||
/// Busca um fechamento pelo campo "id" (UUID externo).
|
||||
pub fn buscar_por_uuid(&self, uuid: &str) -> Result<Option<Value>, SupabaseError> {
|
||||
let url = format!(
|
||||
"{}/rest/v1/fechamentos_web?uuid=eq.{}&select=*",
|
||||
"{}/rest/v1/fechamentos_web?id=eq.{}&select=*",
|
||||
self.base_url, uuid
|
||||
);
|
||||
|
||||
@@ -247,11 +247,11 @@ impl SupabaseClient {
|
||||
}
|
||||
}
|
||||
|
||||
/// Atualiza campos específicos de um fechamento pelo UUID (PATCH).
|
||||
pub fn atualizar_fechamento(&self, uuid: &str, updates: &serde_json::Value) -> Result<Value, SupabaseError> {
|
||||
/// Atualiza campos específicos de um fechamento pelo id numérico (PATCH).
|
||||
pub fn atualizar_fechamento(&self, id: i64, updates: &serde_json::Value) -> Result<Value, SupabaseError> {
|
||||
let url = format!(
|
||||
"{}/rest/v1/fechamentos_web?uuid=eq.{}",
|
||||
self.base_url, uuid
|
||||
"{}/rest/v1/fechamentos_web?id=eq.{}",
|
||||
self.base_url, id
|
||||
);
|
||||
|
||||
let resp = self
|
||||
@@ -262,7 +262,7 @@ impl SupabaseClient {
|
||||
.send()?;
|
||||
|
||||
if resp.status().is_success() {
|
||||
Ok(serde_json::json!({ "ok": true, "uuid": uuid }))
|
||||
Ok(serde_json::json!({ "ok": true, "id": id }))
|
||||
} else {
|
||||
let status = resp.status();
|
||||
let body = resp.text().unwrap_or_default();
|
||||
@@ -274,10 +274,11 @@ impl SupabaseClient {
|
||||
}
|
||||
}
|
||||
pub fn listar_recentes(&self, loja: &str, limite: i64) -> Result<Vec<Value>, SupabaseError> {
|
||||
let loja_normalized = sem_acento(&loja.to_lowercase());
|
||||
let url = format!(
|
||||
"{}/rest/v1/fechamentos_web?loja=eq.{}&order=data.desc,atualizado_em.desc&limit={}&select=id,uuid,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",
|
||||
self.base_url,
|
||||
urlencoding::encode(loja),
|
||||
urlencoding::encode(&loja_normalized),
|
||||
limite,
|
||||
);
|
||||
|
||||
@@ -461,10 +462,10 @@ pub fn sb_buscar_por_id_fechamento(
|
||||
#[tauri::command]
|
||||
pub fn sb_atualizar_fechamento(
|
||||
sb: State<'_, SupabaseClient>,
|
||||
uuid: String,
|
||||
id: i64,
|
||||
updates: serde_json::Value,
|
||||
) -> Result<serde_json::Value, SupabaseError> {
|
||||
sb.atualizar_fechamento(&uuid, &updates)
|
||||
sb.atualizar_fechamento(id, &updates)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
|
||||
+186
-34
@@ -2350,7 +2350,7 @@ function closeRelatorioModal() {
|
||||
window._editMode = false;
|
||||
}
|
||||
|
||||
// Toggle modo de edição — pede senha admin
|
||||
// Toggle modo de edição — pede senha admin via modal (não via prompt)
|
||||
window.toggleEditConsulta = async function() {
|
||||
if (window._editMode) {
|
||||
// Cancela edição
|
||||
@@ -2362,17 +2362,47 @@ window.toggleEditConsulta = async function() {
|
||||
}
|
||||
|
||||
const pw = config.admin_password;
|
||||
let ok = true;
|
||||
if (pw) {
|
||||
const input = prompt('🔐 Digite a senha admin para editar este registro:');
|
||||
ok = (input === pw);
|
||||
if (!ok) { alert('Senha incorreta.'); return; }
|
||||
}
|
||||
|
||||
if (!pw) {
|
||||
window._editMode = true;
|
||||
document.getElementById('edit-section').style.display = 'block';
|
||||
document.getElementById('btn-salvar-consulta').style.display = 'block';
|
||||
document.getElementById('btn-edit-consulta').textContent = '✕ Cancelar';
|
||||
return;
|
||||
}
|
||||
|
||||
// Modal com senha oculta
|
||||
const overlay = document.createElement('div');
|
||||
overlay.style.cssText = 'position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.5);z-index:999999;display:flex;align-items:center;justify-content:center;';
|
||||
overlay.id = 'pw-modal';
|
||||
overlay.innerHTML = `
|
||||
<div style="background:#fff;border-radius:10px;padding:24px;width:300px;text-align:center">
|
||||
<div style="font-size:18px;margin-bottom:16px">🔐 Senha Admin</div>
|
||||
<input type="password" id="pw-input" placeholder="Digite a senha..." style="width:100%;padding:10px;font-size:14px;border:1px solid #ccc;border-radius:6px;box-sizing:border-box;margin-bottom:12px" />
|
||||
<div id="pw-error" style="color:#c0272d;font-size:12px;margin-bottom:8px;display:none">Senha incorreta</div>
|
||||
<div style="display:flex;gap:8px;justify-content:center">
|
||||
<button onclick="document.getElementById('pw-modal').remove()" style="padding:8px 16px;background:#888;color:#fff;border:none;border-radius:6px;cursor:pointer">Cancelar</button>
|
||||
<button id="pw-ok-btn" style="padding:8px 16px;background:#e65100;color:#fff;border:none;border-radius:6px;cursor:pointer">OK</button>
|
||||
</div>
|
||||
</div>`;
|
||||
document.body.appendChild(overlay);
|
||||
const inp = document.getElementById('pw-input');
|
||||
inp.focus();
|
||||
inp.addEventListener('keydown', e => { if (e.key === 'Enter') document.getElementById('pw-ok-btn').click(); });
|
||||
document.getElementById('pw-ok-btn').addEventListener('click', () => {
|
||||
const val = document.getElementById('pw-input').value;
|
||||
const err = document.getElementById('pw-error');
|
||||
if (val === pw) {
|
||||
document.getElementById('pw-modal').remove();
|
||||
window._editMode = true;
|
||||
document.getElementById('edit-section').style.display = 'block';
|
||||
document.getElementById('btn-salvar-consulta').style.display = 'block';
|
||||
document.getElementById('btn-edit-consulta').textContent = '✕ Cancelar';
|
||||
} else {
|
||||
err.style.display = 'block';
|
||||
inp.value = '';
|
||||
inp.focus();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// Salva edições de volta ao Supabase
|
||||
@@ -2392,16 +2422,10 @@ window.salvarEdicaoConsulta = async function() {
|
||||
if (!hasTauri) { alert('Tauri não disponível.'); return; }
|
||||
|
||||
try {
|
||||
let uuid = full.uuid;
|
||||
if (!uuid && full.id_fechamento) {
|
||||
// Buscar uuid pelo id_fechamento primeiro
|
||||
const found = await window.__TAURI__.core.invoke('sb_buscar_por_id_fechamento', { id_fechamento: full.id_fechamento });
|
||||
if (found && found.uuid) uuid = found.uuid;
|
||||
}
|
||||
const id = full.id;
|
||||
if (!id) { alert('ID do registro não encontrado. Não é possível atualizar.'); return; }
|
||||
|
||||
if (!uuid) { alert('UUID do registro não encontrado. Não é possível atualizar.'); return; }
|
||||
|
||||
await window.__TAURI__.core.invoke('sb_atualizar_fechamento', { uuid, updates });
|
||||
await window.__TAURI__.core.invoke('sb_atualizar_fechamento', { id, updates });
|
||||
alert('✅ Atualizado com sucesso!');
|
||||
closeRelatorioModal();
|
||||
} catch(e) {
|
||||
@@ -2410,24 +2434,152 @@ window.salvarEdicaoConsulta = async function() {
|
||||
}
|
||||
};
|
||||
|
||||
// Imprime o relatório (abre janela de impressão do navegador)
|
||||
// Converte o registro "full" do Supabase para o formato usado pelo buildPrintHTML
|
||||
function consultaToPrintData(full) {
|
||||
const fmtDiff = v => 'R$ ' + Math.abs(v || 0).toFixed(2).replace('.', ',');
|
||||
const fmtDiffNeg = v => (v < 0 ? '-' : '') + 'R$ ' + Math.abs(v || 0).toFixed(2).replace('.', ',');
|
||||
const fmt = v => 'R$ ' + (v || 0).toFixed(2).replace('.', ',');
|
||||
|
||||
const cartCred = parseFloat(full.saldo_credito || 0);
|
||||
const cartDeb = parseFloat(full.saldo_debito || 0);
|
||||
const cartAli = parseFloat(full.saldo_alimentacao || 0);
|
||||
const cartPix = parseFloat(full.total_cartao_pix || 0);
|
||||
const pixCnpj = parseFloat(full.total_pixcnpj || 0);
|
||||
const vales = parseFloat(full.saldo_vales || 0);
|
||||
const receber = parseFloat(full.saldo_areceber || 0);
|
||||
const troco = parseFloat(full.saldo_troco || 0);
|
||||
const sysTotal = troco + cartCred + cartDeb + cartAli + cartPix + pixCnpj + vales + receber;
|
||||
const fd = parseFloat(full.fechamento_dinheiro || 0);
|
||||
const fc = parseFloat(full.fechamento_cartoes || 0);
|
||||
const fr = parseFloat(full.fechamento_areceber || 0);
|
||||
const ftotal = fd + fc + fr;
|
||||
const saldoEsp = parseFloat(full.saldo_esperado || 0);
|
||||
const diferenca = parseFloat(full.diferenca || 0);
|
||||
const diffOk = diferenca === 0;
|
||||
const diffStr = diferenca >= 0 ? `+${fmtDiff(diferenca)}` : fmtDiffNeg(diferenca);
|
||||
const dados = full.dados || {};
|
||||
|
||||
const despesas_arr = (dados.despesas || []).map(d => ({ desc: d.desc || '', obs: d.obs || '', valor: parseFloat(d.valor || 0) }));
|
||||
const sangrias_arr = (dados.sangrias || []).map(s => ({ hora: s.hora || '', retirada: parseFloat(s.retirada || 0), gerente: s.gerente || '', valor: parseFloat(s.valor || 0) }));
|
||||
const pixcnpj_arr = (dados.pixcnpj || []).map(p => ({ nome: p.nome || '', valor: parseFloat(p.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 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_debito = (full.cartoes_debito || []).map(v => parseFloat(v || 0));
|
||||
const cartoes_alimentacao = (full.cartoes_alimentacao || []).map(v => parseFloat(v || 0));
|
||||
const cartoes_pix = (full.cartoes_pix || []).map(v => parseFloat(v || 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 totalPixCnpj = pixcnpj_arr.reduce((s, r) => s + r.valor, 0);
|
||||
const totalVales = vales_arr.reduce((s, r) => s + r.valor, 0);
|
||||
const totalReceber = receber_arr.reduce((s, r) => s + r.valor, 0);
|
||||
const totalCancel = cancelamentos_arr.reduce((s, r) => s + r.valor, 0);
|
||||
const totalCartoes = cartCred + cartDeb + cartAli + cartPix;
|
||||
|
||||
return {
|
||||
loja: full.loja || '?',
|
||||
data: full.data || '?',
|
||||
operador: full.operador || '?',
|
||||
turno: full.turno || '?',
|
||||
saldo_troco: troco,
|
||||
saldo_esperado: saldoEsp,
|
||||
fechamento: ftotal,
|
||||
diferenca: diferenca,
|
||||
sys_total: sysTotal,
|
||||
fechamento_dinheiro: fd,
|
||||
fechamento_cartoes: fc,
|
||||
fechamento_areceber: fr,
|
||||
credito: cartCred,
|
||||
debito: cartDeb,
|
||||
alimentacao: cartAli,
|
||||
voucher: cartPix,
|
||||
pixcnpj: pixCnpj,
|
||||
vales: vales,
|
||||
areceber: receber,
|
||||
cancelamentos: totalCancel,
|
||||
despesas_arr,
|
||||
sangrias_arr,
|
||||
pixcnpj_arr,
|
||||
vales_arr,
|
||||
receber_arr,
|
||||
cancelamentos_arr,
|
||||
cartoes_credito,
|
||||
cartoes_debito,
|
||||
cartoes_alimentacao,
|
||||
cartoes_pix,
|
||||
totalSangrias,
|
||||
totalDespesas,
|
||||
totalPixCnpj,
|
||||
totalVales,
|
||||
totalReceber,
|
||||
totalCancel,
|
||||
totalCartoes,
|
||||
sysTotal,
|
||||
saldoEsperado: saldoEsp,
|
||||
diffStr,
|
||||
diffOk,
|
||||
fdin: fd,
|
||||
fcarts: fc,
|
||||
frec: fr,
|
||||
ftotal,
|
||||
observacoes: full.observacoes || '',
|
||||
clientes: full.clientes || 0,
|
||||
frango: full.frango || 0,
|
||||
};
|
||||
}
|
||||
|
||||
// Imprime o relatório — usa iframe como openPrintPreview (Tauri não bloqueia)
|
||||
window.printRelatorio = function() {
|
||||
const inner = document.getElementById('relatorio-inner');
|
||||
if (!inner) return;
|
||||
const Win = window.open('', '', 'width=600,height=700');
|
||||
Win.document.write(`<html><head><title>Relatorio Fechamento</title><style>
|
||||
body{font-family:monospace;font-size:13px;padding:10px;margin:0;width:280px}
|
||||
.header{text-align:center;border-bottom:1px dashed #000;padding-bottom:5px;margin-bottom:5px}
|
||||
.section{border:1px solid #000;margin-bottom:8px}
|
||||
.section-title{background:#000;color:#fff;padding:2px 5px;font-size:11px}
|
||||
.row{display:flex;justify-content:space-between;padding:2px 5px}
|
||||
.total{border-top:1px solid #000;margin-top:2px;padding:2px 5px;font-weight:bold}
|
||||
.result{text-align:center;padding:4px;font-weight:bold}
|
||||
button{display:none}
|
||||
</style></head><body>${inner.innerHTML}</body></html>`);
|
||||
Win.document.close();
|
||||
Win.focus();
|
||||
setTimeout(() => { Win.print(); Win.close(); }, 500);
|
||||
const full = window._currentConsulta;
|
||||
if (!full) return;
|
||||
const data = consultaToPrintData(full);
|
||||
const html = buildPrintHTML(data);
|
||||
const previewStyle = `
|
||||
<style>
|
||||
body { width: 80mm; margin: 0 auto; font-family: 'Courier New', monospace; font-size: 13px; background: #fff; padding: 10px; }
|
||||
.header { text-align: center; margin-bottom: 8px; }
|
||||
.header h1 { font-size: 18px; }
|
||||
.header h2 { font-size: 14px; font-weight: normal; }
|
||||
hr { border: none; border-top: 1px dashed #000; margin: 5px 0; }
|
||||
.section-title { font-weight: bold; font-size: 13px; border-top: 1px dashed #000; padding-top: 3px; margin-top: 6px; }
|
||||
.row { display: flex; justify-content: space-between; padding: 1px 0; font-size: 12px; }
|
||||
.row.total-row { font-weight: bold; }
|
||||
.cart-table { width: 100%; border-collapse: collapse; font-size: 11px; margin-top: 4px; }
|
||||
.cart-table th { font-weight: bold; border-bottom: 1px solid #000; padding: 2px; }
|
||||
.cart-table td { padding: 2px 4px; text-align: right; }
|
||||
.cart-table td:first-child { text-align: left; }
|
||||
.cart-table tr.total-row { font-weight: bold; border-top: 1px dashed #000; }
|
||||
.subtotal { font-size: 12px; margin-top: 4px; }
|
||||
.diff-ok { color: #2e7d32; }
|
||||
.diff-bad { color: #c0272d; }
|
||||
.obs { font-size: 11px; color: #555; margin-top: 6px; white-space: pre-wrap; }
|
||||
.footer { text-align: center; font-size: 11px; color: #555; margin-top: 8px; }
|
||||
@media print { body { background: #fff; } }
|
||||
</style>`;
|
||||
const fullHtml = `<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Recibo</title>${previewStyle}</head><body>${html}</body></html>`;
|
||||
|
||||
const existing = document.getElementById('print-preview-overlay');
|
||||
if (existing) document.body.removeChild(existing);
|
||||
const overlay = document.createElement('div');
|
||||
overlay.id = 'print-preview-overlay';
|
||||
overlay.style.cssText = 'position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.85);z-index:99999;display:flex;flex-direction:column;align-items:center;font-family:\'Courier New\',monospace;';
|
||||
const iframe = document.createElement('iframe');
|
||||
iframe.style.cssText = 'width:360px;height:600px;border:2px solid #555;margin-top:16px;background:#fff;';
|
||||
iframe.id = 'print-iframe';
|
||||
const btnFechar = document.createElement('button');
|
||||
btnFechar.textContent = '✕ Fechar';
|
||||
btnFechar.style.cssText = 'margin-top:12px;padding:10px 32px;background:#444;color:#fff;border:none;border-radius:6px;font-size:15px;cursor:pointer;';
|
||||
btnFechar.onclick = () => document.body.removeChild(overlay);
|
||||
const btnImprimir = document.createElement('button');
|
||||
btnImprimir.textContent = '🖨️ Imprimir';
|
||||
btnImprimir.style.cssText = 'margin-top:8px;padding:10px 32px;background:#e65100;color:#fff;border:none;border-radius:6px;font-size:15px;cursor:pointer;';
|
||||
btnImprimir.onclick = () => { iframe.contentWindow.focus(); iframe.contentWindow.print(); };
|
||||
overlay.appendChild(iframe);
|
||||
overlay.appendChild(btnFechar);
|
||||
overlay.appendChild(btnImprimir);
|
||||
document.body.appendChild(overlay);
|
||||
iframe.srcdoc = fullHtml;
|
||||
};
|
||||
|
||||
// Intercepta o envio — se sync_status=editing, faz PATCH
|
||||
|
||||
Reference in New Issue
Block a user