/** * workshop.js — Taller / Service Orders for Nexus POS * Supports list + kanban views, filters, bitacora and role-based price hiding. */ var Workshop = (function() { 'use strict'; var API = '/pos/api/service-orders'; var token = localStorage.getItem('pos_token'); var orders = []; var catalog = []; var customers = []; var vehicles = []; var employees = []; var couriers = []; var branches = []; var currentOrderId = null; var currentOrder = null; var currentView = 'list'; var currentPage = 1; var perPage = 25; var user = window.POS_USER || {}; var role = (user.role || '').toLowerCase(); var hidePrices = role === 'workshop' || role === 'mechanic'; var perms = user.permissions || []; var canEdit = role === 'owner' || role === 'admin' || perms.indexOf('workshop.edit') !== -1; var canSell = role === 'owner' || role === 'admin' || perms.indexOf('pos.sell') !== -1; var COLUMNS = [ {key: 'received', label: 'Recibido'}, {key: 'diagnosis', label: 'Diagnóstico'}, {key: 'waiting_parts', label: 'Espera refacciones'}, {key: 'repair', label: 'En reparación'}, {key: 'quality_check', label: 'Control calidad'}, {key: 'ready', label: 'Listo'}, {key: 'delivered', label: 'Entregado'}, ]; var STATUS_LABELS = { received: 'Recibido', diagnosis: 'Diagnóstico', waiting_parts: 'Espera refacciones', repair: 'En reparación', quality_check: 'Control calidad', ready: 'Listo', delivered: 'Entregado', cancelled: 'Cancelado' }; var DELIVERY_LABELS = { pickup: 'Pasa cliente', delivery: 'Envío a domicilio', courier: 'Motociclista' }; function headers() { return { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token }; } function fmt(n) { if (n == null) return '0'; return parseFloat(n).toLocaleString('es-MX'); } function fmtMoney(n) { if (n == null) return '$0.00'; return '$' + parseFloat(n).toLocaleString('es-MX', {minimumFractionDigits: 2, maximumFractionDigits: 2}); } function fmtDate(d) { if (!d) return '—'; var dt = new Date(d); if (isNaN(dt.getTime())) return d; return dt.toLocaleDateString('es-MX', {day: '2-digit', month: '2-digit', year: 'numeric'}) + ' ' + dt.toLocaleTimeString('es-MX', {hour: '2-digit', minute: '2-digit', hour12: false}); } function esc(s) { if (s == null) return ''; var el = document.createElement('div'); el.textContent = s; return el.innerHTML; } function api(method, url, body) { var opts = {method: method, headers: headers()}; if (body) opts.body = JSON.stringify(body); return fetch(API + url, opts).then(function(r) { return r.json().then(function(data) { if (!r.ok) throw new Error(data.error || r.statusText); return data; }); }); } // ─── Init ─── function init() { var savedView = localStorage.getItem('workshop_view'); if (savedView) currentView = savedView; bindFilters(); bindDeliverySelect(); if (hidePrices) { var btnCatalog = document.getElementById('btnCatalog'); if (btnCatalog) btnCatalog.style.display = 'none'; document.querySelectorAll('.price-col').forEach(function(el) { el.style.display = 'none'; }); } loadReferenceData(); loadSummary(); setView(currentView); loadOrders(); loadCatalog(); } function bindFilters() { ['filterBranch','filterStatus','filterDelivery','filterDirect','filterSearch'].forEach(function(id) { var el = document.getElementById(id); if (!el) return; el.addEventListener('change', function() { currentPage = 1; loadOrders(); }); if (el.tagName === 'INPUT' && id === 'filterSearch') { el.addEventListener('keyup', debounce(function() { currentPage = 1; loadOrders(); }, 350)); } }); } function bindDeliverySelect() { var sel = document.getElementById('noDelivery'); if (!sel) return; sel.addEventListener('change', function() { var cf = document.getElementById('courierField'); if (cf) cf.style.display = sel.value === 'courier' ? 'block' : 'none'; }); } function debounce(fn, ms) { var t; return function() { clearTimeout(t); t = setTimeout(fn, ms); }; } // ─── Summary ─── function loadSummary() { fetch(API + '/kanban/summary', {headers: headers()}) .then(function(r) { return r.json(); }) .then(function(d) { document.getElementById('statReceived').textContent = fmt(d.received || 0); document.getElementById('statRepair').textContent = fmt((d.repair || 0) + (d.diagnosis || 0) + (d.waiting_parts || 0) + (d.quality_check || 0)); document.getElementById('statReady').textContent = fmt(d.ready || 0); document.getElementById('statOverdue').textContent = fmt(d.overdue || 0); }) .catch(function() {}); } // ─── Orders loading ─── function getFilterQuery() { var params = []; var status = document.getElementById('filterStatus').value; var delivery = document.getElementById('filterDelivery').value; var branch = document.getElementById('filterBranch').value; var direct = document.getElementById('filterDirect').checked; var q = document.getElementById('filterSearch').value.trim(); if (status) params.push('status=' + encodeURIComponent(status)); if (delivery) params.push('delivery_method=' + encodeURIComponent(delivery)); if (branch) params.push('branch_id=' + encodeURIComponent(branch)); if (direct) params.push('is_direct=true'); if (q) params.push('q=' + encodeURIComponent(q)); params.push('page=' + currentPage); params.push('per_page=' + perPage); return '?' + params.join('&'); } function loadOrders() { fetch(API + getFilterQuery(), {headers: headers()}) .then(function(r) { return r.json(); }) .then(function(d) { orders = d.data || []; var pagination = d.pagination || {}; totalPages = pagination.total_pages || 1; if (currentView === 'list') { renderList(); renderPagination(); } else { renderKanban(); } }) .catch(function(e) { console.error(e); document.getElementById('listBody').innerHTML = 'Error cargando órdenes'; }); } var totalPages = 1; // ─── View switching ─── function setView(view) { currentView = view; localStorage.setItem('workshop_view', view); document.querySelectorAll('.view-switch__btn').forEach(function(b) { b.classList.toggle('is-active', b.dataset.view === view); }); document.getElementById('listView').style.display = view === 'list' ? 'block' : 'none'; document.getElementById('kanbanBoard').style.display = view === 'kanban' ? 'flex' : 'none'; if (view === 'list') { renderList(); renderPagination(); } else { renderKanban(); } } // ─── List view ─── function renderList() { var body = document.getElementById('listBody'); if (!orders.length) { body.innerHTML = 'No se encontraron órdenes'; return; } body.innerHTML = orders.map(function(o) { var vehicle = esc((o.vehicle_plate || '—') + ' ' + (o.vehicle_make || '') + ' ' + (o.vehicle_model || '')); return '' + '' + esc(o.branch_name || '—') + '' + '' + esc(o.order_number) + '' + '' + esc(o.customer_name || 'Cliente general') + '' + '' + vehicle + '' + '' + esc(STATUS_LABELS[o.status] || o.status) + '' + '' + fmtMoney(o.total) + '' + '' + ''; }).join(''); if (hidePrices) { document.querySelectorAll('.price-col').forEach(function(el) { el.style.display = 'none'; }); } } function renderPagination() { var el = document.getElementById('listPagination'); if (totalPages <= 1) { el.innerHTML = ''; return; } var html = '' + 'Página ' + currentPage + ' de ' + totalPages + '' + ''; el.innerHTML = html; } function goPage(p) { if (p < 1 || p > totalPages) return; currentPage = p; loadOrders(); } // ─── Kanban view ─── function renderKanban() { var board = document.getElementById('kanbanBoard'); board.innerHTML = ''; COLUMNS.forEach(function(col) { var colOrders = orders.filter(function(o) { return o.status === col.key; }); var colEl = document.createElement('div'); colEl.className = 'kanban-column'; colEl.innerHTML = '
' + ' ' + esc(col.label) + '' + ' ' + colOrders.length + '' + '
' + '
'; board.appendChild(colEl); var body = colEl.querySelector('.kanban-column__body'); if (!colOrders.length) { body.innerHTML = '
Sin órdenes
'; } else { colOrders.forEach(function(o) { body.appendChild(renderCard(o)); }); } }); } function priorityLabel(p) { var map = {normal: 'Normal', high: 'Alta', urgent: 'Urgente'}; return map[p] || p; } function statusBadgeClass(status) { return 'badge--' + (status || 'pending'); } function renderCard(o) { var card = document.createElement('div'); card.className = 'kanban-card'; card.onclick = function() { openDetail(o.id); }; var priceHtml = hidePrices ? '' : '' + fmtMoney(o.estimated_cost || o.total) + ''; card.innerHTML = '
' + ' ' + esc(o.order_number) + '' + ' ' + esc(priorityLabel(o.priority)) + '' + '
' + '
' + esc(o.customer_name || 'Cliente general') + '
' + '
' + esc(o.vehicle_plate || 'Sin vehículo') + '
' + '
' + ' 🔧 ' + esc(o.employee_name || 'Sin asignar') + '' + priceHtml + '
'; return card; } // ─── Detail modal ─── function openDetail(id) { currentOrderId = id; fetch(API + '/' + id, {headers: headers()}) .then(function(r) { return r.json(); }) .then(function(o) { currentOrder = o; document.getElementById('detailTitle').textContent = 'Bitácora Orden: ' + esc(o.order_number); renderDetailBody(o); document.getElementById('detailModal').classList.add('is-open'); }) .catch(function(e) { alert('Error: ' + e.message); }); } function renderDetailBody(o) { var activeTab = document.querySelector('.so-tabs__btn.is-active'); var selectedTab = activeTab ? activeTab.dataset.tab : 'service'; var html = '
' + '
Estatus: ' + esc(STATUS_LABELS[o.status] || o.status) + '
' + '
Fecha: ' + fmtDate(o.created_at) + '
' + '
Registrado por: ' + esc(o.created_by_name || '—') + '
' + '
Sucursal: ' + esc(o.branch_name || '—') + '
' + '
' + '
' + '
Cliente' + esc(o.customer_name || '—') + '
' + '
Dirección' + esc(o.customer_address || '—') + '
' + '
Teléfono' + esc(o.customer_phone || '—') + '
' + '
Vehículo' + esc((o.vehicle_plate || '—') + ' ' + (o.vehicle_make || '') + ' ' + (o.vehicle_model || '')) + '
' + '
Vía de entrega' + esc(DELIVERY_LABELS[o.delivery_method] || o.delivery_method || '—') + '
' + '
Motociclista' + esc(o.courier_name || '—') + '
' + '
Mecánico' + esc(o.employee_name || 'Sin asignar') + '
' + '
Entrega estimada' + fmtDate(o.estimated_completion) + '
' + '
Kilometraje entrada' + fmt(o.mileage_in) + '
' + (hidePrices ? '' : '
Presupuesto' + fmtMoney(o.estimated_cost) + '
') + (hidePrices ? '' : '
Total' + fmtMoney(o.total) + '
') + '
' + '
' + ' ' + ' ' + '
' + '
' + '
' + '

Observaciones

' + '

' + esc(o.reception_notes || 'Sin observaciones') + '

' + '
' + '
' + '

Bitácora

' + renderBitacora(o.status_history || []) + '
' + '
' + '
' + renderArticles(o) + '
'; document.getElementById('detailBody').innerHTML = html; // Footer actions var footer = document.getElementById('detailFooter'); var statusHtml = canEdit ? '
' + ' ' + ' ' + '
' : ''; footer.innerHTML = statusHtml + '' + '' + (canEdit && canSell && o.status === 'ready' && !o.sale_id ? '' : '') + (o.sale_id ? 'Ver venta #' + o.sale_id + '' : ''); } function switchTab(tab) { document.querySelectorAll('.so-tabs__btn').forEach(function(b) { b.classList.toggle('is-active', b.dataset.tab === tab); }); document.getElementById('tab-service').style.display = tab === 'service' ? 'block' : 'none'; document.getElementById('tab-articles').style.display = tab === 'articles' ? 'block' : 'none'; } function renderBitacora(history) { if (!history.length) return '

Sin movimientos

'; var rows = history.map(function(h) { return '' + '' + esc(STATUS_LABELS[h.new_status] || h.new_status) + '' + '' + fmtDate(h.created_at) + '' + '' + esc(h.changed_by_name || '—') + '' + '' + esc(h.notes || '—') + '' + ''; }).join(''); return '' + rows + '
EstatusFechaUsuarioObservaciones
'; } function renderArticles(o) { var partsRows = (o.items || []).map(function(it) { var priceCells = hidePrices ? '' : '' + fmtMoney(it.unit_price) + ''; var actionCell = canEdit && it.status !== 'cancelled' ? '' : ''; return '' + '' + esc(it.name) + '
' + esc(it.part_number || '') + '' + '' + fmt(it.quantity) + '' + priceCells + '' + esc(STATUS_LABELS[it.status] || it.status) + '' + actionCell + ''; }).join(''); var partsHeader = 'ConceptoCant.' + (hidePrices ? '' : 'Precio') + 'Estado'; var laborRows = (o.labor || []).map(function(l) { var priceCells = hidePrices ? '' : '' + fmtMoney(l.hourly_rate) + '' + fmtMoney(l.total_cost) + ''; return '' + '' + esc(l.description) + '' + '' + fmt(l.hours) + '' + priceCells + '' + esc(STATUS_LABELS[l.status] || l.status) + '' + ''; }).join(''); var laborHeader = 'ConceptoHoras' + (hidePrices ? '' : 'Precio/hrTotal') + 'Estado'; var addParts = canEdit ? '
' + ' ' + ' ' + '
' : ''; var addLabor = canEdit ? '
' + ' ' + ' ' + ' ' + (hidePrices ? '' : '') + ' ' + '
' : ''; var html = '
' + '

Refacciones

' + ' ' + partsHeader + '' + (partsRows || '') + '
Sin refacciones
' + addParts + '
' + '
' + '

Mano de obra

' + ' ' + laborHeader + '' + (laborRows || '') + '
Sin mano de obra
' + addLabor + '
'; // schedule labor catalog select population after DOM insertion setTimeout(function() { var sel = document.getElementById('laborCatalogSelect'); if (!sel || sel.dataset.populated) return; catalog.forEach(function(c) { var opt = document.createElement('option'); opt.value = JSON.stringify(c); opt.textContent = c.name + (hidePrices ? '' : ' ($' + fmtMoney(c.suggested_hours * c.suggested_rate).replace('$', '') + ')'); sel.appendChild(opt); }); sel.dataset.populated = '1'; sel.onchange = function() { if (!sel.value) return; var c = JSON.parse(sel.value); document.getElementById('laborDesc').value = c.name; document.getElementById('laborHours').value = c.suggested_hours; if (!hidePrices) document.getElementById('laborRate').value = c.suggested_rate; }; }, 0); return html; } function closeDetailModal() { document.getElementById('detailModal').classList.remove('is-open'); currentOrderId = null; currentOrder = null; } // ─── Actions ─── function changeStatus() { if (!currentOrderId) return; var newStatus = document.getElementById('statusSelect').value; api('PUT', '/' + currentOrderId + '/status', {status: newStatus}) .then(function() { closeDetailModal(); loadSummary(); loadOrders(); }) .catch(function(e) { alert('Error: ' + e.message); }); } function reserveItem(itemId) { api('POST', '/' + currentOrderId + '/items/' + itemId + '/reserve', {}) .then(function() { alert('Refacción reservada'); openDetail(currentOrderId); loadSummary(); }) .catch(function(e) { alert('Error: ' + e.message); }); } function addItemPlaceholder() { var name = document.getElementById('newItemSearch').value.trim(); if (!name) return; api('POST', '/' + currentOrderId + '/items', { name: name, quantity: 1, unit_price: 0, status: 'pending' }).then(function() { openDetail(currentOrderId); }).catch(function(e) { alert('Error: ' + e.message); }); } function addLabor() { var desc = document.getElementById('laborDesc').value.trim(); var hours = parseFloat(document.getElementById('laborHours').value) || 0; var rate = hidePrices ? 0 : parseFloat(document.getElementById('laborRate').value) || 0; if (!desc) return alert('Escribe una descripción'); api('POST', '/' + currentOrderId + '/labor', { description: desc, hours: hours, hourly_rate: rate, status: 'pending' }).then(function() { document.getElementById('laborDesc').value = ''; document.getElementById('laborHours').value = ''; if (!hidePrices) document.getElementById('laborRate').value = ''; openDetail(currentOrderId); }).catch(function(e) { alert('Error: ' + e.message); }); } function convertToSale() { if (!currentOrderId) return; if (!confirm('¿Convertir esta orden en una venta? Se descontarán las refacciones reservadas del inventario.')) return; api('POST', '/' + currentOrderId + '/convert-to-sale', { payment_method: 'efectivo', sale_type: 'cash' }).then(function(r) { alert('Venta creada: #' + r.sale_id + ' Total: ' + fmtMoney(r.total)); closeDetailModal(); loadSummary(); loadOrders(); }).catch(function(e) { alert('Error: ' + e.message); }); } function printOrder() { if (!currentOrderId) return; if (!window.NexusPrinter || !window.NexusPrinter.isConnected()) { var connect = confirm('No hay impresora conectada. ¿Conectar ahora?'); if (connect) { window.NexusPrinter.connect().then(function(r) { if (r.ok) doPrint(); }); } return; } doPrint(); function doPrint() { window.NexusPrinter.printServiceOrder(currentOrderId, 80) .then(function(ok) { if (ok) alert('Orden enviada a la impresora'); else alert('No se pudo imprimir'); }) .catch(function(e) { alert('Error: ' + e.message); }); } } // ─── New order ─── function openNewOrderModal() { populateSelect('noCustomer', customers, function(c) { return {value: c.id, text: c.name + ' (' + (c.phone || '') + ')'}; }); populateSelect('noVehicle', vehicles, function(v) { return {value: v.id, text: v.plate + ' ' + v.make + ' ' + v.model}; }); populateSelect('noMechanic', employees, function(e) { return {value: e.id, text: e.name}; }); populateSelect('noCourier', couriers, function(c) { return {value: c.id, text: c.name}; }); document.getElementById('newOrderModal').classList.add('is-open'); } function closeNewOrderModal() { document.getElementById('newOrderModal').classList.remove('is-open'); document.getElementById('newOrderForm').reset(); var cf = document.getElementById('courierField'); if (cf) cf.style.display = 'none'; } function submitNewOrder() { var customerId = document.getElementById('noCustomer').value; if (!customerId) return alert('Selecciona un cliente'); var delivery = document.getElementById('noDelivery').value; var payload = { customer_id: parseInt(customerId, 10), vehicle_id: parseInt(document.getElementById('noVehicle').value, 10) || null, employee_id: parseInt(document.getElementById('noMechanic').value, 10) || null, priority: document.getElementById('noPriority').value, estimated_completion: document.getElementById('noEstimatedCompletion').value || null, mileage_in: parseInt(document.getElementById('noMileage').value, 10) || null, reception_notes: document.getElementById('noNotes').value, delivery_method: delivery || null, courier_id: delivery === 'courier' ? (parseInt(document.getElementById('noCourier').value, 10) || null) : null, is_direct: document.getElementById('noDirect').checked }; api('POST', '', payload).then(function() { closeNewOrderModal(); loadSummary(); loadOrders(); }).catch(function(e) { alert('Error: ' + e.message); }); } // ─── Catalog ─── function openCatalogModal() { document.getElementById('catalogModal').classList.add('is-open'); renderCatalog(); } function closeCatalogModal() { document.getElementById('catalogModal').classList.remove('is-open'); } function loadCatalog() { fetch(API + '/service-catalog?active_only=true', {headers: headers()}) .then(function(r) { return r.json(); }) .then(function(d) { catalog = d.data || []; }) .catch(function() {}); } function renderCatalog() { var body = document.getElementById('catalogBody'); if (!catalog.length) { body.innerHTML = 'Sin conceptos'; return; } body.innerHTML = catalog.map(function(c) { return '' + '' + esc(c.name) + (c.description ? '
' + esc(c.description) + '' : '') + '' + '' + fmt(c.suggested_hours) + '' + (hidePrices ? '' : '' + fmtMoney(c.suggested_rate) + '' + '' + fmtMoney(c.suggested_hours * c.suggested_rate) + '') + '' + ''; }).join(''); } function addCatalogItem() { var name = document.getElementById('catName').value.trim(); if (!name) return alert('Escribe un nombre'); api('POST', '/service-catalog', { name: name, description: document.getElementById('catDesc').value, suggested_hours: parseFloat(document.getElementById('catHours').value) || 0, suggested_rate: parseFloat(document.getElementById('catRate').value) || 0 }).then(function() { document.getElementById('catName').value = ''; document.getElementById('catDesc').value = ''; document.getElementById('catHours').value = ''; document.getElementById('catRate').value = ''; loadCatalog(); setTimeout(renderCatalog, 200); }).catch(function(e) { alert('Error: ' + e.message); }); } function deleteCatalogItem(id) { if (!confirm('¿Desactivar este concepto?')) return; api('DELETE', '/service-catalog/' + id, {}) .then(function() { loadCatalog(); setTimeout(renderCatalog, 200); }) .catch(function(e) { alert('Error: ' + e.message); }); } // ─── Reference data ─── function loadReferenceData() { // Customers fetch('/pos/api/customers?per_page=500', {headers: headers()}) .then(function(r) { return r.json(); }) .then(function(d) { customers = (d.data || d.customers || []); }) .catch(function() {}); // Vehicles fetch('/pos/api/fleet/vehicles?per_page=500', {headers: headers()}) .then(function(r) { return r.json(); }) .then(function(d) { vehicles = (d.data || []); }) .catch(function() { vehicles = []; }); // Employees fetch('/pos/api/config/employees?per_page=500', {headers: headers()}) .then(function(r) { return r.json(); }) .then(function(d) { employees = (d.data || d.employees || []); }) .catch(function() { employees = []; }); // Couriers fetch('/pos/api/couriers?per_page=500', {headers: headers()}) .then(function(r) { return r.json(); }) .then(function(d) { couriers = (d.data || d.couriers || []); populateSelect('noCourier', couriers, function(c) { return {value: c.id, text: c.name}; }); }) .catch(function() { couriers = []; }); // Branches fetch('/pos/api/config/branches', {headers: headers()}) .then(function(r) { return r.json(); }) .then(function(d) { branches = (d.data || []); populateBranchFilter(); }) .catch(function() { branches = []; }); } function populateBranchFilter() { var sel = document.getElementById('filterBranch'); if (!sel) return; var current = sel.value; sel.innerHTML = ''; branches.forEach(function(b) { var opt = document.createElement('option'); opt.value = b.id; opt.textContent = b.name; sel.appendChild(opt); }); sel.value = current; } function populateSelect(id, items, mapper) { var sel = document.getElementById(id); if (!sel) return; sel.innerHTML = id === 'noCustomer' || id === 'noCourier' ? '' : ''; items.forEach(function(it) { var opt = mapper(it); var el = document.createElement('option'); el.value = opt.value; el.textContent = opt.text; sel.appendChild(el); }); } // ─── Public API ─── return { init: init, setView: setView, goPage: goPage, openDetail: openDetail, closeDetailModal: closeDetailModal, switchTab: switchTab, changeStatus: changeStatus, reserveItem: reserveItem, addItemPlaceholder: addItemPlaceholder, addLabor: addLabor, convertToSale: convertToSale, printOrder: printOrder, openNewOrderModal: openNewOrderModal, closeNewOrderModal: closeNewOrderModal, submitNewOrder: submitNewOrder, openCatalogModal: openCatalogModal, closeCatalogModal: closeCatalogModal, addCatalogItem: addCatalogItem, deleteCatalogItem: deleteCatalogItem, }; })(); document.addEventListener('DOMContentLoaded', Workshop.init);