Compare commits
24 Commits
v1.3.48
...
v1.4.7-fix
| Author | SHA1 | Date | |
|---|---|---|---|
| 42aadcca2c | |||
| a8319d96a6 | |||
| bf878545b3 | |||
| 22cda312cf | |||
| d112ad061e | |||
| be917f8fb7 | |||
| cb48afeb9c | |||
| 2b8ff711ed | |||
| 9a4ccabd1b | |||
| 32728eec37 | |||
| 905ca253d7 | |||
| d89b79a3f8 | |||
| c4dda7e2e5 | |||
| 662f3681a5 | |||
| a56d7188f2 | |||
| 7e1ee6bc04 | |||
| 6a8881d41d | |||
| 3b3eb1a4cc | |||
| c7109b1017 | |||
| f45d1e8170 | |||
| 8ea5ba771a | |||
| 84578fe43d | |||
| 3e94789cb0 | |||
| 292d0b85d9 |
@@ -248,27 +248,60 @@ 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
|
// Campos que o frontend envia mas NÃO existem como colunas na tabela.
|
||||||
let url = if let Some(num) = id {
|
// Arrays e objetos são guardados no JSONB `dados` — não em colunas escalar.
|
||||||
format!("{}/rest/v1/fechamentos_web?id=eq.{}", self.base_url, num)
|
static BLOCKED: &[&str] = &[
|
||||||
} else {
|
"id", "uuid", "criado_em", "atualizado_em", "enviado_por",
|
||||||
format!("{}/rest/v1/fechamentos_web?id=eq.{}", self.base_url, uuid)
|
"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
|
let resp = self
|
||||||
.http
|
.http
|
||||||
.patch(&url)
|
.patch(&url)
|
||||||
.headers(self.headers(true))
|
.headers(self.headers(true))
|
||||||
.json(updates)
|
.header("Prefer", "return=representation")
|
||||||
|
.json(&filtered)
|
||||||
.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 +312,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 +537,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]
|
||||||
|
|||||||
+308
-149
@@ -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.
|
||||||
@@ -613,7 +613,7 @@ const fmt = v => 'R$ ' + (parseFloat(v) || 0).toLocaleString('pt-BR', { minimumF
|
|||||||
const parseNum = v => {
|
const parseNum = v => {
|
||||||
// Already a number? Return directly (don't treat '.' as thousand separator)
|
// Already a number? Return directly (don't treat '.' as thousand separator)
|
||||||
if (typeof v === 'number') return isNaN(v) ? 0 : v;
|
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;
|
if (!s) return 0;
|
||||||
// Brazilian format: 1.234,56 → 1234.56
|
// Brazilian format: 1.234,56 → 1234.56
|
||||||
// Strategy: if string has comma, treat as BRL (decimal comma)
|
// Strategy: if string has comma, treat as BRL (decimal comma)
|
||||||
@@ -1380,32 +1380,32 @@ function buildConfirmHTML(data) {
|
|||||||
<td>${cartPix > 0 ? fmt(cartPix) : '-'}</td>
|
<td>${cartPix > 0 ? fmt(cartPix) : '-'}</td>
|
||||||
</tr>`;
|
</tr>`;
|
||||||
|
|
||||||
return `<!DOCTYPE html>
|
let html = `<!DOCTYPE html>
|
||||||
<html><head>
|
<html><head>
|
||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<title>Fechamento de Caixa</title>
|
<title>Fechamento de Caixa</title>
|
||||||
<style>
|
<style>
|
||||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||||
body { font-family: 'Courier New', monospace; font-size: 13px; width: 80mm; margin: 0 auto; padding: 8px; }
|
body { font-family: 'Courier New', monospace; font-size: 15px; width: 80mm; margin: 0 auto; padding: 8px; font-weight: bold !important; print-color-adjust: exact; -webkit-print-color-adjust: exact; }
|
||||||
.header { text-align: center; margin-bottom: 8px; }
|
.header { text-align: center; margin-bottom: 8px; }
|
||||||
.header h1 { font-size: 18px; }
|
.header h1 { font-size: 20px; font-weight: bold !important; }
|
||||||
.header h2 { font-size: 14px; font-weight: normal; }
|
.header h2 { font-size: 16px; font-weight: bold !important; }
|
||||||
hr { border: none; border-top: 1px dashed #000; margin: 5px 0; }
|
hr { border: none; border-top: 2px solid #000; margin: 6px 0; }
|
||||||
.section-title { font-weight: bold; font-size: 13px; border-top: 1px dashed #000; padding-top: 3px; margin-top: 6px; }
|
.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: 1px 0; font-size: 12px; }
|
.row { display: flex; justify-content: space-between; padding: 2px 0; font-size: 14px; font-weight: bold !important; }
|
||||||
.row.total-row { font-weight: bold; }
|
.row.total-row { font-weight: bold !important; }
|
||||||
.cart-table { width: 100%; border-collapse: collapse; font-size: 11px; margin-top: 4px; }
|
.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; border-bottom: 1px solid #000; padding: 2px; }
|
.cart-table th { font-weight: bold !important; border-bottom: 2px solid #000; padding: 3px; font-size: 13px; width: 25%; }
|
||||||
.cart-table td { padding: 2px 4px; text-align: right; }
|
.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; border-top: 1px dashed #000; }
|
.cart-table tr.total-row { font-weight: bold !important; border-top: 2px solid #000; }
|
||||||
.subtotal { font-size: 12px; margin-top: 4px; }
|
.subtotal { font-size: 13px; margin-top: 4px; }
|
||||||
.diff-ok { color: #2e7d32; }
|
.subtotal .row { padding: 1px 0; font-weight: bold !important; }
|
||||||
.diff-bad { color: #c0272d; }
|
.diff-ok { color: #2e7d32; font-weight: bold !important; }
|
||||||
.obs { font-size: 11px; color: #555; margin-top: 6px; white-space: pre-wrap; }
|
.diff-bad { color: #c0272d; font-weight: bold !important; }
|
||||||
.footer { text-align: center; font-size: 11px; color: #555; margin-top: 8px; }
|
.obs { font-size: 12px; color: #555; margin-top: 6px; white-space: pre-wrap; font-weight: bold !important; }
|
||||||
@media print { body { margin: 0; } }
|
.footer { text-align: center; font-size: 12px; color: #555; margin-top: 8px; font-weight: bold !important; }
|
||||||
</style>
|
@media print { body { background: #fff; font-weight: bold !important; font-size: 15px !important; } }
|
||||||
</head><body>
|
</head><body>
|
||||||
<div class="header">
|
<div class="header">
|
||||||
<h1>${data.loja}</h1>
|
<h1>${data.loja}</h1>
|
||||||
@@ -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');
|
||||||
|
|
||||||
@@ -1604,26 +1606,26 @@ function buildPrintHTML(data) {
|
|||||||
<title>Fechamento de Caixa</title>
|
<title>Fechamento de Caixa</title>
|
||||||
<style>
|
<style>
|
||||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||||
body { font-family: 'Courier New', monospace; font-size: 13px; width: 80mm; margin: 0 auto; padding: 8px; }
|
body { font-family: 'Courier New', monospace; font-size: 15px; width: 80mm; margin: 0 auto; padding: 8px; font-weight: bold !important; print-color-adjust: exact; -webkit-print-color-adjust: exact; }
|
||||||
.header { text-align: center; margin-bottom: 8px; }
|
.header { text-align: center; margin-bottom: 8px; }
|
||||||
.header h1 { font-size: 18px; }
|
.header h1 { font-size: 20px; font-weight: bold !important; }
|
||||||
.header h2 { font-size: 14px; font-weight: normal; }
|
.header h2 { font-size: 16px; font-weight: bold !important; }
|
||||||
hr { border: none; border-top: 1px dashed #000; margin: 5px 0; }
|
hr { border: none; border-top: 2px solid #000; margin: 6px 0; }
|
||||||
.section-title { font-weight: bold; font-size: 13px; border-top: 1px dashed #000; padding-top: 3px; margin-top: 6px; }
|
.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: 1px 0; font-size: 12px; }
|
.row { display: flex; justify-content: space-between; padding: 2px 0; font-size: 14px; font-weight: bold !important; }
|
||||||
.row.total-row { font-weight: bold; }
|
.row.total-row { font-weight: bold !important; }
|
||||||
.cart-table { width: 100%; border-collapse: collapse; font-size: 11px; margin-top: 4px; }
|
.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; border-bottom: 1px solid #000; padding: 2px; }
|
.cart-table th { font-weight: bold !important; border-bottom: 2px solid #000; padding: 3px; font-size: 13px; width: 25%; }
|
||||||
.cart-table td { padding: 2px 4px; text-align: right; }
|
.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; border-top: 1px dashed #000; }
|
.cart-table tr.total-row { font-weight: bold !important; border-top: 2px solid #000; }
|
||||||
.subtotal { font-size: 12px; margin-top: 4px; }
|
.subtotal { font-size: 13px; margin-top: 4px; }
|
||||||
.subtotal .row { padding: 1px 0; }
|
.subtotal .row { padding: 1px 0; font-weight: bold !important; }
|
||||||
.diff-ok { color: #2e7d32; }
|
.diff-ok { color: #2e7d32; font-weight: bold !important; }
|
||||||
.diff-bad { color: #c0272d; }
|
.diff-bad { color: #c0272d; font-weight: bold !important; }
|
||||||
.obs { font-size: 11px; color: #555; margin-top: 6px; white-space: pre-wrap; }
|
.obs { font-size: 12px; color: #555; margin-top: 6px; white-space: pre-wrap; font-weight: bold !important; }
|
||||||
.footer { text-align: center; font-size: 11px; color: #555; margin-top: 8px; }
|
.footer { text-align: center; font-size: 12px; color: #555; margin-top: 8px; font-weight: bold !important; }
|
||||||
@media print { body { margin: 0; } }
|
@media print { body { background: #fff; font-weight: bold !important; font-size: 15px !important; } }
|
||||||
</style>
|
</style>
|
||||||
</head><body>
|
</head><body>
|
||||||
<div class="header">
|
<div class="header">
|
||||||
@@ -1853,9 +1855,11 @@ function triggerWindowPrint() {
|
|||||||
window.print();
|
window.print();
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Recibo 80mm via Tauri (ESC/POS USB) ─────────────────────────────────
|
// ─── buildReciboData — lê do FORMULÁRIO principal (não do estado carregado do BD) ───
|
||||||
// ─── Recibo 80mm via Tauri (ESC/POS USB) ─────────────────────────────────
|
// Importante: quando editing, o estado estápopulado pelo abrirFechamentoEdicao, não do BD
|
||||||
// Build data object shared by both ESC/POS and preview
|
|
||||||
|
// ─── buildReciboData — lê do FORMULÁRIO principal ───────────────────────────
|
||||||
|
// usado tanto para novo fechamento quanto para edição
|
||||||
function buildReciboData() {
|
function buildReciboData() {
|
||||||
const cartCred = estado.cartoes.credito.reduce((s,r) => s+(r.valor||0), 0);
|
const cartCred = estado.cartoes.credito.reduce((s,r) => s+(r.valor||0), 0);
|
||||||
const cartDeb = estado.cartoes.debito.reduce((s,r) => s+(r.valor||0), 0);
|
const cartDeb = estado.cartoes.debito.reduce((s,r) => s+(r.valor||0), 0);
|
||||||
@@ -1876,6 +1880,7 @@ function buildReciboData() {
|
|||||||
return {
|
return {
|
||||||
uuid: estado.uuid,
|
uuid: estado.uuid,
|
||||||
id_local: estado.id_local,
|
id_local: estado.id_local,
|
||||||
|
id: estado.id,
|
||||||
loja: estado.loja,
|
loja: estado.loja,
|
||||||
data: estado.data,
|
data: estado.data,
|
||||||
operador: estado.operador,
|
operador: estado.operador,
|
||||||
@@ -1899,7 +1904,7 @@ function buildReciboData() {
|
|||||||
vales: valesTotal,
|
vales: valesTotal,
|
||||||
areceber: receberTotal,
|
areceber: receberTotal,
|
||||||
cancelamentos: cancelTotal,
|
cancelamentos: cancelTotal,
|
||||||
// Full arrays for preview
|
// Full arrays for preview / Supabase
|
||||||
despesas_arr: estado.despesas.map(r => ({ desc: r.desc||'', obs: r.obs||'', valor: r.valor||0 })),
|
despesas_arr: estado.despesas.map(r => ({ desc: r.desc||'', obs: r.obs||'', valor: r.valor||0 })),
|
||||||
sangrias_arr: estado.sangrias.map(r => ({ hora: r.hora||'', retirada: parseNum(r.retirada)||0, gerente: r.gerente||'' })),
|
sangrias_arr: estado.sangrias.map(r => ({ hora: r.hora||'', retirada: parseNum(r.retirada)||0, gerente: r.gerente||'' })),
|
||||||
pixcnpj_arr: estado.pixcnpj.map(r => ({ nome: r.nome||'', valor: r.valor||0 })),
|
pixcnpj_arr: estado.pixcnpj.map(r => ({ nome: r.nome||'', valor: r.valor||0 })),
|
||||||
@@ -1910,10 +1915,22 @@ function buildReciboData() {
|
|||||||
cartoes_debito: estado.cartoes.debito.map(r => r.valor || 0),
|
cartoes_debito: estado.cartoes.debito.map(r => r.valor || 0),
|
||||||
cartoes_alimentacao: estado.cartoes.alimentacao.map(r => r.valor || 0),
|
cartoes_alimentacao: estado.cartoes.alimentacao.map(r => r.valor || 0),
|
||||||
cartoes_pix: estado.cartoes.pix.map(r => r.valor || 0),
|
cartoes_pix: estado.cartoes.pix.map(r => r.valor || 0),
|
||||||
|
total_cartao_credito: cartCred,
|
||||||
|
total_cartao_debito: cartDeb,
|
||||||
|
total_cartao_alimentacao: cartAli,
|
||||||
|
total_cartao_pix: cartPix,
|
||||||
|
total_pixcnpj: pixCnpjTotal,
|
||||||
|
total_sangrias: sangriasTotal,
|
||||||
|
total_despesas: despesasTotal,
|
||||||
|
total_vales: valesTotal,
|
||||||
|
total_areceber: receberTotal,
|
||||||
|
total_cancelamentos: cancelTotal,
|
||||||
observacoes: estado.observacoes,
|
observacoes: estado.observacoes,
|
||||||
clientes: estado.clientes,
|
clientes: estado.clientes,
|
||||||
frango: estado.frango,
|
frango: estado.frango,
|
||||||
vendas: estado.vendas || 0,
|
vendas: estado.vendas || 0,
|
||||||
|
edited_at: new Date().toISOString(),
|
||||||
|
edited_by: config.admin_user || 'admin',
|
||||||
sync_status: estado.sync_status,
|
sync_status: estado.sync_status,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -2148,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">
|
||||||
@@ -2176,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>
|
||||||
@@ -2187,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);
|
||||||
@@ -2268,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));
|
||||||
@@ -2374,6 +2429,10 @@ window.abrirFechamentoEdicao = function(full) {
|
|||||||
const dados = full.dados || full;
|
const dados = full.dados || full;
|
||||||
if (!dados) { alert('Dados detalhados não encontrados neste registro.'); return; }
|
if (!dados) { alert('Dados detalhados não encontrados neste registro.'); return; }
|
||||||
|
|
||||||
|
// IDs do registro — CRÍTICO para o salvamento via Supabase
|
||||||
|
estado.uuid = full.uuid || null;
|
||||||
|
estado.id = full.id || full.uuid || null;
|
||||||
|
|
||||||
// Preenche o estado global com todos os campos do JSONB
|
// Preenche o estado global com todos os campos do JSONB
|
||||||
estado.loja = dados.loja || full.loja || '';
|
estado.loja = dados.loja || full.loja || '';
|
||||||
estado.data = dados.data || full.data || '';
|
estado.data = dados.data || full.data || '';
|
||||||
@@ -2448,7 +2507,7 @@ window.abrirFechamentoEdicao = function(full) {
|
|||||||
renderTable('tbl-cartao-pix', estado.cartoes.pix);
|
renderTable('tbl-cartao-pix', estado.cartoes.pix);
|
||||||
|
|
||||||
// Recalcula totais
|
// Recalcula totais
|
||||||
calcAll();
|
updateTotals();
|
||||||
|
|
||||||
// Rola para o topo do formulário
|
// Rola para o topo do formulário
|
||||||
window.scrollTo(0, 0);
|
window.scrollTo(0, 0);
|
||||||
@@ -2464,14 +2523,19 @@ window.toggleEditConsulta = async function() {
|
|||||||
// Se já está editando, apenas fecha
|
// Se já está editando, apenas fecha
|
||||||
if (window._editModalOpen) { closeEditModal(); return; }
|
if (window._editModalOpen) { closeEditModal(); return; }
|
||||||
|
|
||||||
// Pede senha admin primeiro (se configurada)
|
// Pede senha admin primeiro — sempre, para proteger edições
|
||||||
const pw = config.admin_password;
|
const pw = config.admin_password;
|
||||||
if (pw) {
|
if (pw) {
|
||||||
const ok = await askPassword();
|
const ok = await askPassword();
|
||||||
if (!ok) return;
|
if (!ok) return;
|
||||||
|
} else {
|
||||||
|
// Sem senha configurada — avisa e abre mesmo assim (primeiro uso)
|
||||||
|
const ok = await askPassword(); // mostra diálogo vazio para o admin configurar mentalmente
|
||||||
|
if (!ok) return;
|
||||||
}
|
}
|
||||||
|
|
||||||
openEditModal(full);
|
openEditModal(full);
|
||||||
|
closeRelatorioModal();
|
||||||
};
|
};
|
||||||
|
|
||||||
// Pede senha admin — retorna Promise<boolean>
|
// Pede senha admin — retorna Promise<boolean>
|
||||||
@@ -2516,14 +2580,21 @@ function askPassword() {
|
|||||||
|
|
||||||
// Monta HTML de uma grade editável dentro do modal
|
// Monta HTML de uma grade editável dentro do modal
|
||||||
function editTableHTML(id, headers, rows, numericCols) {
|
function editTableHTML(id, headers, rows, numericCols) {
|
||||||
|
const fmtNum = v => {
|
||||||
|
const n = parseFloat(v);
|
||||||
|
return isNaN(n) ? '' : 'R$ ' + n.toLocaleString('pt-BR', { minimumFractionDigits: 2 });
|
||||||
|
};
|
||||||
const hdr = headers.map((h,i) => `<th style="padding:2px 4px;text-align:${numericCols.includes(i)?'right':'left'};font-size:10px;white-space:nowrap">${h}</th>`).join('');
|
const hdr = headers.map((h,i) => `<th style="padding:2px 4px;text-align:${numericCols.includes(i)?'right':'left'};font-size:10px;white-space:nowrap">${h}</th>`).join('');
|
||||||
const body = rows.map((row, ri) => {
|
const body = rows.map((row, ri) => {
|
||||||
const cells = row.map((val, ci) => {
|
const cells = row.map((val, ci) => {
|
||||||
const isNum = numericCols.includes(ci);
|
const isNum = numericCols.includes(ci);
|
||||||
const displayVal = (val !== null && val !== undefined && val !== '')
|
const displayVal = (val !== null && val !== undefined && val !== '')
|
||||||
? (isNum ? fmtMoney(val) : val)
|
? (isNum ? fmtNum(val) : val)
|
||||||
: '';
|
: '';
|
||||||
return `<td style="padding:1px 2px"><input data-tbl="${id}" data-row="${ri}" data-col="${ci}" value="${displayVal}" ${isNum ? `style="width:100%;padding:2px;font-size:11px;text-align:right;border:1px solid #ccc;border-radius:2px"` : `style="width:100%;padding:2px;font-size:11px;border:1px solid #ccc;border-radius:2px"`} /></td>`;
|
const extra = isNum
|
||||||
|
? `oninput="window._recalcEditTotals()" onblur="this.value=fmtBR(this)" `
|
||||||
|
: '';
|
||||||
|
return `<td style="padding:1px 2px"><input data-tbl="${id}" data-row="${ri}" data-col="${ci}" value="${displayVal}" ${extra}${isNum ? `style="width:100%;padding:2px;font-size:11px;text-align:right;border:1px solid #ccc;border-radius:2px"` : `style="width:100%;padding:2px;font-size:11px;border:1px solid #ccc;border-radius:2px"`} /></td>`;
|
||||||
}).join('');
|
}).join('');
|
||||||
return `<tr>${cells}</tr>`;
|
return `<tr>${cells}</tr>`;
|
||||||
}).join('');
|
}).join('');
|
||||||
@@ -2549,8 +2620,10 @@ window._editAddRow = function(tblId) {
|
|||||||
for (let c = 0; c < cols; c++) {
|
for (let c = 0; c < cols; c++) {
|
||||||
const td = row.insertCell(-1);
|
const td = row.insertCell(-1);
|
||||||
const isNum = numericCols.includes(c);
|
const isNum = numericCols.includes(c);
|
||||||
td.innerHTML = `<input data-tbl="${tblId}" data-row="${newRowIdx}" data-col="${c}" value="" ${isNum ? `style="width:100%;padding:2px;font-size:11px;text-align:right;border:1px solid #ccc;border-radius:2px"` : `style="width:100%;padding:2px;font-size:11px;border:1px solid #ccc;border-radius:2px"`} />`;
|
td.innerHTML = `<input data-tbl="${tblId}" data-row="${newRowIdx}" data-col="${c}" value="" ${isNum ? `oninput="window._recalcEditTotals()" onblur="this.value=fmtBR(this)" style="width:100%;padding:2px;font-size:11px;text-align:right;border:1px solid #ccc;border-radius:2px"` : `style="width:100%;padding:2px;font-size:11px;border:1px solid #ccc;border-radius:2px"`} />`;
|
||||||
}
|
}
|
||||||
|
// Recalcula após adicionar
|
||||||
|
window._recalcEditTotals();
|
||||||
};
|
};
|
||||||
|
|
||||||
// Lê todos os dados das grades editáveis do modal
|
// Lê todos os dados das grades editáveis do modal
|
||||||
@@ -2582,25 +2655,64 @@ function readEditTables() {
|
|||||||
return tables;
|
return tables;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Recalcula todos os totais do modal de edição e atualiza o display
|
||||||
|
window._recalcEditTotals = function() {
|
||||||
|
const tables = readEditTables();
|
||||||
|
const cartCred_tot = (tables.credito || []).reduce((s, r) => s + (r[0] || 0), 0);
|
||||||
|
const cartDeb_tot = (tables.debito || []).reduce((s, r) => s + (r[0] || 0), 0);
|
||||||
|
const cartAli_tot = (tables.alimentacao || []).reduce((s, r) => s + (r[0] || 0), 0);
|
||||||
|
const cartPix_tot = (tables.pix || []).reduce((s, r) => s + (r[0] || 0), 0);
|
||||||
|
const vales_tot = (tables.vales || []).reduce((s, r) => s + (r[1] || 0), 0);
|
||||||
|
const desp_tot = (tables.despesas || []).reduce((s, r) => s + (r[2] || 0), 0);
|
||||||
|
const sang_tot = (tables.sangrias || []).reduce((s, r) => s + (r[1] || 0), 0);
|
||||||
|
const pixcnpj_tot = (tables.pixcnpj || []).reduce((s, r) => s + (r[1] || 0), 0);
|
||||||
|
const recv_tot = (tables.receber || []).reduce((s, r) => s + (r[1] || 0), 0);
|
||||||
|
const canc_tot = (tables.cancelamentos || []).reduce((s, r) => s + (r[1] || 0), 0);
|
||||||
|
|
||||||
|
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);
|
||||||
|
if (el('edit-total-pix')) el('edit-total-pix').textContent = fmtTot(cartPix_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-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-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
|
// 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 || {};
|
||||||
|
|
||||||
// helper para fmt dinheiro
|
// helper para fmt dinheiro
|
||||||
const fmtMR = v => {
|
const fmtMR = v => {
|
||||||
const n = parseFloat(v||0);
|
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 });
|
return 'R$ ' + n.toLocaleString('pt-BR', { minimumFractionDigits: 2 });
|
||||||
};
|
};
|
||||||
|
|
||||||
// helper para fmt table cell
|
// helper inline para fmt table cell (já em editTableHTML)
|
||||||
const fmtCell = (v, isNum) => {
|
|
||||||
if (v === null || v === undefined || v === '') return '';
|
|
||||||
if (isNum) return fmtMoney(v);
|
|
||||||
return v;
|
|
||||||
};
|
|
||||||
|
|
||||||
const editedInfo = full.edited_at
|
const editedInfo = full.edited_at
|
||||||
? `<div style="background:#fff8e1;border-radius:4px;padding:6px 10px;font-size:11px;color:#666;margin-bottom:8px">
|
? `<div style="background:#fff8e1;border-radius:4px;padding:6px 10px;font-size:11px;color:#666;margin-bottom:8px">
|
||||||
@@ -2609,10 +2721,10 @@ function openEditModal(full) {
|
|||||||
: '';
|
: '';
|
||||||
|
|
||||||
// --- Cartões ---
|
// --- Cartões ---
|
||||||
const cartCred_rows = (dados.cartoes?.credito || full.cartoes_credito || []).map((r, i) => [fmtCell(typeof r === 'object' ? r.valor : r, true)]);
|
const cartCred_rows = (dados.cartoes?.credito || full.cartoes_credito || []).map(r => [typeof r === 'object' ? r.valor : r]);
|
||||||
const cartDeb_rows = (dados.cartoes?.debito || full.cartoes_debito || []).map((r, i) => [fmtCell(typeof r === 'object' ? r.valor : r, true)]);
|
const cartDeb_rows = (dados.cartoes?.debito || full.cartoes_debito || []).map(r => [typeof r === 'object' ? r.valor : r]);
|
||||||
const cartAli_rows = (dados.cartoes?.alimentacao || full.cartoes_alimentacao || []).map((r, i) => [fmtCell(typeof r === 'object' ? r.valor : r, true)]);
|
const cartAli_rows = (dados.cartoes?.alimentacao || full.cartoes_alimentacao || []).map(r => [typeof r === 'object' ? r.valor : r]);
|
||||||
const cartPix_rows = (dados.cartoes?.pix || full.cartoes_pix || []).map((r, i) => [fmtCell(typeof r === 'object' ? r.valor : r, true)]);
|
const cartPix_rows = (dados.cartoes?.pix || full.cartoes_pix || []).map(r => [typeof r === 'object' ? r.valor : r]);
|
||||||
|
|
||||||
const cartCredHTML = editTableHTML('credito', ['Valor (R$)'], cartCred_rows.length ? cartCred_rows : [['']], [0]);
|
const cartCredHTML = editTableHTML('credito', ['Valor (R$)'], cartCred_rows.length ? cartCred_rows : [['']], [0]);
|
||||||
const cartDebHTML = editTableHTML('debito', ['Valor (R$)'], cartDeb_rows.length ? cartDeb_rows : [['']], [0]);
|
const cartDebHTML = editTableHTML('debito', ['Valor (R$)'], cartDeb_rows.length ? cartDeb_rows : [['']], [0]);
|
||||||
@@ -2620,27 +2732,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 || []).map(r => [r.nome||r.Nome||'', fmtCell(r.valor, true), 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 || []).map(r => [r.desc||r.Desc||'', r.obs||r.Obs||'', fmtCell(r.valor, true)]);
|
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 || []).map(r => [r.hora||r.Hora||'', fmtCell(r.retirada, true), 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 || []).map(r => [r.numero||r.Numero||'', fmtCell(r.valor, true), 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 || []).map(r => [r.nome||r.Nome||'', fmtCell(r.valor, true)]);
|
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 || []).map(r => [r.nome||r.Nome||'', fmtCell(r.valor, true)]);
|
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) ---
|
||||||
@@ -2650,10 +2762,12 @@ function openEditModal(full) {
|
|||||||
<div><strong>Total Débito:</strong> <span id="edit-total-debito">${fmtMR(full.total_cartao_debito||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 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 PIX:</strong> <span id="edit-total-pix">${fmtMR(full.total_cartao_pix||0)}</span></div>
|
||||||
<div><strong>Total Sangrias:</strong> ${fmtMR(full.total_sangrias||0)}</div>
|
<div><strong>Total Sangrias:</strong> <span id="edit-total-sangrias">${fmtMR(full.total_sangrias||0)}</span></div>
|
||||||
<div><strong>Total Despesas:</strong> ${fmtMR(full.total_despesas||0)}</div>
|
<div><strong>Total Despesas:</strong> <span id="edit-total-despesas">${fmtMR(full.total_despesas||0)}</span></div>
|
||||||
<div><strong>Total Vales:</strong> ${fmtMR(full.total_vales||0)}</div>
|
<div><strong>Total Vales:</strong> <span id="edit-total-vales">${fmtMR(full.total_vales||0)}</span></div>
|
||||||
<div><strong>Total PIX CNPJ:</strong> ${fmtMR(full.total_pixcnpj||0)}</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>`;
|
</div>`;
|
||||||
|
|
||||||
const overlay = document.createElement('div');
|
const overlay = document.createElement('div');
|
||||||
@@ -2782,25 +2896,26 @@ function openEditModal(full) {
|
|||||||
<div id="tbl-edit-cancelamentos" data-numeric="[1]">${cancelHTML}</div>
|
<div id="tbl-edit-cancelamentos" data-numeric="[1]">${cancelHTML}</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Saldo de Caixa (editável) -->
|
<!-- Saldo de Caixa (SÓ TROCO é editável — restante é soma automática) -->
|
||||||
<div style="margin-bottom:12px">
|
<div style="margin-bottom:12px;background:#f5f5f5;border-radius:6px;padding:8px">
|
||||||
<strong style="font-size:12px;color:#333;margin-bottom:4px;display:block">💰 Saldo de Caixa</strong>
|
<strong style="font-size:12px;color:#333;margin-bottom:4px;display:block">💰 Saldo de Caixa <span style="font-size:10px;color:#888">(apenas Troco é editável)</span></strong>
|
||||||
<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:6px">
|
<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:6px">
|
||||||
<div><label style="font-size:10px;color:#555">Troco:</label><input type="text" id="edit-troco" value="${fmtMR(full.saldo_troco)}" style="width:100%;padding:5px;border:1px solid #ccc;border-radius:4px;text-align:right" onblur="this.value=fmtBR(this)" /></div>
|
<div><label style="font-size:10px;color:#555">Troco:</label><input type="text" id="edit-troco" value="${fmtMR(full.saldo_troco)}" style="width:100%;padding:5px;border:1px solid #2e7d32;border-radius:4px;text-align:right" onblur="this.value=fmtBR(this)" /></div>
|
||||||
<div><label style="font-size:10px;color:#555">Crédito:</label><input type="text" id="edit-sld-credito" value="${fmtMR(full.saldo_credito)}" style="width:100%;padding:5px;border:1px solid #ccc;border-radius:4px;text-align:right" onblur="this.value=fmtBR(this)" /></div>
|
<div><label style="font-size:10px;color:#888">Crédito:</label><input type="text" id="edit-sld-credito" value="${fmtMR(full.saldo_credito)}" readonly tabindex="-1" style="width:100%;padding:5px;border:1px solid #ddd;border-radius:4px;text-align:right;background:#eee;color:#666" /></div>
|
||||||
<div><label style="font-size:10px;color:#555">Débito:</label><input type="text" id="edit-sld-debito" value="${fmtMR(full.saldo_debito)}" style="width:100%;padding:5px;border:1px solid #ccc;border-radius:4px;text-align:right" onblur="this.value=fmtBR(this)" /></div>
|
<div><label style="font-size:10px;color:#888">Débito:</label><input type="text" id="edit-sld-debito" value="${fmtMR(full.saldo_debito)}" readonly tabindex="-1" style="width:100%;padding:5px;border:1px solid #ddd;border-radius:4px;text-align:right;background:#eee;color:#666" /></div>
|
||||||
<div><label style="font-size:10px;color:#555">Alimentação:</label><input type="text" id="edit-sld-alimentacao" value="${fmtMR(full.saldo_alimentacao)}" style="width:100%;padding:5px;border:1px solid #ccc;border-radius:4px;text-align:right" onblur="this.value=fmtBR(this)" /></div>
|
<div><label style="font-size:10px;color:#888">Alimentação:</label><input type="text" id="edit-sld-alimentacao" value="${fmtMR(full.saldo_alimentacao)}" readonly tabindex="-1" style="width:100%;padding:5px;border:1px solid #ddd;border-radius:4px;text-align:right;background:#eee;color:#666" /></div>
|
||||||
<div><label style="font-size:10px;color:#555">Vales:</label><input type="text" id="edit-sld-vales" value="${fmtMR(full.saldo_vales)}" style="width:100%;padding:5px;border:1px solid #ccc;border-radius:4px;text-align:right" onblur="this.value=fmtBR(this)" /></div>
|
<div><label style="font-size:10px;color:#888">Vales:</label><input type="text" id="edit-sld-vales" value="${fmtMR(full.saldo_vales)}" readonly tabindex="-1" style="width:100%;padding:5px;border:1px solid #ddd;border-radius:4px;text-align:right;background:#eee;color:#666" /></div>
|
||||||
<div><label style="font-size:10px;color:#555">PIX CNPJ:</label><input type="text" id="edit-sld-pixcnpj" value="${fmtMR(full.total_pixcnpj)}" style="width:100%;padding:5px;border:1px solid #ccc;border-radius:4px;text-align:right" onblur="this.value=fmtBR(this)" /></div>
|
<div><label style="font-size:10px;color:#888">PIX CNPJ:</label><input type="text" id="edit-sld-pixcnpj" value="${fmtMR(full.total_pixcnpj)}" readonly tabindex="-1" style="width:100%;padding:5px;border:1px solid #ddd;border-radius:4px;text-align:right;background:#eee;color:#666" /></div>
|
||||||
<div><label style="font-size:10px;color:#555">À Receber:</label><input type="text" id="edit-sld-areceber" value="${fmtMR(full.saldo_areceber)}" style="width:100%;padding:5px;border:1px solid #ccc;border-radius:4px;text-align:right" onblur="this.value=fmtBR(this)" /></div>
|
<div><label style="font-size:10px;color:#888">À Receber:</label><input type="text" id="edit-sld-areceber" value="${fmtMR(full.saldo_areceber)}" readonly tabindex="-1" style="width:100%;padding:5px;border:1px solid #ddd;border-radius:4px;text-align:right;background:#eee;color:#666" /></div>
|
||||||
<div><label style="font-size:10px;color:#555">Vendas (R$):</label><input type="text" id="edit-vendas" value="${fmtMR(dados.vendas||full.vendas||0)}" style="width:100%;padding:5px;border:1px solid #e65100;border-radius:4px;text-align:right;font-weight:bold" onblur="this.value=fmtBR(this)" /></div>
|
<div><label style="font-size:10px;color:#888">PIX Cartão:</label><input type="text" id="edit-sld-pixcartao" value="${fmtMR(full.total_cartao_pix)}" readonly tabindex="-1" style="width:100%;padding:5px;border:1px solid #ddd;border-radius:4px;text-align:right;background:#eee;color:#666" /></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Contadores -->
|
<!-- Contadores -->
|
||||||
<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:6px;margin-bottom:12px">
|
<div style="display:grid;grid-template-columns:1fr 1fr 1fr 1fr;gap:6px;margin-bottom:12px">
|
||||||
<div><label style="font-size:10px;color:#555">Clientes:</label><input type="number" id="edit-clientes" value="${dados.clientes||full.clientes||0}" min="0" style="width:100%;padding:5px;border:1px solid #ccc;border-radius:4px" /></div>
|
<div><label style="font-size:10px;color:#555">Clientes:</label><input type="number" id="edit-clientes" value="${dados.clientes||full.clientes||0}" min="0" style="width:100%;padding:5px;border:1px solid #ccc;border-radius:4px" /></div>
|
||||||
<div><label style="font-size:10px;color:#555">Frango Assado:</label><input type="number" id="edit-frango" value="${dados.frango||full.frango||0}" min="0" style="width:100%;padding:5px;border:1px solid #ccc;border-radius:4px" /></div>
|
<div><label style="font-size:10px;color:#555">Frango Assado:</label><input type="number" id="edit-frango" value="${dados.frango||full.frango||0}" min="0" style="width:100%;padding:5px;border:1px solid #ccc;border-radius:4px" /></div>
|
||||||
|
<div><label style="font-size:10px;color:#555">Vendas (R$):</label><input type="text" id="edit-vendas" value="${fmtMR(dados.vendas||full.vendas||0)}" style="width:100%;padding:5px;border:1px solid #e65100;border-radius:4px;text-align:right;font-weight:bold" onblur="this.value=fmtBR(this)" /></div>
|
||||||
<div><label style="font-size:10px;color:#555">Saldo Esperado:</label><input type="text" id="edit-esperado" value="${fmtMR(full.saldo_esperado)}" style="width:100%;padding:5px;border:1px solid #e65100;border-radius:4px;text-align:right;font-weight:bold" onblur="this.value=fmtBR(this)" /></div>
|
<div><label style="font-size:10px;color:#555">Saldo Esperado:</label><input type="text" id="edit-esperado" value="${fmtMR(full.saldo_esperado)}" style="width:100%;padding:5px;border:1px solid #e65100;border-radius:4px;text-align:right;font-weight:bold" onblur="this.value=fmtBR(this)" /></div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -2822,7 +2937,8 @@ function openEditModal(full) {
|
|||||||
// Formata campo de dinheiro brasileiro
|
// Formata campo de dinheiro brasileiro
|
||||||
function fmtBR(inp) {
|
function fmtBR(inp) {
|
||||||
const v = parseNum(inp.value);
|
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 });
|
return 'R$ ' + v.toLocaleString('pt-BR', { minimumFractionDigits: 2 });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2833,10 +2949,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 : ''; };
|
||||||
@@ -2875,6 +3007,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'),
|
||||||
@@ -2893,29 +3028,35 @@ 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')),
|
saldo_areceber: recv_tot,
|
||||||
saldo_areceber: p(inp('edit-sld-areceber')),
|
|
||||||
|
|
||||||
// Totais
|
// Totais
|
||||||
total_vales: vales_tot,
|
total_vales: vales_tot,
|
||||||
total_despesas: desp_tot,
|
total_despesas: desp_tot,
|
||||||
total_sangrias: sang_tot,
|
total_sangrias: sang_tot,
|
||||||
total_areceber: recv_tot,
|
total_pixcnpj: pixcnpj_tot,
|
||||||
|
total_areceber: recv_tot,
|
||||||
total_cancelamentos: canc_tot,
|
total_cancelamentos: canc_tot,
|
||||||
|
|
||||||
// Lançamentos detalhados
|
// Lançamentos detalhados (JSONB — gravados no campo `dados`)
|
||||||
vales: vales,
|
dados: JSON.stringify({
|
||||||
despesas: despesas,
|
cartoes,
|
||||||
sangrias: sangrias,
|
vales,
|
||||||
cancelamentos: cancelamentos,
|
despesas,
|
||||||
pixcnpj: pixcnpj,
|
sangrias,
|
||||||
receber: receber,
|
cancelamentos,
|
||||||
|
pixcnpj,
|
||||||
|
receber,
|
||||||
|
clientes: parseInt(inp('edit-clientes') || '0'),
|
||||||
|
frango: parseInt(inp('edit-frango') || '0'),
|
||||||
|
vendas: p(inp('edit-vendas')),
|
||||||
|
}),
|
||||||
|
|
||||||
// Contadores
|
// Contadores
|
||||||
clientes: parseInt(inp('edit-clientes') || '0'),
|
clientes: parseInt(inp('edit-clientes') || '0'),
|
||||||
@@ -2935,10 +3076,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 {
|
||||||
const id = inp('edit-id') || full.id;
|
// Usa id_fechamento que é a chave natural do registro
|
||||||
if (!id) { alert('ID do registro não encontrado.'); return; }
|
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, 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();
|
closeEditModal();
|
||||||
closeRelatorioModal();
|
closeRelatorioModal();
|
||||||
alert('✅ Atualizado com sucesso!');
|
alert('✅ Atualizado com sucesso!');
|
||||||
@@ -2974,7 +3121,9 @@ window.salvarEdicaoConsulta = async function() {
|
|||||||
frango: parseInt(inp('edit-frango') || '0'),
|
frango: parseInt(inp('edit-frango') || '0'),
|
||||||
vendas: p(inp('edit-vendas')),
|
vendas: p(inp('edit-vendas')),
|
||||||
saldo_esperado: p(inp('edit-esperado')),
|
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);
|
const hasTauri = !!(window.__TAURI__ && window.__TAURI__.core);
|
||||||
@@ -3024,10 +3173,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);
|
||||||
@@ -3094,30 +3243,37 @@ window.printRelatorio = function() {
|
|||||||
const full = window._currentConsulta;
|
const full = window._currentConsulta;
|
||||||
if (!full) return;
|
if (!full) return;
|
||||||
const data = consultaToPrintData(full);
|
const data = consultaToPrintData(full);
|
||||||
const html = buildPrintHTML(data);
|
|
||||||
const previewStyle = `
|
let html = `<!DOCTYPE html>
|
||||||
<style>
|
<html><head>
|
||||||
body { width: 80mm; margin: 0 auto; font-family: 'Courier New', monospace; font-size: 13px; background: #fff; padding: 10px; }
|
<meta charset="UTF-8">
|
||||||
.header { text-align: center; margin-bottom: 8px; }
|
<title>Fechamento de Caixa</title>
|
||||||
.header h1 { font-size: 18px; }
|
<style>
|
||||||
.header h2 { font-size: 14px; font-weight: normal; }
|
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||||
hr { border: none; border-top: 1px dashed #000; margin: 5px 0; }
|
body { font-family: 'Courier New', monospace; font-size: 14px; width: 80mm; margin: 0 auto; padding: 8px; font-weight: bold; print-color-adjust: exact; -webkit-print-color-adjust: exact; }
|
||||||
.section-title { font-weight: bold; font-size: 13px; border-top: 1px dashed #000; padding-top: 3px; margin-top: 6px; }
|
.header { text-align: center; margin-bottom: 8px; }
|
||||||
.row { display: flex; justify-content: space-between; padding: 1px 0; font-size: 12px; }
|
.header h1 { font-size: 20px; font-weight: bold; }
|
||||||
.row.total-row { font-weight: bold; }
|
.header h2 { font-size: 15px; font-weight: normal; }
|
||||||
.cart-table { width: 100%; border-collapse: collapse; font-size: 11px; margin-top: 4px; }
|
hr { border: none; border-top: 2px solid #000; margin: 6px 0; }
|
||||||
.cart-table th { font-weight: bold; border-bottom: 1px solid #000; padding: 2px; }
|
.section-title { font-weight: bold; font-size: 14px; border-top: 2px solid #000; padding-top: 4px; margin-top: 8px; }
|
||||||
.cart-table td { padding: 2px 4px; text-align: right; }
|
.row { display: flex; justify-content: space-between; padding: 2px 0; font-size: 13px; font-weight: bold; }
|
||||||
.cart-table td:first-child { text-align: left; }
|
.row.total-row { font-weight: bold; }
|
||||||
.cart-table tr.total-row { font-weight: bold; border-top: 1px dashed #000; }
|
.cart-table { table-layout: fixed; width: 100%; border-collapse: collapse; font-size: 13px; margin-top: 4px; font-weight: bold; }
|
||||||
.subtotal { font-size: 12px; margin-top: 4px; }
|
.cart-table th { font-weight: bold; border-bottom: 2px solid #000; padding: 2px; width: 25%; }
|
||||||
.diff-ok { color: #2e7d32; }
|
.cart-table td { padding: 2px 4px; text-align: right; font-weight: bold; }
|
||||||
.diff-bad { color: #c0272d; }
|
.cart-table td:first-child { text-align: left; }
|
||||||
.obs { font-size: 11px; color: #555; margin-top: 6px; white-space: pre-wrap; }
|
.cart-table tr.total-row { font-weight: bold; border-top: 2px solid #000; }
|
||||||
.footer { text-align: center; font-size: 11px; color: #555; margin-top: 8px; }
|
.subtotal { font-size: 13px; margin-top: 4px; }
|
||||||
@media print { body { background: #fff; } }
|
.subtotal .row { padding: 2px 0; }
|
||||||
</style>`;
|
.diff-ok { color: #2e7d32; font-weight: bold; }
|
||||||
const fullHtml = `<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Recibo</title>${previewStyle}</head><body>${html}</body></html>`;
|
.diff-bad { color: #c0272d; font-weight: bold; }
|
||||||
|
.obs { font-size: 11px; color: #555; margin-top: 6px; white-space: pre-wrap; font-weight: normal; }
|
||||||
|
.footer { text-align: center; font-size: 11px; color: #555; margin-top: 8px; }
|
||||||
|
@media print { body { background: #fff; font-weight: bold !important; } }
|
||||||
|
</style>
|
||||||
|
</head><body>
|
||||||
|
${buildPrintHTML(data)}
|
||||||
|
</body></html>`;
|
||||||
|
|
||||||
const existing = document.getElementById('print-preview-overlay');
|
const existing = document.getElementById('print-preview-overlay');
|
||||||
if (existing) document.body.removeChild(existing);
|
if (existing) document.body.removeChild(existing);
|
||||||
@@ -3139,7 +3295,7 @@ window.printRelatorio = function() {
|
|||||||
overlay.appendChild(btnFechar);
|
overlay.appendChild(btnFechar);
|
||||||
overlay.appendChild(btnImprimir);
|
overlay.appendChild(btnImprimir);
|
||||||
document.body.appendChild(overlay);
|
document.body.appendChild(overlay);
|
||||||
iframe.srcdoc = fullHtml;
|
iframe.srcdoc = html;
|
||||||
};
|
};
|
||||||
|
|
||||||
// Intercepta o envio — se sync_status=editing, faz PATCH
|
// Intercepta o envio — se sync_status=editing, faz PATCH
|
||||||
@@ -3188,8 +3344,11 @@ async function salvarEdicaoSupabase() {
|
|||||||
// Remove campos que não devem ir no PATCH
|
// Remove campos que não devem ir no PATCH
|
||||||
delete data.uuid;
|
delete data.uuid;
|
||||||
delete data.id_local;
|
delete data.id_local;
|
||||||
|
// Usa o id numérico se disponível, senão usa uuid
|
||||||
|
const id = estado.id || estado.uuid;
|
||||||
|
console.log('[DEBUG] salvando id:', id, 'data:', JSON.stringify(data));
|
||||||
const result = await window.__TAURI__.core.invoke('sb_atualizar_fechamento', {
|
const result = await window.__TAURI__.core.invoke('sb_atualizar_fechamento', {
|
||||||
uuid: estado.uuid,
|
id: id,
|
||||||
updates: JSON.stringify(data)
|
updates: JSON.stringify(data)
|
||||||
});
|
});
|
||||||
console.log('[DEBUG] sb_atualizar_fechamento result:', result);
|
console.log('[DEBUG] sb_atualizar_fechamento result:', result);
|
||||||
|
|||||||
Reference in New Issue
Block a user