!function(){"use strict";var t="/pos/api/inventory",e=localStorage.getItem("pos_token");if(e){var o={Authorization:"Bearer "+e,"Content-Type":"application/json"},n=1,a="",r=null,i=window.switchTab;window.switchTab=function(t){"function"==typeof i&&i(t),"alertas"===t&&v(),"stock"===t&&m(n)};var s,d=document.getElementById("productSearch");d&&d.addEventListener("input",(function(){clearTimeout(s),s=setTimeout((function(){m(1,d.value.trim())}),350)})),window._loadItems=function(t){m(t)},window.loadItems=function(t,e){m(t,e)},window.viewHistory=function(e){c(t+"/items/"+e+"/history").then((function(t){if(t){var e=t.data||[],o="";e.length?(o='',e.forEach((function(t){var e=t.quantity>0?"var(--color-success)":"var(--color-error)";o+='"})),o+="
FechaTipoCantidadCostoEmpleadoNotas
'+u(t.date)+""+u(t.type)+''+(t.quantity>0?"+":"")+t.quantity+''+(t.cost?"$"+l(t.cost):"—")+""+u(t.employee)+''+u(t.notes)+"
"):o='

Sin movimientos

',document.getElementById("historyContent").innerHTML=o,document.getElementById("historyModal").classList.add("is-open")}}))},window.viewProductDetail=g,window.uploadItemImage=function(o){var n=document.createElement("input");n.type="file",n.accept="image/jpeg,image/png,image/webp",n.onchange=function(){if(n.files&&n.files[0]){var a=n.files[0];if(a.size>5242880)alert("Imagen demasiado grande (max 5 MB)");else{var r=new FormData;r.append("file",a);var i=document.getElementById("imgUploadStatus");i&&(i.textContent="Subiendo..."),fetch(t+"/items/"+o+"/image",{method:"POST",headers:{Authorization:"Bearer "+e},body:r}).then((function(t){return t.json()})).then((function(t){t.image_url?g(o):i&&(i.textContent=t.error||"Error")})).catch((function(){i&&(i.textContent="Error de red")}))}}},n.click()},window.deleteItemImage=function(o){confirm("Eliminar imagen de este producto?")&&fetch(t+"/items/"+o+"/image",{method:"DELETE",headers:{Authorization:"Bearer "+e}}).then((function(t){return t.json()})).then((function(t){t.message?g(o):alert(t.error||"Error")})).catch((function(){alert("Error de red")}))},window.closeHistoryModal=function(){document.getElementById("historyModal").classList.remove("is-open")},window.showCreateModal=function(){document.getElementById("createModal").classList.add("is-open");var e=document.getElementById("newPartNumber");e&&!e._classifyBound&&(e._classifyBound=!0,e.addEventListener("blur",(function(){var e=this.value.trim();if(!(e.length<3)){var o,n,a=document.getElementById("newName");if(!a||!a.value.trim())o=e,(n=document.getElementById("createResult")).innerHTML='Consultando IA...',c(t+"/classify/"+encodeURIComponent(o)).then((function(t){if(t){t.name&&(document.getElementById("newName").value=t.name),t.brand&&(document.getElementById("newBrand").value=t.brand);var e=[];t.name&&e.push(t.name),t.brand&&e.push(t.brand),t.vehicle&&e.push(t.vehicle),t.category&&e.push(t.category),e.length>0?n.innerHTML='Sugerido por IA: '+u(e.join(" | "))+"":n.innerHTML='IA no pudo identificar este numero de parte'}})).catch((function(){n.innerHTML=""}))}})))},window.closeCreateModal=function(){document.getElementById("createModal").classList.remove("is-open"),document.getElementById("createResult").innerHTML=""},window.createItem=function(){var e={part_number:document.getElementById("newPartNumber").value.trim(),name:document.getElementById("newName").value.trim(),brand:document.getElementById("newBrand").value.trim(),barcode:document.getElementById("newBarcode").value.trim()||void 0,cost:parseFloat(document.getElementById("newCost").value)||0,price_1:parseFloat(document.getElementById("newPrice1").value)||0,price_2:parseFloat(document.getElementById("newPrice2").value)||0,price_3:parseFloat(document.getElementById("newPrice3").value)||0,min_stock:parseInt(document.getElementById("newMinStock").value)||0,initial_stock:parseInt(document.getElementById("newInitialStock").value)||0,location:document.getElementById("newLocation").value.trim()};e.part_number&&e.name?c(t+"/items",{method:"POST",body:JSON.stringify(e)}).then((function(t){t&&t.id?(document.getElementById("createResult").innerHTML='Creado ID '+t.id+" | Barcode: "+t.barcode+"",m(n)):document.getElementById("createResult").innerHTML=''+(t?t.error||"Error":"Error de red")+""})):document.getElementById("createResult").innerHTML='Numero de parte y nombre son obligatorios'},window.showPurchaseModal=function(){document.getElementById("purchaseModal").classList.add("is-open")},window.closePurchaseModal=function(){document.getElementById("purchaseModal").classList.remove("is-open"),document.getElementById("purchaseResult").innerHTML=""},window.recordPurchase=function(){var e={inventory_id:parseInt(document.getElementById("purchaseItemId").value),quantity:parseInt(document.getElementById("purchaseQty").value),unit_cost:parseFloat(document.getElementById("purchaseCost").value),supplier_invoice:document.getElementById("purchaseInvoice").value.trim(),notes:document.getElementById("purchaseNotes").value.trim()};e.inventory_id&&e.quantity&&e.unit_cost?c(t+"/purchase",{method:"POST",body:JSON.stringify(e)}).then((function(t){document.getElementById("purchaseResult").innerHTML=t&&t.operation_id?'Compra registrada (op #'+t.operation_id+")":''+(t?t.error||"Error":"Error de red")+""})):document.getElementById("purchaseResult").innerHTML='Complete todos los campos obligatorios'},window.showAdjustmentModal=function(){document.getElementById("adjustmentModal").classList.add("is-open")},window.closeAdjustmentModal=function(){document.getElementById("adjustmentModal").classList.remove("is-open"),document.getElementById("adjustResult").innerHTML=""},window.recordAdjustment=function(){var e={inventory_id:parseInt(document.getElementById("adjustItemId").value),quantity:parseInt(document.getElementById("adjustQty").value),reason:document.getElementById("adjustReason").value.trim()};e.inventory_id&&void 0!==e.quantity&&e.reason?c(t+"/adjustment",{method:"POST",body:JSON.stringify(e)}).then((function(t){document.getElementById("adjustResult").innerHTML=t&&t.operation_id?'Ajuste registrado (op #'+t.operation_id+")":''+(t?t.error||"Error":"Error de red")+""})):document.getElementById("adjustResult").innerHTML='Complete todos los campos (razon obligatoria)'},window.showTransferModal=function(){document.getElementById("transferModal").classList.add("is-open")},window.closeTransferModal=function(){document.getElementById("transferModal").classList.remove("is-open"),document.getElementById("transferResult").innerHTML=""},window.recordTransfer=function(){var e={inventory_id:parseInt(document.getElementById("transferItemId").value),from_branch_id:parseInt(document.getElementById("transferFrom").value),to_branch_id:parseInt(document.getElementById("transferTo").value),quantity:parseInt(document.getElementById("transferQty").value),notes:document.getElementById("transferNotes").value.trim()};e.inventory_id&&e.from_branch_id&&e.to_branch_id&&e.quantity?c(t+"/transfer",{method:"POST",body:JSON.stringify(e)}).then((function(t){document.getElementById("transferResult").innerHTML=t&&t.out_operation_id?'Transferencia registrada':''+(t?t.error||"Error":"Error de red")+""})):document.getElementById("transferResult").innerHTML='Complete todos los campos'},window.showCountModal=function(){document.getElementById("countModal").classList.add("is-open"),document.querySelectorAll("#countLines .count-row").length||p()},window.closeCountModal=function(){document.getElementById("countModal").classList.remove("is-open")},window.addCountLine=p,window.startPhysicalCount=function(){var e=document.querySelectorAll("#countLines .count-row"),o=[];e.forEach((function(t){var e=parseInt(t.querySelector(".count-inv-id").value),n=parseInt(t.querySelector(".count-qty").value);e&&!isNaN(n)&&o.push({inventory_id:e,counted_quantity:n})})),o.length?c(t+"/physical-count/start",{method:"POST",body:JSON.stringify({items:o})}).then((function(t){if(t&&t.count_id){r=t.count_id;var e='

Borrador #'+t.count_id+" — "+u(t.message)+"

";e+='',(t.results||[]).forEach((function(t){var o=0===t.difference?"var(--color-success)":t.difference<0?"var(--color-error)":"var(--color-warning)";e+=""})),e+="
IDEsperadoContadoDiferencia
"+t.inventory_id+""+t.expected+""+t.counted+''+(t.difference>0?"+":"")+t.difference+"
",e+='
',e+='',e+='',e+="
",document.getElementById("countResults").innerHTML=e}else document.getElementById("countResults").innerHTML=''+(t?t.error||"Error":"Error de red")+""})):alert("Agregue al menos una linea")},window.approvePhysicalCount=function(){r?c(t+"/physical-count/approve",{method:"POST",body:JSON.stringify({count_id:r})}).then((function(t){t&&"approved"===t.status?(document.getElementById("countResults").innerHTML=''+u(t.message)+"",r=null):document.getElementById("countResults").innerHTML+='
'+(t?t.error||"Error":"Error de red")+""})):alert("No hay borrador activo")},window.cancelDraft=function(){r=null,document.getElementById("countResults").innerHTML='Borrador cancelado'},window.loadAlerts=v,window.printBarcode=function(t,e,o){var n=window.open("","_blank","width=400,height=250");n.document.write("Etiqueta"),n.document.write("

"+t+"

"),n.document.write("

"+e+"

"),n.document.write('

'+o+"

"),n.document.write(""),n.document.close(),n.print()},m(1)}else window.location.href="/pos/login";function c(t,e){return fetch(t,Object.assign({headers:o},e||{})).then((function(t){return 401===t.status?(localStorage.removeItem("pos_token"),window.location.href="/pos/login",null):t.json()}))}function l(t){return(parseFloat(t)||0).toFixed(2)}function u(t){if(!t)return"";var e=document.createElement("div");return e.textContent=t,e.innerHTML}function m(e,o){n=e||1,a=void 0!==o?o:a;var r=new URLSearchParams({page:n,per_page:50});a&&r.set("q",a),c(t+"/items?"+r.toString()).then((function(t){if(t){var e=document.getElementById("productTableBody"),o=t.data||[];if(!o.length)return e.innerHTML='Sin productos',void(document.getElementById("productPagination").innerHTML="");e.innerHTML=o.map((function(t){return''+u(t.barcode)+''+u(t.part_number)+''+u(t.name)+""+u(t.brand)+''+t.stock+'$'+l(t.cost)+'$'+l(t.price_1)+'$'+l(t.price_2)+'$'+l(t.price_3)+""+u(t.location)+' "})).join("");var n=t.pagination||{},a=document.getElementById("productPagination");n.total_pages>1?a.innerHTML='":a.innerHTML=''+(n.total||0)+" productos"}}))}function p(){var t=document.getElementById("countLines"),e=document.createElement("div");e.className="count-row",e.innerHTML='',t.appendChild(e)}function v(){c(t+"/alerts").then((function(t){if(t){var e=t.data||[],o=document.getElementById("alertsContent");if(o)if(e.length){var n="",a=e.filter((function(t){return"critical"===t.severity})),r=e.filter((function(t){return"warning"===t.severity})),i=e.filter((function(t){return"critical"!==t.severity&&"warning"!==t.severity}));a.length&&(n+='
Criticas
'+a.length+"
",n+='
',a.forEach((function(t){var e="zero"===t.type?"AGOTADO":"low"===t.type?"BAJO":t.type.toUpperCase();n+=y(t,e,"critical")})),n+="
"),r.length&&(n+='
Advertencias
'+r.length+"
",n+='
',r.forEach((function(t){n+=y(t,"EXCESO","warning")})),n+="
"),i.length&&(n+='
Informativas
'+i.length+"
",n+='
',i.forEach((function(t){n+=y(t,"INFO","info")})),n+="
"),o.innerHTML=n}else o.innerHTML='

Sin alertas activas

'}}))}function y(t,e,o){return'
['+e+"] "+u(t.part_number)+" — "+u(t.name)+'
Stock: '+t.stock+(t.min_stock?" (min: "+t.min_stock+")":"")+(t.max_stock?" (max: "+t.max_stock+")":"")+" · Sucursal "+t.branch_id+"
"}function g(o){c(t+"/items/"+o).then((function(t){if(t&&!t.error){var n=t.history||[],a="";a+='
',t.image_url?(a+=''+u(t.name)+'',a+='
',a+='',a+='',a+="
"):(a+='
',a+='',a+='
Sin imagen
',a+="
",a+=''),a+='',a+="
",a+='
',a+='
No. Parte'+u(t.part_number)+"
",a+='
Nombre'+u(t.name)+"
",a+='
Marca'+u(t.brand)+"
",a+='
Codigo de Barras'+u(t.barcode)+"
",a+='
Ubicacion'+u(t.location||"-")+"
",a+='
Stock'+(t.stock||0)+"
",a+="
",a+='
',a+='
Costo$'+l(t.cost)+"
",a+='
Precio 1$'+l(t.price_1)+"
",a+='
Precio 2$'+l(t.price_2)+"
",a+='
Precio 3$'+l(t.price_3)+"
",a+="
",a+='
Cross-References / Equivalencias
',a+='
',a+='

Cargando equivalencias...

',a+="
";var r,i=t.part_number,s=t.catalog_part_id;r=s?"/pos/api/catalog/part/"+s:"/pos/api/catalog/search?q="+encodeURIComponent(i),fetch(r,{headers:{Authorization:"Bearer "+e}}).then((function(t){return t.json()})).then((function(t){var o=document.getElementById("crossRefContent");if(o){var n=t.alternatives||[],a=t.bodegas||[];!s&&t.data&&t.data.length>0?fetch("/pos/api/catalog/part/"+t.data[0].id_part,{headers:{Authorization:"Bearer "+e}}).then((function(t){return t.json()})).then((function(t){d(o,t.alternatives||[],t.bodegas||[])})).catch((function(){o.innerHTML='

Sin conexion al catalogo.

'})):d(o,n,a)}})).catch((function(){var t=document.getElementById("crossRefContent");t&&(t.innerHTML='

Sin conexion al catalogo central.

')})),a+='
Vehiculos Compatibles
',a+='
',a+='

Cargando compatibilidades...

',a+="
",fetch("/pos/api/inventory/items/"+o+"/vehicles",{headers:{Authorization:"Bearer "+e}}).then((function(t){return t.json()})).then((function(t){var e=document.getElementById("compatContent");if(e){var n=t.vehicles||[],a="";n.length>0?(a+='',n.forEach((function(t){a+="",a+=''})),a+="
MarcaModeloAnoMotorOrigen
"+u(t.brand||"")+""+u(t.model||"")+""+u(t.year||"")+""+u(t.engine||"")+""+u(t.source||"")+"
"):a+='

Sin vehiculos vinculados.

',a+='
Busca en catalogo central y vincula automaticamente
',e.innerHTML=a}})).catch((function(){var t=document.getElementById("compatContent");t&&(t.innerHTML='

Error al cargar compatibilidades.

')})),a+='
Historial de Movimientos
',n.length?(a+='',n.forEach((function(t){var e=t.quantity>0?"var(--color-success)":"var(--color-error)";a+='"})),a+="
FechaTipoCantidadCostoEmpleadoNotas
'+u(t.date)+""+u(t.type)+''+(t.quantity>0?"+":"")+t.quantity+''+(t.cost?"$"+l(t.cost):"—")+""+u(t.employee)+''+u(t.notes)+"
"):a+='

Sin movimientos

',document.getElementById("historyContent").innerHTML=a,document.getElementById("historyModal").classList.add("is-open")}else alert(t?t.error:"Error de red");function d(t,e,o){var n="";o&&o.length>0&&(n+='
Disponible en Bodegas:
',n+='',o.forEach((function(t){n+=""})),n+="
BodegaStockPrecioUbicacion
"+u(t.business_name||t.bodega||"")+""+(t.stock||t.stock_quantity||0)+'$'+l(t.price||0)+""+u(t.location||t.warehouse_location||"")+"
"),e&&e.length>0&&(n+='
Partes Equivalentes (Aftermarket):
',n+='',e.forEach((function(t){n+='"})),n+="
No. ParteFabricanteNombre
'+u(t.part_number||t.cross_reference_number||"")+""+u(t.manufacturer||t.source_ref||"")+""+u(t.name||t.name_aftermarket_parts||"")+"
"),n||(n='

No se encontraron equivalencias para esta parte.

'),t.innerHTML=n}}))}}();