customer-manager.js

9.17 KB
05/11/2024 06:38
JS
customer-manager.js
const CustomerManager = {
    defaultCustomer: {
        personalInfo: {
            name: '',
            email: '',
            phone: '',
            address: ''
        },
        preferences: {
            notifications: {
                line: true,
                email: true,
                discord: false,
                telegram: false,
                webPush: false
            },
            paymentMethod: 'promptpay'
        },
        orderHistory: []
    },

    init() {
        this.loadCustomerData();
        this.setupEventListeners();
    },

    loadCustomerData() {
        try {
            State.customer = Storage.load(CONFIG.STORAGE_KEYS.CUSTOMER) || 
                            JSON.parse(JSON.stringify(this.defaultCustomer));
        } catch (error) {
            console.error('Error loading customer data:', error);
            State.customer = JSON.parse(JSON.stringify(this.defaultCustomer));
        }
    },

    setupEventListeners() {
        // Profile button click
        document.querySelector('[data-action="show-profile"]')?.addEventListener('click', 
            () => this.showProfileEditor()
        );

        // Close modal buttons
        document.querySelectorAll('.modal-close').forEach(button => {
            button.addEventListener('click', (e) => {
                e.preventDefault();
                const modal = button.closest('.modal');
                if (modal) modal.classList.remove('active');
            });
        });

        // Close modals on outside click
        document.addEventListener('click', (e) => {
            if (e.target.classList.contains('modal')) {
                e.target.classList.remove('active');
            }
        });
    },

    saveCustomerData() {
        try {
            Storage.save(CONFIG.STORAGE_KEYS.CUSTOMER, State.customer);
            return true;
        } catch (error) {
            console.error('Error saving customer data:', error);
            NotificationManager.showError('ไม่สามารถบันทึกข้อมูลได้');
            return false;
        }
    },

    showProfileEditor() {
        const modal = document.getElementById('profileModal');
        if (!modal) return;

        modal.innerHTML = this.createProfileEditorHTML();
        modal.classList.add('active');

        // Fill existing data
        this.fillProfileForm();
        this.setupProfileFormEvents();
    },

    createProfileEditorHTML() {
        return `
            <div class="modal-content">
                <button class="modal-close">
                    <i class="fas fa-times"></i>
                </button>
                <h2><i class="fas fa-user-edit"></i> แก้ไขข้อมูลส่วนตัว</h2>
                
                <form id="profileForm" class="profile-form">
                    <div class="form-section">
                        <h3><i class="fas fa-info-circle"></i> ข้อมูลส่วนตัว</h3>
                        
                        <div class="form-group">
                            <label for="profile-name">ชื่อ-นามสกุล</label>
                            <input type="text" id="profile-name" class="input-modern" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="profile-email">อีเมล</label>
                            <input type="email" id="profile-email" class="input-modern" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="profile-phone">เบอร์โทรศัพท์</label>
                            <input type="tel" id="profile-phone" class="input-modern" required
                                   pattern="[0-9]{10}" title="กรุณากรอกเบอร์โทรศัพท์ 10 หลัก">
                        </div>
                        
                        <div class="form-group">
                            <label for="profile-address">ที่อยู่</label>
                            <textarea id="profile-address" class="input-modern" required></textarea>
                        </div>
                    </div>

                    <div class="form-section">
                        <h3><i class="fas fa-bell"></i> การแจ้งเตือน</h3>
                        
                        <div class="notification-options">
                            <label class="checkbox-label">
                                <input type="checkbox" id="notify-line">
                                <i class="fab fa-line"></i> Line
                            </label>
                            
                            <label class="checkbox-label">
                                <input type="checkbox" id="notify-email">
                                <i class="fas fa-envelope"></i> Email
                            </label>
                            
                            <label class="checkbox-label">
                                <input type="checkbox" id="notify-discord">
                                <i class="fab fa-discord"></i> Discord
                            </label>
                            
                            <label class="checkbox-label">
                                <input type="checkbox" id="notify-telegram">
                                <i class="fab fa-telegram"></i> Telegram
                            </label>
                            
                            <label class="checkbox-label">
                                <input type="checkbox" id="notify-webPush">
                                <i class="fas fa-desktop"></i> Web Push
                            </label>
                        </div>
                    </div>

                    <button type="submit" class="button-modern">
                        <i class="fas fa-save"></i> บันทึกข้อมูล
                    </button>
                </form>
            </div>
        `;
    },

    fillProfileForm() {
        // Fill personal info
        Object.entries(State.customer.personalInfo).forEach(([key, value]) => {
            const input = document.getElementById(`profile-${key}`);
            if (input) input.value = value;
        });

        // Fill notification preferences
        Object.entries(State.customer.preferences.notifications).forEach(([key, value]) => {
            const checkbox = document.getElementById(`notify-${key}`);
            if (checkbox) checkbox.checked = value;
        });
    },

    setupProfileFormEvents() {
        const form = document.getElementById('profileForm');
        if (!form) return;

        form.addEventListener('submit', (e) => this.handleProfileSubmit(e));

        // Input validation
        const phoneInput = document.getElementById('profile-phone');
        if (phoneInput) {
            phoneInput.addEventListener('input', (e) => {
                e.target.value = e.target.value.replace(/[^0-9]/g, '').slice(0, 10);
            });
        }

        const emailInput = document.getElementById('profile-email');
        if (emailInput) {
            emailInput.addEventListener('change', (e) => {
                if (!Utils.validateEmail(e.target.value)) {
                    emailInput.setCustomValidity('กรุณากรอกอีเมลให้ถูกต้อง');
                } else {
                    emailInput.setCustomValidity('');
                }
            });
        }
    },

    async handleProfileSubmit(e) {
        e.preventDefault();

        try {
            // Update personal info
            State.customer.personalInfo = {
                name: document.getElementById('profile-name').value,
                email: document.getElementById('profile-email').value,
                phone: document.getElementById('profile-phone').value,
                address: document.getElementById('profile-address').value
            };

            // Update notification preferences
            Object.keys(State.customer.preferences.notifications).forEach(key => {
                State.customer.preferences.notifications[key] = 
                    document.getElementById(`notify-${key}`).checked;
            });

            if (this.saveCustomerData()) {
                NotificationManager.showSuccess('บันทึกข้อมูลสำเร็จ');
                document.getElementById('profileModal').classList.remove('active');
                
                // Emit event for other components
                EventBus.emit('customerDataUpdated', State.customer);
            }

        } catch (error) {
            console.error('Error saving profile:', error);
            NotificationManager.showError('เกิดข้อผิดพลาดในการบันทึกข้อมูล');
        }
    },

    getCustomerInfo() {
        return State.customer.personalInfo;
    },

    getNotificationPreferences() {
        return State.customer.preferences.notifications;
    },

    hasRequiredInfo() {
        const info = this.getCustomerInfo();
        return info.name && info.phone && info.address;
    }
};