Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9a4ccabd1b | |||
| 32728eec37 | |||
| 905ca253d7 | |||
| d89b79a3f8 |
@@ -248,27 +248,37 @@ 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> {
|
||||
let url = format!(
|
||||
"{}/rest/v1/fechamentos_web?id_fechamento=eq.{}",
|
||||
self.base_url,
|
||||
urlencoding::encode(id_fechamento)
|
||||
);
|
||||
|
||||
// Log do que está sendo enviado (debug)
|
||||
log::info!("[PATCH] url={} body={}", url, updates);
|
||||
|
||||
let resp = self
|
||||
.http
|
||||
.patch(&url)
|
||||
.headers(self.headers(true))
|
||||
.header("Prefer", "return=representation")
|
||||
.json(updates)
|
||||
.send()?;
|
||||
|
||||
if resp.status().is_success() {
|
||||
Ok(serde_json::json!({ "ok": true, "id": id.unwrap_or(0) }))
|
||||
} else {
|
||||
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 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 +514,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]
|
||||
|
||||
+20
-13
@@ -2649,6 +2649,8 @@ window._recalcEditTotals = function() {
|
||||
// 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 || {};
|
||||
|
||||
@@ -2679,27 +2681,27 @@ 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) ---
|
||||
@@ -2898,8 +2900,8 @@ function closeEditModal() {
|
||||
// Salva edições do modal de edição completo
|
||||
window.salvarEdicaoModal = async function() {
|
||||
console.log('[DEBUG] salvarEdicaoModal called');
|
||||
const full = window._currentConsulta;
|
||||
if (!full) { console.log('[DEBUG] _currentConsulta is null'); alert('Nenhum registro selecionado.'); 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);
|
||||
@@ -2939,6 +2941,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'),
|
||||
@@ -2999,13 +3004,15 @@ 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));
|
||||
|
||||
console.log('[DEBUG] invoking sb_atualizar_fechamento...');
|
||||
const result = await window.__TAURI__.core.invoke('sb_atualizar_fechamento', { id: uuid, updates: JSON.stringify(updates) });
|
||||
const result = await window.__TAURI__.core.invoke('sb_atualizar_fechamento', { id_fechamento, updates: JSON.stringify(updates) });
|
||||
console.log('[DEBUG] invoke result:', result);
|
||||
closeEditModal();
|
||||
closeRelatorioModal();
|
||||
|
||||
Reference in New Issue
Block a user