// Trial Period Management JavaScript // This file contains all trial period related functionality // Global variables for trial periods let currentCustomerId = null; let currentTrialPeriods = []; // Initialize trial period modals and event listeners function initTrialPeriodManagement() { const addTrialPeriodModal = document.getElementById('addTrialPeriodModal'); const editTrialPeriodModal = document.getElementById('editTrialPeriodModal'); const addTrialPeriodBtn = document.getElementById('addTrialPeriodBtn'); const addTrialPeriodForm = document.getElementById('addTrialPeriodForm'); const editTrialPeriodForm = document.getElementById('editTrialPeriodForm'); // Add trial period button click if (addTrialPeriodBtn) { addTrialPeriodBtn.addEventListener('click', function () { document.getElementById('trialCustomerId').value = currentCustomerId; addTrialPeriodModal.style.display = 'block'; }); } // Close modals const closeButtons = document.querySelectorAll('.close'); closeButtons.forEach(btn => { btn.addEventListener('click', function () { const modal = this.closest('.modal'); if (modal) { modal.style.display = 'none'; } }); }); // Cancel buttons document.querySelector('.cancel-trial')?.addEventListener('click', function () { addTrialPeriodModal.style.display = 'none'; }); document.querySelector('.cancel-edit-trial')?.addEventListener('click', function () { editTrialPeriodModal.style.display = 'none'; }); // Add trial period form submit if (addTrialPeriodForm) { addTrialPeriodForm.addEventListener('submit', async function (e) { e.preventDefault(); await createTrialPeriod(); }); } // Edit trial period form submit if (editTrialPeriodForm) { editTrialPeriodForm.addEventListener('submit', async function (e) { e.preventDefault(); await updateTrialPeriod(); }); } // Click outside modal to close window.addEventListener('click', function (e) { if (e.target === addTrialPeriodModal) { addTrialPeriodModal.style.display = 'none'; } if (e.target === editTrialPeriodModal) { editTrialPeriodModal.style.display = 'none'; } }); } // Load trial periods for a customer async function loadTrialPeriods(customerId) { currentCustomerId = customerId; try { const response = await authenticatedFetch(`/api/trial-periods?customerId=${customerId}`); const data = await response.json(); currentTrialPeriods = data.trialPeriods || []; renderTrialPeriods(); } catch (error) { console.error('Error loading trial periods:', error); currentTrialPeriods = []; renderTrialPeriods(); } } // Render trial periods table function renderTrialPeriods() { const tbody = document.getElementById('trialPeriodsTableBody'); const noDataMessage = document.getElementById('noTrialPeriodsMessage'); const table = document.querySelector('.trial-periods-table'); if (!tbody) return; tbody.innerHTML = ''; if (currentTrialPeriods.length === 0) { table.style.display = 'none'; noDataMessage.style.display = 'block'; return; } table.style.display = 'table'; noDataMessage.style.display = 'none'; currentTrialPeriods.forEach(period => { const row = document.createElement('tr'); const startTime = formatDateTime(period.startTime); const endTime = formatDateTime(period.endTime); row.innerHTML = ` ${startTime} ${endTime}
`; tbody.appendChild(row); }); // Add event listeners to edit and delete buttons tbody.querySelectorAll('.edit-btn').forEach(btn => { btn.addEventListener('click', function () { const periodId = this.getAttribute('data-id'); openEditTrialPeriodModal(periodId); }); }); tbody.querySelectorAll('.delete-btn').forEach(btn => { btn.addEventListener('click', function () { const periodId = this.getAttribute('data-id'); deleteTrialPeriod(periodId); }); }); } // Format datetime for display function formatDateTime(dateTimeStr) { if (!dateTimeStr) return ''; const date = new Date(dateTimeStr); const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0'); const hours = String(date.getHours()).padStart(2, '0'); const minutes = String(date.getMinutes()).padStart(2, '0'); return `${year}/${month}/${day} ${hours}:${minutes}`; } // Create trial period async function createTrialPeriod() { const customerId = document.getElementById('trialCustomerId').value; const startTime = document.getElementById('trialStartTime').value; const endTime = document.getElementById('trialEndTime').value; if (!startTime || !endTime) { alert('请填写开始时间和结束时间'); return; } const formData = { customerId: customerId, startTime: new Date(startTime).toISOString(), endTime: new Date(endTime).toISOString() }; try { const response = await authenticatedFetch('/api/trial-periods', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(formData) }); if (response.ok) { document.getElementById('addTrialPeriodModal').style.display = 'none'; document.getElementById('addTrialPeriodForm').reset(); await loadTrialPeriods(customerId); } else { alert('添加试用时间时出错'); } } catch (error) { console.error('Error creating trial period:', error); alert('添加试用时间时出错'); } } // Open edit trial period modal function openEditTrialPeriodModal(periodId) { const period = currentTrialPeriods.find(p => p.id === periodId); if (!period) return; document.getElementById('editTrialPeriodId').value = period.id; // Convert ISO string to datetime-local format const startDate = new Date(period.startTime); const endDate = new Date(period.endTime); document.getElementById('editTrialStartTime').value = formatDateTimeLocal(startDate); document.getElementById('editTrialEndTime').value = formatDateTimeLocal(endDate); document.getElementById('editTrialPeriodModal').style.display = 'block'; } // Format date to datetime-local input format function formatDateTimeLocal(date) { const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0'); const hours = String(date.getHours()).padStart(2, '0'); const minutes = String(date.getMinutes()).padStart(2, '0'); return `${year}-${month}-${day}T${hours}:${minutes}`; } // Update trial period async function updateTrialPeriod() { const periodId = document.getElementById('editTrialPeriodId').value; const startTime = document.getElementById('editTrialStartTime').value; const endTime = document.getElementById('editTrialEndTime').value; // Get source value const sourceEl = document.getElementById('editTrialCustomerSource'); const source = sourceEl ? sourceEl.value.trim() : ''; // Get intended product value (use the function from trial-periods-page.js if available) let intendedProduct = ''; if (typeof getIntendedProductValue === 'function') { intendedProduct = getIntendedProductValue('editTrialIntendedProduct', 'editTrialIntendedProductOther'); } else { // Fallback: get values from checkboxes directly const checkboxes = document.querySelectorAll('input[name="editIntendedProduct"]:checked'); const otherInput = document.getElementById('editTrialIntendedProductOther'); const values = []; checkboxes.forEach(cb => { if (cb.value === '其他') { if (otherInput && otherInput.value.trim()) { values.push(otherInput.value.trim()); } } else { values.push(cb.value); } }); intendedProduct = values.join(', '); } // Get isTrial value from radio buttons const isTrialRadio = document.querySelector('input[name="editIsTrial"]:checked'); const isTrial = isTrialRadio ? isTrialRadio.value === 'true' : true; if (!startTime || !endTime) { alert('请填写开始时间和结束时间'); return; } const formData = { source: source, intendedProduct: intendedProduct, startTime: new Date(startTime).toISOString(), endTime: new Date(endTime).toISOString(), isTrial: isTrial }; try { const response = await authenticatedFetch(`/api/trial-periods/${periodId}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(formData) }); if (response.ok) { document.getElementById('editTrialPeriodModal').style.display = 'none'; // Load trial periods for specific customer (for embedded list) if (currentCustomerId) { await loadTrialPeriods(currentCustomerId); } // Also refresh the main trial periods page list if (typeof loadAllTrialPeriods === 'function') { await loadAllTrialPeriods(); } } else { alert('更新试用时间时出错'); } } catch (error) { console.error('Error updating trial period:', error); alert('更新试用时间时出错'); } } // Delete trial period async function deleteTrialPeriod(periodId) { if (!confirm('确定要删除这个试用时间记录吗?')) { return; } try { const response = await authenticatedFetch(`/api/trial-periods/${periodId}`, { method: 'DELETE' }); if (response.ok) { await loadTrialPeriods(currentCustomerId); } else { alert('删除试用时间时出错'); } } catch (error) { console.error('Error deleting trial period:', error); alert('删除试用时间时出错'); } } // Initialize when DOM is loaded document.addEventListener('DOMContentLoaded', function () { initTrialPeriodManagement(); });