Primer version funcional
This commit is contained in:
415
views/finance/concept_view.php
Executable file
415
views/finance/concept_view.php
Executable file
@@ -0,0 +1,415 @@
|
||||
<div class="row mb-4">
|
||||
<div class="col-12">
|
||||
<a href="/dashboard.php?page=finanzas" class="btn btn-outline-secondary mb-2">
|
||||
<i class="bi bi-arrow-left"></i> Volver a Finanzas
|
||||
</a>
|
||||
<h2><i class="bi bi-collection"></i> <?= htmlspecialchars($concept['name']) ?></h2>
|
||||
<p class="text-muted"><?= htmlspecialchars($concept['description'] ?? '') ?></p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row g-4 mb-4">
|
||||
<div class="col-md-3">
|
||||
<div class="card border-primary">
|
||||
<div class="card-body text-center">
|
||||
<h6 class="text-muted">Monto por Casa</h6>
|
||||
<h4 class="text-primary">$<?= number_format($concept['amount_per_house'], 2) ?></h4>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<div class="card border-success">
|
||||
<div class="card-body text-center">
|
||||
<h6 class="text-muted">Recaudado</h6>
|
||||
<h4 class="text-success">$<?= number_format($status['total_collected'], 2) ?></h4>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<div class="card border-danger">
|
||||
<div class="card-body text-center">
|
||||
<h6 class="text-muted">Gastado</h6>
|
||||
<h4 class="text-danger">$<?= number_format($status['total_expenses'], 2) ?></h4>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<div class="card <?= $status['balance'] >= 0 ? 'border-success' : 'border-danger' ?>">
|
||||
<div class="card-body text-center">
|
||||
<h6 class="text-muted">Balance Neto</h6>
|
||||
<h4 class="<?= $status['balance'] >= 0 ? 'text-success' : 'text-danger' ?>">$<?= number_format($status['balance'], 2) ?></h4>
|
||||
<small class="text-muted">(Recaudado - Gastado)</small>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h5 class="card-title mb-0">Pagos por Casa</h5>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<?php if (empty($payments)): ?>
|
||||
<div class="alert alert-info text-center">
|
||||
<i class="bi bi-info-circle"></i>
|
||||
No hay pagos inicializados para este concepto.
|
||||
<br><br>
|
||||
<?php if (Auth::isCapturist()): ?>
|
||||
<button id="init-payments-btn" class="btn btn-primary">
|
||||
<i class="bi bi-plus-circle"></i> Inicializar Pagos
|
||||
</button>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<?php else: ?>
|
||||
<?php if (Auth::isCapturist()): ?>
|
||||
<div class="alert alert-warning text-center mb-3">
|
||||
<i class="bi bi-arrow-clockwise"></i>
|
||||
<button id="reinit-payments-btn" class="btn btn-warning me-2">
|
||||
<i class="bi bi-arrow-clockwise"></i> Reinicializar Pagos
|
||||
</button>
|
||||
<small>Esto actualizará todos los pagos a $0.00</small>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
<div class="table-responsive">
|
||||
<table class="table table-sm table-hover">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Casa</th>
|
||||
<th>Propietario</th>
|
||||
<th>Monto</th>
|
||||
<th>Fecha de Pago</th>
|
||||
<?php if (Auth::isCapturist()): ?>
|
||||
<th>Acciones</th>
|
||||
<?php endif; ?>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php foreach ($payments as $payment):
|
||||
$cellClass = $payment['amount'] > 0 ? 'paid' : 'pending';
|
||||
?>
|
||||
<tr data-payment-id="<?= $payment['id'] ?>" data-house-id="<?= $payment['house_id'] ?>">
|
||||
<td><strong><?= $payment['house_number'] ?></strong></td>
|
||||
<td><?= htmlspecialchars($payment['owner_name'] ?? '-') ?></td>
|
||||
<td class="payment-cell <?= $cellClass ?>"
|
||||
data-amount="<?= $payment['amount'] ?>"
|
||||
data-payment-date="<?= $payment['payment_date'] ?: '' ?>"
|
||||
<?= Auth::isCapturist() ? 'contenteditable="true"' : '' ?>>
|
||||
<?= $payment['amount'] > 0 ? '$' . number_format($payment['amount'], 2) : '-' ?>
|
||||
</td>
|
||||
<td>
|
||||
<?php if (Auth::isCapturist()): ?>
|
||||
<input type="date" class="form-control form-control-sm payment-date-input"
|
||||
value="<?= $payment['payment_date'] ? date('Y-m-d', strtotime($payment['payment_date'])) : '' ?>">
|
||||
<?php else: ?>
|
||||
<?= $payment['payment_date'] ? date('d/m/Y', strtotime($payment['payment_date'])) : '-' ?>
|
||||
<?php endif; ?>
|
||||
</td>
|
||||
<?php if (Auth::isCapturist()): ?>
|
||||
<td>
|
||||
<button class="btn btn-sm btn-primary" onclick="saveConceptPayment(this)">
|
||||
<i class="bi bi-check"></i>
|
||||
</button>
|
||||
</td>
|
||||
<?php endif; ?>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php
|
||||
require_once __DIR__ . '/../../models/Expense.php';
|
||||
$db = Database::getInstance();
|
||||
$conceptExpenses = $db->fetchAll(
|
||||
"SELECT e.*, ec.amount as allocated_amount
|
||||
FROM expense_concept_allocations ec
|
||||
JOIN expenses e ON ec.expense_id = e.id
|
||||
WHERE ec.concept_id = ?
|
||||
ORDER BY e.expense_date DESC",
|
||||
[$concept['id']]
|
||||
);
|
||||
?>
|
||||
|
||||
<div class="card mt-4">
|
||||
<div class="card-header">
|
||||
<h5 class="card-title mb-0">Gastos Asociados</h5>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<?php if (!empty($conceptExpenses)): ?>
|
||||
<div class="table-responsive">
|
||||
<table class="table table-sm">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Fecha</th>
|
||||
<th>Descripción</th>
|
||||
<th>Categoría</th>
|
||||
<th>Asignado</th>
|
||||
<th>Total Gasto</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php foreach ($conceptExpenses as $exp): ?>
|
||||
<tr>
|
||||
<td><?= date('d/m/Y', strtotime($exp['expense_date'])) ?></td>
|
||||
<td><?= htmlspecialchars($exp['description']) ?></td>
|
||||
<td><?= htmlspecialchars($exp['category'] ?? '-') ?></td>
|
||||
<td class="text-end text-info">$<?= number_format($exp['allocated_amount'], 2) ?></td>
|
||||
<td class="text-end">$<?= number_format($exp['amount'], 2) ?></td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr class="table-secondary">
|
||||
<th colspan="3" class="text-end">Total:</th>
|
||||
<th class="text-end text-danger">$<?= number_format($status['total_expenses'], 2) ?></th>
|
||||
<th>-</th>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
<?php else: ?>
|
||||
<p class="text-muted mb-0">No hay gastos asociados a este concepto.</p>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const conceptId = '<?= $concept["id"] ?>';
|
||||
|
||||
window.initializeConceptPayments = function() {
|
||||
console.log('=== Inicializando pagos ===');
|
||||
console.log('Concept ID:', conceptId);
|
||||
|
||||
if (typeof Swal === 'undefined') {
|
||||
alert('Error: SweetAlert no está cargado');
|
||||
return;
|
||||
}
|
||||
|
||||
Swal.fire({
|
||||
title: '¿Inicializar pagos?',
|
||||
text: 'Esto creará registros de pago para todas las casas activas con monto $0.00. ¿Continuar?',
|
||||
icon: 'question',
|
||||
showCancelButton: true,
|
||||
confirmButtonText: 'Sí, inicializar',
|
||||
confirmButtonColor: '#3085d6',
|
||||
cancelButtonText: 'Cancelar'
|
||||
}).then(function(result) {
|
||||
console.log('=== Resultado del sweetalert ===', result);
|
||||
|
||||
if (result.isConfirmed) {
|
||||
console.log('=== Iniciando fetch ===');
|
||||
var url = '/dashboard.php?page=concept_view_actions&action=initialize_concept_payments&concept_id=' + conceptId;
|
||||
console.log('URL:', url);
|
||||
|
||||
fetch(url, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
})
|
||||
.then(function(response) {
|
||||
console.log('=== Respuesta del servidor ===', response);
|
||||
console.log('Status:', response.status);
|
||||
console.log('OK:', response.ok);
|
||||
|
||||
if (!response.ok) {
|
||||
return response.text().then(function(text) {
|
||||
console.log('Error response text:', text);
|
||||
throw new Error('HTTP ' + response.status + ': ' + text);
|
||||
});
|
||||
}
|
||||
|
||||
return response.text().then(function(text) {
|
||||
console.log('Response text:', text);
|
||||
try {
|
||||
return JSON.parse(text);
|
||||
} catch (e) {
|
||||
console.error('JSON parse error:', e);
|
||||
console.error('Response text:', text);
|
||||
throw new Error('Error al parsear JSON: ' + e.message);
|
||||
}
|
||||
});
|
||||
})
|
||||
.then(function(data) {
|
||||
console.log('=== Datos recibidos ===', data);
|
||||
|
||||
if (data.success) {
|
||||
Swal.fire('Éxito', data.message, 'success').then(function() {
|
||||
console.log('Recargando página...');
|
||||
location.reload();
|
||||
});
|
||||
} else {
|
||||
Swal.fire('Error', data.message || 'Error desconocido', 'error');
|
||||
}
|
||||
})
|
||||
.catch(function(error) {
|
||||
console.error('=== Error en fetch ===', error);
|
||||
console.error('Error message:', error.message);
|
||||
Swal.fire('Error', 'Ocurrió un error: ' + error.message, 'error');
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
<?php if (Auth::isCapturist()): ?>
|
||||
document.querySelectorAll('.payment-cell[contenteditable="true"]').forEach(function(cell) {
|
||||
let originalValue = '';
|
||||
|
||||
cell.addEventListener('focus', function() {
|
||||
originalValue = this.textContent.trim();
|
||||
this.classList.add('editing');
|
||||
|
||||
const currentValue = this.textContent.trim();
|
||||
|
||||
if (currentValue === '-' || currentValue === '') {
|
||||
this.textContent = '';
|
||||
} else if (currentValue.includes('$')) {
|
||||
this.textContent = currentValue.replace(/[^0-9.]/g, '');
|
||||
} else {
|
||||
this.textContent = currentValue;
|
||||
}
|
||||
|
||||
setTimeout(() => {
|
||||
const selection = window.getSelection();
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(this);
|
||||
selection.removeAllRanges();
|
||||
selection.addRange(range);
|
||||
}, 0);
|
||||
});
|
||||
|
||||
cell.addEventListener('blur', function() {
|
||||
this.classList.remove('editing');
|
||||
const newValue = this.textContent.trim();
|
||||
|
||||
if (newValue === '') {
|
||||
this.textContent = originalValue;
|
||||
} else {
|
||||
let value = parseFloat(newValue.replace(/[^0-9.-]+/g, '')) || 0;
|
||||
|
||||
if (value < 0 || isNaN(value)) {
|
||||
this.textContent = originalValue;
|
||||
} else if (value === 0) {
|
||||
this.textContent = '$0.00';
|
||||
} else {
|
||||
this.textContent = '$' + value.toFixed(2);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
cell.addEventListener('keydown', function(e) {
|
||||
if (!((e.key >= '0' && e.key <= '9') ||
|
||||
e.key === '.' ||
|
||||
e.key === 'Backspace' ||
|
||||
e.key === 'Delete' ||
|
||||
e.key === 'Tab' ||
|
||||
e.key === 'Enter' ||
|
||||
e.key === 'ArrowLeft' ||
|
||||
e.key === 'ArrowRight')) {
|
||||
e.preventDefault();
|
||||
}
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
const btn = this.parentElement.querySelector('.btn-primary');
|
||||
if (btn) {
|
||||
btn.click();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
cell.addEventListener('blur', function() {
|
||||
this.classList.remove('editing');
|
||||
const newValue = this.textContent.trim();
|
||||
|
||||
if (newValue === '') {
|
||||
// If cell is empty on blur, restore the original value (cancel edit)
|
||||
this.textContent = originalValue;
|
||||
} else {
|
||||
let value = parseFloat(newValue.replace(/[^0-g.-]+/g, '')) || 0;
|
||||
if (value <= 0) {
|
||||
this.textContent = '-';
|
||||
} else {
|
||||
this.textContent = '$' + value.toFixed(2);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
cell.addEventListener('keydown', function(e) {
|
||||
if (!((e.key >= '0' && e.key <= '9') ||
|
||||
e.key === '.' ||
|
||||
e.key === 'Backspace' ||
|
||||
e.key === 'Delete' ||
|
||||
e.key === 'Tab' ||
|
||||
e.key === 'Enter' ||
|
||||
e.key === 'ArrowLeft' ||
|
||||
e.key === 'ArrowRight')) {
|
||||
e.preventDefault();
|
||||
}
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
this.blur();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
window.saveConceptPayment = function(btn) {
|
||||
const row = btn.closest('tr');
|
||||
const cell = row.querySelector('.payment-cell');
|
||||
const dateInput = row.querySelector('.payment-date-input');
|
||||
const houseId = row.dataset.houseId;
|
||||
const value = cell.textContent.trim();
|
||||
const amount = parseFloat(value.replace(/[^0-9.-]+/g, '')) || 0;
|
||||
const paymentDate = dateInput ? dateInput.value : null;
|
||||
|
||||
console.log('=== Guardando pago ===');
|
||||
console.log('House ID:', houseId);
|
||||
console.log('Amount:', amount);
|
||||
console.log('Payment Date:', paymentDate);
|
||||
|
||||
cell.innerHTML = '<span class="spinner-border spinner-border-sm"></span>';
|
||||
|
||||
fetch('/dashboard.php?page=concept_view_actions&action=save_concept_payment', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
concept_id: '<?= $concept["id"] ?>',
|
||||
house_id: houseId,
|
||||
amount: amount,
|
||||
payment_date: paymentDate
|
||||
})
|
||||
})
|
||||
.then(function(r) {
|
||||
console.log('Response status:', r.status);
|
||||
return r.json();
|
||||
})
|
||||
.then(function(data) {
|
||||
console.log('Save payment data:', data);
|
||||
if (data.success) {
|
||||
location.reload();
|
||||
} else {
|
||||
Swal.fire('Error', data.message, 'error');
|
||||
}
|
||||
})
|
||||
.catch(function(error) {
|
||||
console.error('Save payment error:', error);
|
||||
Swal.fire('Error', 'Ocurrió un error: ' + error.message, 'error');
|
||||
});
|
||||
};
|
||||
|
||||
// Attach event listener to button
|
||||
const initButton = document.getElementById('init-payments-btn');
|
||||
if (initButton) {
|
||||
initButton.addEventListener('click', window.initializeConceptPayments);
|
||||
}
|
||||
|
||||
// Attach event listener to reinitialize button
|
||||
const reinitButton = document.getElementById('reinit-payments-btn');
|
||||
if (reinitButton) {
|
||||
reinitButton.addEventListener('click', window.initializeConceptPayments);
|
||||
}
|
||||
<?php endif; ?>
|
||||
</script>
|
||||
258
views/finance/concept_view.php.backup
Executable file
258
views/finance/concept_view.php.backup
Executable file
@@ -0,0 +1,258 @@
|
||||
<div class="row mb-4">
|
||||
<div class="col-12">
|
||||
<a href="/dashboard.php?page=finanzas" class="btn btn-outline-secondary mb-2">
|
||||
<i class="bi bi-arrow-left"></i> Volver a Finanzas
|
||||
</a>
|
||||
<h2><i class="bi bi-collection"></i> <?= htmlspecialchars($concept['name']) ?></h2>
|
||||
<p class="text-muted"><?= htmlspecialchars($concept['description'] ?? '') ?></p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row g-4 mb-4">
|
||||
<div class="col-md-3">
|
||||
<div class="card border-primary">
|
||||
<div class="card-body text-center">
|
||||
<h6 class="text-muted">Monto por Casa</h6>
|
||||
<h4 class="text-primary">$<?= number_format($concept['amount_per_house'], 2) ?></h4>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<div class="card border-success">
|
||||
<div class="card-body text-center">
|
||||
<h6 class="text-muted">Recaudado</h6>
|
||||
<h4 class="text-success">$<?= number_format($status['total_collected'], 2) ?></h4>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<div class="card border-danger">
|
||||
<div class="card-body text-center">
|
||||
<h6 class="text-muted">Gastado</h6>
|
||||
<h4 class="text-danger">$<?= number_format($status['total_expenses'], 2) ?></h4>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<div class="card <?= $status['balance'] >= 0 ? 'border-success' : 'border-danger' ?>">
|
||||
<div class="card-body text-center">
|
||||
<h6 class="text-muted">Balance Neto</h6>
|
||||
<h4 class="<?= $status['balance'] >= 0 ? 'text-success' : 'text-danger' ?>">$<?= number_format($status['balance'], 2) ?></h4>
|
||||
<small class="text-muted">(Recaudado - Gastado)</small>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h5 class="card-title mb-0">Pagos por Casa</h5>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<?php if (empty($payments)): ?>
|
||||
<div class="alert alert-info text-center">
|
||||
<i class="bi bi-info-circle"></i>
|
||||
No hay pagos inicializados para este concepto.
|
||||
<br><br>
|
||||
<?php if (Auth::isCapturist()): ?>
|
||||
<button class="btn btn-primary" onclick="initializeConceptPayments()">
|
||||
<i class="bi bi-plus-circle"></i> Inicializar Pagos
|
||||
</button>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<?php else: ?>
|
||||
<div class="table-responsive">
|
||||
<table class="table table-sm table-hover">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Casa</th>
|
||||
<th>Propietario</th>
|
||||
<th>Monto</th>
|
||||
<th>Fecha de Pago</th>
|
||||
<?php if (Auth::isCapturist()): ?>
|
||||
<th>Acciones</th>
|
||||
<?php endif; ?>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php foreach ($payments as $payment):
|
||||
$cellClass = $payment['amount'] > 0 ? 'paid' : 'pending';
|
||||
?>
|
||||
<tr data-payment-id="<?= $payment['id'] ?>" data-house-id="<?= $payment['house_id'] ?>">
|
||||
<td><strong><?= $payment['house_number'] ?></strong></td>
|
||||
<td><?= htmlspecialchars($payment['owner_name'] ?? '-') ?></td>
|
||||
<td class="payment-cell <?= $cellClass ?>"
|
||||
data-amount="<?= $payment['amount'] ?>"
|
||||
<?= Auth::isCapturist() ? 'contenteditable="true"' : '' ?>>
|
||||
<?= $payment['amount'] > 0 ? '$' . number_format($payment['amount'], 2) : '-' ?>
|
||||
</td>
|
||||
<td><?= $payment['payment_date'] ? date('d/m/Y', strtotime($payment['payment_date'])) : '-' ?></td>
|
||||
<?php if (Auth::isCapturist()): ?>
|
||||
<td>
|
||||
<button class="btn btn-sm btn-primary" onclick="saveConceptPayment(this)">
|
||||
<i class="bi bi-check"></i>
|
||||
</button>
|
||||
</td>
|
||||
<?php endif; ?>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php
|
||||
require_once __DIR__ . '/../../models/Expense.php';
|
||||
$conceptExpenses = $db->fetchAll(
|
||||
"SELECT e.*, ec.amount as allocated_amount
|
||||
FROM expense_concept_collections ec
|
||||
JOIN expenses e ON ec.expense_id = e.id
|
||||
WHERE ec.concept_id = ?
|
||||
ORDER BY e.expense_date DESC",
|
||||
[$concept['id']]
|
||||
);
|
||||
?>
|
||||
|
||||
<div class="card mt-4">
|
||||
<div class="card-header">
|
||||
<h5 class="card-title mb-0">Gastos Asociados</h5>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<?php if (!empty($conceptExpenses)): ?>
|
||||
<div class="table-responsive">
|
||||
<table class="table table-sm">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Fecha</th>
|
||||
<th>Descripción</th>
|
||||
<th>Categoría</th>
|
||||
<th>Asignado</th>
|
||||
<th>Total Gasto</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php foreach ($conceptExpenses as $exp): ?>
|
||||
<tr>
|
||||
<td><?= date('d/m/Y', strtotime($exp['expense_date'])) ?></td>
|
||||
<td><?= htmlspecialchars($exp['description']) ?></td>
|
||||
<td><?= htmlspecialchars($exp['category'] ?? '-') ?></td>
|
||||
<td class="text-end text-info">$<?= number_format($exp['allocated_amount'], 2) ?></td>
|
||||
<td class="text-end">$<?= number_format($exp['amount'], 2) ?></td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr class="table-secondary">
|
||||
<th colspan="3" class="text-end">Total:</th>
|
||||
<th class="text-end text-danger">$<?= number_format($status['total_expenses'], 2) ?></th>
|
||||
<th>-</th>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
<?php else: ?>
|
||||
<p class="text-muted mb-0">No hay gastos asociados a este concepto.</p>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const conceptId = '<?= $concept['id'] ?>';
|
||||
|
||||
function initializeConceptPayments() {
|
||||
console.log('Inicializando pagos...');
|
||||
console.log('Concept ID:', conceptId);
|
||||
|
||||
if (typeof Swal === 'undefined') {
|
||||
alert('Error: SweetAlert no está cargado');
|
||||
return;
|
||||
}
|
||||
|
||||
Swal.fire({
|
||||
title: '¿Inicializar pagos?',
|
||||
text: 'Esto creará registros de pago para todas las casas activas con monto $0.00. ¿Continuar?',
|
||||
icon: 'question',
|
||||
showCancelButton: true,
|
||||
confirmButtonText: 'Sí, inicializar',
|
||||
confirmButtonColor: '#3085d6',
|
||||
cancelButtonText: 'Cancelar'
|
||||
}).then(function(result) {
|
||||
console.log('Resultado del sweetalert:', result);
|
||||
|
||||
if (result.isConfirmed) {
|
||||
console.log('Iniciando fetch...');
|
||||
console.log('URL:', '/api/initialize_concept_payments.php?concept_id=' + conceptId);
|
||||
|
||||
fetch('/api/initialize_concept_payments.php?concept_id=' + conceptId)
|
||||
.then(function(r) {
|
||||
console.log('Respuesta del servidor:', r);
|
||||
return r.json();
|
||||
})
|
||||
.then(function(data) {
|
||||
console.log('Datos recibidos:', data);
|
||||
if (data.success) {
|
||||
Swal.fire('Éxito', data.message, 'success').then(function() {
|
||||
location.reload();
|
||||
});
|
||||
} else {
|
||||
Swal.fire('Error', data.message, 'error');
|
||||
}
|
||||
})
|
||||
.catch(function(error) {
|
||||
console.error('Error:', error);
|
||||
Swal.fire('Error', 'Ocurrió un error: ' + error.message, 'error');
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
<?php if (Auth::isCapturist()): ?>
|
||||
document.querySelectorAll('.payment-cell[contenteditable="true"]').forEach(function(cell) {
|
||||
cell.addEventListener('focus', function() {
|
||||
this.classList.add('editing');
|
||||
});
|
||||
|
||||
cell.addEventListener('blur', function() {
|
||||
this.classList.remove('editing');
|
||||
});
|
||||
|
||||
cell.addEventListener('keydown', function(e) {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
function saveConceptPayment(btn) {
|
||||
const row = btn.closest('tr');
|
||||
const cell = row.querySelector('.payment-cell');
|
||||
const houseId = row.dataset.houseId;
|
||||
const value = cell.textContent.trim();
|
||||
const amount = parseFloat(value.replace(/[^0-9.-]+/g, '')) || 0;
|
||||
|
||||
cell.innerHTML = '<span class="spinner-border spinner-border-sm"></span>';
|
||||
|
||||
fetch('/api/save_concept_payment.php', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
concept_id: '<?= $concept['id'] ?>',
|
||||
house_id: houseId,
|
||||
amount: amount
|
||||
})
|
||||
})
|
||||
.then(function(r) {
|
||||
return r.json();
|
||||
})
|
||||
.then(function(data) {
|
||||
if (data.success) {
|
||||
location.reload();
|
||||
} else {
|
||||
Swal.fire('Error', data.message, 'error');
|
||||
}
|
||||
});
|
||||
}
|
||||
<?php endif; ?>
|
||||
</script>
|
||||
560
views/finance/index.php
Executable file
560
views/finance/index.php
Executable file
@@ -0,0 +1,560 @@
|
||||
<div class="row mb-4">
|
||||
<div class="col-12">
|
||||
<h2><i class="bi bi-cash-coin"></i> Finanzas</h2>
|
||||
<p class="text-muted">Gestión de gastos y conceptos especiales</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ul class="nav nav-tabs mb-4" id="financeTabs">
|
||||
<li class="nav-item">
|
||||
<button class="nav-link active" data-bs-toggle="tab" data-bs-target="#concepts">
|
||||
<i class="bi bi-collection"></i> Conceptos Especiales
|
||||
</button>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<button class="nav-link" data-bs-toggle="tab" data-bs-target="#expenses">
|
||||
<i class="bi bi-receipt"></i> Gastos
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<div class="tab-content">
|
||||
<div class="tab-pane fade show active" id="concepts">
|
||||
<div class="card">
|
||||
<div class="card-header d-flex justify-content-between align-items-center">
|
||||
<h5 class="card-title mb-0">Conceptos Especiales</h5>
|
||||
<?php if (Auth::isCapturist()): ?>
|
||||
<button id="newConceptBtn" class="btn btn-primary btn-sm">
|
||||
<i class="bi bi-plus"></i> Nuevo Concepto
|
||||
</button>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="row">
|
||||
<?php foreach ($concepts as $concept):
|
||||
$status = CollectionConcept::getCollectionStatus($concept['id']);
|
||||
?>
|
||||
<div class="col-md-6 mb-3">
|
||||
<div class="card">
|
||||
<div class="card-body">
|
||||
<h6 class="card-title">[ID: <?= $concept['id'] ?>] <?= htmlspecialchars($concept['name']) ?></h6>
|
||||
<p class="card-text small text-muted"><?= htmlspecialchars($concept['description'] ?? '') ?></p>
|
||||
<div class="mb-2">
|
||||
<small>Monto Total:</small> <strong>$<?= number_format($concept['total_amount'], 2) ?></strong>
|
||||
</div>
|
||||
<div class="mb-2">
|
||||
<small>Monto por casa:</small> <strong>$<?= number_format($concept['amount_per_house'], 2) ?></strong>
|
||||
</div>
|
||||
<div class="progress mb-2" style="height: 20px;">
|
||||
<div class="progress-bar bg-success" style="width: <?= $status['percentage'] ?>%">
|
||||
<?= $status['percentage'] ?>%
|
||||
</div>
|
||||
</div>
|
||||
<div class="mb-2">
|
||||
<small class="text-muted">Recaudado:</small> <strong>$<?= number_format($status['total_collected'], 2) ?></strong>
|
||||
</div>
|
||||
<div class="mb-2">
|
||||
<small class="text-muted">Gastado:</small> <strong class="text-danger">$<?= number_format($status['total_expenses'], 2) ?></strong>
|
||||
</div>
|
||||
<div class="mb-2">
|
||||
<small class="text-muted">Balance Neto:</small> <strong class="<?= $status['balance'] >= 0 ? 'text-success' : 'text-danger' ?>">$<?= number_format($status['balance'], 2) ?></strong>
|
||||
</div>
|
||||
<div class="mt-2">
|
||||
<a href="/dashboard.php?page=concept_view&id=<?= $concept['id'] ?>" class="btn btn-sm btn-outline-primary">
|
||||
Ver Detalles
|
||||
</a>
|
||||
<?php if (Auth::isCapturist()): ?>
|
||||
<button class="btn btn-sm btn-outline-secondary btn-edit-concept" data-concept-id="<?= $concept['id'] ?>">
|
||||
<i class="bi bi-pencil"></i> Editar
|
||||
</button>
|
||||
<?php endif; ?>
|
||||
<?php if (Auth::isAdmin()): ?>
|
||||
<button class="btn btn-sm btn-outline-danger btn-delete-concept" data-concept-id="<?= $concept['id'] ?>">
|
||||
<i class="bi bi-trash"></i> Eliminar
|
||||
</button>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="tab-pane fade" id="expenses">
|
||||
<div class="card">
|
||||
<div class="card-header d-flex justify-content-between align-items-center">
|
||||
<h5 class="card-title mb-0">Gastos Registrados</h5>
|
||||
<?php if (Auth::isCapturist()): ?>
|
||||
<button id="newExpenseBtn" class="btn btn-primary btn-sm">
|
||||
<i class="bi bi-plus"></i> Nuevo Gasto
|
||||
</button>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="table-responsive">
|
||||
<table class="table table-sm">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Fecha</th>
|
||||
<th>Descripción</th>
|
||||
<th>Conceptos</th>
|
||||
<th>Categoría</th>
|
||||
<th>Comprobante</th>
|
||||
<th>Monto</th>
|
||||
<th>Acciones</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php foreach ($expenses as $expense):
|
||||
$expenseConcepts = Expense::getConcepts($expense['id']);
|
||||
?>
|
||||
<tr>
|
||||
<td><?= date('d/m/Y', strtotime($expense['expense_date'])) ?></td>
|
||||
<td><?= htmlspecialchars($expense['description']) ?></td>
|
||||
<td>
|
||||
<?php if (!empty($expenseConcepts)): ?>
|
||||
<div>
|
||||
<?php foreach ($expenseConcepts as $ec): ?>
|
||||
<span class="badge bg-info" title="Monto: $<?= number_format($ec['amount'], 2) ?>">
|
||||
<?= htmlspecialchars($ec['concept_name']) ?>
|
||||
</span>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
<?php else: ?>
|
||||
<span class="text-muted">Sin concepto</span>
|
||||
<?php endif; ?>
|
||||
</td>
|
||||
<td><?= htmlspecialchars($expense['category'] ?? '-') ?></td>
|
||||
<td>
|
||||
<?php if (!empty($expense['receipt_path'])): ?>
|
||||
<a href="<?= htmlspecialchars($expense['receipt_path']) ?>" target="_blank" class="btn btn-sm btn-outline-info">
|
||||
<i class="bi bi-eye"></i> Ver
|
||||
</a>
|
||||
<?php else: ?>
|
||||
<span class="text-muted">-</span>
|
||||
<?php endif; ?>
|
||||
</td>
|
||||
<td class="text-end">$<?= number_format($expense['amount'], 2) ?></td>
|
||||
<td>
|
||||
<?php if (Auth::isCapturist()): ?>
|
||||
<button class="btn btn-sm btn-outline-primary btn-edit-expense" data-expense-id="<?= $expense['id'] ?>">
|
||||
<i class="bi bi-pencil"></i> Editar
|
||||
</button>
|
||||
<?php endif; ?>
|
||||
<?php if (Auth::isAdmin()): ?>
|
||||
<button class="btn btn-sm btn-danger btn-delete-expense" data-expense-id="<?= $expense['id'] ?>">
|
||||
<i class="bi bi-trash"></i>
|
||||
</button>
|
||||
<?php endif; ?>
|
||||
</td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php if (Auth::isCapturist()): ?>
|
||||
<div class="modal fade" id="conceptModal" tabindex="-1">
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="conceptModalTitle">Nuevo Concepto Especial</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
|
||||
</div>
|
||||
<form id="conceptForm">
|
||||
<div class="modal-body">
|
||||
<input type="hidden" name="id" id="conceptIdInput">
|
||||
<div class="mb-3">
|
||||
<label class="form-label">Nombre del Concepto</label>
|
||||
<input type="text" class="form-control" name="name" required>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label">Descripción</label>
|
||||
<textarea class="form-control" name="description" rows="2"></textarea>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label">Monto Total a Recaudar ($)</label>
|
||||
<input type="number" step="0.01" class="form-control" name="total_amount" id="totalAmountInput" placeholder="Ej: 20000.00">
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label">Monto por Casa ($)</label>
|
||||
<input type="number" step="0.01" class="form-control" name="amount_per_house" id="perHouseAmountInput" placeholder="Ej: 200.00">
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="col-md-6 mb-3">
|
||||
<label class="form-label">Fecha del Concepto</label>
|
||||
<input type="date" class="form-control" name="concept_date" required>
|
||||
</div>
|
||||
<div class="col-md-6 mb-3">
|
||||
<label class="form-label">Fecha de Vencimiento (opcional)</label>
|
||||
<input type="date" class="form-control" name="due_date">
|
||||
</div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label">Categoría</label>
|
||||
<input type="text" class="form-control" name="category" placeholder="Ej: Mantenimiento, Mejora">
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
|
||||
<button type="submit" class="btn btn-primary" id="conceptFormSubmitBtn">Guardar</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="modal fade" id="expenseModal" tabindex="-1">
|
||||
<div class="modal-dialog modal-lg">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="expenseModalTitle">Registrar Gasto</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
|
||||
</div>
|
||||
<form id="expenseForm">
|
||||
<input type="hidden" name="id" id="expenseIdInput">
|
||||
<div class="modal-body">
|
||||
<div class="mb-3">
|
||||
<label class="form-label">Descripción</label>
|
||||
<input type="text" class="form-control" name="description" required>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="col-md-6 mb-3">
|
||||
<label class="form-label">Monto del Gasto</label>
|
||||
<input type="number" step="0.01" class="form-control" name="amount" required>
|
||||
</div>
|
||||
<div class="col-md-6 mb-3">
|
||||
<label class="form-label">Fecha</label>
|
||||
<input type="date" class="form-control" name="expense_date" required>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label">Comprobante (Imagen o PDF)</label>
|
||||
<input type="file" class="form-control" name="receipt" accept=".jpg,.jpeg,.png,.pdf" id="expenseReceiptInput">
|
||||
<small class="text-muted" id="existingReceiptHint"></small>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label">Asignar Gasto a Conceptos</label>
|
||||
<div id="expense-concept-allocations" class="p-2 border rounded" style="max-height: 250px; overflow-y: auto;">
|
||||
<?php if (empty($concepts)): ?>
|
||||
<p class="text-muted">No hay conceptos especiales para asignar.</p>
|
||||
<?php else: ?>
|
||||
<?php foreach ($concepts as $c):
|
||||
$status = CollectionConcept::getCollectionStatus($c['id']);
|
||||
?>
|
||||
<div class="allocation-row mb-2">
|
||||
<div class="form-check">
|
||||
<input class="form-check-input concept-checkbox" type="checkbox" value="<?= $c['id'] ?>" id="alloc_concept_<?= $c['id'] ?>">
|
||||
<label class="form-check-label" for="alloc_concept_<?= $c['id'] ?>">
|
||||
<?= htmlspecialchars($c['name']) ?>
|
||||
<small class="text-success">(Balance: $<?= number_format($status['balance'], 2) ?>)</small>
|
||||
</label>
|
||||
</div>
|
||||
<div class="input-group input-group-sm mt-1">
|
||||
<span class="input-group-text">$</span>
|
||||
<input type="number" step="0.01" class="form-control allocation-amount" name="allocations[<?= $c['id'] ?>]" placeholder="0.00" disabled>
|
||||
</div>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
<div class="alert alert-secondary mt-2">
|
||||
<div class="d-flex justify-content-between"><span>Monto del Gasto:</span> <strong id="summary-expense-amount">$0.00</strong></div>
|
||||
<div class="d-flex justify-content-between"><span>Total Asignado:</span> <strong id="summary-allocated-amount">$0.00</strong></div>
|
||||
<hr class="my-1">
|
||||
<div class="d-flex justify-content-between fw-bold"><span>Restante:</span> <strong id="summary-remaining-amount">$0.00</strong></div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label">Categoría</label>
|
||||
<input type="text" class="form-control" name="category" placeholder="Ej: Mantenimiento, Limpieza">
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
|
||||
<button type="submit" class="btn btn-primary">Guardar Gasto</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
if (!<?= Auth::isCapturist() ? 'true' : 'false' ?>) return;
|
||||
|
||||
const expenseModalEl = document.getElementById('expenseModal');
|
||||
if (!expenseModalEl) return;
|
||||
|
||||
// --- Concept Modal ---
|
||||
const conceptModalEl = document.getElementById('conceptModal');
|
||||
const conceptModal = conceptModalEl ? new bootstrap.Modal(conceptModalEl) : null;
|
||||
const conceptForm = document.getElementById('conceptForm');
|
||||
|
||||
const openConceptModal = (id = null) => {
|
||||
conceptForm.reset();
|
||||
conceptForm.elements['id'].value = '';
|
||||
if (id) {
|
||||
conceptModalEl.querySelector('#conceptModalTitle').textContent = 'Editar Concepto Especial';
|
||||
conceptModalEl.querySelector('#conceptFormSubmitBtn').textContent = 'Guardar Cambios';
|
||||
fetch(`/dashboard.php?page=finanzas&action=get_concept&id=${id}`).then(r => r.json()).then(res => {
|
||||
if (res.success && res.data) {
|
||||
const c = res.data;
|
||||
conceptForm.elements['id'].value = c.id;
|
||||
conceptForm.elements['name'].value = c.name || '';
|
||||
conceptForm.elements['description'].value = c.description || '';
|
||||
conceptForm.elements['total_amount'].value = c.total_amount || '';
|
||||
conceptForm.elements['amount_per_house'].value = c.amount_per_house || '';
|
||||
conceptForm.elements['concept_date'].value = c.concept_date || '';
|
||||
conceptForm.elements['due_date'].value = c.due_date || '';
|
||||
conceptForm.elements['category'].value = c.category || '';
|
||||
conceptModal.show();
|
||||
} else {
|
||||
Swal.fire('Error', res.message || 'No se pudo cargar el concepto.', 'error');
|
||||
}
|
||||
});
|
||||
} else {
|
||||
conceptModalEl.querySelector('#conceptModalTitle').textContent = 'Nuevo Concepto Especial';
|
||||
conceptModalEl.querySelector('#conceptFormSubmitBtn').textContent = 'Crear Concepto';
|
||||
conceptModal.show();
|
||||
}
|
||||
};
|
||||
|
||||
const deleteConcept = (id) => {
|
||||
if (!<?= Auth::isAdmin() ? 'true' : 'false' ?>) {
|
||||
Swal.fire('Acceso Denegado', 'No tienes permisos para eliminar conceptos', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
Swal.fire({
|
||||
title: '¿Eliminar Concepto?',
|
||||
text: 'Esta acción eliminará el concepto, sus pagos y asignaciones de gastos.',
|
||||
icon: 'warning',
|
||||
showCancelButton: true,
|
||||
confirmButtonText: 'Sí, eliminar'
|
||||
}).then(res => {
|
||||
if (res.isConfirmed) {
|
||||
fetch(`/dashboard.php?page=finanzas&action=delete_concept&id=${id}`, { method: 'GET' }).then(r => r.json()).then(data => {
|
||||
if (data.success) {
|
||||
Swal.fire('Eliminado', data.message, 'success').then(() => location.reload());
|
||||
} else {
|
||||
Swal.fire('Error', data.message, 'error');
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
document.getElementById('newConceptBtn')?.addEventListener('click', () => openConceptModal());
|
||||
document.getElementById('concepts').addEventListener('click', e => {
|
||||
const editBtn = e.target.closest('.btn-edit-concept');
|
||||
if (editBtn) openConceptModal(editBtn.dataset.conceptId);
|
||||
const deleteBtn = e.target.closest('.btn-delete-concept');
|
||||
if (deleteBtn) deleteConcept(deleteBtn.dataset.conceptId);
|
||||
});
|
||||
|
||||
conceptForm.addEventListener('submit', e => {
|
||||
e.preventDefault();
|
||||
const data = Object.fromEntries(new FormData(e.target).entries());
|
||||
data.total_amount = data.total_amount ? parseFloat(data.total_amount) : null;
|
||||
data.amount_per_house = data.amount_per_house ? parseFloat(data.amount_per_house) : null;
|
||||
fetch('/dashboard.php?page=finanzas&action=save_concept', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data)
|
||||
}).then(r => r.json()).then(res => {
|
||||
if (res.success) {
|
||||
conceptModal.hide();
|
||||
Swal.fire('Éxito', res.message, 'success').then(() => location.reload());
|
||||
} else {
|
||||
Swal.fire('Error', res.message || 'Error desconocido.', 'error');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// --- Expense Modal ---
|
||||
const expenseModal = new bootstrap.Modal(expenseModalEl);
|
||||
const expenseForm = document.getElementById('expenseForm');
|
||||
const expenseAmountInput = expenseForm.querySelector('input[name="amount"]');
|
||||
const allocationContainer = document.getElementById('expense-concept-allocations');
|
||||
|
||||
const updateAllocationSummary = () => {
|
||||
const expenseAmount = parseFloat(expenseAmountInput.value) || 0;
|
||||
let allocatedAmount = 0;
|
||||
allocationContainer.querySelectorAll('.allocation-row').forEach(row => {
|
||||
const amountInput = row.querySelector('.allocation-amount');
|
||||
if (!amountInput.disabled) {
|
||||
allocatedAmount += parseFloat(amountInput.value) || 0;
|
||||
}
|
||||
});
|
||||
const remainingAmount = expenseAmount - allocatedAmount;
|
||||
document.getElementById('summary-expense-amount').textContent = `$${expenseAmount.toFixed(2)}`;
|
||||
document.getElementById('summary-allocated-amount').textContent = `$${allocatedAmount.toFixed(2)}`;
|
||||
const remainingEl = document.getElementById('summary-remaining-amount');
|
||||
remainingEl.textContent = `$${remainingAmount.toFixed(2)}`;
|
||||
remainingEl.classList.toggle('text-danger', remainingAmount < 0 || (remainingAmount > 0 && allocatedAmount > 0));
|
||||
};
|
||||
|
||||
document.getElementById('newExpenseBtn')?.addEventListener('click', () => {
|
||||
openExpenseModal();
|
||||
});
|
||||
|
||||
const openExpenseModal = (id = null) => {
|
||||
expenseForm.reset();
|
||||
expenseForm.elements['id'].value = '';
|
||||
document.getElementById('existingReceiptHint').textContent = '';
|
||||
allocationContainer.querySelectorAll('.allocation-row').forEach(row => {
|
||||
row.querySelector('.concept-checkbox').checked = false;
|
||||
const amountInput = row.querySelector('.allocation-amount');
|
||||
amountInput.value = '';
|
||||
amountInput.disabled = true;
|
||||
});
|
||||
updateAllocationSummary();
|
||||
|
||||
if (id) {
|
||||
expenseModalEl.querySelector('#expenseModalTitle').textContent = 'Editar Gasto';
|
||||
fetch(`/dashboard.php?page=finanzas&action=get_expense&id=${id}`).then(r => r.json()).then(res => {
|
||||
if (res.success && res.data) {
|
||||
const e = res.data;
|
||||
expenseForm.elements['id'].value = e.id;
|
||||
expenseForm.elements['description'].value = e.description || '';
|
||||
expenseForm.elements['amount'].value = e.amount || '';
|
||||
expenseForm.elements['expense_date'].value = e.expense_date || '';
|
||||
expenseForm.elements['category'].value = e.category || '';
|
||||
|
||||
if (e.receipt_path) {
|
||||
document.getElementById('existingReceiptHint').textContent = 'Comprobante existente: ' + e.receipt_path.split('/').pop();
|
||||
}
|
||||
|
||||
// Load allocations
|
||||
if (e.allocations && e.allocations.length > 0) {
|
||||
allocationContainer.querySelectorAll('.allocation-row').forEach(row => {
|
||||
const checkbox = row.querySelector('.concept-checkbox');
|
||||
const amountInput = row.querySelector('.allocation-amount');
|
||||
const alloc = e.allocations.find(a => a.concept_id == checkbox.value);
|
||||
if (alloc) {
|
||||
checkbox.checked = true;
|
||||
amountInput.value = alloc.amount;
|
||||
amountInput.disabled = false;
|
||||
}
|
||||
});
|
||||
updateAllocationSummary();
|
||||
}
|
||||
|
||||
expenseModal.show();
|
||||
} else {
|
||||
Swal.fire('Error', res.message || 'No se pudo cargar el gasto.', 'error');
|
||||
}
|
||||
});
|
||||
} else {
|
||||
expenseModalEl.querySelector('#expenseModalTitle').textContent = 'Registrar Gasto';
|
||||
expenseModal.show();
|
||||
}
|
||||
};
|
||||
|
||||
expenseAmountInput.addEventListener('input', updateAllocationSummary);
|
||||
allocationContainer.addEventListener('change', e => {
|
||||
if (e.target.classList.contains('concept-checkbox')) {
|
||||
e.target.closest('.allocation-row').querySelector('.allocation-amount').disabled = !e.target.checked;
|
||||
if (!e.target.checked) e.target.closest('.allocation-row').querySelector('.allocation-amount').value = '';
|
||||
}
|
||||
updateAllocationSummary();
|
||||
});
|
||||
allocationContainer.addEventListener('input', e => {
|
||||
if (e.target.classList.contains('allocation-amount')) updateAllocationSummary();
|
||||
});
|
||||
|
||||
expenseForm.addEventListener('submit', e => {
|
||||
e.preventDefault();
|
||||
|
||||
const formData = new FormData(expenseForm);
|
||||
formData.append('id', expenseForm.elements['id'].value);
|
||||
formData.append('description', expenseForm.elements['description'].value);
|
||||
formData.append('amount', expenseForm.elements['amount'].value);
|
||||
formData.append('expense_date', expenseForm.elements['expense_date'].value);
|
||||
formData.append('category', expenseForm.elements['category'].value);
|
||||
|
||||
const allocations = [];
|
||||
allocationContainer.querySelectorAll('.allocation-row').forEach(row => {
|
||||
const checkbox = row.querySelector('.concept-checkbox');
|
||||
const amountInput = row.querySelector('.allocation-amount');
|
||||
if (checkbox.checked) {
|
||||
const amount = parseFloat(amountInput.value) || 0;
|
||||
if (amount > 0) {
|
||||
allocations.push({ concept_id: checkbox.value, amount: amount });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
formData.append('allocations', JSON.stringify(allocations));
|
||||
|
||||
const allocatedTotal = allocations.reduce((sum, a) => sum + a.amount, 0);
|
||||
const expenseAmount = parseFloat(expenseForm.elements['amount'].value);
|
||||
|
||||
if (allocations.length > 0 && Math.abs(expenseAmount - allocatedTotal) > 0.01) {
|
||||
Swal.fire('Error', 'El total asignado a los conceptos no coincide con el monto del gasto.', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
Swal.fire({
|
||||
title: 'Guardando...',
|
||||
text: 'Procesando gasto y comprobante',
|
||||
allowOutsideClick: false,
|
||||
didOpen: () => Swal.showLoading()
|
||||
});
|
||||
|
||||
fetch('/dashboard.php?page=finanzas&action=save_expense', {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
})
|
||||
.then(r => r.json())
|
||||
.then(res => {
|
||||
if (res.success) {
|
||||
expenseModal.hide();
|
||||
Swal.fire('Éxito', res.message, 'success').then(() => location.reload());
|
||||
} else {
|
||||
Swal.fire('Error', res.message || 'Error desconocido.', 'error');
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
Swal.fire('Error', 'Error de conexión', 'error');
|
||||
});
|
||||
});
|
||||
|
||||
// Delegate deleteExpense and editExpense events from main table
|
||||
document.getElementById('expenses')?.addEventListener('click', e => {
|
||||
const deleteBtn = e.target.closest('.btn-delete-expense');
|
||||
if(deleteBtn) deleteExpense(deleteBtn.dataset.expenseId);
|
||||
const editBtn = e.target.closest('.btn-edit-expense');
|
||||
if(editBtn) openExpenseModal(editBtn.dataset.expenseId);
|
||||
});
|
||||
|
||||
const deleteExpense = (id) => {
|
||||
if (!<?= Auth::isAdmin() ? 'true' : 'false' ?>) {
|
||||
Swal.fire('Acceso Denegado', 'No tienes permisos para eliminar gastos', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
Swal.fire({
|
||||
title: '¿Eliminar Gasto?',
|
||||
text: 'Esta acción no se puede deshacer.',
|
||||
icon: 'warning',
|
||||
showCancelButton: true,
|
||||
confirmButtonText: 'Sí, eliminar'
|
||||
}).then(res => {
|
||||
if (res.isConfirmed) {
|
||||
fetch(`/dashboard.php?page=finanzas&action=delete_expense&id=${id}`, { method: 'GET' }).then(r => r.json()).then(data => {
|
||||
if (data.success) location.reload();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
</script>
|
||||
<?php endif; ?>
|
||||
Reference in New Issue
Block a user