Tự động Thống kê Chi Tiêu Shopee

 avatar
user_9912716
javascript
a year ago
2.7 kB
2
Indexable
async function getOrders(offset, limit) {
    const url = `https://shopee.vn/api/v4/order/get_all_order_and_checkout_list?limit=${limit}&offset=${offset}`;
    const ordersData = (await (await fetch(url)).json()).data.order_data;
    const detailList = ordersData.details_list || [];
    return detailList;
}

function formatVietNamCurrency(number) {
    return new Intl.NumberFormat('vi-VN', { style: 'currency', currency: 'VND' }).format(number);
}

async function getAllOrders() {
    const limit = 20;
    let offset = 0;
    const allOrders = [
        'Tên chung\tSố lượng\tTổng tiền\tTrạng thái\tTên shop\tChi tiết\tTiền gốc'
    ];
    let sum = 0;
    let count = 0;

    while (true) {
        const data = await getOrders(offset, limit);
        if (data.length === 0) break;

        for (const item of data) {
            const { info_card, list_type } = item;
            let strListType;

            switch (list_type) {
                case 3: strListType = "Hoàn thành"; break;
                case 4: strListType = "Đã hủy"; break;
                case 7: strListType = "Vận chuyển"; break;
                case 8: strListType = "Đang giao"; break;
                case 9: strListType = "Chờ thanh toán"; break;
                case 12: strListType = "Trả hàng"; break;
                default: strListType = "Không rõ"; break;
            }

            const { product_count, subtotal, order_list_cards } = info_card;
            const subTotal = (list_type !== 4 && list_type !== 12) ? subtotal / 1e5 : 0;
            count += product_count;
            const orderCard = order_list_cards[0];
            const shopName = `${orderCard.shop_info.username} - ${orderCard.shop_info.shop_name}`;
            const products = orderCard.product_info.item_groups;
            const productSummary = products.map(product =>
                product.items.map(item => `${item.name}--amount: ${item.amount}--price: ${formatVietNamCurrency(item.item_price)}`).join(', ')
            ).join('; ');

            const name = products[0].items[0].name;
            if (list_type !== 4 && list_type !== 12) sum += subTotal;

            const subTotalNative = formatVietNamCurrency(subTotal);
            allOrders.push(`${name}\t${product_count}\t${subTotalNative}\t${strListType}\t${shopName}\t${productSummary}\t${subTotal}`);
        }

        console.log(`Collected: ${offset}`);
        offset += limit;
    }

    allOrders.push(`Tổng cộng:\t${count}\t${formatVietNamCurrency(sum)}`);
    const text = allOrders.join('\r\n');
    document.write(`<textarea>${text}</textarea>`);
}

getAllOrders();
Leave a Comment