{{-- Partial: Reusable Planning Form JavaScript Functions (Pre, Interm, Final, Evaluation) --}} function escapeHtml(text) { if (!text) return ''; return String(text) .replace(/&/g, '&') .replace(/"/g, '"') .replace(/'/g, ''') .replace(//g, '>'); } let specialCargoCounter = 0; function addSpecialCargoCard(data = null) { const scIdx = specialCargoCounter++; const container = document.getElementById('special-cargos-container'); const emptyState = document.getElementById('special-cargos-empty-state'); if (emptyState) emptyState.style.display = 'none'; const cargoType = data ? (data.cargo_type || '') : ''; const nominativeOwner = data ? (data.nominative_owner || '') : ''; const issue = data ? (data.issue || '') : ''; const handlingPlan = data ? (data.handling_plan || '') : ''; const note = data ? (data.note || '') : ''; const card = document.createElement('div'); card.id = `special-cargo-card-${scIdx}`; card.className = 'special-cargo-card bg-white border border-slate-200 rounded-2xl shadow-sm overflow-hidden transition-all'; card.innerHTML = `
${container.children.length + 1}

Special Handling Cargo #${container.children.length + 1}

{{-- 1. Cargo Type --}}
{{-- 2. Nominative Owner --}}
{{-- 3. Issue --}}
{{-- 4. Handling Plan --}}
{{-- 5. Note --}}
`; container.appendChild(card); updateSpecialCargoNumbers(); } function removeSpecialCargoCard(scIdx) { const card = document.getElementById(`special-cargo-card-${scIdx}`); if (card) { card.remove(); updateSpecialCargoNumbers(); } } function updateSpecialCargoNumbers() { const container = document.getElementById('special-cargos-container'); const emptyState = document.getElementById('special-cargos-empty-state'); const cards = container.querySelectorAll('.special-cargo-card'); if (cards.length === 0) { if (emptyState) emptyState.style.display = 'block'; } else { if (emptyState) emptyState.style.display = 'none'; } cards.forEach((card, idx) => { const badge = card.querySelector('.special-cargo-badge'); if (badge) badge.textContent = idx + 1; const numEl = card.querySelector('.special-cargo-number-label'); if (numEl) numEl.textContent = `#${idx + 1}`; }); const grandEl = document.getElementById('grand-special-cargo-count'); if (grandEl) grandEl.textContent = cards.length; } // ========================================== // OPERATING VESSEL HELPERS & CALCULATIONS // ========================================== function getOperatingVesselRowByName(nameQuery) { const rows = document.querySelectorAll('.row-op-vessel'); const q = nameQuery.toLowerCase().trim().replace(/rampdor\b/g, 'rampdoor'); for (const row of rows) { const nameInput = row.querySelector('input[name*="[name]"]'); const nameVal = (nameInput ? nameInput.value.toLowerCase().trim() : '').replace(/rampdor\b/g, 'rampdoor'); if (nameVal === q || (q.includes('open') && q.includes('ramp') && nameVal.includes('open') && nameVal.includes('ramp')) || (q.includes('close') && q.includes('ramp') && nameVal.includes('close') && nameVal.includes('ramp')) || (q.includes('completed') && (nameVal.includes('completed') || nameVal.includes('complete'))) || (q.includes('commence') && nameVal.includes('commence')) || (q.includes('berthed') && nameVal.includes('berthed')) || (q.includes('sailed') && nameVal.includes('sailed')) || (nameVal.includes(q)) ) { return row; } } return null; } function calcOpVesselRow(idx) { const row = document.querySelector(`.row-op-vessel[data-op-idx="${idx}"]`); if (!row) return; const planDateInput = document.getElementById(`op-plan-date-${idx}`); const planTimeInput = document.getElementById(`op-plan-time-${idx}`); const actDateInput = document.getElementById(`op-act-date-${idx}`); const actTimeInput = document.getElementById(`op-act-time-${idx}`); const diffInput = document.getElementById(`op-diff-${idx}`); const planTimeRaw = planTimeInput ? planTimeInput.value : ''; const actTimeRaw = actTimeInput ? actTimeInput.value : ''; const planTime = planTimeRaw.trim().replace(/\./g, ':'); const actTime = actTimeRaw.trim().replace(/\./g, ':'); if (!planTime || !actTime) { if (diffInput) diffInput.value = ''; calcOpStrategicAvailableTime(); calcOpStrategicActualAvailableTime(); return; } let diffMinutes = 0; const planDate = planDateInput ? planDateInput.value : ''; const actDate = actDateInput ? actDateInput.value : ''; if (planDate && actDate) { const planDt = new Date(`${planDate}T${planTime}:00`); const actDt = new Date(`${actDate}T${actTime}:00`); if (!isNaN(planDt.getTime()) && !isNaN(actDt.getTime())) { diffMinutes = Math.round((planDt - actDt) / (1000 * 60)); } else { const [pH, pM] = planTime.split(':').map(Number); const [aH, aM] = actTime.split(':').map(Number); diffMinutes = (pH * 60 + pM) - (aH * 60 + aM); } } else { const [pH, pM] = planTime.split(':').map(Number); const [aH, aM] = actTime.split(':').map(Number); diffMinutes = (pH * 60 + pM) - (aH * 60 + aM); } const sign = diffMinutes > 0 ? '+' : (diffMinutes < 0 ? '-' : ''); const absDiff = Math.abs(diffMinutes); const hours = Math.floor(absDiff / 60); const mins = absDiff % 60; const formatted = `${sign}${String(hours).padStart(2, '0')}:${String(mins).padStart(2, '0')}`; if (diffInput) { diffInput.value = formatted; } calcOpStrategicAvailableTime(); calcOpStrategicActualAvailableTime(); } function calcAllOpVesselRows() { document.querySelectorAll('.row-op-vessel').forEach(row => { const idx = row.dataset.opIdx; calcOpVesselRow(idx); }); } // ========================================== // DUAL-MODE TIME PICKER & SMART TYPING FOR OPERATING VESSEL (FORM CHECKER STYLE) // ========================================== document.addEventListener('click', function(e) { const btn = e.target.closest('.btn-open-time-picker, .btn-open-picker'); if (!btn) return; const container = btn.closest('.relative'); if (!container) return; const textInp = container.querySelector('.milestone-time-input, input[type="text"]'); const hiddenInp = container.querySelector('.hidden-time-input, input[type="time"]'); if (textInp && hiddenInp) { e.preventDefault(); e.stopPropagation(); if (textInp.value && /^(\d{1,2}):(\d{2})$/.test(textInp.value.trim())) { hiddenInp.value = textInp.value.trim(); } try { hiddenInp.showPicker(); } catch (err) { hiddenInp.click(); } } }); document.addEventListener('dblclick', function(e) { if (!e.target.classList.contains('milestone-time-input')) return; const container = e.target.closest('.relative'); const hiddenInp = container?.querySelector('.hidden-time-input, input[type="time"]'); if (hiddenInp) { if (e.target.value && /^(\d{1,2}):(\d{2})$/.test(e.target.value.trim())) { hiddenInp.value = e.target.value.trim(); } try { hiddenInp.showPicker(); } catch (err) { hiddenInp.click(); } } }); document.addEventListener('change', function(e) { if (e.target.matches('.hidden-time-input, .hidden-time-picker')) { const container = e.target.closest('.relative'); const textInp = container?.querySelector('.milestone-time-input, input[type="text"]'); if (textInp && e.target.value) { textInp.value = e.target.value; textInp.dispatchEvent(new Event('input', { bubbles: true })); textInp.dispatchEvent(new Event('change', { bubbles: true })); } } }); document.addEventListener('input', function(e) { if (!e.target.classList.contains('milestone-time-input')) return; if (e.target.dataset.smartTimeEnhanced === 'true') return; if (e.inputType === 'deleteContentBackward') return; if (e.target.value.includes(':')) return; let val = e.target.value.replace(/[^0-9]/g, ''); if (val.length >= 3) { e.target.value = val.slice(0, 2) + ':' + val.slice(2, 4); } }); document.addEventListener('blur', function(e) { if (!e.target.classList.contains('milestone-time-input')) return; if (e.target.dataset.smartTimeEnhanced === 'true') return; let val = e.target.value.trim().replace(/\./g, ':').replace(/[^0-9:]/g, ''); if (!val) return; let formatted = val; if (/^\d{1,2}$/.test(val)) { let num = Math.min(23, parseInt(val, 10)); formatted = String(num).padStart(2, '0') + ':00'; } else if (/^\d{3}$/.test(val)) { let h = Math.min(23, parseInt(val.slice(0, 1), 10)); let m = Math.min(59, parseInt(val.slice(1, 3), 10)); formatted = String(h).padStart(2, '0') + ':' + String(m).padStart(2, '0'); } else if (/^\d{4}$/.test(val)) { let h = Math.min(23, parseInt(val.slice(0, 2), 10)); let m = Math.min(59, parseInt(val.slice(2, 4), 10)); formatted = String(h).padStart(2, '0') + ':' + String(m).padStart(2, '0'); } else if (/^(\d{1,2}):(\d{0,2})$/.test(val)) { const PART = val.split(':'); let h = Math.min(23, parseInt(PART[0] || '0', 10)); let m = PART[1] ? (PART[1].length === 1 ? parseInt(PART[1] + '0', 10) : parseInt(PART[1], 10)) : 0; m = Math.min(59, m); formatted = String(h).padStart(2, '0') + ':' + String(m).padStart(2, '0'); } if (formatted !== e.target.value) { e.target.value = formatted; e.target.dispatchEvent(new Event('input', { bubbles: true })); e.target.dispatchEvent(new Event('change', { bubbles: true })); } }, true); document.addEventListener('keydown', function(e) { if (!e.target.classList.contains('milestone-time-input')) return; if (e.target.dataset.smartTimeEnhanced === 'true') return; if (e.key === 'ArrowUp' || e.key === 'ArrowDown') { e.preventDefault(); const stepMinutes = (e.key === 'ArrowUp' ? 1 : -1) * (e.shiftKey ? 60 : 1); let current = e.target.value.trim(); let h = 0, m = 0; if (/^(\d{1,2}):(\d{2})$/.test(current)) { const PART = current.split(':'); h = parseInt(PART[0], 10); m = parseInt(PART[1], 10); } else { const now = new Date(); h = now.getHours(); m = now.getMinutes(); } let totalMins = (h * 60 + m + stepMinutes) % (24 * 60); if (totalMins < 0) totalMins += 24 * 60; const newH = Math.floor(totalMins / 60); const newM = totalMins % 60; e.target.value = String(newH).padStart(2, '0') + ':' + String(newM).padStart(2, '0'); e.target.dispatchEvent(new Event('input', { bubbles: true })); e.target.dispatchEvent(new Event('change', { bubbles: true })); } else if (e.key === 'Enter') { e.target.blur(); } }); // ========================================== // OPERATION STRATEGIC AVAILABLE TIME CALCULATIONS // ========================================== function calcDurationColonFromDates(openDate, openTimeRaw, closeDate, closeTimeRaw) { const openTime = (openTimeRaw || '').trim().replace(/\./g, ':'); const closeTime = (closeTimeRaw || '').trim().replace(/\./g, ':'); if (!openTime || !closeTime) return null; let diffMinutes = 0; if (openDate && closeDate) { const openDt = new Date(`${openDate}T${openTime}:00`); const closeDt = new Date(`${closeDate}T${closeTime}:00`); if (!isNaN(openDt.getTime()) && !isNaN(closeDt.getTime())) { diffMinutes = Math.round((closeDt - openDt) / (1000 * 60)); if (diffMinutes < 0 && openDate === closeDate) { diffMinutes += 24 * 60; } } else { const [oH, oM] = openTime.split(':').map(Number); const [cH, cM] = closeTime.split(':').map(Number); diffMinutes = (cH * 60 + cM) - (oH * 60 + oM); if (diffMinutes < 0) diffMinutes += 24 * 60; } } else { const [oH, oM] = openTime.split(':').map(Number); const [cH, cM] = closeTime.split(':').map(Number); diffMinutes = (cH * 60 + cM) - (oH * 60 + oM); if (diffMinutes < 0) diffMinutes += 24 * 60; } if (diffMinutes < 0) return null; const h = Math.floor(diffMinutes / 60); const m = diffMinutes % 60; return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}`; } // Rumus: Close Ramp (Plan) - Open Ramp (Plan) -> Format HH:MM function calcOpStrategicAvailableTime(force = false) { const availInp = document.getElementById('op-strat-available-time'); if (!availInp) return; if (!force && availInp.dataset.manual === 'true') return; const openRow = getOperatingVesselRowByName('open ramp') || getOperatingVesselRowByName('open rampdoor'); const closeRow = getOperatingVesselRowByName('close ramp') || getOperatingVesselRowByName('close rampdoor'); if (!openRow || !closeRow) return; const openIdx = openRow.dataset.opIdx; const closeIdx = closeRow.dataset.opIdx; const result = calcDurationColonFromDates( document.getElementById(`op-plan-date-${openIdx}`)?.value || '', document.getElementById(`op-plan-time-${openIdx}`)?.value || '', document.getElementById(`op-plan-date-${closeIdx}`)?.value || '', document.getElementById(`op-plan-time-${closeIdx}`)?.value || '' ); if (result !== null) { availInp.value = result; } else if (availInp.value.trim() === '' || availInp.value.trim() === '-') { availInp.value = '00:00'; } } // Rumus: Close Ramp (Actual) - Open Ramp (Actual) -> Format HH:MM function calcOpStrategicActualAvailableTime(force = false) { const actAvailInp = document.getElementById('op-strat-actual-available-time'); if (!actAvailInp) return; if (!force && actAvailInp.dataset.manual === 'true') return; const openRow = getOperatingVesselRowByName('open ramp') || getOperatingVesselRowByName('open rampdoor'); const closeRow = getOperatingVesselRowByName('close ramp') || getOperatingVesselRowByName('close rampdoor'); if (!openRow || !closeRow) return; const openIdx = openRow.dataset.opIdx; const closeIdx = closeRow.dataset.opIdx; const result = calcDurationColonFromDates( document.getElementById(`op-act-date-${openIdx}`)?.value || '', document.getElementById(`op-act-time-${openIdx}`)?.value || '', document.getElementById(`op-act-date-${closeIdx}`)?.value || '', document.getElementById(`op-act-time-${closeIdx}`)?.value || '' ); if (result !== null) { actAvailInp.value = result; } else if (actAvailInp.value.trim() === '' || actAvailInp.value.trim() === '-') { actAvailInp.value = '00:00'; } } // Rumus Evaluation Realtime Operation: // Actual Duration Time - Waiting Cargo / Document - Idle Time / Stop Operation - Shifting - MEAL BREAK -> Format HH:MM function calcOpStrategicRealtimeOperation(force = false) { const rtInp = document.getElementById('op-strat-realtime-operation'); if (!rtInp) return; if (!force && rtInp.dataset.manual === 'true') return; const actDurMin = parseDurationStringToMinutes(document.getElementById('op-strat-actual-dur')?.value || ''); const waitMin = parseDurationStringToMinutes(document.getElementById('op-strat-actual-waiting-cargo-doc')?.value || ''); const idleMin = parseDurationStringToMinutes(document.getElementById('op-strat-actual-idle-time')?.value || ''); const shiftMin = parseDurationStringToMinutes(document.getElementById('op-strat-actual-shifting')?.value || ''); const mealMin = parseDurationStringToMinutes(document.getElementById('op-strat-actual-meal-break')?.value || ''); const diffMin = actDurMin - waitMin - idleMin - shiftMin - mealMin; const sign = diffMin < 0 ? '-' : ''; const absMin = Math.abs(diffMin); const h = Math.floor(absMin / 60); const m = absMin % 60; rtInp.value = `${sign}${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}`; } ['input', 'change'].forEach((evType) => { document.addEventListener(evType, function(e) { if (e.target && [ 'op-strat-actual-dur', 'op-strat-actual-waiting-cargo-doc', 'op-strat-actual-idle-time', 'op-strat-actual-shifting', 'op-strat-actual-meal-break', ].includes(e.target.id)) { calcOpStrategicRealtimeOperation(); } }); }); // ========================================== // TIME UTILITY FUNCTIONS (Continuous >24h Format Support) // ========================================== function parseTimeToMinutes(str) { if (!str || typeof str !== 'string') return 0; str = str.trim(); if (!str || str === '-' || str === '00:00' || str === '00.00' || str === '0.00' || str === '0' || str === '0:00') return 0; const isNeg = str.startsWith('-'); if (isNeg && /^-\s*\d+(?:[:.,]\d*)?$/.test(str)) { return -parseTimeToMinutes(str.slice(1).trim()); } // Support time ranges like "08:00 - 21:00" or "08.00 - 21.00" if (str.includes('-')) { const rangeParts = str.split(/\s*[-–—]\s*/); if (rangeParts.length === 2 && /[:.]/.test(rangeParts[0]) && /[:.]/.test(rangeParts[1])) { const sM = parseTimeToMinutes(rangeParts[0]); let eM = parseTimeToMinutes(rangeParts[1]); if (eM < sM) eM += 24 * 60; // overnight rollover return Math.max(0, eM - sM); } } // Support comma as decimal separator e.g. "3,45" -> "3.45" str = str.replace(',', '.'); // Check if format is "3hr45min" or similar const hrMinMatch = str.match(/(\d+)\s*hr\s*(\d+)?/i); if (hrMinMatch) { const h = parseInt(hrMinMatch[1], 10) || 0; const m = parseInt(hrMinMatch[2], 10) || 0; return (h * 60) + m; } if (str.includes(':')) { const PART = str.split(':'); const h = parseInt(PART[0], 10) || 0; const m = parseInt(PART[1], 10) || 0; return (h * 60) + m; } if (str.includes('.')) { const PART = str.split('.'); const h = parseInt(PART[0], 10) || 0; const mPart = PART[1]; if (mPart.length <= 2 && parseInt(mPart, 10) < 60) { const m = parseInt(mPart.length === 1 ? mPart + '0' : mPart, 10) || 0; return (h * 60) + m; } else { const dec = parseFloat(str) || 0; return Math.round(dec * 60); } } const hOnly = parseFloat(str) || 0; return Math.round(hOnly * 60); } function parseTimeToHours(str) { return parseTimeToMinutes(str) / 60; } function formatMinutesToContinuousTime(totalMinutes) { if (totalMinutes <= 0 || isNaN(totalMinutes)) return '00:00'; const h = Math.floor(totalMinutes / 60); const m = Math.round(totalMinutes % 60); return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}`; } function formatActualDurationInput(input) { if (!input) return; const val = (input.value || '').trim(); if (!val || val === '-' || val === '00:00' || val === '0') { input.value = '00:00'; return; } const mins = parseTimeToMinutes(val); input.value = formatMinutesToContinuousTime(mins); } function parseDurationStringToMinutes(val) { return parseTimeToMinutes(val); } // ========================================== // SQUANCING DATA CARGO REALTIME CALCULATION // ========================================== let currentSeqTab = 'discharging'; function switchSequencingTab(mode) { currentSeqTab = mode; const tbodyDis = document.getElementById('seq-tbody-discharging'); const tbodyLoad = document.getElementById('seq-tbody-loading'); const tbodyShift = document.getElementById('seq-tbody-shifting'); const btnDis = document.getElementById('btn-seq-tab-discharging'); const btnLoad = document.getElementById('btn-seq-tab-loading'); const btnShift = document.getElementById('btn-seq-tab-shifting'); const labelsDis = document.querySelectorAll('.seq-header-label-discharging'); const labelsLoad = document.querySelectorAll('.seq-header-label-loading'); const labelsShift = document.querySelectorAll('.seq-header-label-shifting'); const activeClass = 'px-3.5 py-1.5 rounded-lg font-bold transition-all bg-white text-blue-600 shadow-sm border border-slate-200/60 cursor-pointer'; const inactiveClass = 'px-3.5 py-1.5 rounded-lg font-bold transition-all text-slate-600 hover:text-slate-900 border border-transparent cursor-pointer'; if (tbodyDis) tbodyDis.classList.toggle('hidden', mode !== 'discharging'); if (tbodyLoad) tbodyLoad.classList.toggle('hidden', mode !== 'loading'); if (tbodyShift) tbodyShift.classList.toggle('hidden', mode !== 'shifting'); labelsDis.forEach(el => el.classList.toggle('hidden', mode !== 'discharging')); labelsLoad.forEach(el => el.classList.toggle('hidden', mode !== 'loading')); labelsShift.forEach(el => el.classList.toggle('hidden', mode !== 'shifting')); const colStdDuration = document.querySelectorAll('.seq-col-std-duration'); colStdDuration.forEach(el => el.classList.toggle('hidden', mode === 'shifting')); const colgroup = document.getElementById('seq-cargo-colgroup'); const hasActualSeqCols = !!document.getElementById('seq-discharging-act-dur-0'); if (colgroup) { if (mode === 'shifting') { colgroup.innerHTML = hasActualSeqCols ? ` ` : ` `; } else { colgroup.innerHTML = hasActualSeqCols ? ` ` : ` `; } } if (btnDis) btnDis.className = mode === 'discharging' ? activeClass : inactiveClass; if (btnLoad) btnLoad.className = mode === 'loading' ? activeClass : inactiveClass; if (btnShift) btnShift.className = mode === 'shifting' ? activeClass : inactiveClass; recalculateSequencingTotals(mode, mode === 'shifting'); if (mode === 'shifting' && typeof syncShiftingFromSof === 'function') { syncShiftingFromSof(false, false); } } function calculateRowSequencing(mode, rowIdx, triggerSource = 'auto') { if (mode === 'shifting') { recalculateSequencingTotals('shifting'); return; } const qtyInput = document.getElementById(`seq-${mode}-qty-${rowIdx}`); const row = document.querySelector(`.row-seq-${mode}[data-row-idx="${rowIdx}"]`) || (qtyInput ? qtyInput.closest('tr') : null); if (!row) return; const stdRate = parseFloat(row.dataset.stdRate) || 0; const stdTimeCell = document.getElementById(`seq-${mode}-std-time-${rowIdx}`); const stdTimeVal = document.getElementById(`seq-${mode}-std-time-val-${rowIdx}`); const actPerfInput = document.getElementById(`seq-${mode}-act-perf-${rowIdx}`); const actDurInput = document.getElementById(`seq-${mode}-act-dur-${rowIdx}`); const qty = parseFloat((qtyInput ? qtyInput.value : '').replace(/[^0-9.]/g, '')) || 0; // 1. Calculate STD Duration: qty / stdRate if (stdRate > 0 && qty > 0) { const totalHours = qty / stdRate; const h = Math.floor(totalHours); const m = Math.round((totalHours - h) * 60); const formattedTime = `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}`; if (stdTimeCell) stdTimeCell.textContent = formattedTime; if (stdTimeVal) stdTimeVal.value = formattedTime; } else { if (stdTimeCell) stdTimeCell.textContent = '00:00'; if (stdTimeVal) stdTimeVal.value = '00:00'; } // 2. Calculate Actual Performance & Actual Duration Time const isActualSource = (triggerSource === 'perf' || triggerSource === 'dur' || triggerSource === 'ts' || triggerSource === 'sof' || triggerSource === 'qty'); const tsSyncedEl = document.getElementById(`seq-${mode}-ts-synced-${rowIdx}`); const sofSyncedEl = document.getElementById(`seq-${mode}-sof-synced-${rowIdx}`); const isPerfFromTs = tsSyncedEl && tsSyncedEl.value === '1'; const isDurFromSof = sofSyncedEl && sofSyncedEl.value === '1'; if (actPerfInput && actDurInput) { if (triggerSource === 'sof') { // Duration updated by SOF Daily Working Record HOURS; preserve TimeSheet Actual Performance } else if (triggerSource === 'perf' || triggerSource === 'ts') { const actPerf = parseFloat((actPerfInput.value || '').replace(/[^0-9.]/g, '')) || 0; if (!isDurFromSof && actDurInput.dataset.manual !== 'true') { if (actPerf > 0 && qty > 0) { const totalActMinutes = (qty / actPerf) * 60; actDurInput.value = formatMinutesToContinuousTime(totalActMinutes); } else { actDurInput.value = '00:00'; } } } else if (triggerSource === 'dur') { const actDurHours = parseTimeToHours(actDurInput.value); if (!isPerfFromTs) { if (actDurHours > 0 && qty > 0) { const rate = qty / actDurHours; const formattedRate = (rate % 1 === 0) ? rate.toString() : rate.toFixed(2); actPerfInput.value = formattedRate; } else if (actDurHours === 0 && actDurInput.value.trim() === '') { actPerfInput.value = ''; } } } else { // triggerSource === 'qty' or 'auto' const actDurHours = parseTimeToHours(actDurInput.value); const actPerf = parseFloat((actPerfInput.value || '').replace(/[^0-9.]/g, '')) || 0; if (isDurFromSof) { // Preserve SOF Daily Working Record HOURS duration if (!isPerfFromTs && actDurHours > 0 && qty > 0 && actPerf === 0) { const rate = qty / actDurHours; actPerfInput.value = (rate % 1 === 0) ? rate.toString() : rate.toFixed(2); } } else if (actDurInput.dataset.manual === 'true' && actDurHours > 0) { if (!isPerfFromTs && qty > 0) { const rate = qty / actDurHours; const formattedRate = (rate % 1 === 0) ? rate.toString() : rate.toFixed(2); actPerfInput.value = formattedRate; } } else if (actPerf > 0) { if (qty > 0) { const totalActMinutes = (qty / actPerf) * 60; actDurInput.value = formatMinutesToContinuousTime(totalActMinutes); } else { actDurInput.value = '00:00'; } } else if (actDurHours > 0) { if (!isPerfFromTs && qty > 0) { const rate = qty / actDurHours; const formattedRate = (rate % 1 === 0) ? rate.toString() : rate.toFixed(2); actPerfInput.value = formattedRate; } } else if (actDurInput.dataset.manual !== 'true') { actDurInput.value = '00:00'; } } } recalculateSequencingTotals(mode, isActualSource); } function recalculateSequencingTotals(mode, forceSync = false) { const rows = document.querySelectorAll(`.row-seq-${mode}`); if (mode === 'shifting') { let totalQty = 0; let totalActMinutes = 0; let totalActPerfMinutes = 0; rows.forEach(row => { const idx = row.dataset.rowIdx; const qtyInput = document.getElementById(`seq-shifting-qty-${idx}`); if (qtyInput && qtyInput.value) { const q = parseFloat(qtyInput.value.replace(/[^0-9.]/g, '')) || 0; totalQty += q; } const actPerfInput = document.getElementById(`seq-shifting-act-perf-${idx}`); const actDurInput = document.getElementById(`seq-shifting-act-dur-${idx}`); if (actDurInput && actDurInput.value) { totalActMinutes += parseTimeToMinutes(actDurInput.value); } else if (actPerfInput && actPerfInput.value) { totalActMinutes += parseTimeToMinutes(actPerfInput.value); } }); totalActPerfMinutes = totalActMinutes; const totalQtyEl = document.getElementById('seq-shifting-total-qty'); if (totalQtyEl) { totalQtyEl.textContent = totalQty > 0 ? totalQty.toLocaleString() : '-'; } const totalQtyInp = document.getElementById('seq-shifting-total-qty-input'); if (totalQtyInp) { totalQtyInp.value = totalQty > 0 ? totalQty : ''; } // Total Actual Time (Column 3: Actual working time is range from-to, so total is "-") const actPerfEl = document.getElementById('seq-shifting-total-act-perf'); const actPerfFmtEl = document.getElementById('seq-shifting-total-act-perf-formatted'); const actPerfInp = document.getElementById('seq-shifting-total-act-perf-input'); const actPerfTimeInp = document.getElementById('seq-shifting-total-act-perf-time-input'); const actPerfFmtInp = document.getElementById('seq-shifting-total-act-perf-formatted-input') || document.getElementById('seq-shifting-total-act-formatted-input'); if (actPerfEl) actPerfEl.textContent = '-'; if (actPerfFmtEl) actPerfFmtEl.textContent = ''; if (actPerfInp) actPerfInp.value = ''; if (actPerfTimeInp) actPerfTimeInp.value = ''; if (actPerfFmtInp) actPerfFmtInp.value = ''; // Total Actual Duration Time (Column 4: Actual Duration Time - tetap kosong/0:00 kecuali diisi manual) const actH = Math.floor(totalActMinutes / 60); const actM = totalActMinutes % 60; const actTimeStr = totalActMinutes > 0 ? `${actH}:${String(actM).padStart(2, '0')}` : '0:00'; const actFormattedStr = totalActMinutes > 0 ? `${actH}hr${String(actM).padStart(2, '0')}min` : '0hr00min'; const actTimeEl = document.getElementById('seq-shifting-total-act-time'); const actFmtEl = document.getElementById('seq-shifting-total-act-formatted'); const actTimeInp = document.getElementById('seq-shifting-total-act-time-input'); const actFmtInp = document.getElementById('seq-shifting-total-act-formatted-input'); if (actTimeEl) actTimeEl.textContent = actTimeStr; if (actFmtEl) actFmtEl.textContent = `(${actFormattedStr})`; if (actTimeInp) actTimeInp.value = actTimeStr; if (actFmtInp) actFmtInp.value = actFormattedStr; syncToOperationStrategic(true, false); return; } let totalStdMinutes = 0; let totalActMinutes = 0; rows.forEach(row => { const idx = row.dataset.rowIdx; const stdTimeVal = document.getElementById(`seq-${mode}-std-time-val-${idx}`); const actDurInput = document.getElementById(`seq-${mode}-act-dur-${idx}`); if (stdTimeVal && stdTimeVal.value) { totalStdMinutes += parseTimeToMinutes(stdTimeVal.value); } if (actDurInput && actDurInput.value) { totalActMinutes += parseTimeToMinutes(actDurInput.value); } }); const stdH = Math.floor(totalStdMinutes / 60); const stdM = totalStdMinutes % 60; const stdTimeStr = `${stdH}:${String(stdM).padStart(2, '0')}`; const stdFormattedStr = `${stdH}hr${stdM}min`; const stdTimeEl = document.getElementById(`seq-${mode}-total-std-time`); const stdFmtEl = document.getElementById(`seq-${mode}-total-std-formatted`); const stdTimeInp = document.getElementById(`seq-${mode}-total-std-time-input`); const stdFmtInp = document.getElementById(`seq-${mode}-total-std-formatted-input`); if (stdTimeEl) stdTimeEl.textContent = stdTimeStr; if (stdFmtEl) stdFmtEl.textContent = stdFormattedStr; if (stdTimeInp) stdTimeInp.value = stdTimeStr; if (stdFmtInp) stdFmtInp.value = stdFormattedStr; const actH = Math.floor(totalActMinutes / 60); const actM = totalActMinutes % 60; const actTimeStr = `${actH}:${String(actM).padStart(2, '0')}`; const actFormattedStr = `${actH}hr${actM}min`; const actTimeEl = document.getElementById(`seq-${mode}-total-act-time`); const actFmtEl = document.getElementById(`seq-${mode}-total-act-formatted`); const actTimeInp = document.getElementById(`seq-${mode}-total-act-time-input`); const actFmtInp = document.getElementById(`seq-${mode}-total-act-formatted-input`); if (actTimeEl) actTimeEl.textContent = actTimeStr; if (actFmtEl) actFmtEl.textContent = `(${actFormattedStr})`; if (actTimeInp) actTimeInp.value = actTimeStr; if (actFmtInp) actFmtInp.value = actFormattedStr; syncToOperationStrategic(false, forceSync); } function syncToOperationStrategic(forceShifting = false, forceActualDur = false) { const approxInp = document.getElementById('op-strat-total-approx'); if (approxInp && (!approxInp.dataset.manual || approxInp.dataset.manual !== 'true')) { const disStdVal = document.getElementById('seq-discharging-total-std-time-input')?.value || document.getElementById('seq-discharging-total-std-time')?.textContent || ''; const loadStdVal = document.getElementById('seq-loading-total-std-time-input')?.value || document.getElementById('seq-loading-total-std-time')?.textContent || ''; const disStdMin = parseDurationStringToMinutes(disStdVal); const loadStdMin = parseDurationStringToMinutes(loadStdVal); const totalStdMin = disStdMin + loadStdMin; if (totalStdMin > 0) { const h = Math.floor(totalStdMin / 60); const m = totalStdMin % 60; approxInp.value = `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}`; } else { approxInp.value = '00:00'; } } // Ambil data Shifting (Actual Duration Time) dari Shifting Sequencing Total Actual Duration Time (Column 4) const shiftActDurVal = document.getElementById('seq-shifting-total-act-time-input')?.value || document.getElementById('seq-shifting-total-act-time')?.textContent || ''; let shiftActPerfMin = parseDurationStringToMinutes(shiftActDurVal); if (shiftActPerfMin === 0) { document.querySelectorAll('.row-seq-shifting').forEach(row => { const idx = row.dataset.rowIdx; const d = document.getElementById(`seq-shifting-act-dur-${idx}`)?.value || ''; const p = document.getElementById(`seq-shifting-act-perf-${idx}`)?.value || ''; shiftActPerfMin += (parseTimeToMinutes(d) || parseTimeToMinutes(p)); }); } const actDurInp = document.getElementById('op-strat-actual-dur'); if (actDurInp) { if (forceActualDur) { delete actDurInp.dataset.manual; } if (!actDurInp.dataset.manual || actDurInp.dataset.manual !== 'true') { const disActVal = document.getElementById('seq-discharging-total-act-time-input')?.value || document.getElementById('seq-discharging-total-act-time')?.textContent || ''; const loadActVal = document.getElementById('seq-loading-total-act-time-input')?.value || document.getElementById('seq-loading-total-act-time')?.textContent || ''; const disActMin = parseDurationStringToMinutes(disActVal); const loadActMin = parseDurationStringToMinutes(loadActVal); const totalActMin = disActMin + loadActMin; if (totalActMin > 0) { const ah = Math.floor(totalActMin / 60); const am = totalActMin % 60; actDurInp.value = `${String(ah).padStart(2, '0')}:${String(am).padStart(2, '0')}`; } else { actDurInp.value = '00:00'; } } } // Shifting pada Actual Duration Time Operation Strategic sinkron dengan Total Actual Duration Time Sequencing const shiftActInp = document.getElementById('op-strat-actual-shifting'); const shiftingFormattedVal = shiftActPerfMin > 0 ? `${String(Math.floor(shiftActPerfMin / 60)).padStart(2, '0')}:${String(shiftActPerfMin % 60).padStart(2, '0')}` : ''; if (shiftActInp) { if (forceShifting) { delete shiftActInp.dataset.manual; } if (!shiftActInp.dataset.manual || shiftActInp.dataset.manual !== 'true') { shiftActInp.value = shiftingFormattedVal || '00:00'; } } calcOpStrategicRealtimeOperation(); } function recalcAllSequencing(mode = null) { if (!mode) { recalcAllSequencing('discharging'); recalcAllSequencing('loading'); recalcAllSequencing('shifting'); return; } if (mode === 'shifting') { recalculateSequencingTotals('shifting', true); return; } const rows = document.querySelectorAll(`.row-seq-${mode}`); rows.forEach(row => { calculateRowSequencing(mode, row.dataset.rowIdx); }); } // ========================================== // DATA CARGO TAB SWITCHING (DISCHARGING / LOADING) // ========================================== // ========================================== // SILENT AUTOMATIC SOF SYNC (NO WARNING BANNER) // ========================================== let currentCargoTab = 'discharging'; let lastSofSyncedKey = ''; let sofSyncTimer = null; let sofSyncAbortCtrl = null; let lastTsSyncedKey = ''; let tsSyncAbortCtrl = null; function isSofEmptyValue(val) { return ['', '-', '0', '0:00', '00:00', '0.00', '00.00'].includes(String(val ?? '').trim()); } function applySofSyncedInput(el, newVal, isVesselChange, dispatchEvents = false) { if (!el) return false; if (el.dataset.manual === 'true' && !isVesselChange) return false; if (isVesselChange && el.dataset.sofSynced === 'true') { delete el.dataset.manual; } const canOverwrite = isVesselChange || isSofEmptyValue(el.value) || el.dataset.sofSynced === 'true'; if (!canOverwrite || el.dataset.manual === 'true') return false; if (el.value !== newVal) { el.value = newVal; if (dispatchEvents) { el.dispatchEvent(new Event('input', { bubbles: true })); el.dispatchEvent(new Event('change', { bubbles: true })); } } el.dataset.sofSynced = 'true'; return true; } async function syncShiftingFromSof(force = false, isVesselChange = false) { const bar = document.getElementById('seq-shifting-sof-bar'); if (!bar) return; const endpoint = bar.dataset.endpoint; if (!endpoint) return; const vesselInput = document.querySelector('input[name="vessel"]'); const voyageInput = document.querySelector('input[name="no_voyage"]'); const groupInput = document.querySelector('input[name="planning_group_id"], select[name="planning_group_id"]'); const planningId = bar.dataset.planningId || ''; const planningGroupId = (groupInput && groupInput.value) ? groupInput.value : (bar.dataset.planningGroupId || ''); const vessel = vesselInput ? vesselInput.value.trim() : ''; const voyage = voyageInput ? voyageInput.value.trim() : ''; if (!vessel && !planningId && !planningGroupId) return; const syncKey = `${planningId}|${planningGroupId}|${vessel.toLowerCase()}|${voyage.toLowerCase()}`; if (!force && syncKey === lastSofSyncedKey) return; const params = new URLSearchParams(); if (planningId) params.set('planning_id', planningId); if (planningGroupId) params.set('planning_group_id', planningGroupId); if (vessel) params.set('vessel', vessel); if (voyage) params.set('voyage', voyage); if (sofSyncAbortCtrl) { sofSyncAbortCtrl.abort(); } sofSyncAbortCtrl = new AbortController(); try { const resp = await fetch(`${endpoint}?${params.toString()}`, { headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }, signal: sofSyncAbortCtrl.signal, }); if (!resp.ok) return; const data = await resp.json(); lastSofSyncedKey = syncKey; if (!data.found) return; const rows = document.querySelectorAll('#seq-tbody-shifting tr.row-seq-shifting'); const byCategory = data.by_category || {}; const qtyByCategory = data.shifting_qty_by_category || {}; const workingTimes = data.working_times || {}; const hasEvalShiftingQtySync = !!document.getElementById('seq-shifting-sof-qty-synced-0'); rows.forEach((tr) => { const idx = tr.dataset.rowIdx; if (idx === undefined) return; const catInput = tr.querySelector(`input[name="sequencing_cargo_data[shifting][rows][${idx}][category]"]`); const actPerfInput = document.getElementById(`seq-shifting-act-perf-${idx}`); const actDurInput = document.getElementById(`seq-shifting-act-dur-${idx}`); const syncedInput = document.getElementById(`seq-shifting-sof-synced-${idx}`); const qtyInput = document.getElementById(`seq-shifting-qty-${idx}`); const qtySyncedInput = document.getElementById(`seq-shifting-sof-qty-synced-${idx}`); if (!catInput) return; const cat = catInput.value; // 1. Sync Shifting Qty (ONLY on Evaluation form) from SOF Daily Working Record REMARKS numbers if (hasEvalShiftingQtySync && qtyInput && qtySyncedInput) { const wasQtySynced = qtySyncedInput.value === '1'; const isQtyManual = !isVesselChange && qtyInput.dataset.manual === 'true' && !wasQtySynced; if (!isQtyManual) { const sofQty = qtyByCategory[cat] ? String(qtyByCategory[cat]).trim() : ''; const curQty = qtyInput.value.trim(); const isQtyEmpty = (curQty === '' || curQty === '-'); if (sofQty !== '') { if (isQtyEmpty || wasQtySynced || isVesselChange) { qtyInput.value = sofQty; delete qtyInput.dataset.manual; qtySyncedInput.value = '1'; } } else if (wasQtySynced || isVesselChange) { if (wasQtySynced || isQtyEmpty) { qtyInput.value = ''; delete qtyInput.dataset.manual; qtySyncedInput.value = ''; } } } } // 2. Sync Shifting Actual Working Time & Actual Duration Time if (!actPerfInput && !actDurInput) return; const isRowManual = !isVesselChange && ((actPerfInput && actPerfInput.dataset.manual === 'true') || (actDurInput && actDurInput.dataset.manual === 'true')); if (isRowManual) return; const durVal = byCategory[cat] || ''; const wtVal = workingTimes[cat] || durVal; const wasSofSynced = syncedInput && syncedInput.value === '1'; if (durVal !== '' || wtVal !== '') { if (actPerfInput) { actPerfInput.value = wtVal; delete actPerfInput.dataset.manual; } if (actDurInput) { actDurInput.value = durVal; delete actDurInput.dataset.manual; } if (syncedInput) syncedInput.value = '1'; } else if (wasSofSynced || isVesselChange) { if (actPerfInput && (wasSofSynced || isSofEmptyValue(actPerfInput.value))) { actPerfInput.value = ''; delete actPerfInput.dataset.manual; } if (actDurInput && (wasSofSynced || isSofEmptyValue(actDurInput.value))) { actDurInput.value = ''; delete actDurInput.dataset.manual; } if (syncedInput) syncedInput.value = ''; } }); recalculateSequencingTotals('shifting', true); // Sinkronkan Actual Duration Time pada Discharging & Loading dari Daily Working Record HOURS SOF sesuai remark if (document.getElementById('seq-discharging-act-dur-0')) { ['discharging', 'loading'].forEach((mode) => { const modeDurations = mode === 'discharging' ? (data.discharging_durations || {}) : (data.loading_durations || {}); const modeRows = document.querySelectorAll(`#seq-tbody-${mode} tr.row-seq-${mode}`); let updatedMode = false; modeRows.forEach((tr) => { const idx = tr.dataset.rowIdx; if (idx === undefined) return; const catInput = tr.querySelector(`input[name="sequencing_cargo_data[${mode}][rows][${idx}][category]"]`); const actDurInput = document.getElementById(`seq-${mode}-act-dur-${idx}`); const sofSyncedInput = document.getElementById(`seq-${mode}-sof-synced-${idx}`); if (!catInput || !actDurInput) return; const wasSofSynced = sofSyncedInput && sofSyncedInput.value === '1'; const isRowManual = !isVesselChange && actDurInput.dataset.manual === 'true' && !wasSofSynced; if (isRowManual) return; const cat = catInput.value; const sofDur = modeDurations[cat] ? String(modeDurations[cat]).trim() : ''; if (sofDur !== '') { if (actDurInput.value.trim() !== sofDur || !wasSofSynced) { actDurInput.value = sofDur; updatedMode = true; } delete actDurInput.dataset.manual; if (sofSyncedInput) sofSyncedInput.value = '1'; calculateRowSequencing(mode, idx, 'sof'); } else if (wasSofSynced) { actDurInput.value = '00:00'; delete actDurInput.dataset.manual; if (sofSyncedInput) sofSyncedInput.value = ''; calculateRowSequencing(mode, idx, 'ts'); updatedMode = true; } }); if (updatedMode) { recalculateSequencingTotals(mode, true); } }); } // Sinkronkan Waiting Cargo / Document pada Operation Strategic (Actual) if (data.waiting_cargo_doc !== undefined && data.waiting_cargo_doc !== '') { const waitVal = data.waiting_cargo_doc === '-' ? '00:00' : data.waiting_cargo_doc; applySofSyncedInput(document.getElementById('op-strat-actual-waiting-cargo-doc'), waitVal, isVesselChange); } // Sinkronkan Idle Time / Stop Operation pada Operation Strategic (Actual) dari HOURS Daily Working Record sesuai remark if (data.daily_working_total_hours !== undefined && data.daily_working_total_hours !== '') { const idleVal = data.daily_working_total_hours === '-' ? '00:00' : data.daily_working_total_hours; const idleEl = document.getElementById('op-strat-actual-idle-time'); const idleApplied = applySofSyncedInput(idleEl, idleVal, isVesselChange); const idleSyncHidden = document.getElementById('op-strat-actual-idle-time-sof-synced'); if (idleSyncHidden && idleApplied) { idleSyncHidden.value = '1'; } } // Sinkronkan MEAL BREAK pada Operation Strategic (Actual) dari HOURS Daily Working Record sesuai remark if (data.meal_break !== undefined && data.meal_break !== '') { const mealVal = data.meal_break === '-' ? '00:00' : data.meal_break; const mealEl = document.getElementById('op-strat-actual-meal-break'); const mealApplied = applySofSyncedInput(mealEl, mealVal, isVesselChange); const mealSyncHidden = document.getElementById('op-strat-actual-meal-break-sof-synced'); if (mealSyncHidden && mealApplied) { mealSyncHidden.value = '1'; } } calcOpStrategicRealtimeOperation(); // Sinkronkan Open ramp & Close ramp actual time/date + Actual Available Time dari SOF const openRow = getOperatingVesselRowByName('open ramp') || getOperatingVesselRowByName('open rampdoor'); const closeRow = getOperatingVesselRowByName('close ramp') || getOperatingVesselRowByName('close rampdoor'); if (openRow && (data.open_ramp_time || data.open_ramp_date)) { const idx = openRow.dataset.opIdx; if (data.open_ramp_date) { applySofSyncedInput(document.getElementById(`op-act-date-${idx}`), data.open_ramp_date, isVesselChange, true); } if (data.open_ramp_time) { applySofSyncedInput(document.getElementById(`op-act-time-${idx}`), data.open_ramp_time, isVesselChange, true); } } if (closeRow && (data.close_ramp_time || data.close_ramp_date)) { const idx = closeRow.dataset.opIdx; if (data.close_ramp_date) { applySofSyncedInput(document.getElementById(`op-act-date-${idx}`), data.close_ramp_date, isVesselChange, true); } if (data.close_ramp_time) { applySofSyncedInput(document.getElementById(`op-act-time-${idx}`), data.close_ramp_time, isVesselChange, true); } } if (data.actual_available_time !== undefined && data.actual_available_time !== '' && data.has_ramp_avail) { applySofSyncedInput(document.getElementById('op-strat-actual-available-time'), data.actual_available_time, isVesselChange); } else if (isVesselChange) { const actAvailEl = document.getElementById('op-strat-actual-available-time'); if (actAvailEl && actAvailEl.dataset.sofSynced === 'true' && actAvailEl.dataset.manual !== 'true') { actAvailEl.value = '00:00'; delete actAvailEl.dataset.sofSynced; } } } catch (err) { if (err && err.name === 'AbortError') return; } } async function syncPerformanceFromTimeSheet(force = false, isVesselChange = false) { const bar = document.getElementById('seq-shifting-sof-bar'); if (!bar) return; // Only run on Evaluation form where Discharging & Loading Actual Performance inputs exist if (!document.getElementById('seq-discharging-act-perf-0')) return; const endpoint = bar.dataset.timesheetEndpoint; if (!endpoint) return; const vesselInput = document.querySelector('input[name="vessel"]'); const voyageInput = document.querySelector('input[name="no_voyage"]'); const groupInput = document.querySelector('input[name="planning_group_id"], select[name="planning_group_id"]'); const planningId = bar.dataset.planningId || ''; const planningGroupId = (groupInput && groupInput.value) ? groupInput.value : (bar.dataset.planningGroupId || ''); const vessel = vesselInput ? vesselInput.value.trim() : ''; const voyage = voyageInput ? voyageInput.value.trim() : ''; if (!vessel && !planningId && !planningGroupId) return; const syncKey = `${planningId}|${planningGroupId}|${vessel.toLowerCase()}|${voyage.toLowerCase()}`; if (!force && syncKey === lastTsSyncedKey) return; const params = new URLSearchParams(); if (planningId) params.set('planning_id', planningId); if (planningGroupId) params.set('planning_group_id', planningGroupId); if (vessel) params.set('vessel', vessel); if (voyage) params.set('voyage', voyage); if (tsSyncAbortCtrl) { tsSyncAbortCtrl.abort(); } tsSyncAbortCtrl = new AbortController(); try { const resp = await fetch(`${endpoint}?${params.toString()}`, { headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }, signal: tsSyncAbortCtrl.signal, }); if (!resp.ok) return; const data = await resp.json(); lastTsSyncedKey = syncKey; if (!data.found) return; ['discharging', 'loading'].forEach((mode) => { const modeData = data[mode] || {}; const rows = document.querySelectorAll(`#seq-tbody-${mode} tr.row-seq-${mode}`); let updatedAny = false; rows.forEach((tr) => { const idx = tr.dataset.rowIdx; if (idx === undefined) return; const catInput = tr.querySelector(`input[name="sequencing_cargo_data[${mode}][rows][${idx}][category]"]`); const actPerfInput = document.getElementById(`seq-${mode}-act-perf-${idx}`); const tsSyncedInput = document.getElementById(`seq-${mode}-ts-synced-${idx}`); if (!catInput || !actPerfInput) return; const isRowManual = !isVesselChange && actPerfInput.dataset.manual === 'true'; if (isRowManual) return; const cat = catInput.value; const tsVal = modeData[cat] ? String(modeData[cat]).trim() : ''; const curVal = actPerfInput.value.trim(); const isEmpty = (curVal === '' || curVal === '-' || curVal === '0'); const wasSynced = tsSyncedInput && tsSyncedInput.value === '1'; if (tsVal !== '') { if (isEmpty || wasSynced || isVesselChange) { actPerfInput.value = tsVal; delete actPerfInput.dataset.manual; if (tsSyncedInput) tsSyncedInput.value = '1'; calculateRowSequencing(mode, idx, 'ts'); updatedAny = true; } } else if (wasSynced || isVesselChange) { if (wasSynced || isEmpty) { actPerfInput.value = ''; delete actPerfInput.dataset.manual; if (tsSyncedInput) tsSyncedInput.value = ''; calculateRowSequencing(mode, idx, 'ts'); updatedAny = true; } } }); if (updatedAny) { recalculateSequencingTotals(mode, true); } }); } catch (err) { if (err && err.name === 'AbortError') return; } } function scheduleAutoSofSync(isVesselChange = true, delayMs = 300) { if (!document.getElementById('seq-shifting-sof-bar')) return; if (sofSyncTimer) clearTimeout(sofSyncTimer); sofSyncTimer = setTimeout(() => { syncShiftingFromSof(isVesselChange, isVesselChange); syncPerformanceFromTimeSheet(isVesselChange, isVesselChange); }, delayMs); } function initAutoSofSync() { const bar = document.getElementById('seq-shifting-sof-bar'); if (!bar) return; // Track genuine user edits on SOF-synced and TimeSheet-synced fields so automatic sync respects manual overrides document.addEventListener('input', function(e) { if (!e.isTrusted || !e.target) return; if (e.target.matches('.row-seq-shifting input[id^="seq-shifting-act-"], .row-op-vessel input[id^="op-act-"]')) { if (e.target.value.trim() === '') { delete e.target.dataset.manual; } else { e.target.dataset.manual = 'true'; delete e.target.dataset.sofSynced; } } else if (e.target.matches('input[id^="seq-discharging-act-perf-"], input[id^="seq-loading-act-perf-"]')) { const syncHidden = e.target.id.replace('-act-perf-', '-ts-synced-'); const tsEl = document.getElementById(syncHidden); if (tsEl) tsEl.value = ''; if (e.target.value.trim() === '') { delete e.target.dataset.manual; } else { e.target.dataset.manual = 'true'; } } else if (e.target.matches('input[id^="seq-shifting-qty-"]')) { const qtySyncedHidden = e.target.id.replace('-qty-', '-sof-qty-synced-'); const qEl = document.getElementById(qtySyncedHidden); if (qEl) qEl.value = ''; if (e.target.value.trim() === '') { delete e.target.dataset.manual; } else { e.target.dataset.manual = 'true'; } } else if (e.target.matches('input[id^="seq-discharging-act-dur-"], input[id^="seq-loading-act-dur-"]')) { const sofHidden = e.target.id.replace('-act-dur-', '-sof-synced-'); const sofEl = document.getElementById(sofHidden); if (sofEl) sofEl.value = ''; const val = e.target.value.trim(); if (val === '' || val === '00:00') { delete e.target.dataset.manual; } else { e.target.dataset.manual = 'true'; } } }); const triggerSelectors = ['input[name="vessel"]', 'input[name="no_voyage"]', 'input[name="planning_group_id"]', 'select[name="planning_group_id"]']; document.querySelectorAll(triggerSelectors.join(', ')).forEach((el) => { el.addEventListener('input', () => scheduleAutoSofSync(true, 350)); el.addEventListener('change', () => scheduleAutoSofSync(true, 50)); }); // Initial automatic sync on page load (no click or warning needed) syncShiftingFromSof(false, false); syncPerformanceFromTimeSheet(false, false); } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', initAutoSofSync); } else { initAutoSofSync(); } function switchCargoTab(mode) { currentCargoTab = mode; const tbodyDis = document.getElementById('cargo-tbody'); const tbodyLoad = document.getElementById('cargo-loading-tbody'); const tfootDis = document.getElementById('cargo-tfoot-discharging'); const tfootLoad = document.getElementById('cargo-tfoot-loading'); const emptyDis = document.getElementById('cargo-empty-state'); const emptyLoad = document.getElementById('cargo-loading-empty-state'); const btnDis = document.getElementById('btn-cargo-tab-discharging'); const btnLoad = document.getElementById('btn-cargo-tab-loading'); const labelsDis = document.querySelectorAll('.cargo-header-label-discharging'); const labelsLoad = document.querySelectorAll('.cargo-header-label-loading'); const badge = document.getElementById('cargo-row-counter-badge'); const disCount = document.querySelectorAll('.cargo-row').length; const loadCount = document.querySelectorAll('.cargo-loading-row').length; if (mode === 'discharging') { if (tbodyDis) tbodyDis.classList.remove('hidden'); if (tbodyLoad) tbodyLoad.classList.add('hidden'); if (tfootDis) tfootDis.classList.remove('hidden'); if (tfootLoad) tfootLoad.classList.add('hidden'); if (emptyDis) emptyDis.classList.toggle('hidden', disCount > 0); if (emptyLoad) emptyLoad.classList.add('hidden'); labelsDis.forEach(el => el.classList.remove('hidden')); labelsLoad.forEach(el => el.classList.add('hidden')); if (btnDis) { btnDis.className = 'px-3.5 py-1.5 rounded-lg font-bold transition-all bg-white text-blue-600 shadow-sm border border-slate-200/60 cursor-pointer'; } if (btnLoad) { btnLoad.className = 'px-3.5 py-1.5 rounded-lg font-bold transition-all text-slate-600 hover:text-slate-900 border border-transparent cursor-pointer'; } if (badge) badge.textContent = `${disCount} Item`; } else { if (tbodyDis) tbodyDis.classList.add('hidden'); if (tbodyLoad) tbodyLoad.classList.remove('hidden'); if (tfootDis) tfootDis.classList.add('hidden'); if (tfootLoad) tfootLoad.classList.remove('hidden'); if (emptyDis) emptyDis.classList.add('hidden'); if (emptyLoad) emptyLoad.classList.toggle('hidden', loadCount > 0); labelsDis.forEach(el => el.classList.add('hidden')); labelsLoad.forEach(el => el.classList.remove('hidden')); if (btnDis) { btnDis.className = 'px-3.5 py-1.5 rounded-lg font-bold transition-all text-slate-600 hover:text-slate-900 border border-transparent cursor-pointer'; } if (btnLoad) { btnLoad.className = 'px-3.5 py-1.5 rounded-lg font-bold transition-all bg-white text-blue-600 shadow-sm border border-slate-200/60 cursor-pointer'; } if (badge) badge.textContent = `${loadCount} Item`; } } function addCurrentCargoRow() { if (currentCargoTab === 'discharging') { addCargoRow(); } else { addLoadingCargoRow(); } } // ========================================== // DATA CARGO REALTIME MANAGEMENT & CALCULATION // ========================================== let cargoRowCounter = 0; function escapeCargoHtml(str) { if (str === null || str === undefined) return ''; return String(str) .replace(/&/g, '&') .replace(/"/g, '"') .replace(/'/g, ''') .replace(//g, '>'); } function updateCargoRowHighlight(elem) { const tr = elem && elem.closest ? elem.closest('tr') : (elem && elem.tagName === 'TR' ? elem : null); if (!tr) return; const steveSelect = tr.querySelector('[name*="[stevedoring]"]'); const cargoSelect = tr.querySelector('[name*="[cargodoring]"]'); const steve = (steveSelect ? steveSelect.value : '').trim().toUpperCase(); const cargo = (cargoSelect ? cargoSelect.value : '').trim().toUpperCase(); function getHighlightClass(val) { if (val === 'UNCERTAIN') return 'marked-uncertain'; if (val && val !== 'APS' && val !== '-' && val !== '0') return 'marked-non-aps'; if (val === 'APS') return 'marked-aps'; return ''; } // Stevedoring cell const steveTd = steveSelect ? steveSelect.closest('td') : null; if (steveTd) { steveTd.classList.remove('marked-non-aps', 'marked-uncertain', 'marked-aps'); const sc = getHighlightClass(steve); if (sc) steveTd.classList.add(sc); } // Cargodoring cell const cargoTd = cargoSelect ? cargoSelect.closest('td') : null; if (cargoTd) { cargoTd.classList.remove('marked-non-aps', 'marked-uncertain', 'marked-aps'); const cc = getHighlightClass(cargo); if (cc) cargoTd.classList.add(cc); } // Discharging and Loading quantity cells remain clean without coloring const qtyTds = tr.querySelectorAll('.cargo-qty-td, .cargo-loading-qty-td'); qtyTds.forEach(td => td.classList.remove('marked-non-aps', 'marked-uncertain', 'marked-aps')); // Status highlight for Nominative Owner (Consignee) const isUncertain = (steve === 'UNCERTAIN' || cargo === 'UNCERTAIN'); const isNonAps = !isUncertain && ((steve && steve !== 'APS' && steve !== '-' && steve !== '0') || (cargo && cargo !== 'APS' && cargo !== '-' && cargo !== '0')); const isAps = !isUncertain && !isNonAps && (steve === 'APS' || cargo === 'APS'); const rowClass = isNonAps ? 'marked-non-aps' : (isUncertain ? 'marked-uncertain' : (isAps ? 'marked-aps' : '')); const consigneeTds = tr.querySelectorAll('.cargo-consignee-td, .cargo-loading-consignee-td'); consigneeTds.forEach(td => { td.classList.remove('marked-non-aps', 'marked-uncertain', 'marked-aps'); if (rowClass) td.classList.add(rowClass); }); } function addCargoRow(data = {}) { const tbody = document.getElementById('cargo-tbody'); if (!tbody) return; const rowIdx = cargoRowCounter++; const cargo = data.cargo || data.cargo_name || data.name || ''; const cargoType = data.cargo_type || data.type || ''; const discharging = data.discharging !== undefined && data.discharging !== null ? data.discharging : ''; const unit = (data.unit || 'UNITS').toUpperCase() === 'PKGS' ? 'PKGS' : 'UNITS'; const stevedoring = data.stevedoring || 'APS'; const cargodoring = data.cargodoring || 'APS'; const consignee = data.consignee || ''; const tr = document.createElement('tr'); tr.className = 'transition-colors odd:bg-blue-50/70 even:bg-blue-100/60 hover:bg-blue-100 text-slate-900 cargo-row'; tr.id = `cargo-row-${rowIdx}`; tr.dataset.cargoIdx = rowIdx; tr.innerHTML = ` 1
`; tbody.appendChild(tr); updateCargoRowHighlight(tr); updateCargoRowNumbers(); recalculateCargoTotals(); } function removeCargoRow(rowIdx) { const row = document.getElementById(`cargo-row-${rowIdx}`); if (row) { row.remove(); updateCargoRowNumbers(); recalculateCargoTotals(); } } function updateCargoRowNumbers() { const rows = document.querySelectorAll('.cargo-row'); rows.forEach((row, idx) => { const numEl = row.querySelector('.cargo-row-number'); if (numEl) numEl.textContent = idx + 1; }); const emptyState = document.getElementById('cargo-empty-state'); if (emptyState) { if (rows.length === 0 && currentCargoTab === 'discharging') { emptyState.classList.remove('hidden'); } else { emptyState.classList.add('hidden'); } } const badge = document.getElementById('cargo-row-counter-badge'); if (badge && currentCargoTab === 'discharging') { badge.textContent = `${rows.length} Item`; } const summaryLabel = document.getElementById('cargo-total-summary-label'); if (summaryLabel) summaryLabel.textContent = ""; } function recalculateCargoTotals() { let total = 0; let totalUnits = 0; let totalPkgs = 0; document.querySelectorAll('.cargo-row').forEach(row => { const inp = row.querySelector('.cargo-discharging-input'); const sel = row.querySelector('.cargo-unit-select'); const val = parseInt(inp ? inp.value : 0, 10) || 0; const u = sel ? sel.value : 'UNITS'; total += val; if (u === 'PKGS') { totalPkgs += val; } else { totalUnits += val; } }); const totalEl = document.getElementById('cargo-total-discharging'); if (totalEl) { if (totalPkgs > 0 && totalUnits > 0) { totalEl.textContent = `${new Intl.NumberFormat('id-ID').format(totalUnits)} UNITS + ${new Intl.NumberFormat('id-ID').format(totalPkgs)} PKGS`; } else if (totalPkgs > 0) { totalEl.textContent = `${new Intl.NumberFormat('id-ID').format(totalPkgs)} PKGS`; } else { totalEl.textContent = new Intl.NumberFormat('id-ID').format(total); } } syncCombinedEstimasiUnit(); recalculateTotalCargoSummary(); } function syncCombinedEstimasiUnit() { let totalD = 0; document.querySelectorAll('.cargo-row').forEach(row => { const inp = row.querySelector('.cargo-discharging-input'); totalD += parseInt(inp ? inp.value : 0, 10) || 0; }); let totalL = 0; document.querySelectorAll('.cargo-loading-row').forEach(row => { const inp = row.querySelector('.cargo-loading-input'); totalL += parseInt(inp ? inp.value : 0, 10) || 0; }); const combined = totalD + totalL; const unitInp = document.querySelector('input[name="estimasi_unit"]'); if (unitInp && (!unitInp.value || unitInp.value === '0') && combined > 0) { unitInp.value = combined; } } // ========================================== // DATA CARGO LOADING REALTIME MANAGEMENT & CALCULATION // ========================================== let loadingCargoRowCounter = 0; function addLoadingCargoRow(data = {}) { const tbody = document.getElementById('cargo-loading-tbody'); if (!tbody) return; const rowIdx = loadingCargoRowCounter++; const cargo = data.cargo || data.cargo_name || data.name || ''; const cargoType = data.cargo_type || data.type || ''; const loading = data.loading !== undefined && data.loading !== null ? data.loading : ''; const unit = (data.unit || 'UNITS').toUpperCase() === 'PKGS' ? 'PKGS' : 'UNITS'; const stevedoring = data.stevedoring || 'APS'; const cargodoring = data.cargodoring || 'APS'; const consignee = data.consignee || ''; const tr = document.createElement('tr'); tr.className = 'transition-colors odd:bg-blue-50/70 even:bg-blue-100/60 hover:bg-blue-100 text-slate-900 cargo-loading-row'; tr.id = `cargo-loading-row-${rowIdx}`; tr.dataset.cargoIdx = rowIdx; tr.innerHTML = ` 1
`; tbody.appendChild(tr); updateCargoRowHighlight(tr); updateLoadingCargoRowNumbers(); recalculateLoadingCargoTotals(); } function removeLoadingCargoRow(rowIdx) { const row = document.getElementById(`cargo-loading-row-${rowIdx}`); if (row) { row.remove(); updateLoadingCargoRowNumbers(); recalculateLoadingCargoTotals(); } } function updateLoadingCargoRowNumbers() { const rows = document.querySelectorAll('.cargo-loading-row'); rows.forEach((row, idx) => { const numEl = row.querySelector('.cargo-loading-row-number'); if (numEl) numEl.textContent = idx + 1; }); const emptyState = document.getElementById('cargo-loading-empty-state'); if (emptyState) { if (rows.length === 0 && currentCargoTab === 'loading') { emptyState.classList.remove('hidden'); } else { emptyState.classList.add('hidden'); } } const badge = document.getElementById('cargo-row-counter-badge'); if (badge && currentCargoTab === 'loading') { badge.textContent = `${rows.length} Item`; } const summaryLabel = document.getElementById('cargo-loading-total-summary-label'); if (summaryLabel) summaryLabel.textContent = ""; } function recalculateLoadingCargoTotals() { let total = 0; let totalUnits = 0; let totalPkgs = 0; document.querySelectorAll('.cargo-loading-row').forEach(row => { const inp = row.querySelector('.cargo-loading-input'); const sel = row.querySelector('.cargo-loading-unit-select'); const val = parseInt(inp ? inp.value : 0, 10) || 0; const u = sel ? sel.value : 'UNITS'; total += val; if (u === 'PKGS') { totalPkgs += val; } else { totalUnits += val; } }); const totalEl = document.getElementById('cargo-total-loading'); if (totalEl) { if (totalPkgs > 0 && totalUnits > 0) { totalEl.textContent = `${new Intl.NumberFormat('id-ID').format(totalUnits)} UNITS + ${new Intl.NumberFormat('id-ID').format(totalPkgs)} PKGS`; } else if (totalPkgs > 0) { totalEl.textContent = `${new Intl.NumberFormat('id-ID').format(totalPkgs)} PKGS`; } else { totalEl.textContent = new Intl.NumberFormat('id-ID').format(total); } } syncCombinedEstimasiUnit(); recalculateTotalCargoSummary(); } // ========================================== // TOTAL KATEGORI CARGO (DISCHARGING + LOADING) // ========================================== function categorizeCargo(cargoName, cargoType, unit) { const type = (cargoType || '').trim().toLowerCase(); const name = (cargoName || '').trim().toLowerCase(); const u = (unit || '').trim().toUpperCase(); if (u === 'PKGS' || type.includes('part') || name.includes('part') || name.includes('sparepart') || type.includes('pkg')) { return 'part'; } if (type.includes('mafi') || name.includes('mafi')) { return 'mafi'; } if (type === 'hh' || type.includes('heavy') || type.includes('alat berat') || name.includes('excavator') || name.includes('forklift') || name.includes('bulldozer') || name.includes('loader') || name.includes('crane')) { return 'hh'; } if (type.includes('bus') || name.includes('bus') || name.includes('commuter') || name.includes('coaster') || name.includes('microbus')) { return 'bus'; } if (type.includes('truck') || type.includes('truk') || name.includes('truck') || name.includes('truk') || name.includes('dyna') || name.includes('fuso') || name.includes('hino') || name.includes('canter') || name.includes('tronton') || name.includes('trailer')) { return 'truck'; } return 'mobil_cbu'; } function recalculateTotalCargoSummary() { const summary = { mobil_cbu: { discharging: 0, loading: 0, total: 0 }, truck: { discharging: 0, loading: 0, total: 0 }, bus: { discharging: 0, loading: 0, total: 0 }, hh: { discharging: 0, loading: 0, total: 0 }, part: { discharging: 0, loading: 0, total: 0 }, mafi: { discharging: 0, loading: 0, total: 0 } }; // Scan Discharging rows document.querySelectorAll('.cargo-row').forEach(row => { const nameInput = row.querySelector('input[name*="[cargo]"]'); const typeInput = row.querySelector('input[name*="[cargo_type]"]'); const qtyInput = row.querySelector('.cargo-discharging-input'); const unitSelect = row.querySelector('.cargo-unit-select'); const name = nameInput ? nameInput.value : ''; const type = typeInput ? typeInput.value : ''; const qty = parseInt(qtyInput ? qtyInput.value : 0, 10) || 0; const unit = unitSelect ? unitSelect.value : 'UNITS'; if (qty > 0 || name || type) { const cat = categorizeCargo(name, type, unit); if (summary[cat]) { summary[cat].discharging += qty; } } }); // Scan Loading rows document.querySelectorAll('.cargo-loading-row').forEach(row => { const nameInput = row.querySelector('input[name*="[cargo]"]'); const typeInput = row.querySelector('input[name*="[cargo_type]"]'); const qtyInput = row.querySelector('.cargo-loading-input'); const unitSelect = row.querySelector('.cargo-loading-unit-select'); const name = nameInput ? nameInput.value : ''; const type = typeInput ? typeInput.value : ''; const qty = parseInt(qtyInput ? qtyInput.value : 0, 10) || 0; const unit = unitSelect ? unitSelect.value : 'UNITS'; if (qty > 0 || name || type) { const cat = categorizeCargo(name, type, unit); if (summary[cat]) { summary[cat].loading += qty; } } }); let grandDischarging = 0; let grandLoading = 0; let grandTotal = 0; const cats = ['mobil_cbu', 'truck', 'bus', 'hh', 'part', 'mafi']; cats.forEach(cat => { const d = summary[cat].discharging; const l = summary[cat].loading; const t = d + l; summary[cat].total = t; grandDischarging += d; grandLoading += l; const dInp = document.getElementById(`total-summary-discharging-${cat}`); const lInp = document.getElementById(`total-summary-loading-${cat}`); const tInp = document.getElementById(`total-summary-total-${cat}`); if (dInp) dInp.value = d; if (lInp) lInp.value = l; if (tInp && tInp.dataset.manual !== 'true') { tInp.value = t; } const currentTotalVal = parseInt(tInp ? tInp.value : 0, 10) || t; grandTotal += currentTotalVal; }); const grandDEl = document.getElementById('grand-summary-discharging'); const grandLEl = document.getElementById('grand-summary-loading'); const grandTEl = document.getElementById('grand-summary-total'); if (grandDEl) grandDEl.textContent = new Intl.NumberFormat('id-ID').format(grandDischarging); if (grandLEl) grandLEl.textContent = new Intl.NumberFormat('id-ID').format(grandLoading); if (grandTEl) grandTEl.textContent = new Intl.NumberFormat('id-ID').format(grandTotal); // Auto-sync into Sequencing Cargo Operation rows syncToSquancingDataCargo(summary); } function updateGrandCargoSummary() { const cats = ['mobil_cbu', 'truck', 'bus', 'hh', 'part', 'mafi']; let grandTotal = 0; cats.forEach(cat => { const tInp = document.getElementById(`total-summary-total-${cat}`); grandTotal += parseInt(tInp ? tInp.value : 0, 10) || 0; }); const grandTEl = document.getElementById('grand-summary-total'); if (grandTEl) grandTEl.textContent = new Intl.NumberFormat('id-ID').format(grandTotal); } function resetTotalCargoSummaryManual() { const cats = ['mobil_cbu', 'truck', 'bus', 'hh', 'part', 'mafi']; cats.forEach(cat => { const tInp = document.getElementById(`total-summary-total-${cat}`); if (tInp) delete tInp.dataset.manual; }); recalculateTotalCargoSummary(); } function syncToSquancingDataCargo(summary) { const mapping = [ { idx: 0, cat: 'mobil_cbu' }, // CBU { idx: 1, cat: 'truck' }, // Truck { idx: 2, cat: 'bus' }, // Bus { idx: 3, cat: 'hh' }, // HH { idx: 4, cat: 'part' }, // PART { idx: 5, cat: 'mafi' }, // Mafi ]; mapping.forEach(m => { // Discharging tab const disQtyInp = document.getElementById(`seq-discharging-qty-${m.idx}`); if (disQtyInp && (!disQtyInp.dataset.manual || disQtyInp.dataset.manual !== 'true')) { const val = summary[m.cat].discharging; if (val > 0) { disQtyInp.value = val; calculateRowSequencing('discharging', m.idx); } } // Loading tab const loadQtyInp = document.getElementById(`seq-loading-qty-${m.idx}`); if (loadQtyInp && (!loadQtyInp.dataset.manual || loadQtyInp.dataset.manual !== 'true')) { const val = summary[m.cat].loading; if (val > 0) { loadQtyInp.value = val; calculateRowSequencing('loading', m.idx); } } }); }