modified: Dockerfile

modified:   README.md
	modified:   app.py
	new file:   blueprints/__init__.py
	new file:   blueprints/__pycache__/.gitignore
	new file:   blueprints/auth.py
	new file:   blueprints/finance.py
	new file:   blueprints/inventory.py
	new file:   blueprints/pos.py
	new file:   blueprints/sales.py
	new file:   core/__pycache__/.gitignore
	new file:   core/db.py
	new file:   core/db/.gitignore
	new file:   core/events.py
	new file:   core/openfood.py
	new file:   core/utils.py
	modified:   static/style.css
	modified:   templates/checkout.html
	modified:   templates/dicom.html
	modified:   templates/login.html
	modified:   templates/macros/base.html
	modified:   templates/macros/modals.html
	modified:   templates/macros/navbar.html
This commit is contained in:
2026-05-21 00:05:31 -04:00
parent c2373c3ed6
commit a5babd8131
23 changed files with 2102 additions and 1169 deletions

View File

@@ -312,7 +312,104 @@
</div>
</div>
<!-- Dicom Checkout Modal -->
<div class="modal fade" id="dicomModal" tabindex="-1" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title"><i class="bi bi-person-plus me-2"></i>Mandar a Dicom</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<div class="mb-3">
<label class="form-label text-muted small mb-1">Seleccionar Deudor</label>
<div class="input-group">
<select id="dicom-debtor-select" class="form-select" onchange="toggleNewDebtorInput()">
<option value="">-- Seleccionar deudor --</option>
</select>
<button class="btn btn-success" type="button" onclick="showNewDebtorInput()" title="Nuevo deudor">
<i class="bi bi-plus-lg"></i> Nuevo
</button>
</div>
<input type="text" id="dicom-debtor-name" class="form-control mt-2" placeholder="Nombre del nuevo deudor..." style="display:none;">
<small id="debtor-count" class="text-muted"></small>
</div>
<div class="mb-3">
<label class="form-label text-muted small mb-1">Información de Contacto (Opcional)</label>
<input type="text" id="dicom-contact-info" class="form-control" placeholder="Teléfono, dirección...">
</div>
<div class="p-3 rounded mb-2" style="background: var(--input-bg);">
<div class="d-flex justify-content-between">
<span class="text-muted">Total a Dicom:</span>
<span id="dicom-total" class="fw-bold" style="color: var(--danger); font-size: 1.2rem;">$0</span>
</div>
</div>
<div class="mb-2">
<label class="form-label fw-bold small mb-1" style="color: #198754;">
<i class="bi bi-cash-coin me-1"></i>Pago inicial (opcional)
</label>
<div class="input-group">
<span class="input-group-text" style="background: #198754; border-color: #198754; color: #fff;">$</span>
<input type="text" id="dicom-initial-payment" class="form-control fw-bold border-start-0" style="border-color: #198754;" placeholder="0" oninput="formatDicomPayment(this)">
</div>
</div>
<div class="p-2 rounded" style="background: var(--input-bg);">
<div class="d-flex justify-content-between">
<span class="text-muted">Saldo pendiente:</span>
<span id="dicom-remaining" class="fw-bold" style="color: #198754;">$0</span>
</div>
</div>
</div>
<div class="modal-footer d-flex">
<button class="btn btn-secondary flex-grow-1" data-bs-dismiss="modal">Cancelar</button>
<button class="btn btn-danger flex-grow-1" onclick="processDicomCheckout()">
<i class="bi bi-send me-1"></i>Enviar a Dicom
</button>
</div>
</div>
</div>
</div>
<!-- Dicom Success Modal -->
<div class="modal fade" id="dicomSuccessModal" tabindex="-1">
<div class="modal-dialog modal-dialog-centered modal-sm">
<div class="modal-content">
<div class="modal-header bg-success text-white">
<h5 class="modal-title"><i class="bi bi-check-circle me-2"></i>Enviado a Dicom</h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body text-center py-4">
<div class="mb-3">
<i class="bi bi-receipt" style="font-size: 3rem; color: var(--success);"></i>
</div>
<h6 class="mb-2">Ticket #<span id="dicom-success-ticket-id"></span></h6>
<p class="text-muted mb-0">Registrado para</p>
<h5 class="text-success mb-0" id="dicom-success-debtor"></h5>
</div>
<div class="modal-footer d-flex">
<button class="btn btn-success flex-grow-1" data-bs-dismiss="modal">Aceptar</button>
</div>
</div>
</div>
</div>
<div class="container-fluid">
<!-- Kitchen Ticket Print Zone -->
<div id="kitchen-print-zone" class="d-none d-print-block">
<style>
@media print {
@page { size: 80mm auto; margin: 0; }
nav, .discord-card, .modal, .row, #kitchen-print-zone { display: none !important; }
#kitchen-print-zone, #kitchen-print-zone * { visibility: visible; }
#kitchen-print-zone {
position: absolute; left: 0; top: 0; width: 80mm;
padding: 5mm; display: block !important;
}
}
</style>
<div id="kitchen-ticket-content"></div>
</div>
<div class="row g-3">
<div class="col-md-8">
<div class="discord-card p-3">
@@ -359,11 +456,44 @@
</div>
<div class="col-md-4">
<!-- Restaurant Mode Panel -->
<div id="restaurant-panel" class="discord-card p-3 mb-3 d-none">
<div class="d-flex justify-content-between align-items-center mb-3">
<h6 class="mb-0"><i class="bi bi-receipt me-2"></i>Comanda</h6>
<span class="badge bg-accent">Modo Comida</span>
</div>
<div class="mb-2">
<label class="form-label text-muted small mb-1">Nombre del Cliente</label>
<input type="text" id="restaurant-client-name" class="form-control" placeholder="Ej: Juan" autocomplete="off">
</div>
<div class="mb-2">
<label class="form-label text-muted small mb-1">Tipo</label>
<select id="restaurant-order-type" class="form-select">
<option value="servir">Para Servir</option>
<option value="llevar">Para Llevar</option>
</select>
</div>
<div class="mb-3">
<label class="form-label text-muted small mb-1">Notas Adicionales</label>
<input type="text" id="restaurant-notes" class="form-control" placeholder="Sin cebolla, extra salsa..." autocomplete="off">
</div>
<div class="d-flex gap-2">
<button class="btn btn-accent flex-grow-1" onclick="printKitchenTicket()">
<i class="bi bi-printer me-1"></i>Imprimir Comanda
</button>
<button id="btn-reset-comanda" class="btn btn-outline-secondary d-none" onclick="resetKitchenTicket()">
<i class="bi bi-arrow-counterclockwise"></i>
</button>
</div>
</div>
<div class="discord-card p-3 mb-3 text-center shadow-sm">
<p class="mb-1 fw-semibold text-uppercase" style="color:var(--text-muted); font-size:0.7rem">Último Escaneado</p>
<img id="display-img" src="./static/placeholder.png" class="mb-2" alt="product">
<h6 id="display-name" class="mb-0 text-truncate">Esperando scan...</h6>
<small id="display-barcode" class="text-muted font-monospace" style="font-size: 0.7rem"></small>
<div id="last-scanned-content">
<p class="mb-1 fw-semibold text-uppercase" style="color:var(--text-muted); font-size:0.7rem">Último Escaneado</p>
<img id="display-img" src="./static/placeholder.png" class="mb-2" alt="product">
<h6 id="display-name" class="mb-0 text-truncate">Esperando scan...</h6>
<small id="display-barcode" class="text-muted font-monospace" style="font-size: 0.7rem"></small>
</div>
<div class="total-banner text-center mb-3 mt-3">
<h2 class="mb-0">TOTAL</h2>
@@ -379,6 +509,9 @@
<button class="btn btn-danger w-100 btn-lg" onclick="clearCart()">
<i class="bi bi-trash3"></i> VACIAR
</button>
<button class="btn btn-outline-danger w-100 btn-lg mt-2" id="btn-mandar-dicom" onclick="openDicomModal()">
<i class="bi bi-person-plus"></i> Mandar a Dicom
</button>
</div>
</div>
</div>
@@ -390,7 +523,12 @@
/* =========================================
1. GLOBAL STATE & FORMATTERS
========================================= */
let cart = [];
let cart = JSON.parse(localStorage.getItem('seki_cart') || '[]');
function saveCart() {
localStorage.setItem('seki_cart', JSON.stringify(cart));
}
let pendingProduct = null;
let missingProductData = null;
let tempBarcode = null;
@@ -407,6 +545,18 @@
// Fetch the pinned items from local storage
let pinnedBarcodes = JSON.parse(localStorage.getItem('seki_pinned_products')) || [];
// Restaurant Mode (Modo Comida) initialization
const modoComida = localStorage.getItem('modo_comida') === 'true';
if (modoComida) {
document.getElementById('restaurant-panel').classList.remove('d-none');
}
// Last Scanned panel toggle
const showLastScanned = localStorage.getItem('seki_last_scanned') !== 'false';
if (!showLastScanned) {
document.getElementById('last-scanned-content').classList.add('d-none');
}
let socket = io();
const clp = new Intl.NumberFormat('es-CL', {
@@ -491,6 +641,16 @@
document.getElementById('grand-total').innerText = clp.format(total);
saveCart();
// Enable/disable Mandar a Dicom button
const dicomBtn = document.getElementById('btn-mandar-dicom');
if (cart.length === 0) {
dicomBtn.classList.add('disabled');
dicomBtn.setAttribute('disabled', 'true');
} else {
dicomBtn.classList.remove('disabled');
dicomBtn.removeAttribute('disabled');
}
}
function addToCart(product, qty) {
@@ -499,8 +659,9 @@
cart[existingIndex].qty += qty;
cart[existingIndex].subtotal = calculateSubtotal(cart[existingIndex].price, cart[existingIndex].qty);
} else {
cart.push({ ...product, qty, subtotal: calculateSubtotal(product.price, qty) });
cart.push({ ...product, qty, subtotal: calculateSubtotal(product.price, qty), printed_qty: 0 });
}
saveCart();
renderCart();
}
@@ -511,6 +672,7 @@
removeItem(index, cart[index].name);
} else {
cart[index].subtotal = calculateSubtotal(cart[index].price, cart[index].qty);
saveCart();
renderCart();
}
}
@@ -520,6 +682,7 @@
if (isNaN(newQty) || newQty <= 0) return;
cart[index].qty = newQty;
cart[index].subtotal = calculateSubtotal(cart[index].price, cart[index].qty);
saveCart();
renderCart();
}
@@ -532,6 +695,7 @@
function executeRemoveItem() {
if (itemIndexToRemove !== null) {
cart.splice(itemIndexToRemove, 1);
saveCart();
renderCart();
bootstrap.Modal.getInstance(document.getElementById('removeConfirmModal')).hide();
itemIndexToRemove = null;
@@ -545,6 +709,7 @@
function executeClearCart() {
cart = [];
saveCart();
renderCart();
clearLastScanned();
bootstrap.Modal.getInstance(document.getElementById('clearCartModal')).hide();
@@ -558,7 +723,16 @@
function loadCart() {
const saved = localStorage.getItem('seki_cart');
if (saved) {
try { cart = JSON.parse(saved); renderCart(); }
try {
cart = JSON.parse(saved);
// Ensure all items have printed_qty property
cart.forEach(item => {
if (typeof item.printed_qty === 'undefined') {
item.printed_qty = 0;
}
});
renderCart();
}
catch (e) { console.error(e); cart = []; }
}
}
@@ -714,7 +888,8 @@
price: priceInput,
image: '',
stock: 0,
unit: unitInput
unit: unitInput,
printed_qty: 0
};
if (unitInput === 'kg') {
@@ -751,7 +926,8 @@
subtotal: price,
image: '',
stock: 0,
unit: 'unit'
unit: 'unit',
printed_qty: 0
}, 1);
bootstrap.Modal.getInstance(document.getElementById('variosModal')).hide();
}
@@ -918,6 +1094,7 @@
bootstrap.Modal.getOrCreateInstance(document.getElementById('successModal')).show();
cart = [];
saveCart();
renderCart();
clearLastScanned();
setTimeout(() => bootstrap.Modal.getInstance(document.getElementById('successModal')).hide(), 2000);
@@ -960,7 +1137,7 @@
const quickCart = [{
barcode: `RAPIDA-${Date.now().toString().slice(-6)}`,
name: '* Varios', price: amount, qty: 1, subtotal: amount, unit: 'unit'
name: '* Varios', price: amount, qty: 1, subtotal: amount, unit: 'unit', printed_qty: 0
}];
try {
@@ -992,6 +1169,262 @@
}
}
/* =========================================
RESTAURANT MODE (MODO COMIDA)
========================================= */
function printKitchenTicket() {
const clientName = document.getElementById('restaurant-client-name').value.trim();
const orderType = document.getElementById('restaurant-order-type').value;
const notes = document.getElementById('restaurant-notes').value.trim();
// Calculate delta items (qty - printed_qty)
const deltaItems = cart.filter(item => {
const printed = item.printed_qty || 0;
return item.qty > printed;
}).map(item => ({
...item,
delta: item.qty - (item.printed_qty || 0)
}));
if (deltaItems.length === 0) {
alert('No hay items nuevos para imprimir.');
return;
}
// Update printed_qty for delta items
cart.forEach(item => {
if (item.qty > (item.printed_qty || 0)) {
item.printed_qty = item.qty;
}
});
// Show reset button if anything has been printed
const hasPrinted = cart.some(item => (item.printed_qty || 0) > 0);
document.getElementById('btn-reset-comanda').classList.toggle('d-none', !hasPrinted);
// Get comanda size setting
const comandaSize = localStorage.getItem('seki_comanda_size') || 'medium';
const sizeMap = {
small: { header: '14px', title: '16px', item: '12px', qty: '12px' },
medium: { header: '16px', title: '20px', item: '14px', qty: '14px' },
large: { header: '18px', title: '24px', item: '18px', qty: '18px' },
xlarge: { header: '20px', title: '28px', item: '22px', qty: '22px' }
};
const sizes = sizeMap[comandaSize];
// Build the kitchen ticket HTML
const ticketHtml = `
<div style="font-family: 'Courier New', monospace; padding: 10px; font-size: ${sizes.header};">
<div style="text-align: center; border-bottom: 2px dashed #000; padding-bottom: 10px; margin-bottom: 10px;">
<strong style="font-size: ${sizes.title};">COMANDA</strong><br>
${clientName ? `<span>Cliente: ${clientName}</span><br>` : ''}
<span>${orderType === 'servir' ? '🍽️ PARA SERVIR' : '🥡 PARA LLEVAR'}</span>
${notes ? `<br><em>Nota: ${notes}</em>` : ''}
</div>
<table style="width: 100%; border-collapse: collapse;">
<thead>
<tr style="border-bottom: 1px dashed #000;">
<th style="text-align: left; padding: 3px 0;">Cant</th>
<th style="text-align: left; padding: 3px 0;">Producto</th>
</tr>
</thead>
<tbody>
${deltaItems.map(item => `
<tr>
<td style="padding: 2px 0; font-size: ${sizes.qty};"><strong>${item.unit === 'kg' ? item.delta.toFixed(3) : item.delta}</strong></td>
<td style="padding: 2px 0; font-size: ${sizes.item};">${item.name}</td>
</tr>
`).join('')}
</tbody>
</table>
<div style="text-align: center; margin-top: 15px; font-size: 11px;">
${new Date().toLocaleString('es-CL')}
</div>
</div>
`;
// Create a temporary print window
const printWindow = window.open('', '_blank');
printWindow.document.write(`
<!DOCTYPE html>
<html>
<head>
<title>Comanda - ${clientName || 'Sin nombre'}</title>
<style>
@media print {
body { margin: 0; padding: 0; }
@page { size: 80mm auto; margin: 0; }
}
</style>
</head>
<body>${ticketHtml}</body>
</html>
`);
printWindow.document.close();
printWindow.focus();
setTimeout(() => {
printWindow.print();
printWindow.close();
}, 250);
}
function resetKitchenTicket() {
// Reset printed_qty for all items
cart.forEach(item => {
item.printed_qty = 0;
});
// Clear inputs
document.getElementById('restaurant-client-name').value = '';
document.getElementById('restaurant-notes').value = '';
document.getElementById('restaurant-order-type').value = 'servir';
// Hide reset button
document.getElementById('btn-reset-comanda').classList.add('d-none');
}
/* =========================================
DICOM CHECKOUT
========================================= */
function openDicomModal() {
const total = cart.reduce((sum, item) => sum + item.subtotal, 0);
document.getElementById('dicom-total').innerText = clp.format(total);
document.getElementById('dicom-remaining').innerText = clp.format(total);
document.getElementById('dicom-debtor-name').value = '';
document.getElementById('dicom-contact-info').value = '';
document.getElementById('dicom-initial-payment').value = '';
bootstrap.Modal.getOrCreateInstance(document.getElementById('dicomModal')).show();
fetchDebtorsList();
}
// Format payment input with dots
function formatDicomPayment(input) {
let value = input.value.replace(/\./g, '').replace(/[^0-9]/g, '');
const total = cart.reduce((sum, item) => sum + item.subtotal, 0);
if (value && parseInt(value) > total) {
value = total.toString();
}
if (value) {
value = parseInt(value).toLocaleString('es-CL');
}
input.value = value;
// Update remaining
const rawValue = parseInt(input.value.replace(/\./g, '')) || 0;
const remaining = Math.max(0, total - rawValue);
document.getElementById('dicom-remaining').innerText = clp.format(remaining);
}
// Update remaining when initial payment changes
document.getElementById('dicom-initial-payment').addEventListener('input', function() {
formatDicomPayment(this);
});
// Load when modal is fully shown
document.getElementById('dicomModal').addEventListener('shown.bs.modal', function() {
fetchDebtorsList();
});
async function fetchDebtorsList() {
try {
const res = await fetch('/api/dicom/debtors', { credentials: 'same-origin' });
if (!res.ok) return;
const debtors = await res.json();
const select = document.getElementById('dicom-debtor-select');
const countLabel = document.getElementById('debtor-count');
select.innerHTML = '<option value="">-- Seleccionar deudor --</option>';
if (debtors && debtors.length > 0) {
for (let d of debtors) {
const opt = document.createElement('option');
opt.value = d.name;
opt.textContent = d.contact_info ? `${d.name} - ${d.contact_info}` : d.name;
select.appendChild(opt);
}
countLabel.textContent = `${debtors.length} deudor(es)`;
} else {
countLabel.textContent = 'No hay deudores';
}
} catch (e) {
console.error('Error loading debtors:', e);
}
}
function showNewDebtorInput() {
document.getElementById('dicom-debtor-select').value = '';
document.getElementById('dicom-debtor-name').style.display = 'block';
document.getElementById('dicom-debtor-name').focus();
}
function toggleNewDebtorInput() {
const select = document.getElementById('dicom-debtor-select');
const nameInput = document.getElementById('dicom-debtor-name');
if (select.value === '') {
nameInput.style.display = 'block';
} else {
nameInput.style.display = 'none';
nameInput.value = '';
}
}
async function processDicomCheckout() {
// Check if selecting existing or entering new
const select = document.getElementById('dicom-debtor-select');
const nameInput = document.getElementById('dicom-debtor-name');
let debtorName = select.value || nameInput.value.trim();
const contactInfo = document.getElementById('dicom-contact-info').value.trim();
const paymentInput = document.getElementById('dicom-initial-payment').value.replace(/\./g, '');
const initialPayment = parseInt(paymentInput) || 0;
if (!debtorName) {
alert('Por favor ingresa el nombre del deudor.');
return;
}
try {
const res = await fetch('/api/dicom/checkout', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'same-origin',
body: JSON.stringify({
cart: cart,
debtor_name: debtorName,
contact_info: contactInfo,
initial_payment: initialPayment
})
});
const result = await res.json();
if (res.ok) {
bootstrap.Modal.getInstance(document.getElementById('dicomModal')).hide();
document.getElementById('dicom-success-ticket-id').textContent = result.ticket_id;
document.getElementById('dicom-success-debtor').textContent = result.debtor;
bootstrap.Modal.getOrCreateInstance(document.getElementById('dicomSuccessModal')).show();
// Clear cart
cart = [];
saveCart();
renderCart();
clearLastScanned();
} else {
alert('Error: ' + (result.error || 'Error desconocido'));
}
} catch (e) {
console.error(e);
alert('Error de conexión.');
}
}
function printReceipt(total, saleId, paidAmount = 0) {
const tbody = document.getElementById('receipt-items-print');
tbody.innerHTML = '';

View File

@@ -1,155 +1,188 @@
{% extends "macros/base.html" %}
{% from 'macros/modals.html' import confirm_modal %}
{% block title %}Dicom{% endblock %}
{% block content %}
<style>
.debtor-item {
background: var(--card-bg);
border-radius: 12px;
padding: 16px 20px;
margin-bottom: 12px;
transition: all 0.2s ease;
border: 1px solid rgba(255,255,255,0.05);
}
.debtor-item:hover {
background: var(--input-bg);
border-color: rgba(255,255,255,0.1);
}
.debtor-item .debtor-avatar {
width: 48px;
height: 48px;
min-width: 48px;
border-radius: 12px;
display: flex;
align-items: center;
justify-content: center;
font-size: 1.2rem;
}
.debtor-name {
font-size: 1.05rem;
font-weight: 600;
color: var(--text-main);
}
.debtor-contact {
font-size: 0.85rem;
color: var(--text-muted);
}
.debtor-debt {
font-size: 1.3rem;
font-weight: 700;
color: var(--danger);
}
.debtor-debt.paid {
color: var(--success);
}
.ticket-card {
background: var(--card-bg);
border-radius: 10px;
padding: 16px;
margin-bottom: 10px;
border: 1px solid rgba(255,255,255,0.05);
transition: all 0.2s ease;
}
.ticket-card:hover {
border-color: rgba(255,255,255,0.15);
}
.ticket-status {
font-size: 0.75rem;
font-weight: 600;
padding: 4px 10px;
border-radius: 20px;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.ticket-status.paid { background: rgba(40, 167, 69, 0.2); color: #28a745; }
.ticket-status.partial { background: rgba(255, 193, 7, 0.2); color: #ffc107; }
.ticket-status.unpaid { background: rgba(220, 53, 69, 0.2); color: #dc3545; }
.ticket-item-row {
padding: 6px 0;
border-bottom: 1px solid rgba(255,255,255,0.03);
}
.ticket-item-row:last-child { border-bottom: none; }
.chevron-icon {
transition: transform 0.3s ease;
font-size: 1.1rem;
}
.chevron-icon.rotated {
transform: rotate(180deg);
}
.btn-pay-all {
font-size: 0.8rem;
padding: 6px 14px;
border-radius: 8px;
font-weight: 600;
}
.btn-delete-debtor {
width: 36px;
height: 36px;
padding: 0;
border-radius: 8px;
display: flex;
align-items: center;
justify-content: center;
}
.empty-state {
text-align: center;
padding: 60px 20px;
color: var(--text-muted);
}
.empty-state i {
font-size: 3rem;
opacity: 0.3;
}
</style>
<div class="row g-3">
<div class="col-12">
<div class="discord-card p-3">
<div class="d-flex justify-content-between align-items-center mb-3 gap-3">
<div class="position-relative flex-grow-1">
<input type="text" id="dicom-search" class="form-control ps-5 py-2"
placeholder="Buscar cliente por nombre..." onkeyup="filterDicom()">
<i class="bi bi-search position-absolute top-50 start-0 translate-middle-y ms-3 text-muted"></i>
</div>
<button class="btn btn-accent text-nowrap py-2 px-3 fw-bold" onclick="openNewModal()">
<i class="bi bi-plus-lg me-1"></i> Nuevo Deudor
</button>
<div class="discord-card p-4">
<div class="d-flex justify-content-between align-items-center mb-4">
<h4 class="mb-0"><i class="bi bi-people me-2"></i>Deudores</h4>
<span class="badge bg-secondary">{{ debtors|length }} registrados</span>
</div>
<div class="table-responsive">
<table class="table mb-0" id="dicom-table">
<thead>
<tr>
<th style="width: 60px;">Foto</th>
<th>Nombre</th>
<th>Deuda Total</th>
<th>Última Nota</th>
<th>Actualizado</th>
<th class="text-end">Acciones</th>
</tr>
</thead>
<tbody>
{% for d in debtors %}
<tr>
<td>
{% if d[5] %}
<img src="{{ d[5] }}" class="rounded shadow-sm" style="width: 40px; height: 40px; object-fit: cover; cursor: pointer;"
onclick="window.open(this.src, '_blank')">
{% else %}
<div class="bg-secondary rounded" style="width: 40px; height: 40px; display: flex; align-items: center; justify-content: center; opacity: 0.3;">
<i class="bi bi-person text-white"></i>
</div>
{% endif %}
</td>
<td class="fw-bold align-middle">{{ d[1] }}</td>
<td class="fw-bold price-cell align-middle fs-5" data-value="{{ d[2] }}"></td>
<td class="text-muted small align-middle">{{ d[3] }}</td>
<td class="text-muted small align-middle">{{ d[4] }}</td>
<td class="text-end align-middle">
<button class="btn btn-sm btn-outline-secondary" onclick="openQuickEditModal('{{ d[1] }}', '{{ d[3] }}')"
title="Actualizar Deuda">
<i class="bi bi-pencil"></i>
</button>
<button class="btn btn-sm btn-outline-danger ms-1"
onclick="forgiveDebt({{ d[0] }}, '{{ d[1] }}')" title="Eliminar Registro">
<i class="bi bi-trash"></i>
</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<div id="debtors-list">
{% for d in debtors %}
<div class="debtor-item" data-debtor-id="{{ d[0] }}">
<div class="d-flex justify-content-between align-items-center">
<div class="d-flex align-items-center gap-3 flex-grow-1 cursor-pointer" onclick="toggleDebtor({{ d[0] }})">
<div class="debtor-avatar {% if d[3] > 0 %}bg-danger{% else %}bg-success{% endif %} text-white">
<i class="bi bi-person-fill"></i>
</div>
<div class="flex-grow-1">
<div class="debtor-name">{{ d[1] }}</div>
<div class="debtor-contact">{{ d[2] or 'Sin contacto' }}</div>
</div>
</div>
<div class="text-end me-3">
<div class="debtor-debt {% if d[3] <= 0 %}paid{% endif %} price-cell" data-value="{{ d[3] }}"></div>
<small class="text-muted">{% if d[3] > 0 %}Deuda pendiente{% else %}Saldo cero{% endif %}</small>
</div>
<div class="d-flex align-items-center gap-2">
{% if d[3] > 0 %}
<button class="btn btn-sm btn-success btn-pay-all" onclick="payAllDebtor({{ d[0] }}, {{ d[3] }})" title="Pagar toda la deuda">
<i class="bi bi-check-lg me-1"></i>Pagar Todo
</button>
{% endif %}
<button class="btn btn-sm btn-outline-danger btn-delete-debtor" onclick="deleteDebtor({{ d[0] }}, '{{ d[1] }}')" title="Eliminar deudor">
<i class="bi bi-trash"></i>
</button>
<i class="bi bi-chevron-down text-muted chevron-icon" id="chevron-{{ d[0] }}"></i>
</div>
</div>
<!-- Expanded tickets view -->
<div id="debtor-{{ d[0] }}" class="d-none mt-3 pt-3" style="border-top: 1px solid rgba(255,255,255,0.05);">
<div id="tickets-container-{{ d[0] }}" class="text-center text-muted py-3">
<span class="spinner-border spinner-border-sm me-2"></span>Cargando tickets...
</div>
</div>
</div>
{% else %}
<div class="empty-state">
<i class="bi bi-emoji-frown d-block mb-3"></i>
<p class="mb-0">No hay deudores registrados</p>
</div>
{% endfor %}
</div>
</div>
</div>
</div>
<div class="modal fade" id="dicomModal" tabindex="-1" data-bs-backdrop="static">
<!-- Payment Modal -->
<div class="modal fade" id="paymentModal" tabindex="-1">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header border-0 pb-0">
<h5 class="modal-title w-100 text-center text-muted text-uppercase" style="font-size: 0.8rem;" id="dicomModalTitle">
Registrar Movimiento
</h5>
<button type="button" class="btn-close position-absolute end-0 top-0 m-3" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body pt-2 pb-4">
<div class="mb-3">
<label class="small text-muted mb-1">Nombre del Cliente</label>
<input type="text" id="dicom-name" class="form-control form-control-lg fw-bold" placeholder="Ej: Doña Juanita">
</div>
<div class="mb-3">
<label class="small text-muted mb-1">Monto (CLP)</label>
<input type="number" id="dicom-amount" class="form-control form-control-lg text-center fw-bold fs-4" placeholder="$0">
</div>
<div class="mb-3">
<label class="small text-muted mb-1">Nota (Opcional)</label>
<input type="text" id="dicom-notes" class="form-control" placeholder="Ej: Pan y bebida"
onkeydown="if(event.key === 'Enter') submitDicom('add')">
</div>
<div class="mb-4">
<label class="small text-muted mb-1">Foto / Comprobante (Opcional)</label>
<div class="input-group">
<input type="text" id="dicom-image-url" class="form-control" placeholder="URL de imagen" readonly>
<input type="file" id="dicom-camera-input" accept="image/*" capture="environment" style="display: none;"
onchange="handleDicomUpload(this)">
<button class="btn btn-outline-secondary" type="button"
onclick="document.getElementById('dicom-camera-input').click()">
<i class="bi bi-camera"></i>
</button>
</div>
<div id="dicom-img-preview-container" class="mt-2 text-center d-none">
<img id="dicom-img-preview" src="" class="img-thumbnail rounded" style="max-height: 120px; border-color: var(--border);">
</div>
</div>
<div class="d-flex gap-2">
<button class="btn btn-danger flex-grow-1 py-3 fw-bold" onclick="submitDicom('add')">
<i class="bi bi-cart-plus me-1"></i> Fiar
</button>
<button class="btn btn-success flex-grow-1 py-3 fw-bold" onclick="submitDicom('pay')">
<i class="bi bi-cash-coin me-1"></i> Abonar
</button>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="quickEditModal" tabindex="-1">
<div class="modal-dialog modal-dialog-centered modal-sm">
<div class="modal-content">
<div class="modal-header border-0 pb-0">
<h5 class="modal-title w-100 text-center text-muted text-uppercase" style="font-size: 0.8rem;">
Actualizar Deuda
<h5 class="modal-title w-100 text-center text-muted text-uppercase" style="font-size: 0.8rem">
Pagar Deuda
</h5>
<button type="button" class="btn-close position-absolute end-0 top-0 m-3" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body text-center pt-1 pb-4">
<h4 id="quick-edit-name" class="mb-3 fw-bold" style="color: var(--text-main);"></h4>
<div class="mb-3 text-start">
<label class="text-muted small mb-1">Monto a agregar/restar (CLP)</label>
<input type="number" id="quick-edit-amount" class="form-control form-control-lg text-center fw-bold fs-4" placeholder="$0"
onkeydown="if(event.key === 'Enter') submitQuickEdit('add')">
<div class="mb-4">
<span class="text-muted small">Total a Pagar:</span><br>
<span id="payment-remaining-display" class="fs-1 fw-bold" style="color: var(--accent)">$0</span>
</div>
<div class="mb-4 text-start">
<label class="text-muted small mb-1">Nota Actualizada</label>
<input type="text" id="quick-edit-notes" class="form-control" placeholder="Ej: Pan y bebida"
onkeydown="if(event.key === 'Enter') submitQuickEdit('add')">
</div>
<div class="d-flex gap-2">
<button class="btn btn-danger flex-grow-1 py-2 fw-bold" onclick="submitQuickEdit('add')">
<i class="bi bi-cart-plus me-1"></i> Fiar
<div class="d-grid gap-3 px-3">
<button class="btn btn-lg btn-success py-3" onclick="confirmPayment('efectivo')">
<i class="bi bi-cash-coin me-2" style="font-size: 1.5rem; vertical-align: middle"></i> Efectivo (1)
</button>
<button class="btn btn-success flex-grow-1 py-2 fw-bold" onclick="submitQuickEdit('pay')">
<i class="bi bi-cash-coin me-1"></i> Abonar
<button class="btn btn-lg btn-secondary py-3" onclick="confirmPayment('tarjeta')">
<i class="bi bi-credit-card me-2" style="font-size: 1.5rem; vertical-align: middle"></i> Tarjeta (2)
</button>
<button class="btn btn-lg btn-info py-3 text-white" onclick="confirmPayment('transferencia')">
<i class="bi bi-bank me-2" style="font-size: 1.5rem; vertical-align: middle"></i> Transferencia (3)
</button>
</div>
</div>
@@ -157,222 +190,400 @@
</div>
</div>
{% call confirm_modal('deleteDebtModal', 'Eliminar Registro', 'btn-danger', 'Eliminar Permanente', 'executeForgiveDebt()') %}
<div class="text-center">
<i class="bi bi-exclamation-triangle-fill text-danger mb-3" style="font-size: 3rem;"></i>
<p class="mb-1">¿Estás seguro de que quieres perdonar la deuda y eliminar completamente a <strong id="deleteDebtName" style="color: var(--text-main);"></strong> del registro?</p>
<p class="text-muted small">Esta acción no se puede deshacer.</p>
<!-- Vuelto Modal -->
<div class="modal" id="dicomVueltoModal" tabindex="-1" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-sm">
<div class="modal-content">
<div class="modal-header border-0 pb-0">
<h5 class="modal-title w-100 text-center text-muted text-uppercase" style="font-size: 0.8rem">Pago en Efectivo</h5>
<button type="button" class="btn-close position-absolute end-0 top-0 m-3" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body text-center pt-1 pb-4">
<div class="mb-3">
<span class="text-muted small">Total a Pagar:</span><br>
<span id="dicom-vuelto-total" class="fs-4 fw-bold" style="color: var(--text-main)">$0</span>
</div>
<div class="mb-3 text-start">
<label class="text-muted small mb-1">Monto Recibido</label>
<input type="text" inputmode="numeric" id="dicom-monto-recibido" class="form-control form-control-lg text-center fw-bold fs-4"
placeholder="$0"
oninput="let v = this.value.replace(/\D/g, ''); this.value = v ? parseInt(v, 10).toLocaleString('es-CL') : ''; calculateDicomVuelto();">
</div>
<div class="d-flex flex-wrap justify-content-center gap-2 mb-3">
<button class="btn btn-outline-secondary btn-sm" onclick="setDicomVuelto(1000)">$1.000</button>
<button class="btn btn-outline-secondary btn-sm" onclick="setDicomVuelto(2000)">$2.000</button>
<button class="btn btn-outline-secondary btn-sm" onclick="setDicomVuelto(5000)">$5.000</button>
<button class="btn btn-outline-secondary btn-sm" onclick="setDicomVuelto(10000)">$10.000</button>
<button class="btn btn-outline-secondary btn-sm" onclick="setDicomVuelto(20000)">$20.000</button>
</div>
<div class="p-3 mb-3" style="background: var(--input-bg); border-radius: 8px">
<span class="text-muted small text-uppercase fw-bold">Vuelto a Entregar</span><br>
<span id="dicom-vuelto-amount" class="fs-1 fw-bold text-muted">$0</span>
</div>
<button id="btn-confirm-dicom-vuelto" class="btn btn-success w-100 py-3 fw-bold" onclick="confirmDicomPayment()" disabled>Confirmar Pago</button>
</div>
</div>
</div>
{% endcall %}
</div>
<!-- Success Modal -->
<div class="modal fade" id="dicomSuccessModal" tabindex="-1">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content border-success">
<div class="modal-body text-center py-4">
<i class="bi bi-check-circle-fill text-success" style="font-size: 4rem;"></i>
<h4 class="mt-3">¡Pago Exitoso!</h4>
<p class="text-muted">El pago se ha procesado correctamente.</p>
<button class="btn btn-accent px-5" data-bs-dismiss="modal">Listo</button>
</div>
</div>
</div>
</div>
<!-- Delete Confirmation Modal -->
<div class="modal fade" id="dicomDeleteModal" tabindex="-1">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content border-danger">
<div class="modal-header pb-0 border-0">
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body text-center pt-0 pb-4">
<i class="bi bi-exclamation-triangle-fill text-danger mb-3" style="font-size: 3rem;"></i>
<h4 class="mb-3" id="dicom-delete-title">¿Eliminar?</h4>
<p class="text-muted small px-3" id="dicom-delete-desc">Esta acción no se puede deshacer.</p>
<div class="d-flex gap-2 justify-content-center mt-4 px-3">
<button class="btn btn-secondary w-50" data-bs-dismiss="modal">Cancelar</button>
<button class="btn btn-danger w-50" id="dicom-delete-confirm-btn">Eliminar</button>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
{% block scripts %}
<script>
const clp = new Intl.NumberFormat('es-CL', { style: 'currency', currency: 'CLP', minimumFractionDigits: 0 });
let currentDebtorId = null;
let currentTicketId = null;
let expandedDebtorId = null;
let payAllMode = false;
let pendingPaymentMethod = null;
let pendingPaymentAmount = 0;
let deleteCallback = null;
// Format debts and flip colors (Negative = Debt/Red, Positive = Credit/Green)
document.querySelectorAll('.price-cell').forEach(td => {
const val = parseFloat(td.getAttribute('data-value'));
td.innerText = clp.format(val);
if (val < 0) {
td.classList.add('text-danger');
} else if (val > 0) {
td.classList.add('text-success');
} else {
td.classList.add('text-muted');
}
});
// Modal Control Functions
function openNewModal() {
clearDicomForm();
bootstrap.Modal.getOrCreateInstance(document.getElementById('dicomModal')).show();
setTimeout(() => document.getElementById('dicom-name').focus(), 500);
}
let currentQuickEditName = '';
function openQuickEditModal(name, notes) {
currentQuickEditName = name;
document.getElementById('quick-edit-name').innerText = name;
document.getElementById('quick-edit-amount').value = '';
// Inject the existing note directly into the new input field
document.getElementById('quick-edit-notes').value = notes || '';
const modal = bootstrap.Modal.getOrCreateInstance(document.getElementById('quickEditModal'));
modal.show();
setTimeout(() => document.getElementById('quick-edit-amount').focus(), 500);
}
async function submitQuickEdit(action) {
const amount = document.getElementById('quick-edit-amount').value;
const notes = document.getElementById('quick-edit-notes').value; // Grab the newly edited note
if (!amount || amount <= 0 || isNaN(amount)) {
alert('Ingresa un monto válido mayor a 0.');
return;
}
try {
const res = await fetch('/api/dicom/update', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: currentQuickEditName,
amount: amount,
notes: notes, // Send the UI value instead of the background variable
action: action,
image_url: ''
})
});
if (res.ok) {
bootstrap.Modal.getInstance(document.getElementById('quickEditModal')).hide();
window.location.reload();
} else {
alert("Error al actualizar la deuda.");
const deleteConfirmBtn = document.getElementById('dicom-delete-confirm-btn');
if (deleteConfirmBtn) {
deleteConfirmBtn.addEventListener('click', function() {
if (deleteCallback) {
deleteCallback();
deleteCallback = null;
}
} catch (e) { alert("Error de conexión."); }
}
function clearDicomForm() {
document.getElementById('dicom-name').value = '';
document.getElementById('dicom-amount').value = '';
document.getElementById('dicom-notes').value = '';
document.getElementById('dicom-image-url').value = '';
document.getElementById('dicom-img-preview-container').classList.add('d-none');
}
// Image Compression & Upload
function compressImage(file, maxWidth, quality) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = event => {
const img = new Image();
img.src = event.target.result;
img.onload = () => {
const canvas = document.createElement('canvas');
let width = img.width;
let height = img.height;
if (width > maxWidth) {
height = Math.round((height * maxWidth) / width);
width = maxWidth;
}
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, width, height);
canvas.toBlob(blob => resolve(blob), 'image/jpeg', quality);
};
};
bootstrap.Modal.getInstance(document.getElementById('dicomDeleteModal')).hide();
});
}
async function handleDicomUpload(input) {
const name = document.getElementById('dicom-name').value.trim();
if (!name) {
alert("Primero ingresa el nombre del cliente arriba para asociar la foto.");
input.value = '';
return;
}
const file = input.files[0];
if (!file) return;
try {
const compressedBlob = await compressImage(file, 800, 0.7);
const formData = new FormData();
formData.append('image', compressedBlob, `debt_${name}_${Date.now()}.jpg`);
formData.append('barcode', `debt_${name}`);
const res = await fetch('/upload_image', { method: 'POST', body: formData });
const data = await res.json();
if (res.ok) {
document.getElementById('dicom-image-url').value = data.image_url;
document.getElementById('dicom-img-preview').src = data.image_url;
document.getElementById('dicom-img-preview-container').classList.remove('d-none');
}
} catch (e) {
alert("Error procesando imagen.");
}
}
// Database Actions
async function submitDicom(action) {
const name = document.getElementById('dicom-name').value.trim();
const amount = document.getElementById('dicom-amount').value;
const notes = document.getElementById('dicom-notes').value;
const image_url = document.getElementById('dicom-image-url').value;
if (!name || amount <= 0 || isNaN(amount)) {
alert('Ingresa un nombre y monto válido mayor a 0.');
return;
}
try {
const res = await fetch('/api/dicom/update', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name, amount, notes, action, image_url })
});
if (res.ok) {
bootstrap.Modal.getInstance(document.getElementById('dicomModal')).hide();
window.location.reload();
} else {
alert("Error al guardar en la base de datos.");
}
} catch (e) { alert("Error de conexión."); }
}
let debtIdToDelete = null;
function forgiveDebt(id, name) {
debtIdToDelete = id;
document.getElementById('deleteDebtName').innerText = name;
bootstrap.Modal.getOrCreateInstance(document.getElementById('deleteDebtModal')).show();
}
async function executeForgiveDebt() {
if (!debtIdToDelete) return;
function showDeleteConfirm(title, desc, callback) {
const titleEl = document.getElementById('dicom-delete-title');
const descEl = document.getElementById('dicom-delete-desc');
const modalEl = document.getElementById('dicomDeleteModal');
try {
const res = await fetch(`/api/dicom/${debtIdToDelete}`, { method: 'DELETE' });
if (res.ok) {
window.location.reload();
} else {
alert("Error al eliminar el registro.");
}
} catch (e) {
alert("Error de conexión.");
} finally {
bootstrap.Modal.getInstance(document.getElementById('deleteDebtModal')).hide();
if (titleEl) titleEl.textContent = title;
if (descEl) descEl.textContent = desc;
deleteCallback = callback;
if (modalEl) {
bootstrap.Modal.getOrCreateInstance(modalEl).show();
}
}
// Global listener to accept with the Enter key
document.addEventListener('keydown', function(event) {
if (event.key === 'Enter') {
const deleteModal = document.getElementById('deleteDebtModal');
if (deleteModal && deleteModal.classList.contains('show')) {
event.preventDefault();
executeForgiveDebt();
// Format price cells on page load
document.querySelectorAll('.price-cell').forEach(el => {
const val = parseFloat(el.dataset.value) || 0;
el.innerText = clp.format(val);
});
function toggleDebtor(debtorId) {
const container = document.getElementById(`debtor-${debtorId}`);
const chevron = document.getElementById(`chevron-${debtorId}`);
if (container.classList.contains('d-none')) {
container.classList.remove('d-none');
chevron.classList.add('rotated');
expandedDebtorId = debtorId;
loadTickets(debtorId);
} else {
container.classList.add('d-none');
chevron.classList.remove('rotated');
expandedDebtorId = null;
}
}
async function loadTickets(debtorId) {
const container = document.getElementById(`tickets-container-${debtorId}`);
try {
const res = await fetch(`/api/dicom/debtor/${debtorId}`);
const tickets = await res.json();
if (tickets.length === 0) {
container.innerHTML = '<div class="text-muted small py-3">No hay tickets registrados</div>';
return;
}
container.innerHTML = tickets.map(ticket => `
<div class="ticket-card">
<div class="d-flex justify-content-between align-items-center mb-3">
<div class="d-flex align-items-center gap-2">
<span class="ticket-status ${ticket.status}">
${ticket.status === 'paid' ? 'Pagado' : ticket.status === 'partial' ? 'Parcial' : 'Pendiente'}
</span>
<span class="text-muted small">${new Date(ticket.date).toLocaleDateString('es-CL', { day: '2-digit', month: 'short', year: 'numeric' })}</span>
</div>
<div class="d-flex align-items-center gap-2">
<div class="text-end me-2">
<div class="fw-bold" style="font-size: 1.1rem;">${clp.format(ticket.total)}</div>
<small class="text-muted">Pagado: ${clp.format(ticket.amount_paid)}</small>
</div>
<button class="btn btn-sm btn-outline-danger" onclick="deleteTicket(${ticket.id})" title="Eliminar ticket" style="border-radius: 8px; width: 34px; height: 34px; padding: 0; display: flex; align-items: center; justify-content: center;">
<i class="bi bi-trash"></i>
</button>
</div>
</div>
<!-- Items -->
<div style="background: var(--input-bg); border-radius: 8px; padding: 12px 16px;">
${ticket.items.map(item => `
<div class="ticket-item-row d-flex justify-content-between align-items-center">
<div>
<span class="fw-semibold">${item.qty}x</span>
<span class="ms-2">${item.name}</span>
</div>
<div class="d-flex align-items-center gap-2">
<span class="text-muted">${clp.format(item.subtotal)}</span>
<button class="btn btn-sm btn-outline-danger py-0 px-1" onclick="deleteItem(${item.id})" title="Eliminar" style="border-radius: 6px; width: 24px; height: 24px; padding: 0; display: flex; align-items: center; justify-content: center; font-size: 0.75rem;">
<i class="bi bi-x"></i>
</button>
</div>
</div>
`).join('')}
</div>
${ticket.remaining > 0 ? `
<div class="d-flex justify-content-between align-items-center mt-3 pt-3" style="border-top: 1px solid rgba(255,255,255,0.05);">
<div>
<span class="text-muted small d-block">Restante</span>
<span class="text-danger fw-bold" style="font-size: 1.1rem;">${clp.format(ticket.remaining)}</span>
</div>
<button class="btn btn-sm btn-success btn-pay-all" onclick="openPaymentModal(${ticket.id}, ${ticket.remaining})">
<i class="bi bi-check-lg me-1"></i>Pagar Todo
</button>
</div>
` : '<div class="text-center mt-3"><span class="badge bg-success px-3 py-2"><i class="bi bi-check-circle me-1"></i>Pagado completamente</span></div>'}
</div>
`).join('');
} catch (e) {
console.error(e);
container.innerHTML = '<div class="text-danger small py-3">Error al cargar tickets</div>';
}
}
function openPaymentModal(ticketId, remaining) {
currentTicketId = ticketId;
payAllMode = false;
pendingPaymentAmount = remaining;
document.getElementById('payment-remaining-display').innerText = clp.format(remaining);
bootstrap.Modal.getOrCreateInstance(document.getElementById('paymentModal')).show();
}
function openPayAllModal(debtorId, totalDebt) {
currentDebtorId = debtorId;
payAllMode = true;
pendingPaymentAmount = totalDebt;
document.getElementById('payment-remaining-display').innerText = clp.format(totalDebt);
bootstrap.Modal.getOrCreateInstance(document.getElementById('paymentModal')).show();
}
// Focus monto recibido when vuelto modal opens
document.getElementById('dicomVueltoModal').addEventListener('shown.bs.modal', function() {
const input = document.getElementById('dicom-monto-recibido');
input.value = '';
setTimeout(() => input.focus(), 100);
});
// Enter key to confirm payment in vuelto modal
document.getElementById('dicom-monto-recibido').addEventListener('keypress', function(e) {
if (e.key === 'Enter' && !document.getElementById('btn-confirm-dicom-vuelto').disabled) {
confirmDicomPayment();
}
});
// Search
function filterDicom() {
const q = document.getElementById('dicom-search').value.toLowerCase();
document.querySelectorAll('#dicom-table tbody tr').forEach(row => {
const name = row.cells[1].innerText.toLowerCase(); // Index 1 is the name column
row.style.display = name.includes(q) ? '' : 'none';
// Keyboard shortcuts for payment modal
document.addEventListener('keydown', function(e) {
const modal = document.getElementById('paymentModal');
if (modal.classList.contains('show')) {
if (e.key === '1') confirmPayment('efectivo');
if (e.key === '2') confirmPayment('tarjeta');
if (e.key === '3') confirmPayment('transferencia');
}
});
// Store remaining value for calculation
const observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.attributeName === 'data-value') {
const el = mutation.target;
el.innerText = clp.format(parseFloat(el.dataset.value));
}
});
});
document.querySelectorAll('.price-cell').forEach(el => {
observer.observe(el, { attributes: true });
});
// Delete debtor
function deleteDebtor(debtorId, debtorName) {
showDeleteConfirm(
'Eliminar deudor',
`¿Eliminar al deudor "${debtorName}" y todos sus tickets? Esta acción no se puede deshacer.`,
async function() {
try {
const res = await fetch(`/api/dicom/debtor/${debtorId}`, { method: 'DELETE' });
if (res.ok) {
location.reload();
} else {
const data = await res.json();
alert('Error: ' + (data.error || 'Error desconocido'));
}
} catch (e) {
alert('Error de conexión');
}
}
);
}
// Delete ticket
function deleteTicket(ticketId) {
showDeleteConfirm(
'Eliminar ticket',
'¿Eliminar este ticket y todos sus productos? Esta acción no se puede deshacer.',
async function() {
try {
const res = await fetch(`/api/dicom/ticket/${ticketId}`, { method: 'DELETE' });
if (res.ok) {
if (expandedDebtorId) {
loadTickets(expandedDebtorId);
}
} else {
const data = await res.json();
alert('Error: ' + (data.error || 'Error desconocido'));
}
} catch (e) {
alert('Error de conexión');
}
}
);
}
// Delete individual item
function deleteItem(itemId) {
showDeleteConfirm(
'Eliminar producto',
'¿Eliminar este producto del ticket? Esta acción no se puede deshacer.',
async function() {
try {
const res = await fetch(`/api/dicom/item/${itemId}`, { method: 'DELETE' });
const data = await res.json();
if (res.ok) {
if (expandedDebtorId) {
loadTickets(expandedDebtorId);
}
} else {
alert('Error: ' + (data.error || 'Error desconocido'));
}
} catch (e) {
alert('Error de conexión');
}
}
);
}
// Pay all tickets for a debtor
function payAllDebtor(debtorId, totalDebt) {
openPayAllModal(debtorId, totalDebt);
}
async function confirmPayment(paymentMethod) {
const amount = pendingPaymentAmount;
// For efectivo, open the vuelto modal
if (paymentMethod === 'efectivo') {
pendingPaymentMethod = paymentMethod;
document.getElementById('dicom-vuelto-total').innerText = clp.format(amount);
document.getElementById('dicom-monto-recibido').value = '';
document.getElementById('dicom-vuelto-amount').innerText = '$0';
document.getElementById('btn-confirm-dicom-vuelto').disabled = true;
bootstrap.Modal.getInstance(document.getElementById('paymentModal')).hide();
bootstrap.Modal.getOrCreateInstance(document.getElementById('dicomVueltoModal')).show();
return;
}
// For other methods, process directly
await processDicomPayment(amount, paymentMethod);
}
function setDicomVuelto(amount) {
const formatted = amount.toLocaleString('es-CL');
document.getElementById('dicom-monto-recibido').value = formatted;
calculateDicomVuelto();
}
function calculateDicomVuelto() {
const receivedStr = document.getElementById('dicom-monto-recibido').value;
const received = parseInt(receivedStr.replace(/\./g, '')) || 0;
const total = pendingPaymentAmount;
const change = Math.max(0, received - total);
document.getElementById('dicom-vuelto-amount').innerText = clp.format(change);
document.getElementById('btn-confirm-dicom-vuelto').disabled = received < total;
}
async function confirmDicomPayment() {
await processDicomPayment(pendingPaymentAmount, pendingPaymentMethod);
bootstrap.Modal.getInstance(document.getElementById('dicomVueltoModal')).hide();
}
async function processDicomPayment(amount, paymentMethod) {
try {
let res;
if (payAllMode) {
res = await fetch(`/api/dicom/debtor/${currentDebtorId}/pay-all`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ amount: amount, payment_method: paymentMethod })
});
} else {
res = await fetch(`/api/dicom/pay`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ticket_id: currentTicketId, amount: amount, payment_method: paymentMethod })
});
}
if (res.ok) {
bootstrap.Modal.getInstance(document.getElementById('paymentModal')).hide();
payAllMode = false;
// Show success modal
bootstrap.Modal.getOrCreateInstance(document.getElementById('dicomSuccessModal')).show();
// Reload page after modal hides
setTimeout(() => location.reload(), 2500);
} else {
const data = await res.json();
alert('Error: ' + (data.error || 'Error desconocido'));
}
} catch (e) {
alert('Error de conexión');
}
}
</script>
{% endblock %}
{% endblock %}

