{"id":28,"date":"2025-12-12T16:42:10","date_gmt":"2025-12-12T16:42:10","guid":{"rendered":"https:\/\/utiles.fagales360.com\/?page_id=28"},"modified":"2026-01-25T00:58:35","modified_gmt":"2026-01-25T00:58:35","slug":"sistema-contable-f360","status":"publish","type":"page","link":"https:\/\/utiles.fagales360.com\/?page_id=28","title":{"rendered":"Sistema Contable F360"},"content":{"rendered":"\n<style>\n    @import url('https:\/\/fonts.googleapis.com\/css2?family=JetBrains+Mono:wght@400;700&family=Inter:wght@400;600;800&display=swap');\n    \n    \/* Encapsulamiento para evitar conflictos con temas de WordPress *\/\n    .f360-wp-wrapper {\n        all: initial; \/* Resetea estilos heredados del tema *\/\n        display: block;\n        font-family: 'Inter', sans-serif;\n        background-color: #f1f5f9;\n        color: #1e293b;\n        line-height: 1.5;\n        width: 100%;\n        min-height: 600px;\n    }\n\n    .f360-wp-wrapper * { box-sizing: border-box; }\n    .f360-wp-wrapper .mono { font-family: 'JetBrains Mono', monospace !important; }\n    .f360-wp-wrapper .tab-btn.active { border-bottom: 3px solid #0ea5e9 !important; color: #0284c7 !important; background-color: #f0f9ff !important; }\n    .f360-wp-wrapper button { cursor: pointer; transition: opacity 0.2s; }\n    .f360-wp-wrapper button:hover { opacity: 0.9; }\n    .f360-wp-wrapper .hidden { display: none !important; }\n    \n    \/* Scrollbars finas *\/\n    .f360-wp-wrapper .scroller::-webkit-scrollbar { width: 4px; height: 4px; }\n    .f360-wp-wrapper .scroller::-webkit-scrollbar-thumb { background-color: #cbd5e1; border-radius: 10px; }\n<\/style>\n\n<!-- Scripts necesarios cargados de forma segura -->\n<script src=\"https:\/\/cdn.tailwindcss.com\"><\/script>\n<link href=\"https:\/\/cdnjs.cloudflare.com\/ajax\/libs\/font-awesome\/6.0.0\/css\/all.min.css\" rel=\"stylesheet\">\n\n<div class=\"f360-wp-wrapper\">\n    <div class=\"f360-container bg-slate-100 min-h-screen pb-10\">\n        <!-- Navbar -->\n        <nav class=\"bg-slate-900 text-white p-4 sticky top-0 z-50 shadow-2xl border-b border-slate-700\">\n            <div class=\"max-w-7xl mx-auto flex flex-col lg:flex-row justify-between items-center gap-4\">\n                <div class=\"flex flex-col\">\n                    <div class=\"flex items-center gap-3\">\n                        <div class=\"bg-yellow-500 text-slate-900 p-1 px-2 rounded font-bold text-xs\">F360<\/div>\n                        <h1 class=\"text-lg font-bold tracking-tight uppercase\">Fagales<span class=\"text-yellow-500\">360<\/span><\/h1>\n                    <\/div>\n                    <div class=\"text-[10px] text-slate-400 mt-1 flex gap-3\">\n                        <span><i class=\"fa-solid fa-sack-dollar text-emerald-500\"><\/i> Capital: $325,325<\/span>\n                        <span><i class=\"fa-solid fa-vault text-blue-400\"><\/i> Reserva: <span id=\"usd-reserve\">0.00<\/span> USD<\/span>\n                    <\/div>\n                <\/div>\n\n                <div class=\"flex gap-2 items-center flex-wrap justify-center\">\n                    <button onclick=\"window.openUSDModal()\" class=\"bg-slate-800 text-emerald-400 border border-slate-600 px-3 py-1 rounded text-[10px] font-bold\">\n                        <i class=\"fa-solid fa-rotate\"><\/i> VENDER USD\n                    <\/button>\n                    <button onclick=\"window.reconcileCash()\" class=\"text-[10px] text-yellow-300 border border-yellow-600 bg-yellow-900\/30 px-3 py-1 rounded font-bold\">\n                        <i class=\"fa-solid fa-scale-balanced\"><\/i> ARQUEO\n                    <\/button>\n                    <button onclick=\"window.exportData()\" class=\"text-[10px] text-blue-300 border border-blue-900 bg-blue-900\/30 px-3 py-1 rounded\">\n                        <i class=\"fa-solid fa-download\"><\/i> BACKUP\n                    <\/button>\n                    <button onclick=\"window.resetData()\" class=\"text-[10px] text-red-400 border border-red-900 bg-red-900\/20 px-3 py-1 rounded font-bold\">\n                        <i class=\"fa-solid fa-trash\"><\/i> RESET\n                    <\/button>\n                <\/div>\n            <\/div>\n        <\/nav>\n\n        <div class=\"max-w-7xl mx-auto p-4 space-y-6\">\n            <!-- KPIs -->\n            <div class=\"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4\">\n                <div class=\"bg-white p-4 rounded-xl shadow-sm border-l-4 border-purple-600\">\n                    <p class=\"text-[10px] text-slate-500 uppercase font-bold\">Caja F\u00edsica (CUP)<\/p>\n                    <p class=\"text-2xl font-bold mono text-purple-700 mt-1\" id=\"kpi-caja\">$0.00<\/p>\n                <\/div>\n                <div class=\"bg-white p-4 rounded-xl shadow-sm border-l-4 border-blue-600\">\n                    <p class=\"text-[10px] text-slate-500 uppercase font-bold\">Stock Actual (Costo)<\/p>\n                    <p class=\"text-2xl font-bold mono text-blue-700 mt-1\" id=\"kpi-inventario-valor\">$0.00<\/p>\n                <\/div>\n                <div class=\"bg-white p-4 rounded-xl shadow-sm border-l-4 border-emerald-500\">\n                    <p class=\"text-[10px] text-slate-500 uppercase font-bold\">Ganancia Neta<\/p>\n                    <p class=\"text-2xl font-bold mono text-emerald-600 mt-1\" id=\"kpi-ganancia\">$0.00<\/p>\n                <\/div>\n                <div class=\"bg-white p-4 rounded-xl shadow-sm border-l-4 border-slate-600\">\n                    <p class=\"text-[10px] text-slate-500 uppercase font-bold\">Patrimonio Total<\/p>\n                    <p class=\"text-2xl font-bold mono text-slate-700 mt-1\" id=\"kpi-patrimonio\">$0.00<\/p>\n                <\/div>\n            <\/div>\n\n            <!-- Botones Operativos -->\n            <div class=\"grid grid-cols-3 gap-2 bg-white p-2 rounded-xl shadow-sm\">\n                <button onclick=\"window.openModal('venta')\" class=\"bg-emerald-600 text-white py-4 rounded-lg font-bold transition flex flex-col items-center justify-center gap-1 shadow-md\">\n                    <i class=\"fa-solid fa-cash-register text-xl\"><\/i><span class=\"text-[10px]\">VENTA<\/span>\n                <\/button>\n                <button onclick=\"window.openModal('compra')\" class=\"bg-blue-600 text-white py-4 rounded-lg font-bold transition flex flex-col items-center justify-center gap-1 shadow-md\">\n                    <i class=\"fa-solid fa-truck-ramp-box text-xl\"><\/i><span class=\"text-[10px]\">COMPRA<\/span>\n                <\/button>\n                <button onclick=\"window.openModal('gasto')\" class=\"bg-red-600 text-white py-4 rounded-lg font-bold transition flex flex-col items-center justify-center gap-1 shadow-md\">\n                    <i class=\"fa-solid fa-receipt text-xl\"><\/i><span class=\"text-[10px]\">GASTO<\/span>\n                <\/button>\n            <\/div>\n\n            <!-- Dashboard principal -->\n            <div class=\"bg-white rounded-xl shadow-sm overflow-hidden min-h-[500px] flex flex-col\">\n                <div class=\"flex border-b border-slate-200 overflow-x-auto scroller bg-slate-50\">\n                    <button onclick=\"window.switchTab('inventario')\" id=\"tab-inventario\" class=\"tab-btn active px-6 py-4 font-bold text-xs whitespace-nowrap\">INVENTARIO<\/button>\n                    <button onclick=\"window.switchTab('distribucion')\" id=\"tab-distribucion\" class=\"tab-btn px-6 py-4 font-bold text-xs whitespace-nowrap\">DISTRIBUCI\u00d3N<\/button>\n                    <button onclick=\"window.switchTab('movimientos')\" id=\"tab-movimientos\" class=\"tab-btn px-6 py-4 font-bold text-xs whitespace-nowrap\">MOVIMIENTOS<\/button>\n                    <button onclick=\"window.switchTab('estadisticas')\" id=\"tab-estadisticas\" class=\"tab-btn px-6 py-4 font-bold text-xs whitespace-nowrap\">ANALIZAR<\/button>\n                    <button onclick=\"window.switchTab('activos')\" id=\"tab-activos\" class=\"tab-btn px-6 py-4 font-bold text-xs whitespace-nowrap\">ACTIVOS<\/button>\n                <\/div>\n\n                <!-- Vistas -->\n                <div id=\"view-inventario\" class=\"p-4 flex-1\">\n                    <div class=\"flex justify-between items-center mb-4\">\n                        <h3 class=\"font-bold text-slate-800 text-sm\">Control de Stock<\/h3>\n                        <div class=\"text-right\"><span class=\"font-bold text-blue-700 text-sm\" id=\"inv-total-sum\">$0.00<\/span><\/div>\n                    <\/div>\n                    <div class=\"overflow-x-auto scroller\">\n                        <table class=\"w-full text-xs text-left\">\n                            <thead class=\"text-[10px] text-slate-500 uppercase bg-slate-100\">\n                                <tr><th class=\"px-4 py-3\">Producto<\/th><th class=\"px-4 py-3 text-right\">In<\/th><th class=\"px-4 py-3 text-right\">Out<\/th><th class=\"px-4 py-3 text-right font-bold bg-slate-200\">Stock<\/th><th class=\"px-4 py-3 text-right\">Costo<\/th><th class=\"px-4 py-3 text-right\">Valor<\/th><\/tr>\n                            <\/thead>\n                            <tbody id=\"inventory-table-body\" class=\"divide-y divide-slate-100\"><\/tbody>\n                        <\/table>\n                    <\/div>\n                <\/div>\n\n                <div id=\"view-distribucion\" class=\"hidden p-6 flex-1 bg-slate-50 text-sm\">\n                    <div class=\"max-w-xl mx-auto bg-white p-6 rounded-xl shadow-sm border\">\n                        <div class=\"flex justify-between items-center mb-6 border-b pb-4\">\n                            <h2 class=\"font-bold uppercase text-slate-800\">Utilidades<\/h2>\n                            <span class=\"font-mono text-xl font-bold text-emerald-600\" id=\"dist-net-profit\">$0.00<\/span>\n                        <\/div>\n                        <div class=\"grid grid-cols-1 gap-3 mb-6\">\n                            <div class=\"bg-blue-50 p-4 rounded border border-blue-100 flex justify-between\"><span>T\u00fa + Inversor (60%)<\/span><span class=\"font-bold\" id=\"share-partners\">$0<\/span><\/div>\n                            <div class=\"bg-emerald-50 p-4 rounded border border-emerald-100 flex justify-between\"><span>Fagales + Reinversi\u00f3n (40%)<\/span><span class=\"font-bold\" id=\"share-reserve\">$0<\/span><\/div>\n                        <\/div>\n                        <button onclick=\"window.registerDistribution()\" class=\"w-full bg-slate-900 text-white py-4 rounded font-bold\">RETIRAR DIVIDENDOS SOCIOS<\/button>\n                    <\/div>\n                <\/div>\n\n                <div id=\"view-movimientos\" class=\"hidden p-4 flex-1\">\n                    <div class=\"flex justify-between items-center mb-4\">\n                        <h3 class=\"font-bold text-sm\">Historial<\/h3>\n                        <input type=\"text\" id=\"searchTrans\" placeholder=\"Buscar...\" class=\"border rounded px-3 py-1 text-xs outline-none\" onkeyup=\"window.renderTable()\">\n                    <\/div>\n                    <div class=\"overflow-x-auto scroller max-h-[400px]\">\n                        <table class=\"w-full text-xs text-left\">\n                            <thead class=\"text-[10px] uppercase bg-slate-100 sticky top-0\">\n                                <tr><th class=\"px-4 py-2\">Fecha<\/th><th class=\"px-4 py-2\">Tipo<\/th><th class=\"px-4 py-2\">Concepto<\/th><th class=\"px-4 py-2 text-right\">Monto<\/th><th class=\"px-4 py-2\"><\/th><\/tr>\n                            <\/thead>\n                            <tbody id=\"transaction-table-body\" class=\"divide-y divide-slate-100\"><\/tbody>\n                        <\/table>\n                    <\/div>\n                <\/div>\n\n                <div id=\"view-estadisticas\" class=\"hidden p-6 flex-1 text-sm\">\n                    <div class=\"max-w-2xl mx-auto space-y-6\">\n                        <div class=\"bg-white p-4 rounded-xl border grid grid-cols-1 md:grid-cols-3 gap-4 items-end\">\n                            <div><label class=\"text-[10px] font-bold\">DESDE<\/label><input type=\"date\" id=\"statsStart\" class=\"w-full border p-2 rounded text-xs\"><\/div>\n                            <div><label class=\"text-[10px] font-bold\">HASTA<\/label><input type=\"date\" id=\"statsEnd\" class=\"w-full border p-2 rounded text-xs\"><\/div>\n                            <button onclick=\"window.calculateStats()\" class=\"bg-blue-600 text-white py-2 rounded font-bold text-xs uppercase\">Analizar<\/button>\n                        <\/div>\n                        <div id=\"statsResults\" class=\"hidden grid grid-cols-2 gap-2 text-center\">\n                             <div class=\"p-3 bg-emerald-50 rounded border\"><p class=\"text-[9px] font-bold uppercase\">Ventas<\/p><p class=\"font-bold\" id=\"stat-sales\">$0<\/p><\/div>\n                             <div class=\"p-3 bg-red-50 rounded border\"><p class=\"text-[9px] font-bold uppercase\">Gastos<\/p><p class=\"font-bold\" id=\"stat-expenses\">$0<\/p><\/div>\n                             <div class=\"p-3 bg-blue-50 rounded border\"><p class=\"text-[9px] font-bold uppercase\">Costos<\/p><p class=\"font-bold\" id=\"stat-cost\">$0<\/p><\/div>\n                             <div class=\"p-3 bg-slate-900 text-white rounded\"><p class=\"text-[9px] text-yellow-400 font-bold uppercase\">Utilidad<\/p><p class=\"font-bold\" id=\"stat-net\">$0<\/p><\/div>\n                        <\/div>\n                    <\/div>\n                <\/div>\n\n                <div id=\"view-activos\" class=\"hidden p-4 flex-1\">\n                    <div class=\"flex justify-between items-center mb-4\">\n                        <h3 class=\"font-bold text-sm\">Activos Fijos<\/h3>\n                        <button onclick=\"window.addAssetPrompt()\" class=\"bg-slate-800 text-white px-3 py-1 rounded text-[10px] font-bold\">A\u00d1ADIR<\/button>\n                    <\/div>\n                    <div id=\"assets-grid\" class=\"grid grid-cols-1 md:grid-cols-3 gap-3\"><\/div>\n                <\/div>\n            <\/div>\n        <\/div>\n    <\/div>\n\n    <!-- Modales (Aislados con z-index alto) -->\n    <div id=\"entryModal\" class=\"fixed inset-0 bg-slate-900\/90 hidden flex items-center justify-center z-[9999] p-4 backdrop-blur-sm\">\n        <div class=\"bg-white rounded-xl shadow-2xl w-full max-w-sm overflow-hidden\">\n            <div class=\"bg-slate-900 p-4 flex justify-between items-center text-white\">\n                <span class=\"font-bold uppercase text-xs\" id=\"modalTitle\">Nuevo Movimiento<\/span>\n                <button onclick=\"window.closeModal()\"><i class=\"fa-solid fa-times\"><\/i><\/button>\n            <\/div>\n            <form id=\"transactionForm\" class=\"p-5 space-y-4\">\n                <input type=\"hidden\" id=\"entryType\">\n                <div class=\"grid grid-cols-1 gap-3\">\n                    <input type=\"date\" id=\"entryDate\" required class=\"w-full border-b py-2 text-sm outline-none\">\n                    <input type=\"text\" id=\"entryProduct\" placeholder=\"Producto\" required class=\"w-full border-b py-2 text-sm outline-none\" list=\"productSuggestions\" oninput=\"window.checkCostSuggestion()\">\n                    <datalist id=\"productSuggestions\"><\/datalist>\n                    <input type=\"number\" step=\"0.01\" id=\"entryQty\" placeholder=\"Cantidad\" required class=\"w-full border-b py-2 text-sm outline-none\">\n                    <div id=\"costFieldGroup\"><input type=\"number\" step=\"0.01\" id=\"entryCost\" placeholder=\"Costo Unit.\" class=\"w-full border-b py-2 text-sm outline-none\"><\/div>\n                    <div id=\"priceFieldGroup\"><input type=\"number\" step=\"0.01\" id=\"entryPrice\" placeholder=\"Precio Venta\" class=\"w-full border-b py-2 text-sm outline-none\"><\/div>\n                <\/div>\n                <button type=\"submit\" class=\"w-full bg-slate-900 text-white py-3 rounded font-bold text-xs\">GUARDAR<\/button>\n            <\/form>\n        <\/div>\n    <\/div>\n\n    <div id=\"usdModal\" class=\"fixed inset-0 bg-slate-900\/90 hidden flex items-center justify-center z-[9999] p-4 backdrop-blur-sm\">\n        <div class=\"bg-white rounded-xl w-full max-w-xs p-5 space-y-4\">\n            <h3 class=\"font-bold text-center uppercase text-sm\">Canje USD<\/h3>\n            <div class=\"bg-emerald-50 p-2 rounded text-center text-emerald-600 font-bold\" id=\"modalUsdBalance\">0.00 USD<\/div>\n            <input type=\"number\" id=\"convertAmount\" class=\"w-full border p-2 rounded text-sm\" placeholder=\"Monto USD\">\n            <input type=\"number\" id=\"convertRate\" class=\"w-full border p-2 rounded text-sm\" placeholder=\"Tasa CUP\">\n            <div class=\"text-center font-bold text-lg\" id=\"previewConversion\">$0<\/div>\n            <div class=\"flex gap-2\">\n                <button onclick=\"document.getElementById('usdModal').classList.add('hidden')\" class=\"flex-1 bg-slate-200 p-2 rounded text-xs font-bold uppercase\">Cerrar<\/button>\n                <button onclick=\"window.processConversion()\" class=\"flex-1 bg-emerald-600 text-white p-2 rounded text-xs font-bold uppercase\">Vender<\/button>\n            <\/div>\n        <\/div>\n    <\/div>\n<\/div>\n\n<script>\n(function() {\n    \"use strict\";\n\n    \/\/ Datos maestros blindados\n    const MASTER_DATA = [\n        { id: 'cap1', date: '2025-12-01', type: 'capital', product: 'Inversi\u00f3n Inicial CUP', qty: 1, cost: 0, price: 105325 },\n        { id: 'cap2', date: '2025-12-01', type: 'capital', product: 'Venta 500 USD (Capital)', qty: 1, cost: 0, price: 220000 },\n        { id: 'inv1', date: '2025-12-20', type: 'compra', product: 'HELADO GOIBA', qty: 10, cost: 2300, price: 0 },\n        { id: 'inv2', date: '2025-12-20', type: 'compra', product: 'PASTA DE TOMATE', qty: 24, cost: 315, price: 0 },\n        { id: 'inv3', date: '2025-12-20', type: 'compra', product: 'QUESO GOUDA', qty: 12, cost: 2800, price: 0 },\n        { id: 'inv4', date: '2025-12-20', type: 'compra', product: 'CODITOS ADA', qty: 40, cost: 230, price: 0 },\n        { id: 'inv5', date: '2025-12-20', type: 'compra', product: 'LECHE 500G', qty: 30, cost: 800, price: 0 },\n        { id: 'inv6', date: '2025-12-25', type: 'compra', product: 'LECHE CONDENSADA', qty: 48, cost: 380, price: 0 },\n        { id: 'inv7', date: '2025-12-25', type: 'compra', product: 'SORBETO RAYAN', qty: 40, cost: 140, price: 0 },\n        { id: 'inv8', date: '2025-12-25', type: 'compra', product: 'GALLETAS MARIE', qty: 24, cost: 125, price: 0 },\n        { id: 'inv9', date: '2025-12-25', type: 'compra', product: 'ESPAGUETIS 500G', qty: 20, cost: 235, price: 0 },\n        { id: 'inv10', date: '2025-12-25', type: 'compra', product: 'GALLETAS TEA', qty: 10, cost: 170, price: 0 },\n        { id: 'inv11', date: '2025-12-27', type: 'compra', product: 'HELADOS NESTLE', qty: 4, cost: 5170, price: 0 },\n        { id: 'inv12', date: '2026-01-05', type: 'compra', product: 'AZUCAR 1KG', qty: 10, cost: 545, price: 0 },\n        { id: 'inv13', date: '2025-12-31', type: 'compra', product: 'CAKE', qty: 1, cost: 2000, price: 0 },\n        { id: 'v1', date: '2025-12-31', type: 'venta', product: 'QUESO GOUDA', qty: 5, cost: 2800, price: 3800 },\n        { id: 'v2', date: '2025-12-31', type: 'venta', product: 'PASTA DE TOMATE', qty: 2, cost: 315, price: 395 },\n        { id: 'v3', date: '2025-12-31', type: 'venta', product: 'LECHE 500G', qty: 12, cost: 800, price: 1050 },\n        { id: 'v4', date: '2025-12-31', type: 'venta', product: 'LECHE CONDENSADA', qty: 6, cost: 380, price: 500 },\n        { id: 'v5', date: '2025-12-31', type: 'venta', product: 'SORBETO RAYAN', qty: 24, cost: 140, price: 250 },\n        { id: 'v8', date: '2025-12-31', type: 'venta', product: 'AZUCAR 1KG', qty: 3, cost: 545, price: 600 },\n        { id: 'v9', date: '2025-12-31', type: 'venta', product: 'HELADOS NESTLE', qty: 4, cost: 5170, price: 5700 },\n        { id: 'v10', date: '2025-12-31', type: 'venta', product: 'CAKE', qty: 1, cost: 2000, price: 2500 },\n        { id: 'v88', date: '2026-01-01', type: 'venta', product: 'HELADO GOIBA', qty: 2, cost: 2300, price: 0 },\n        { id: 'v89', date: '2026-01-06', type: 'venta', product: 'HELADO GOIBA', qty: 7, cost: 2300, price: 2600 },\n        { id: 'v6_1', date: '2025-12-31', type: 'venta', product: 'GALLETAS MARIE', qty: 4, cost: 125, price: 175 },\n        { id: 'v6_2', date: '2026-01-04', type: 'venta', product: 'GALLETAS MARIE', qty: 3, cost: 125, price: 175 },\n        { id: 'v6_3', date: '2026-01-05', type: 'venta', product: 'GALLETAS MARIE', qty: 1, cost: 125, price: 125 },\n        { id: 'v6_4', date: '2026-01-10', type: 'venta', product: 'GALLETAS MARIE', qty: 8, cost: 125, price: 150 },\n        { id: 'v7_1', date: '2025-12-31', type: 'venta', product: 'GALLETAS TEA', qty: 4, cost: 170, price: 250 },\n        { id: 'v7_2', date: '2026-01-10', type: 'venta', product: 'GALLETAS TEA', qty: 4, cost: 170, price: 250 },\n        { id: 'vr_900', date: '2026-01-06', type: 'venta', product: 'Venta Adicional \/ Reyes', qty: 1, cost: 0, price: 3235 },\n        { id: 'adj1', date: '2026-01-24', type: 'retiro', product: 'Ajuste \/ Retiros \/ Diferencia', qty: 1, cost: 0, price: 171390 }\n    ];\n\n    \/\/ Carga inicial segura\n    let savedTrans = localStorage.getItem('fagales_trans');\n    window.transactions = (!savedTrans || JSON.parse(savedTrans).length === 0) ? MASTER_DATA : JSON.parse(savedTrans);\n    window.assets = JSON.parse(localStorage.getItem('fagales_assets')) || [{ id: 'a1', name: 'Nevera Exhibidora', value: 118000 }, { id: 'a2', name: 'Protector Voltaje', value: 3500 }];\n    window.usdBalance = parseFloat(localStorage.getItem('fagales_usd')) || 505;\n\n    window.formatMoney = function(amount) {\n        return new Intl.NumberFormat('es-US', { style: 'currency', currency: 'USD' }).format(amount).replace('USD', 'CUP');\n    };\n\n    window.saveData = function() {\n        localStorage.setItem('fagales_trans', JSON.stringify(window.transactions));\n        localStorage.setItem('fagales_assets', JSON.stringify(window.assets));\n        localStorage.setItem('fagales_usd', window.usdBalance);\n        window.refreshAll();\n    };\n\n    window.refreshAll = function() {\n        if(!document.getElementById('kpi-caja')) return; \/\/ Evitar error si el DOM no est\u00e1 listo\n        renderKPIs();\n        window.renderTable();\n        window.renderInventory();\n        window.renderAssets();\n        updateSuggestions();\n        document.getElementById('usd-reserve').innerText = window.usdBalance.toFixed(2);\n        document.getElementById('modalUsdBalance').innerText = window.usdBalance.toFixed(2) + \" USD\";\n    };\n\n    function renderKPIs() {\n        let caja = 0, ventasTotal = 0, costosVentaTotal = 0, gastosTotal = 0;\n        window.transactions.forEach(t => {\n            const total = t.qty * (['venta', 'capital', 'ingreso', 'aporte'].includes(t.type) ? t.price : t.cost);\n            if (['capital', 'ingreso', 'venta', 'aporte'].includes(t.type)) caja += total;\n            if (['compra', 'gasto', 'retiro'].includes(t.type)) caja -= total;\n            if (t.type === 'venta') { ventasTotal += total; costosVentaTotal += (t.qty * t.cost); }\n            if (t.type === 'gasto') gastosTotal += total;\n        });\n        const netProfit = ventasTotal - costosVentaTotal - gastosTotal;\n        const invData = calculateInventory();\n        let stockValue = Object.values(invData).reduce((s, i) => s + (i.stock * i.lastCost), 0);\n        let assetsValue = window.assets.reduce((s, a) => s + a.value, 0);\n\n        document.getElementById('kpi-caja').innerText = window.formatMoney(caja);\n        document.getElementById('kpi-inventario-valor').innerText = window.formatMoney(stockValue);\n        document.getElementById('kpi-ganancia').innerText = window.formatMoney(netProfit);\n        document.getElementById('kpi-patrimonio').innerText = window.formatMoney(caja + stockValue + assetsValue);\n        document.getElementById('inv-total-sum').innerText = window.formatMoney(stockValue);\n        \n        document.getElementById('dist-net-profit').innerText = window.formatMoney(Math.max(0, netProfit));\n        document.getElementById('share-partners').innerText = window.formatMoney(Math.max(0, netProfit) * 0.60);\n        document.getElementById('share-reserve').innerText = window.formatMoney(Math.max(0, netProfit) * 0.40);\n    }\n\n    function calculateInventory() {\n        const inv = {};\n        const sorted = [...window.transactions].sort((a,b) => new Date(a.date) - new Date(b.date));\n        sorted.forEach(t => {\n            if (['capital', 'gasto', 'retiro', 'aporte', 'ingreso'].includes(t.type)) return;\n            const name = t.product.trim().toUpperCase();\n            if (!inv[name]) inv[name] = { in: 0, out: 0, stock: 0, lastCost: 0 };\n            if (t.type === 'compra') { inv[name].in += t.qty; inv[name].lastCost = t.cost; }\n            else if (t.type === 'venta') { inv[name].out += t.qty; if(inv[name].lastCost === 0) inv[name].lastCost = t.cost; }\n            inv[name].stock = inv[name].in - inv[name].out;\n        });\n        return inv;\n    }\n\n    window.renderInventory = function() {\n        const inv = calculateInventory();\n        const tbody = document.getElementById('inventory-table-body');\n        if(!tbody) return;\n        tbody.innerHTML = '';\n        Object.keys(inv).sort().forEach(key => {\n            const item = inv[key];\n            if (item.in === 0 && item.stock === 0) return;\n            tbody.insertAdjacentHTML('beforeend', `\n                <tr class=\"border-b\">\n                    <td class=\"px-4 py-3 font-medium\">${key}<\/td>\n                    <td class=\"px-4 py-3 text-right text-slate-400\">${item.in}<\/td>\n                    <td class=\"px-4 py-3 text-right text-slate-400\">${item.out}<\/td>\n                    <td class=\"px-4 py-3 text-right font-bold bg-slate-50 ${item.stock <= 0 ? 'text-red-500' : ''}\">${item.stock}<\/td>\n                    <td class=\"px-4 py-3 text-right\">${window.formatMoney(item.lastCost)}<\/td>\n                    <td class=\"px-4 py-3 text-right font-bold text-blue-700\">${window.formatMoney(item.stock * item.lastCost)}<\/td>\n                <\/tr>`);\n        });\n    };\n\n    window.renderTable = function() {\n        const tbody = document.getElementById('transaction-table-body');\n        const searchInput = document.getElementById('searchTrans');\n        if(!tbody) return;\n        const search = searchInput ? searchInput.value.toUpperCase() : \"\";\n        tbody.innerHTML = '';\n        const sorted = [...window.transactions].sort((a,b) => new Date(b.date) - new Date(a.date) || b.id - a.id);\n        sorted.forEach(t => {\n            if(search && !t.product.toUpperCase().includes(search)) return;\n            let val = (['venta', 'capital', 'ingreso', 'aporte', 'retiro'].includes(t.type)) ? (t.qty * t.price) : (t.qty * t.cost);\n            let color = ['venta', 'ingreso', 'aporte', 'capital'].includes(t.type) ? 'text-emerald-600' : 'text-red-600';\n            if(t.type === 'compra') color = 'text-blue-600';\n            tbody.insertAdjacentHTML('beforeend', `\n                <tr class=\"border-b\">\n                    <td class=\"px-4 py-2 font-mono text-[10px]\">${t.date}<\/td>\n                    <td class=\"px-4 py-2\"><span class=\"font-bold uppercase text-[9px]\">${t.type}<\/span><\/td>\n                    <td class=\"px-4 py-2\">${t.product}<\/td>\n                    <td class=\"px-4 py-2 text-right font-bold ${color}\">${window.formatMoney(val)}<\/td>\n                    <td class=\"px-4 py-2 text-center\"><button onclick=\"window.deleteTrans('${t.id}')\" class=\"text-slate-300 hover:text-red-500\"><i class=\"fa-solid fa-trash-can\"><\/i><\/button><\/td>\n                <\/tr>`);\n        });\n    };\n\n    window.calculateStats = function() {\n        const start = document.getElementById('statsStart').value, end = document.getElementById('statsEnd').value;\n        if(!start || !end) return alert(\"Selecciona rango.\");\n        let sales = 0, costs = 0, expenses = 0;\n        const sDate = new Date(start), eDate = new Date(end);\n        window.transactions.forEach(t => {\n            const tDate = new Date(t.date);\n            if(tDate >= sDate && tDate <= eDate) {\n                if(t.type === 'venta') { sales += (t.qty * t.price); costs += (t.qty * t.cost); }\n                if(t.type === 'gasto') expenses += (t.qty * t.cost);\n            }\n        });\n        document.getElementById('stat-sales').innerText = window.formatMoney(sales);\n        document.getElementById('stat-expenses').innerText = window.formatMoney(expenses);\n        document.getElementById('stat-cost').innerText = window.formatMoney(costs);\n        document.getElementById('stat-net').innerText = window.formatMoney(sales - costs - expenses);\n        document.getElementById('statsResults').classList.remove('hidden');\n    };\n\n    function updateSuggestions() {\n        const list = document.getElementById('productSuggestions');\n        if(!list) return;\n        const products = [...new Set(window.transactions.filter(t => t.type === 'compra' || t.type === 'venta').map(t => t.product.toUpperCase()))];\n        list.innerHTML = products.map(p => `<option value=\"${p}\">`).join('');\n    }\n\n    window.checkCostSuggestion = function() {\n        const name = document.getElementById('entryProduct').value.trim().toUpperCase();\n        if(document.getElementById('entryType').value === 'venta') {\n            const inv = calculateInventory();\n            if(inv[name]) document.getElementById('entryCost').value = inv[name].lastCost;\n        }\n    };\n\n    window.openModal = function(type) {\n        document.getElementById('entryModal').classList.remove('hidden');\n        document.getElementById('entryType').value = type;\n        document.getElementById('entryDate').valueAsDate = new Date();\n        document.getElementById('modalTitle').innerText = \"Nuevo \" + type.toUpperCase();\n        const costG = document.getElementById('costFieldGroup'), priceG = document.getElementById('priceFieldGroup');\n        if(type === 'venta') { costG.classList.remove('hidden'); priceG.classList.remove('hidden'); }\n        else { priceG.classList.add('hidden'); costG.classList.remove('hidden'); }\n    };\n\n    window.closeModal = function() { document.getElementById('entryModal').classList.add('hidden'); };\n\n    document.getElementById('transactionForm').addEventListener('submit', function(e) {\n        e.preventDefault();\n        window.transactions.push({\n            id: Date.now().toString(),\n            date: document.getElementById('entryDate').value,\n            type: document.getElementById('entryType').value,\n            product: document.getElementById('entryProduct').value.trim().toUpperCase(),\n            qty: parseFloat(document.getElementById('entryQty').value) || 0,\n            cost: parseFloat(document.getElementById('entryCost').value) || 0,\n            price: parseFloat(document.getElementById('entryPrice').value) || 0\n        });\n        window.saveData(); window.closeModal(); e.target.reset();\n    });\n\n    window.deleteTrans = function(id) {\n        if(confirm(\"\u00bfEliminar?\")) { window.transactions = window.transactions.filter(t => t.id !== id); window.saveData(); }\n    };\n\n    window.reconcileCash = function() {\n        const current = parseFloat(document.getElementById('kpi-caja').innerText.replace(\/[^0-9.-]+\/g,\"\"));\n        const target = parseFloat(prompt(\"SALDO REAL EN CAJA (CUP):\", \"158510\"));\n        if(isNaN(target)) return;\n        const diff = target - current;\n        if(Math.abs(diff) < 1) return alert(\"Caja cuadrada.\");\n        if(confirm(\"Diferencia de \" + window.formatMoney(diff) + \". \u00bfAjustar?\")) {\n            window.transactions.push({ id: Date.now().toString(), date: new Date().toISOString().split('T')[0], type: diff > 0 ? 'aporte' : 'retiro', product: 'Ajuste de Arqueo', qty: 1, cost: 0, price: Math.abs(diff)});\n            window.saveData();\n        }\n    };\n\n    window.openUSDModal = function() { document.getElementById('usdModal').classList.remove('hidden'); };\n    \n    document.getElementById('convertAmount').oninput = updateConv;\n    document.getElementById('convertRate').oninput = updateConv;\n    function updateConv() {\n        const a = document.getElementById('convertAmount').value || 0, r = document.getElementById('convertRate').value || 0;\n        document.getElementById('previewConversion').innerText = window.formatMoney(a * r);\n    }\n\n    window.processConversion = function() {\n        const a = parseFloat(document.getElementById('convertAmount').value) || 0, r = parseFloat(document.getElementById('convertRate').value) || 0;\n        if(a > 0 && a <= window.usdBalance) {\n            window.usdBalance -= a;\n            window.transactions.push({ id: Date.now().toString(), date: new Date().toISOString().split('T')[0], type: 'ingreso', product: \"Canje \" + a + \" USD\", qty: 1, cost: 0, price: a*r });\n            window.saveData(); document.getElementById('usdModal').classList.add('hidden');\n        } else { alert(\"Saldo insuficiente.\"); }\n    }\n\n    window.switchTab = function(id) {\n        document.querySelectorAll('[id^=\"view-\"]').forEach(el => el.classList.add('hidden'));\n        document.getElementById('view-' + id).classList.remove('hidden');\n        document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));\n        document.getElementById('tab-' + id).classList.add('active');\n    };\n\n    window.registerDistribution = function() {\n        const p = parseFloat(document.getElementById('dist-net-profit').innerText.replace(\/[^0-9.-]+\/g,\"\"));\n        if(p <= 0) return alert(\"No hay ganancias.\");\n        const val = p * 0.60;\n        if(confirm(\"\u00bfRetirar \" + window.formatMoney(val) + \" para socios?\")) {\n            window.transactions.push({ id: Date.now().toString(), date: new Date().toISOString().split('T')[0], type: 'retiro', product: 'Pago Dividendos (60%)', qty: 1, cost: 0, price: val });\n            window.saveData();\n        }\n    };\n\n    window.addAssetPrompt = function() {\n        const n = prompt(\"Nombre:\"), v = parseFloat(prompt(\"Valor (CUP):\"));\n        if(n &#038;&#038; v) { window.assets.push({id: Date.now().toString(), name: n, value: v}); window.saveData(); }\n    };\n\n    window.renderAssets = function() {\n        const grid = document.getElementById('assets-grid');\n        if(!grid) return;\n        grid.innerHTML = window.assets.map(a => `<div class=\"bg-white p-3 rounded border flex justify-between shadow-sm\"><span class=\"font-bold text-xs\">${a.name}<\/span><span class=\"font-bold text-xs\">${window.formatMoney(a.value)}<\/span><\/div>`).join('');\n    };\n\n    window.exportData = function() {\n        const blob = new Blob([JSON.stringify({transactions: window.transactions, assets: window.assets, usdBalance: window.usdBalance})], {type: 'application\/json'});\n        const a = document.createElement('a');\n        a.href = URL.createObjectURL(blob); a.download = \"F360_Backup.json\"; a.click();\n    };\n\n    window.resetData = function() {\n        if(confirm(\"\u00bfRESET TOTAL? Se perder\u00e1n todos los datos actuales.\")) { localStorage.clear(); location.reload(); }\n    };\n\n    \/\/ Triple arranque de seguridad para WordPress\n    document.addEventListener('DOMContentLoaded', window.refreshAll);\n    setTimeout(window.refreshAll, 100);\n    setTimeout(window.refreshAll, 1000);\n\n})();\n<\/script>\n","protected":false},"excerpt":{"rendered":"<p>F360 Fagales360 Capital: $325,325 Reserva: 0.00 USD VENDER USD ARQUEO BACKUP RESET Caja F\u00edsica (CUP) $0.00 Stock Actual (Costo) $0.00 [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"class_list":["post-28","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/utiles.fagales360.com\/index.php?rest_route=\/wp\/v2\/pages\/28","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/utiles.fagales360.com\/index.php?rest_route=\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/utiles.fagales360.com\/index.php?rest_route=\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/utiles.fagales360.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/utiles.fagales360.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=28"}],"version-history":[{"count":45,"href":"https:\/\/utiles.fagales360.com\/index.php?rest_route=\/wp\/v2\/pages\/28\/revisions"}],"predecessor-version":[{"id":114,"href":"https:\/\/utiles.fagales360.com\/index.php?rest_route=\/wp\/v2\/pages\/28\/revisions\/114"}],"wp:attachment":[{"href":"https:\/\/utiles.fagales360.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=28"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}