image compression, initial checkout(?

This commit is contained in:
2026-03-04 22:47:02 -03:00
parent 5e79b6938c
commit 423d563cc0
8 changed files with 580 additions and 11 deletions

1
.gitignore vendored
View File

@@ -1,3 +1,4 @@
pos_database.db pos_database.db
ScannerGO/ScannerGO-* ScannerGO/ScannerGO-*
ScannerGO/config.json ScannerGO/config.json
DataToolsGO/imageTools-*

42
DataToolsGO/build.sh Executable file
View File

@@ -0,0 +1,42 @@
#!/bin/bash
# Define binary names
LINUX_BIN="imageTools-linux"
LINUX_ARM_BIN="imageTools-linuxARMv7"
WINDOWS_BIN="imageTools-windows.exe"
echo "Starting build process..."
# Build for Linux (64-bit)
echo "Building for Linux..."
GOOS=linux GOARCH=amd64 go build -o "$LINUX_BIN" main.go
if [ $? -eq 0 ]; then
echo "Successfully built: $LINUX_BIN"
else
echo "Failed to build Linux binary"
exit 1
fi
# Build for Windows (64-bit)
echo "Building for Windows..."
GOOS=windows GOARCH=amd64 go build -o "$WINDOWS_BIN" main.go
if [ $? -eq 0 ]; then
echo "Successfully built: $WINDOWS_BIN"
else
echo "Failed to build Windows binary"
exit 1
fi
# Build for Linux ARM (ARMv7)
echo "Building for Linux ARMv7..."
GOOS=linux GOARCH=arm GOARM=7 go build -o "$LINUX_ARM_BIN" main.go
if [ $? -eq 0 ]; then
echo "Successfully built: $LINUX_ARM_BIN"
else
echo "Failed to build Linux ARMv7 binary"
exit 1
fi
echo "Build complete."

5
DataToolsGO/go.mod Normal file
View File

@@ -0,0 +1,5 @@
module dataTools
go 1.25.7
require github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646

2
DataToolsGO/go.sum Normal file
View File

@@ -0,0 +1,2 @@
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 h1:zYyBkD/k9seD2A7fsi6Oo2LfFZAehjjQMERAvZLEDnQ=
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646/go.mod h1:jpp1/29i3P1S/RLdc7JQKbRpFeM1dOBd8T9ki5s+AY8=

84
DataToolsGO/main.go Normal file
View File

@@ -0,0 +1,84 @@
package main
import (
"flag"
"fmt"
"image"
"image/jpeg"
"os"
"path/filepath"
"strings"
"github.com/nfnt/resize"
)
func main() {
// Command line arguments
dirPath := flag.String("dir", "./", "Directory containing images")
maxWidth := flag.Uint("width", 1000, "Maximum width for resizing")
quality := flag.Int("quality", 75, "JPEG quality (1-100)")
flag.Parse()
files, err := os.ReadDir(*dirPath)
if err != nil {
fmt.Printf("Error reading directory: %v\n", err)
return
}
fmt.Printf("Processing images in %s (Max Width: %d, Quality: %d)\n", *dirPath, *maxWidth, *quality)
for _, file := range files {
if file.IsDir() {
continue
}
ext := strings.ToLower(filepath.Ext(file.Name()))
if ext != ".jpg" && ext != ".jpeg" && ext != ".png" {
continue
}
filePath := filepath.Join(*dirPath, file.Name())
processImage(filePath, *maxWidth, *quality)
}
fmt.Println("Done. Your storage can finally breathe again.")
}
func processImage(path string, maxWidth uint, quality int) {
file, err := os.Open(path)
if err != nil {
fmt.Printf("Failed to open %s: %v\n", path, err)
return
}
img, _, err := image.Decode(file)
file.Close()
if err != nil {
fmt.Printf("Failed to decode %s: %v\n", path, err)
return
}
// Only resize if original is wider than maxWidth
bounds := img.Bounds()
var finalImg image.Image
if uint(bounds.Dx()) > maxWidth {
finalImg = resize.Resize(maxWidth, 0, img, resize.Lanczos3)
fmt.Printf("Resized and compressed: %s\n", filepath.Base(path))
} else {
finalImg = img
fmt.Printf("Compressed (no resize needed): %s\n", filepath.Base(path))
}
// Overwrite the original file
out, err := os.Create(path)
if err != nil {
fmt.Printf("Failed to create output file %s: %v\n", path, err)
return
}
defer out.Close()
err = jpeg.Encode(out, finalImg, &jpeg.Options{Quality: quality})
if err != nil {
fmt.Printf("Failed to encode %s: %v\n", path, err)
}
}

20
app.py
View File

@@ -112,7 +112,8 @@ def login():
@app.route('/logout') @app.route('/logout')
@login_required @login_required
def logout(): def logout():
logout_user(); return redirect(url_for('login')) logout_user()
return redirect(url_for('login'))
@app.route('/') @app.route('/')
@login_required @login_required
@@ -121,7 +122,13 @@ def index():
products = conn.execute('SELECT * FROM products').fetchall() products = conn.execute('SELECT * FROM products').fetchall()
return render_template('index.html', products=products, user=current_user) return render_template('index.html', products=products, user=current_user)
@app.route('/upsert', methods=['POST']) @app.route("/checkout")
@login_required
def checkout():
return render_template("checkout.html", user=current_user)
@app.route("/upsert", methods=["POST"])
@login_required @login_required
def upsert(): def upsert():
d = request.form d = request.form
@@ -161,10 +168,11 @@ def scan():
return jsonify({"status": "error", "message": "empty barcode"}), 400 return jsonify({"status": "error", "message": "empty barcode"}), 400
with sqlite3.connect(DB_FILE) as conn: with sqlite3.connect(DB_FILE) as conn:
p = conn.execute('SELECT * FROM products WHERE barcode = ?', (barcode,)).fetchone() # Specifically select the 4 columns the code expects
p = conn.execute('SELECT barcode, name, price, image_url FROM products WHERE barcode = ?', (barcode,)).fetchone()
# 1. Product exists in local Database
if p: if p:
# Now this will always have exactly 4 values, regardless of DB changes
barcode_val, name, price, image_path = p barcode_val, name, price, image_path = p
# Image recovery logic for missing local files # Image recovery logic for missing local files
@@ -266,8 +274,8 @@ def upload_image():
barcode = request.form['barcode'] barcode = request.form['barcode']
if file.filename == '' or not barcode: if file.filename == '' or not barcode:
return jsonify({"error": "Invalid data"}), 400 return jsonify({"error": "Invalid data"}), 400
ext = mimetypes.guess_extension(file.mimetype) or '.jpg'
filename = f"{barcode}{ext}" filename = f"{barcode}.jpg"
filepath = os.path.join(CACHE_DIR, filename) filepath = os.path.join(CACHE_DIR, filename)
file.save(filepath) file.save(filepath)
timestamp = int(time.time()) timestamp = int(time.time())

381
templates/checkout.html Normal file
View File

@@ -0,0 +1,381 @@
<!DOCTYPE html>
<html lang="es" data-theme="light">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SekiPOS - Caja</title>
<link rel="shortcut icon" href="./static/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">
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
<style>
:root {
--bg: #ebedef;
--card-bg: #ffffff;
--text-main: #2e3338;
--text-muted: #4f5660;
--border: #e3e5e8;
--navbar-bg: #ffffff;
--accent: #5865f2;
--accent-hover: #4752c4;
--input-bg: #e3e5e8;
}
[data-theme="dark"] {
--bg: #36393f;
--card-bg: #2f3136;
--text-main: #dcddde;
--text-muted: #b9bbbe;
--border: #202225;
--navbar-bg: #202225;
--input-bg: #202225;
}
body {
background: var(--bg);
color: var(--text-main);
font-family: "gg sans", "Segoe UI", sans-serif;
transition: background 0.2s, color 0.2s;
min-height: 100vh;
}
/* ── Navbar ── */
.navbar {
background: var(--navbar-bg) !important;
border-bottom: 1px solid var(--border);
transition: background 0.2s;
}
.navbar-brand {
color: var(--text-main) !important;
font-weight: 700;
}
/* ── Cards ── */
.cart-card,
.discord-card,
.modal-content {
background: var(--card-bg) !important;
color: var(--text-main);
border: 1px solid var(--border);
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
/* ── Product Preview (Matching Index) ── */
#display-img {
width: 100%;
max-width: 250px;
height: 250px;
object-fit: contain;
background: var(--bg);
border-radius: 8px;
padding: 10px;
}
/* ── Table Styling ── */
.table {
color: var(--text-main) !important;
--bs-table-bg: transparent;
--bs-table-border-color: var(--border);
}
.table thead th {
background: var(--bg);
color: var(--text-muted);
font-size: 0.75rem;
text-transform: uppercase;
border-bottom: 1px solid var(--border);
}
.table td {
border-bottom: 1px solid var(--border);
vertical-align: middle;
}
/* ── UI Elements ── */
.btn-accent {
background: var(--accent);
color: #fff;
border: none;
}
.btn-accent:hover {
background: var(--accent-hover);
color: #fff;
}
.form-control {
background: var(--input-bg);
color: var(--text-main);
border: none;
}
.form-control:focus {
background: var(--input-bg);
color: var(--text-main);
outline: 2px solid var(--accent);
box-shadow: none;
}
#grand-total {
color: var(--accent);
font-family: "gg sans", sans-serif;
}
.dropdown-menu {
background: var(--card-bg);
border: 1px solid var(--border);
}
.dropdown-item {
color: var(--text-main) !important;
}
.dropdown-item:hover {
background: var(--input-bg);
}
.btn-danger-discord {
background: var(--danger, #ed4245);
color: #fff;
border: none;
border-radius: 4px;
padding: 4px 8px;
transition: background 0.2s;
}
.btn-danger-discord:hover {
background: #c23235;
color: #fff;
}
[data-theme="dark"] .btn-close {
filter: invert(1) grayscale(100%) brightness(200%);
}
[data-theme="dark"] .table {
--bs-table-color: var(--text-main);
color: var(--text-main) !important;
}
[data-theme="dark"] .table thead th {
background: #292b2f;
color: var(--text-muted);
}
[data-theme="dark"] .text-muted {
color: var(--text-muted) !important;
}
/* Fix for the weight modal text */
[data-theme="dark"] .modal-body {
color: var(--text-main);
}
</style>
</head>
<body>
<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;">Caja</small></span>
<div class="ms-3">
<a href="/" class="btn btn-outline-primary btn-sm">
<i class="bi bi-box-seam me-1"></i>Inventario
</a>
</div>
<div class="ms-auto">
<div class="dropdown">
<button class="btn btn-accent dropdown-toggle" type="button" data-bs-toggle="dropdown"
aria-expanded="false">
<i class="bi bi-person-circle me-1"></i>
<span class="d-none d-sm-inline">{{ user.username }}</span>
</button>
<ul class="dropdown-menu dropdown-menu-end shadow">
<li>
<button class="dropdown-item" onclick="toggleTheme()">
<i class="bi bi-moon-stars me-2" id="theme-icon"></i>
<span id="theme-label">Modo Oscuro</span>
</button>
</li>
<li>
<hr class="dropdown-divider" style="border-color: var(--border);">
</li>
<li>
<a class="dropdown-item text-danger" href="/logout">
<i class="bi bi-box-arrow-right me-2"></i>Salir
</a>
</li>
</ul>
</div>
</div>
</nav>
<div class="container-fluid">
<div class="row g-3">
<div class="col-md-8">
<div class="cart-card p-3 shadow-sm">
<h4><i class="bi bi-cart3"></i> Carrito</h4>
<table class="table mt-3" id="cart-table">
<thead>
<tr>
<th>Producto</th>
<th>Precio/U</th>
<th>Cant/Peso</th>
<th>Subtotal</th>
<th></th>
</tr>
</thead>
<tbody id="cart-items">
</tbody>
</table>
</div>
</div>
<div class="col-md-4">
<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>
<div class="total-banner text-center mb-3">
<div class="total-banner text-center mb-3">
<h2 class="mb-0">TOTAL</h2>
<h1 id="grand-total" style="font-size: 3.5rem; font-weight: 800;">$0</h1>
</div>
<button class="btn btn-success w-100 btn-lg mb-2" onclick="processSale()">
<i class="bi bi-cash-coin"></i> COBRAR
</button>
<button class="btn btn-danger w-100" onclick="clearCart()">Vaciar</button>
</div>
</div>
</div>
<div class="modal fade" id="weightModal" tabindex="-1" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h5>Ingresar Peso (kg)</h5>
</div>
<div class="modal-body">
<input type="number" id="weight-input" class="form-control form-control-lg" step="0.001"
placeholder="0.000">
</div>
<div class="modal-footer">
<button class="btn btn-primary w-100" onclick="confirmWeight()">Agregar</button>
</div>
</div>
</div>
</div>
<script>
const socket = io();
let cart = [];
let pendingProduct = null;
const clp = new Intl.NumberFormat('es-CL', { style: 'currency', currency: 'CLP', minimumFractionDigits: 0 });
socket.on('new_scan', (product) => {
// Update the Preview Card
document.getElementById('display-name').innerText = product.name;
document.getElementById('display-barcode').innerText = product.barcode;
document.getElementById('display-img').src = product.image || './static/placeholder.png';
if (product.unit === 'kg') {
pendingProduct = product;
new bootstrap.Modal('#weightModal').show();
setTimeout(() => document.getElementById('weight-input').focus(), 500);
} else {
addToCart(product, 1);
}
});
socket.on('scan_error', (data) => {
if (confirm("Producto no encontrado. ¿Deseas crearlo?")) {
window.location.href = `/?barcode=${data.barcode}`;
}
});
function confirmWeight() {
const weight = parseFloat(document.getElementById('weight-input').value);
if (weight > 0) {
addToCart(pendingProduct, weight);
bootstrap.Modal.getInstance('#weightModal').hide();
document.getElementById('weight-input').value = '';
}
}
function addToCart(product, qty) {
const subtotal = product.price * qty;
cart.push({ ...product, qty, subtotal });
renderCart();
}
function renderCart() {
const tbody = document.getElementById('cart-items');
tbody.innerHTML = '';
let total = 0;
cart.forEach((item, index) => {
total += item.subtotal;
const row = document.createElement('tr');
row.innerHTML = `
<td>${item.name}</td>
<td>${clp.format(item.price)}</td>
<td>${item.qty} ${item.unit === 'kg' ? 'kg' : 'u'}</td>
<td>${clp.format(item.subtotal)}</td>
<td>
<button class="btn-danger-discord btn-sm" onclick="removeItem(${index}, '${item.name}')">
<i class="bi bi-trash"></i>
</button>
</td>
`;
tbody.appendChild(row);
});
document.getElementById('grand-total').innerText = clp.format(total);
}
// Updated removeItem with confirmation prompt
function removeItem(idx, name) {
if (confirm(`¿Quitar ${name} del carrito?`)) {
cart.splice(idx, 1);
renderCart();
}
}
function clearCart() { cart = []; renderCart(); }
function processSale() { alert("Venta procesada con éxito"); clearCart(); }
function applyTheme(t) {
document.documentElement.setAttribute('data-theme', t);
const isDark = t === 'dark';
const themeIcon = document.getElementById('theme-icon');
const themeLabel = document.getElementById('theme-label');
if (themeIcon) themeIcon.className = isDark ? 'bi bi-sun me-2' : 'bi bi-moon-stars me-2';
if (themeLabel) themeLabel.innerText = isDark ? 'Modo Claro' : 'Modo Oscuro';
localStorage.setItem('theme', t);
}
function toggleTheme() {
const current = document.documentElement.getAttribute('data-theme');
const next = current === 'dark' ? 'light' : 'dark';
applyTheme(next);
}
// Initialize on load
(function initTheme() {
const savedTheme = localStorage.getItem('theme') || 'light';
applyTheme(savedTheme);
})();
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

View File

@@ -261,7 +261,11 @@
<nav class="navbar navbar-expand-md sticky-top px-3 mb-3"> <nav class="navbar navbar-expand-md sticky-top px-3 mb-3">
<span class="navbar-brand">SekiPOS <small class="text-muted fw-normal" <span class="navbar-brand">SekiPOS <small class="text-muted fw-normal"
style="font-size:0.65rem;">v1.6</small></span> style="font-size:0.65rem;">v1.6</small></span>
<div class="ms-3">
<a href="/checkout" class="btn btn-outline-primary btn-sm">
<i class="bi bi-cart-fill me-1"></i>Ir a Caja
</a>
</div>
<!-- Always-visible dropdown on the right --> <!-- Always-visible dropdown on the right -->
<div class="ms-auto"> <div class="ms-auto">
<div class="dropdown"> <div class="dropdown">
@@ -714,11 +718,17 @@
const file = input.files[0]; const file = input.files[0];
if (!file) return; if (!file) return;
const formData = new FormData(); // Show a "loading" state if you feel like being fancy
formData.append('image', file); const originalBtnContent = document.querySelector('button[onclick*="camera-input"]').innerHTML;
formData.append('barcode', barcode); document.querySelector('button[onclick*="camera-input"]').innerHTML = '<span class="spinner-border spinner-border-sm"></span>';
try { try {
const compressedBlob = await compressImage(file, 800, 0.7); // Max 800px, 70% quality
const formData = new FormData();
formData.append('image', compressedBlob, `photo_${barcode}.jpg`);
formData.append('barcode', barcode);
const res = await fetch('/upload_image', { const res = await fetch('/upload_image', {
method: 'POST', method: 'POST',
body: formData body: formData
@@ -733,10 +743,46 @@
} }
} catch (err) { } catch (err) {
console.error(err); console.error(err);
alert("Error de conexión al subir imagen."); alert("Error procesando imagen.");
} finally {
document.querySelector('button[onclick*="camera-input"]').innerHTML = originalBtnContent;
} }
} }
// The compression engine
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);
};
img.onerror = err => reject(err);
};
reader.onerror = err => reject(err);
});
}
function applyBulkPrice() { function applyBulkPrice() {
const price = document.getElementById('bulk-price-input').value; const price = document.getElementById('bulk-price-input').value;
const checked = document.querySelectorAll('.product-checkbox:checked'); const checked = document.querySelectorAll('.product-checkbox:checked');