View File

@@ -1,38 +1,24 @@
<!DOCTYPE html>
<html lang="es" data-theme="light">
{% extends "macros/base.html" %}
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SekiPOS Login</title>
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.png') }}" type="image/x-icon">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" rel="stylesheet">
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
{% block title %}Login{% endblock %}
<body>
<div class="login-box text-center">
<h2 class="fw-bold mb-1">SekiPOS</h2>
<p class="mb-4" style="opacity:.7;">¡Hola de nuevo!</p>
{% block content %}
<div class="login-box text-center">
<h2 class="fw-bold mb-1">SekiPOS</h2>
<p class="mb-4 text-muted">¡Hola de nuevo!</p>
{% with messages = get_flashed_messages() %}
{% if messages %}
<div class="error-alert p-2 mb-3">{{ messages[0] }}</div>
{% endif %}
{% endwith %}
{% with messages = get_flashed_messages() %}
{% if messages %}
<div class="error-alert p-2 mb-3">{{ messages[0] }}</div>
{% endif %}
{% endwith %}
<form method="POST">
<input class="form-control mb-3" type="text" name="username" placeholder="Usuario" required autofocus>
<input class="form-control mb-3" type="password" name="password" placeholder="Contraseña" required>
<button type="submit" class="btn btn-login w-100">
Iniciar Sesión
</button>
</form>
</div>
<script src="{{ url_for('static', filename='cookieStuff.js') }}"></script>
<script src="{{ url_for('static', filename='themeStuff.js') }}"></script>
</body>
</html>
<form method="POST">
<input class="form-control mb-3" type="text" name="username" placeholder="Usuario" required autofocus>
<input class="form-control mb-3" type="password" name="password" placeholder="Contraseña" required>
<button type="submit" class="btn btn-login w-100">
Iniciar Sesión
</button>
</form>
</div>
{% endblock %}

