Diving into WooCommerce Sales Reports with Vue.js

In the bustling world of e-commerce, understanding sales performance is crucial for growth. WooCommerce, the popular WordPress plugin, offers a wealth of data through its reporting system. However, extracting this data and presenting it in a visually appealing and insightful way can be a challenge. This is where the power of Vue.js comes in.

This blog post will guide you through the process of integrating Vue.js with WooCommerce to build a robust and interactive sales reporting dashboard. We’ll cover everything from retrieving data, structuring it for efficient use, and creating interactive visualizations using Vuetify.

Setting the Stage

  1. WordPress and WooCommerce: Ensure you have a working WordPress site with WooCommerce installed and configured.

  2. Vue.js Environment: Set up a Vue.js project using the Vue CLI:

    vue create vue-woocommerce-reports

    Choose your preferred options during the setup process.

  3. Installing Dependencies:

    npm install axios vuetify
    • axios: Used for making API requests to WooCommerce.
    • vuetify: Provides a rich set of UI components for building the dashboard.

Connecting Vue.js to WooCommerce

We’ll use the WooCommerce REST API to access sales data. Let’s start by creating a service in Vue.js to handle API requests:

src/services/WooCommerceService.js:

import axios from 'axios';

const API_URL = 'https://your-woocommerce-store.com/wp-json/wc/v3/'; // Replace with your store URL
const API_KEY = 'ck_your_consumer_key'; // Replace with your consumer key
const API_SECRET = 'cs_your_consumer_secret'; // Replace with your consumer secret

export default {
  async getOrders(params) {
    try {
      const response = await axios.get(`${API_URL}orders`, {
        params,
        headers: {
          'Authorization': `Basic ${Buffer.from(`${API_KEY}:${API_SECRET}`).toString('base64')}`,
          'Content-Type': 'application/json',
        },
      });
      return response.data;
    } catch (error) {
      console.error('Error fetching orders:', error);
      throw error;
    }
  },
  // Add more methods for other reports, e.g., getProducts(), getCustomers()
};

This service uses axios to make authenticated requests to the WooCommerce REST API. You need to replace the placeholder values with your actual WooCommerce store URL, consumer key, and consumer secret.

Fetching and Processing Data

Let’s create a component to display the sales report:

src/components/SalesReport.vue:

<template>
  <v-container fluid>
    <v-row>
      <v-col cols="12">
        <h1>Sales Report</h1>
      </v-col>
    </v-row>
    <v-row>
      <v-col cols="12">
        <v-card>
          <v-card-text>
            <div v-if="loading">Loading data...</div>
            <div v-else>
              <!-- Add report visualization here -->
            </div>
          </v-card-text>
        </v-card>
      </v-col>
    </v-row>
  </v-container>
</template>

<script>
import WooCommerceService from '@/services/WooCommerceService';

export default {
  data() {
    return {
      orders: [],
      loading: true,
    };
  },
  mounted() {
    this.fetchOrders();
  },
  methods: {
    async fetchOrders() {
      try {
        this.loading = true;
        this.orders = await WooCommerceService.getOrders();
        this.loading = false;
      } catch (error) {
        console.error('Error fetching orders:', error);
      }
    },
  },
};
</script>

This component uses the WooCommerceService to fetch order data. The loading state variable manages the loading state of the component.

Visualizing Data with Vuetify

We’ll use Vuetify charts to visualize the sales data. Let’s enhance the SalesReport component to display a bar chart showing the total sales per day:

<template>
  <v-container fluid>
    <v-row>
      <v-col cols="12">
        <h1>Sales Report</h1>
      </v-col>
    </v-row>
    <v-row>
      <v-col cols="12">
        <v-card>
          <v-card-text>
            <div v-if="loading">Loading data...</div>
            <div v-else>
              <v-chart :options="chartOptions"></v-chart>
            </div>
          </v-card-text>
        </v-card>
      </v-col>
    </v-row>
  </v-container>
</template>

<script>
import WooCommerceService from '@/services/WooCommerceService';
import { ref } from 'vue';

