Spaces:
Running

inventory-request / index.html
Marckxb's picture
crea una base datos en SQL para almacenar los datos y hacer las consultas. - Follow Up Deployment
5788d15 verified
Raw History Blame Contribute Delete
44.3 kB
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sistema de Solicitud de Partes - Máquinas Tragamonedas</title>
<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
.tab-content {
display: none;
}
.tab-content.active {
display: block;
}
.tab-button.active {
background-color: #3b82f6;
color: white;
}
.autocomplete-items {
position: absolute;
border: 1px solid #d4d4d4;
border-bottom: none;
border-top: none;
z-index: 99;
top: 100%;
left: 0;
right: 0;
}
.autocomplete-items div {
padding: 10px;
cursor: pointer;
background-color: #fff;
border-bottom: 1px solid #d4d4d4;
}
.autocomplete-items div:hover {
background-color: #e9e9e9;
}
.autocomplete-active {
background-color: DodgerBlue !important;
color: #ffffff;
}
</style>
</head>
<body class="bg-gray-100">
<div class="container mx-auto p-4 max-w-6xl">
<h1 class="text-3xl font-bold text-center mb-8 text-blue-800">
<i class="fas fa-sliders-h mr-2"></i>Sistema de Solicitud de Partes
</h1>
<!-- Tab Navigation -->
<div class="flex border-b mb-6">
<button class="tab-button py-2 px-4 font-medium rounded-t-lg hover:bg-blue-100 active" onclick="openTab(event, 'request-tab')">
<i class="fas fa-file-alt mr-2"></i>Solicitud
</button>
<button class="tab-button py-2 px-4 font-medium rounded-t-lg hover:bg-blue-100" onclick="openTab(event, 'database-tab')">
<i class="fas fa-database mr-2"></i>Base de Datos
</button>
<button class="tab-button py-2 px-4 font-medium rounded-t-lg hover:bg-blue-100" onclick="openTab(event, 'query-tab')">
<i class="fas fa-search mr-2"></i>Consulta
</button>
</div>
<!-- Request Tab -->
<div id="request-tab" class="tab-content active bg-white p-6 rounded-lg shadow-md">
<h2 class="text-2xl font-semibold mb-4 text-blue-700">
<i class="fas fa-plus-circle mr-2"></i>Nueva Solicitud
</h2>
<div class="mb-4 p-4 bg-blue-50 rounded-lg">
<span class="font-bold">Número de Solicitud:</span>
<span id="request-number" class="ml-2 px-3 py-1 bg-blue-100 rounded-full">00001</span>
</div>
<form id="request-form" class="space-y-4">
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<!-- CodeSAP Field with Autocomplete -->
<div class="autocomplete">
<label for="codeSAP" class="block text-sm font-medium text-gray-700 mb-1">
<i class="fas fa-barcode mr-1"></i>CodeSAP *
</label>
<input type="text" id="codeSAP" name="codeSAP" minlength="10" maxlength="10"
class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
required placeholder="Ingrese el código SAP">
</div>
<!-- Material Description (auto-filled) -->
<div>
<label for="materialDesc" class="block text-sm font-medium text-gray-700 mb-1">
<i class="fas fa-file-alt mr-1"></i>Material Description
</label>
<input type="text" id="materialDesc" name="materialDesc" readonly
class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm bg-gray-100">
</div>
<!-- SAGE (auto-filled) -->
<div>
<label for="sage" class="block text-sm font-medium text-gray-700 mb-1">
<i class="fas fa-hashtag mr-1"></i>SAGE
</label>
<input type="number" id="sage" name="sage" readonly
class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm bg-gray-100">
</div>
<!-- QTY -->
<div>
<label for="qty" class="block text-sm font-medium text-gray-700 mb-1">
<i class="fas fa-cubes mr-1"></i>Cantidad (QTY) *
</label>
<input type="number" id="qty" name="qty" step="1"
class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
required placeholder="Ingrese cantidad positiva o negativa">
</div>
<!-- Origen -->
<div>
<label for="origin" class="block text-sm font-medium text-gray-700 mb-1">
<i class="fas fa-map-marker-alt mr-1"></i>Origen *
</label>
<select id="origin" name="origin"
class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500" required>
<option value="">Seleccione origen</option>
<option value="ALM001">Almacén Principal</option>
<option value="ALM002">Almacén Secundario</option>
<option value="TAL001">Taller Mecánico</option>
<option value="ELE001">Área Eléctrica</option>
<option value="PRO001">Producción</option>
</select>
</div>
<!-- Destino -->
<div>
<label for="destination" class="block text-sm font-medium text-gray-700 mb-1">
<i class="fas fa-map-marked-alt mr-1"></i>Destino *
</label>
<select id="destination" name="destination"
class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500" required>
<option value="">Seleccione destino</option>
<option value="ALM001">Almacén Principal</option>
<option value="ALM002">Almacén Secundario</option>
<option value="TAL001">Taller Mecánico</option>
<option value="ELE001">Área Eléctrica</option>
<option value="PRO001">Producción</option>
</select>
</div>
<!-- Factory -->
<div>
<label for="factory" class="block text-sm font-medium text-gray-700 mb-1">
<i class="fas fa-industry mr-1"></i>Factory (6 dígitos) *
</label>
<input type="number" id="factory" name="factory" min="100000" max="999999"
class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
required placeholder="123456">
</div>
<!-- Serial -->
<div>
<label for="serial" class="block text-sm font-medium text-gray-700 mb-1">
<i class="fas fa-barcode mr-1"></i>Serial (40 caracteres)
</label>
<input type="text" id="serial" name="serial" maxlength="40"
class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
placeholder="Número de serie del componente">
</div>
</div>
<!-- Movement Type -->
<div class="mt-4">
<label for="movementType" class="block text-sm font-medium text-gray-700 mb-1">
<i class="fas fa-exchange-alt mr-1"></i>Tipo de Movimiento *
</label>
<select id="movementType" name="movementType"
class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500" required>
<option value="">Seleccione tipo de movimiento</option>
<option value="MEA">MEA - Movimiento entre almacenes</option>
<option value="MSA">MSA - Movimiento salida a área</option>
<option value="MASG">MASG - Movimiento ajuste ganancia</option>
<option value="MMM">MMM - Movimiento mantenimiento máquina</option>
</select>
</div>
<!-- Notes -->
<div class="mt-4">
<label for="notes" class="block text-sm font-medium text-gray-700 mb-1">
<i class="fas fa-sticky-note mr-1"></i>Notas
</label>
<textarea id="notes" name="notes" rows="3"
class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
placeholder="Comentarios relevantes sobre la solicitud"></textarea>
</div>
<!-- Buttons -->
<div class="flex justify-end space-x-4 mt-6">
<button type="reset" class="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
<i class="fas fa-eraser mr-1"></i>Limpiar
</button>
<button type="button" onclick="confirmSubmit()" class="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
<i class="fas fa-save mr-1"></i>Guardar Solicitud
</button>
</div>
</form>
</div>
<!-- Database Tab -->
<div id="database-tab" class="tab-content bg-white p-6 rounded-lg shadow-md">
<h2 class="text-2xl font-semibold mb-4 text-blue-700">
<i class="fas fa-database mr-2"></i>Administración de Base de Datos
</h2>
<div class="mb-6">
<div class="flex space-x-4 mb-4">
<div class="flex-1">
<label for="search-type" class="block text-sm font-medium text-gray-700 mb-1">
<i class="fas fa-filter mr-1"></i>Buscar por:
</label>
<select id="search-type" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
<option value="request-id">ID de Solicitud</option>
<option value="code-sap">CodeSAP</option>
</select>
</div>
<div class="flex-1">
<label for="search-value" class="block text-sm font-medium text-gray-700 mb-1">
<i class="fas fa-search mr-1"></i>Valor a buscar:
</label>
<div class="flex">
<input type="text" id="search-value"
class="flex-1 px-3 py-2 border border-gray-300 rounded-l-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
placeholder="Ingrese valor">
<button onclick="searchDatabase()" class="px-4 py-2 bg-blue-600 text-white rounded-r-md hover:bg-blue-700">
<i class="fas fa-search"></i>
</button>
</div>
</div>
</div>
<div class="overflow-x-auto">
<table class="min-w-full divide-y divide-gray-200">
<thead class="bg-gray-50">
<tr>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">CodeSAP</th>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Descripción</th>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">SAGE</th>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Stock</th>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Acciones</th>
</tr>
</thead>
<tbody id="database-results" class="bg-white divide-y divide-gray-200">
<!-- Results will be inserted here by JavaScript -->
</tbody>
</table>
</div>
</div>
<div id="edit-form-container" class="hidden mt-8 p-4 border border-gray-200 rounded-lg">
<h3 class="text-lg font-medium mb-4">
<i class="fas fa-edit mr-1"></i>Editar Registro
</h3>
<form id="edit-form" class="space-y-4">
<input type="hidden" id="edit-id">
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label for="edit-codeSAP" class="block text-sm font-medium text-gray-700 mb-1">CodeSAP</label>
<input type="text" id="edit-codeSAP" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm">
</div>
<div>
<label for="edit-materialDesc" class="block text-sm font-medium text-gray-700 mb-1">Material Description</label>
<input type="text" id="edit-materialDesc" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm">
</div>
<div>
<label for="edit-sage" class="block text-sm font-medium text-gray-700 mb-1">SAGE</label>
<input type="number" id="edit-sage" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm">
</div>
<div>
<label for="edit-stock" class="block text-sm font-medium text-gray-700 mb-1">Stock</label>
<input type="number" id="edit-stock" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm">
</div>
</div>
<div class="flex justify-end space-x-4">
<button type="button" onclick="cancelEdit()" class="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50">
Cancelar
</button>
<button type="button" onclick="saveEdit()" class="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-green-600 hover:bg-green-700">
Guardar Cambios
</button>
<button type="button" onclick="confirmDelete()" class="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-red-600 hover:bg-red-700">
Eliminar
</button>
</div>
</form>
</div>
</div>
<!-- Query Tab -->
<div id="query-tab" class="tab-content bg-white p-6 rounded-lg shadow-md">
<h2 class="text-2xl font-semibold mb-4 text-blue-700">
<i class="fas fa-search mr-2"></i>Consultas
</h2>
<div class="mb-6">
<div class="flex space-x-4 mb-4">
<div class="flex-1">
<label for="query-type" class="block text-sm font-medium text-gray-700 mb-1">
<i class="fas fa-filter mr-1"></i>Consultar por:
</label>
<select id="query-type" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
<option value="request-id">ID de Solicitud</option>
<option value="code-sap">CodeSAP</option>
</select>
</div>
<div class="flex-1">
<label for="query-value" class="block text-sm font-medium text-gray-700 mb-1">
<i class="fas fa-search mr-1"></i>Valor a consultar:
</label>
<div class="flex">
<input type="text" id="query-value"
class="flex-1 px-3 py-2 border border-gray-300 rounded-l-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
placeholder="Ingrese valor">
<button onclick="executeQuery()" class="px-4 py-2 bg-blue-600 text-white rounded-r-md hover:bg-blue-700">
<i class="fas fa-search"></i>
</button>
</div>
</div>
</div>
<div class="overflow-x-auto">
<table class="min-w-full divide-y divide-gray-200">
<thead class="bg-gray-50">
<tr>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Fecha</th>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">CodeSAP</th>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Descripción</th>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Cantidad</th>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Origen</th>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Destino</th>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Tipo Mov.</th>
</tr>
</thead>
<tbody id="query-results" class="bg-white divide-y divide-gray-200">
<!-- Results will be inserted here by JavaScript -->
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- Confirmation Modal -->
<div id="confirmation-modal" class="fixed inset-0 bg-gray-600 bg-opacity-50 flex items-center justify-center hidden">
<div class="bg-white p-6 rounded-lg shadow-xl max-w-md w-full">
<h3 class="text-lg font-medium mb-4" id="modal-title">Confirmación</h3>
<p class="mb-4" id="modal-message">¿Está seguro que desea guardar esta solicitud?</p>
<div class="flex justify-end space-x-4">
<button onclick="hideModal()" class="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50">
Cancelar
</button>
<button onclick="submitRequest()" class="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700">
Confirmar
</button>
</div>
</div>
</div>
<!-- Alert Modal -->
<div id="alert-modal" class="fixed inset-0 bg-gray-600 bg-opacity-50 flex items-center justify-center hidden">
<div class="bg-white p-6 rounded-lg shadow-xl max-w-md w-full">
<div class="flex items-start mb-4">
<div class="flex-shrink-0">
<i class="fas fa-exclamation-triangle text-yellow-500 text-2xl"></i>
</div>
<div class="ml-3">
<h3 class="text-lg font-medium" id="alert-title">Advertencia</h3>
<p class="mt-1 text-sm text-gray-500" id="alert-message">No hay suficiente stock para realizar esta operación.</p>
</div>
</div>
<div class="flex justify-end">
<button onclick="hideAlert()" class="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700">
Aceptar
</button>
</div>
</div>
</div>
<script>
// SQL Database setup (simulated with localStorage for this demo)
function initDatabase() {
if (!localStorage.getItem('slotMachinePartsDB')) {
const db = {
materials: [
{ id: 1, codeSAP: "TRG0012345", materialDesc: "Rodamiento para carrete", sage: 789456, stock: 15 },
{ id: 2, codeSAP: "TRG0012346", materialDesc: "Motor principal 220V", sage: 789457, stock: 8 },
{ id: 3, codeSAP: "TRG0012347", materialDesc: "Pantalla LED táctil", sage: 789458, stock: 5 },
{ id: 4, codeSAP: "TRG0012348", materialDesc: "Tarjeta controladora", sage: 789459, stock: 12 },
{ id: 5, codeSAP: "TRG0012349", materialDesc: "Cableado eléctrico", sage: 789460, stock: 25 }
],
requests: [
{ id: 1, date: new Date().toISOString().split('T')[0], codeSAP: "TRG0012345", materialDesc: "Rodamiento para carrete", qty: -2, origin: "ALM001", destination: "TAL001", movementType: "MSA" },
{ id: 2, date: new Date().toISOString().split('T')[0], codeSAP: "TRG0012346", materialDesc: "Motor principal 220V", qty: -1, origin: "ALM001", destination: "ELE001", movementType: "MSA" },
{ id: 3, date: new Date().toISOString().split('T')[0], codeSAP: "TRG0012347", materialDesc: "Pantalla LED táctil", qty: 3, origin: "PRO001", destination: "ALM001", movementType: "MEA" },
{ id: 4, date: new Date().toISOString().split('T')[0], codeSAP: "TRG0012348", materialDesc: "Tarjeta controladora", qty: -1, origin: "ALM001", destination: "TAL001", movementType: "MMM" }
],
locations: [
{ code: "ALM001", name: "Almacén Principal" },
{ code: "ALM002", name: "Almacén Secundario" },
{ code: "TAL001", name: "Taller Mecánico" },
{ code: "ELE001", name: "Área Eléctrica" },
{ code: "PRO001", name: "Producción" }
],
nextRequestId: 5,
nextMaterialId: 6
};
localStorage.setItem('slotMachinePartsDB', JSON.stringify(db));
}
}
// Database operations
function getDB() {
return JSON.parse(localStorage.getItem('slotMachinePartsDB'));
}
function saveDB(db) {
localStorage.setItem('slotMachinePartsDB', JSON.stringify(db));
}
// SQL-like query functions
function queryMaterials(whereClause = '') {
const db = getDB();
let materials = db.materials;
if (whereClause.includes('codeSAP LIKE')) {
const searchTerm = whereClause.split("'")[1].replace('%', '');
materials = materials.filter(m => m.codeSAP.includes(searchTerm));
}
return materials;
}
function queryRequests(whereClause = '') {
const db = getDB();
let requests = db.requests;
if (whereClause.includes('id =')) {
const id = parseInt(whereClause.split('=')[1].trim());
requests = requests.filter(r => r.id === id);
} else if (whereClause.includes('codeSAP LIKE')) {
const searchTerm = whereClause.split("'")[1].replace('%', '');
requests = requests.filter(r => r.codeSAP.includes(searchTerm));
}
return requests;
}
function getMaterialByCodeSAP(codeSAP) {
const db = getDB();
return db.materials.find(m => m.codeSAP === codeSAP);
}
function getLocationName(code) {
const db = getDB();
const location = db.locations.find(l => l.code === code);
return location ? location.name : code;
}
// Current request number (would come from database in real app)
let currentRequestNumber = 1;
// Tab functionality
function openTab(evt, tabName) {
const tabContents = document.getElementsByClassName("tab-content");
for (let i = 0; i < tabContents.length; i++) {
tabContents[i].classList.remove("active");
}
const tabButtons = document.getElementsByClassName("tab-button");
for (let i = 0; i < tabButtons.length; i++) {
tabButtons[i].classList.remove("active");
}
document.getElementById(tabName).classList.add("active");
evt.currentTarget.classList.add("active");
}
// Autocomplete for CodeSAP
function autocomplete(inp, arr) {
let currentFocus;
inp.addEventListener("input", function(e) {
let a, b, i, val = this.value;
closeAllLists();
if (!val) { return false; }
currentFocus = -1;
a = document.createElement("DIV");
a.setAttribute("id", this.id + "autocomplete-list");
a.setAttribute("class", "autocomplete-items");
this.parentNode.appendChild(a);
for (i = 0; i < arr.length; i++) {
if (arr[i].codeSAP.substr(0, val.length).toUpperCase() == val.toUpperCase()) {
b = document.createElement("DIV");
b.innerHTML = "<strong>" + arr[i].codeSAP.substr(0, val.length) + "</strong>";
b.innerHTML += arr[i].codeSAP.substr(val.length);
b.innerHTML += "<br><small>" + arr[i].materialDesc + "</small>";
b.innerHTML += "<input type='hidden' value='" + arr[i].codeSAP + "'>";
b.addEventListener("click", function(e) {
inp.value = this.getElementsByTagName("input")[0].value;
closeAllLists();
// Fill the related fields
const selectedItem = arr.find(item => item.codeSAP === inp.value);
if (selectedItem) {
document.getElementById("materialDesc").value = selectedItem.materialDesc;
document.getElementById("sage").value = selectedItem.sage;
}
});
a.appendChild(b);
}
}
});
inp.addEventListener("keydown", function(e) {
let x = document.getElementById(this.id + "autocomplete-list");
if (x) x = x.getElementsByTagName("div");
if (e.keyCode == 40) { // Down arrow
currentFocus++;
addActive(x);
} else if (e.keyCode == 38) { // Up arrow
currentFocus--;
addActive(x);
} else if (e.keyCode == 13) { // Enter
e.preventDefault();
if (currentFocus > -1) {
if (x) x[currentFocus].click();
}
}
});
function addActive(x) {
if (!x) return false;
removeActive(x);
if (currentFocus >= x.length) currentFocus = 0;
if (currentFocus < 0) currentFocus = (x.length - 1);
x[currentFocus].classList.add("autocomplete-active");
}
function removeActive(x) {
for (let i = 0; i < x.length; i++) {
x[i].classList.remove("autocomplete-active");
}
}
function closeAllLists(elmnt) {
const x = document.getElementsByClassName("autocomplete-items");
for (let i = 0; i < x.length; i++) {
if (elmnt != x[i] && elmnt != inp) {
x[i].parentNode.removeChild(x[i]);
}
}
}
document.addEventListener("click", function (e) {
closeAllLists(e.target);
});
}
// Initialize autocomplete
autocomplete(document.getElementById("codeSAP"), sampleDatabase);
// Form submission
function confirmSubmit() {
const form = document.getElementById("request-form");
if (!form.checkValidity()) {
form.reportValidity();
return;
}
const qty = parseInt(document.getElementById("qty").value);
const codeSAP = document.getElementById("codeSAP").value;
// Check if we're subtracting and if there's enough stock
if (qty < 0) {
const item = sampleDatabase.find(i => i.codeSAP === codeSAP);
if (item && item.stock < Math.abs(qty)) {
showAlert("Stock insuficiente", `No hay suficiente stock para realizar esta operación. Stock actual: ${item.stock}`);
return;
}
}
showModal("Confirmación", "¿Está seguro que desea guardar esta solicitud?");
}
function submitRequest() {
hideModal();
const db = getDB();
const form = document.getElementById("request-form");
const codeSAP = form.codeSAP.value;
const qty = parseInt(form.qty.value);
// Update material stock
const material = db.materials.find(m => m.codeSAP === codeSAP);
if (material) {
material.stock += qty;
// Create new request
const newRequest = {
id: db.nextRequestId++,
date: new Date().toISOString().split('T')[0],
codeSAP: codeSAP,
materialDesc: form.materialDesc.value,
qty: qty,
origin: form.origin.value,
destination: form.destination.value,
movementType: form.movementType.value,
factory: form.factory.value,
serial: form.serial.value,
notes: form.notes.value
};
db.requests.push(newRequest);
saveDB(db);
// Update UI
document.getElementById("request-number").textContent = db.nextRequestId.toString().padStart(5, '0');
form.reset();
showAlert("Éxito", "La solicitud ha sido guardada correctamente.");
// Refresh queries
searchDatabase();
executeQuery();
}
}
// Database search
function searchDatabase() {
const searchType = document.getElementById("search-type").value;
const searchValue = document.getElementById("search-value").value;
const resultsContainer = document.getElementById("database-results");
resultsContainer.innerHTML = "";
let results = [];
if (searchType === "request-id") {
results = queryRequests(`id = ${searchValue}`);
} else if (searchType === "code-sap") {
results = queryMaterials(`codeSAP LIKE '%${searchValue}%'`);
}
if (results.length === 0) {
resultsContainer.innerHTML = `<tr><td colspan="6" class="px-6 py-4 text-center text-gray-500">No se encontraron resultados</td></tr>`;
return;
}
results.forEach(item => {
const row = document.createElement("tr");
row.innerHTML = `
<td class="px-6 py-4 whitespace-nowrap">${item.id}</td>
<td class="px-6 py-4 whitespace-nowrap">${item.codeSAP}</td>
<td class="px-6 py-4">${item.materialDesc}</td>
<td class="px-6 py-4 whitespace-nowrap">${item.sage}</td>
<td class="px-6 py-4 whitespace-nowrap">${item.stock}</td>
<td class="px-6 py-4 whitespace-nowrap">
<button onclick="editItem(${item.id})" class="text-blue-600 hover:text-blue-900 mr-3">
<i class="fas fa-edit"></i>
</button>
<button onclick="deleteItem(${item.id})" class="text-red-600 hover:text-red-900">
<i class="fas fa-trash-alt"></i>
</button>
</td>
`;
resultsContainer.appendChild(row);
});
}
// Query execution
function executeQuery() {
const queryType = document.getElementById("query-type").value;
const queryValue = document.getElementById("query-value").value.toLowerCase();
const resultsContainer = document.getElementById("query-results");
resultsContainer.innerHTML = "";
let results = [];
if (queryType === "request-id") {
results = sampleRequests.filter(req =>
req.id.toString().includes(queryValue)
);
} else if (queryType === "code-sap") {
results = sampleRequests.filter(req =>
req.codeSAP.toLowerCase().includes(queryValue) ||
req.materialDesc.toLowerCase().includes(queryValue)
);
}
if (results.length === 0) {
resultsContainer.innerHTML = `<tr><td colspan="8" class="px-6 py-4 text-center text-gray-500">No se encontraron resultados</td></tr>`;
return;
}
results.forEach(req => {
const row = document.createElement("tr");
row.innerHTML = `
<td class="px-6 py-4 whitespace-nowrap">${req.id}</td>
<td class="px-6 py-4 whitespace-nowrap">${req.date}</td>
<td class="px-6 py-4 whitespace-nowrap">${req.codeSAP}</td>
<td class="px-6 py-4">${req.materialDesc}</td>
<td class="px-6 py-4 whitespace-nowrap">${req.qty > 0 ? '+' : ''}${req.qty}</td>
<td class="px-6 py-4 whitespace-nowrap">${getLocationName(req.origin)}</td>
<td class="px-6 py-4 whitespace-nowrap">${getLocationName(req.destination)}</td>
<td class="px-6 py-4 whitespace-nowrap">${req.movementType}</td>
`;
resultsContainer.appendChild(row);
});
}
function getLocationName(code) {
const locations = {
"ALM001": "Almacén Principal",
"ALM002": "Almacén Secundario",
"TAL001": "Taller Mecánico",
"ELE001": "Área Eléctrica",
"PRO001": "Producción"
};
return locations[code] || code;
}
// Database CRUD operations
function editItem(id) {
const item = sampleDatabase.find(i => i.id === id);
if (!item) return;
document.getElementById("edit-id").value = item.id;
document.getElementById("edit-codeSAP").value = item.codeSAP;
document.getElementById("edit-materialDesc").value = item.materialDesc;
document.getElementById("edit-sage").value = item.sage;
document.getElementById("edit-stock").value = item.stock;
document.getElementById("edit-form-container").classList.remove("hidden");
}
function saveEdit() {
const id = parseInt(document.getElementById("edit-id").value);
const item = sampleDatabase.find(i => i.id === id);
if (!item) return;
// In a real app, this would send to a server
item.codeSAP = document.getElementById("edit-codeSAP").value;
item.materialDesc = document.getElementById("edit-materialDesc").value;
item.sage = parseInt(document.getElementById("edit-sage").value);
item.stock = parseInt(document.getElementById("edit-stock").value);
cancelEdit();
searchDatabase();
showAlert("Éxito", "Los cambios han sido guardados correctamente.");
}
function cancelEdit() {
document.getElementById("edit-form").reset();
document.getElementById("edit-form-container").classList.add("hidden");
}
function deleteItem(id) {
const item = sampleDatabase.find(i => i.id === id);
if (!item) return;
document.getElementById("edit-id").value = item.id;
showModal("Confirmar eliminación", `¿Está seguro que desea eliminar el registro ${item.codeSAP} - ${item.materialDesc}?`, "confirmDelete");
}
function confirmDelete() {
const id = parseInt(document.getElementById("edit-id").value);
const index = sampleDatabase.findIndex(i => i.id === id);
if (index !== -1) {
// In a real app, this would send to a server
sampleDatabase.splice(index, 1);
hideModal();
searchDatabase();
showAlert("Éxito", "El registro ha sido eliminado correctamente.");
}
}
// Modal functions
function showModal(title, message, action = "submitRequest") {
document.getElementById("modal-title").textContent = title;
document.getElementById("modal-message").textContent = message;
document.getElementById("confirmation-modal").classList.remove("hidden");
// Update the confirm button's onclick based on the action
const confirmBtn = document.querySelector("#confirmation-modal button:last-child");
confirmBtn.onclick = window[action];
}
function hideModal() {
document.getElementById("confirmation-modal").classList.add("hidden");
}
function showAlert(title, message) {
document.getElementById("alert-title").textContent = title;
document.getElementById("alert-message").textContent = message;
document.getElementById("alert-modal").classList.remove("hidden");
}
function hideAlert() {
document.getElementById("alert-modal").classList.add("hidden");
}
// Initialize
document.addEventListener("DOMContentLoaded", function() {
initDatabase();
const db = getDB();
// Set initial request number
document.getElementById("request-number").textContent = db.nextRequestId.toString().padStart(5, '0');
// Populate location dropdowns
const originSelect = document.getElementById("origin");
const destinationSelect = document.getElementById("destination");
db.locations.forEach(location => {
const option1 = document.createElement("option");
option1.value = location.code;
option1.textContent = location.name;
originSelect.appendChild(option1);
const option2 = document.createElement("option");
option2.value = location.code;
option2.textContent = location.name;
destinationSelect.appendChild(option2);
});
// Perform initial searches
searchDatabase();
executeQuery();
});
</script>
<p style="border-radius: 8px; text-align: center; font-size: 12px; color: #fff; margin-top: 16px;position: fixed; left: 8px; bottom: 8px; z-index: 10; background: rgba(0, 0, 0, 0.8); padding: 4px 8px;">Made with <img src="https://deepsite.hf.co/logo.svg" alt="DeepSite Logo" style="width: 16px; height: 16px; vertical-align: middle;display:inline-block;margin-right:3px;filter:brightness(0) invert(1);"><a href="https://deepsite.hf.co" style="color: #fff;text-decoration: underline;" target="_blank" >DeepSite</a> - 🧬 <a href="https://deepsite.hf.co?remix=Marckxb/inventory-request" style="color: #fff;text-decoration: underline;" target="_blank" >Remix</a></p></body>
</html>