View File

@@ -1,5 +1,5 @@
<!DOCTYPE html>
<html lang="es" data-theme="light">
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
@@ -7,6 +7,20 @@
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.png') }}" type="image/x-icon">
<script>
// Apply theme BEFORE any CSS loads to prevent flash
(function() {
var theme = localStorage.getItem('theme');
var isDark = (theme === 'dark') || (!theme && window.matchMedia('(prefers-color-scheme: dark)').matches);
if (isDark) {
document.documentElement.setAttribute('data-theme', 'dark');
}
if (localStorage.getItem('seki_food_mode') === 'true') {
document.body.classList.add('food-mode-active');
}
})();
</script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
@@ -17,13 +31,6 @@
</head>
<body>
<script>
// Inject Food Mode class immediately to appease the kitchen staff
if (localStorage.getItem('seki_food_mode') === 'true') {
document.body.classList.add('food-mode-active');
}
</script>
{% include 'macros/navbar.html' %}
<main class="container-fluid px-3">

View File

@@ -307,6 +307,23 @@
<i class="bi bi-egg-fried"></i> Modo Comida (Letras Grandes)
</label>
</div>
<div class="form-check form-switch mb-3">
<input class="form-check-input" type="checkbox" id="setting-last-scanned">
<label class="form-check-label text-muted small" for="setting-last-scanned">
<i class="bi bi-upc-scan"></i> Mostrar "Último Escaneado" en Caja
</label>
</div>
<div class="mb-3">
<label class="form-label text-muted small mb-1">Tamaño de letra Comanda</label>
<select id="setting-comanda-size" class="form-select">
<option value="small">Pequeño</option>
<option value="medium" selected>Mediano</option>
<option value="large">Grande</option>
<option value="xlarge">Extra Grande</option>
</select>
</div>
</div>
<div class="modal-footer d-flex">
<button class="btn btn-secondary flex-grow-1" data-bs-dismiss="modal">Cancelar</button>
@@ -329,6 +346,9 @@
document.getElementById('setting-auto-print').checked = localStorage.getItem('seki_auto_print') !== 'false';
document.getElementById('setting-ask-order-details').checked = localStorage.getItem('seki_ask_order_details') === 'true';
document.getElementById('setting-food-mode').checked = localStorage.getItem('seki_food_mode') === 'true';
document.getElementById('setting-last-scanned').checked = localStorage.getItem('seki_last_scanned') !== 'false';
const comandaSize = localStorage.getItem('seki_comanda_size') || 'medium';
document.getElementById('setting-comanda-size').value = comandaSize;
const showSii = localStorage.getItem('seki_show_sii') === 'true';
document.getElementById('setting-show-sii').checked = showSii;
@@ -348,11 +368,16 @@
const askDetails = document.getElementById('setting-ask-order-details').checked;
const showSii = document.getElementById('setting-show-sii').checked;
const foodMode = document.getElementById('setting-food-mode').checked;
const lastScanned = document.getElementById('setting-last-scanned').checked;
const comandaSize = document.getElementById('setting-comanda-size').value;
localStorage.setItem('seki_biz_name', bizName);
localStorage.setItem('seki_auto_print', autoPrint);
localStorage.setItem('seki_ask_order_details', askDetails);
localStorage.setItem('seki_show_sii', showSii);
localStorage.setItem('seki_food_mode', foodMode);
localStorage.setItem('modo_comida', foodMode);
localStorage.setItem('seki_last_scanned', lastScanned);
localStorage.setItem('seki_comanda_size', comandaSize);
if (showSii) {
localStorage.setItem('seki_rut', document.getElementById('setting-rut').value.trim());

View File

@@ -1,9 +1,10 @@
<nav class="navbar navbar-expand-md sticky-top px-3 mb-3">
<span class="navbar-brand">
SekiPOS
<small class="text-muted fw-normal" style="font-size:0.65rem;">v2.2</small>
<small class="text-muted fw-normal" style="font-size:0.65rem;">v3.0</small>
</span>
{% if user and user.is_authenticated %}
<div class="ms-3 gap-2 d-flex">
<a href="/inventory" class="btn btn-sm {{ 'btn-primary' if active_page == 'inventory' else 'btn-outline-primary' }}">
<i class="bi bi-box-seam me-1"></i>Inventario
@@ -22,8 +23,10 @@
<i class="bi bi-journal-x me-1"></i>Dicom
</a>
</div>
{% endif %}
<div class="ms-auto">
{% if user and user.is_authenticated %}
<div class="dropdown">
<button class="btn btn-accent dropdown-toggle" type="button" data-bs-toggle="dropdown">
<i class="bi bi-person-circle me-1"></i>
@@ -32,7 +35,7 @@
<ul class="dropdown-menu dropdown-menu-end shadow">
<li>
<button class="dropdown-item" onclick="toggleTheme()">
<i class="bi bi-moon-stars me-2"></i>Modo Oscuro
<i class="bi bi-moon-stars me-2" id="theme-icon"></i><span id="theme-label">Modo Oscuro</span>
</button>
</li>
<li>
@@ -58,5 +61,10 @@
</li>
</ul>
</div>
{% else %}
<a href="/login" class="btn btn-accent">
<i class="bi bi-box-arrow-in-right me-1"></i>Iniciar Sesión
</a>
{% endif %}
</div>
</nav>