export default {
  data() {
    return {
      orders: [],
      loading: true,
      chartOptions: ref(null),
    };
  },
  mounted() {
    this.fetchOrders();
  },
  methods: {
    async fetchOrders() {
      try {
        this.loading = true;
        this.orders = await WooCommerceService.getOrders();
        this.loading = false;
        this.prepareChartData();
      } catch (error) {
        console.error('Error fetching orders:', error);
      }
    },
    prepareChartData() {
      const salesPerDay = {};
      this.orders.forEach(order => {
        const date = new Date(order.date_created).toLocaleDateString();
        if (salesPerDay[date]) {
          salesPerDay[date] += parseFloat(order.total);
        } else {
          salesPerDay[date] = parseFloat(order.total);
        }
      });
      this.chartOptions.value = {
        chart: {
          type: 'bar',
        },
        series: [{
          name: 'Total Sales',
          data: Object.entries(salesPerDay).map(([date, amount]) => ({ x: date, y: amount })),
        }],
        xaxis: {
          categories: Object.keys(salesPerDay),
        },
      };
    },
  },
};
</script>

This updated component processes the order data to create a salesPerDay object, which is then used to generate the chart options. The chart displays the total sales for each day.

Expanding the Report

You can expand this basic report to display more detailed insights:

  1. Filtering: Allow users to filter the report by date range, product categories, or customer groups.
  2. Metrics: Include additional metrics such as average order value, revenue by product, or customer lifetime value.
  3. Visualizations: Utilize different chart types (line, pie, scatter) to represent various data points.
  4. User Interface: Customize the dashboard’s UI with Vuetify components for an enhanced user experience.

Example: Product Sales Report

Let’s add a new component to display product-wise sales:

src/components/ProductSalesReport.vue:

<template>
  <v-container fluid>
    <v-row>
      <v-col cols="12">
        <h1>Product Sales Report</h1>
      </v-col>
    </v-row>
    <v-row>
      <v-col cols="12">
        <v-card>
          <v-card-text>
            <div v-if="loading">Loading data...</div>
            <div v-else>
              <v-chart :options="chartOptions"></v-chart>
            </div>
          </v-card-text>
        </v-card>
      </v-col>
    </v-row>
  </v-container>
</template>

<script>
import WooCommerceService from '@/services/WooCommerceService';
import { ref } from 'vue';

export default {
  data() {
    return {
      orders: [],
      products: [],
      loading: true,
      chartOptions: ref(null),
    };
  },
  mounted() {
    this.fetchOrders();
    this.fetchProducts();
  },
  methods: {
    async fetchOrders() {
      try {
        this.loading = true;
        this.orders = await WooCommerceService.getOrders();
        this.loading = false;
        this.prepareChartData();
      } catch (error) {
        console.error('Error fetching orders:', error);
      }
    },
    async fetchProducts() {
      try {
        this.products = await WooCommerceService.getProducts();
      } catch (error) {
        console.error('Error fetching products:', error);
      }
    },
    prepareChartData() {
      const salesPerProduct = {};
      this.orders.forEach(order => {
        order.line_items.forEach(item => {
          const product = this.products.find(p => p.id === item.product_id);
          if (product) {
            const productName = product.name;
            if (salesPerProduct[productName]) {
              salesPerProduct[productName] += parseFloat(item.total);
            } else {
              salesPerProduct[productName] = parseFloat(item.total);
            }
          }
        });
      });
      this.chartOptions.value = {
        chart: {
          type: 'pie',
        },
        series: Object.values(salesPerProduct),
        labels: Object.keys(salesPerProduct),
      };
    },
  },
};
</script>

This component fetches both orders and products and calculates sales per product, displaying the data in a pie chart.

Conclusion

By combining Vue.js with the WooCommerce REST API and leveraging the powerful features of Vuetify, you can create dynamic and insightful sales reports for your e-commerce business. Remember to adapt these examples to your specific needs, implement additional features, and continuously improve your dashboard to gain deeper understanding and make data-driven decisions.

This blog post has only scratched the surface of what’s possible with Vue.js and WooCommerce. Feel free to explore advanced functionalities like real-time updates, custom visualizations, and integration with other business tools to create a comprehensive and powerful analytics platform.

Leave a Reply

Your email address will not be published. Required fields are marked *

Trending