order-manager.js

6.25 KB
05/11/2024 06:30
JS
order-manager.js
const OrderManager = {
    async createOrder(orderData) {
        try {
            Utils.showLoading();

            // Generate order ID
            const orderId = `ORD${Date.now()}`;

            // Prepare order data
            const order = {
                id: orderId,
                items: State.cart,
                customer: State.customer.personalInfo,
                total: this.calculateTotal(State.cart),
                status: 'pending',
                paymentMethod: orderData.paymentMethod,
                createdAt: new Date().toISOString()
            };

            // Process payment
            const paymentResult = await PaymentManager.processPayment(order);

            if (paymentResult.success) {
                // Save order
                await this.saveOrder(order);

                // Send notifications
                await NotificationService.sendOrderNotification(order);

                // Update customer order history
                this.updateOrderHistory(order);

                // Clear cart
                CartManager.clearCart();

                return {
                    success: true,
                    order,
                    paymentData: paymentResult.data
                };
            }

            throw new Error('การชำระเงินไม่สำเร็จ');

        } catch (error) {
            console.error('Order creation failed:', error);
            NotificationManager.showError(error.message || 'เกิดข้อผิดพลาดในการสั่งซื้อ');
            return { success: false, error };
        } finally {
            Utils.hideLoading();
        }
    },

    calculateTotal(items) {
        const subtotal = items.reduce((sum, item) => 
            sum + (item.price * item.quantity), 0);
        
        // Add delivery fee if subtotal is less than free delivery amount
        const deliveryFee = subtotal >= CONFIG.FREE_DELIVERY_AMOUNT ? 
            0 : CONFIG.DELIVERY_FEE;

        return subtotal + deliveryFee;
    },

    async saveOrder(order) {
        // In real application, save to backend
        const orders = Storage.load('orders') || [];
        orders.push(order);
        Storage.save('orders', orders);
    },

    updateOrderHistory(order) {
        State.customer.orderHistory.push({
            id: order.id,
            total: order.total,
            items: order.items.length,
            date: order.createdAt
        });
        CustomerManager.saveCustomerData();
    },

    showOrderConfirmation(order, paymentData) {
        const modal = document.createElement('div');
        modal.className = 'modal active';
        
        modal.innerHTML = `
            <div class="modal-content">
                <h2><i class="fas fa-check-circle"></i> สั่งซื้อสำเร็จ</h2>
                
                <div class="order-confirmation">
                    <p>หมายเลขคำสั่งซื้อ: ${order.id}</p>
                    <p>วันที่สั่งซื้อ: ${new Date(order.createdAt).toLocaleString()}</p>
                    
                    <div class="order-summary">
                        <h3>รายการสินค้า</h3>
                        <div class="order-items">
                            ${order.items.map(item => `
                                <div class="order-item">
                                    <span>${item.name} x${item.quantity}</span>
                                    <span>${Utils.formatPrice(item.price * item.quantity)}</span>
                                </div>
                            `).join('')}
                        </div>
                        
                        <div class="order-total">
                            ยอดรวมทั้งสิ้น: ${Utils.formatPrice(order.total)}
                        </div>
                    </div>
                    
                    <div class="next-steps">
                        <h3>ขั้นตอนต่อไป</h3>
                        <p>1. ชำระเงินผ่าน ${order.paymentMethod}</p>
                        <p>2. รอรับการยืนยันจากทางร้าน</p>
                        <p>3. รอรับสินค้า</p>
                    </div>
                </div>
                
                <button class="button-modern" onclick="this.closest('.modal').remove()">
                    <i class="fas fa-times"></i> ปิด
                </button>
            </div>
        `;
        
        document.body.appendChild(modal);
    },

    getOrderHistory() {
        return State.customer.orderHistory;
    },

    showOrderHistory() {
        const orders = this.getOrderHistory();
        const modal = document.createElement('div');
        modal.className = 'modal active';
        
        modal.innerHTML = `
            <div class="modal-content">
                <h2><i class="fas fa-history"></i> ประวัติการสั่งซื้อ</h2>
                
                <div class="order-history">
                    ${orders.length ? orders.map(order => `
                        <div class="order-history-item">
                            <div class="order-history-header">
                                <span>หมายเลขคำสั่งซื้อ: ${order.id}</span>
                                <span>วันที่: ${new Date(order.date).toLocaleDateString()}</span>
                            </div>
                            <div class="order-history-details">
                                <p>จำนวนสินค้า: ${order.items} รายการ</p>
                                <p>ยอดรวม: ${Utils.formatPrice(order.total)}</p>
                            </div>
                        </div>
                    `).join('') : '<p>ไม่มีประวัติการสั่งซื้อ</p>'}
                </div>
                
                <button class="button-modern" onclick="this.closest('.modal').remove()">
                    <i class="fas fa-times"></i> ปิด
                </button>
            </div>
        `;
        
        document.body.appendChild(modal);
    }
};