mercredi 22 mai 2019

I want to calculate all of the values of the previous month and compare them to the current month

I'm using laravel for my backend and vue components to build my frontend. My goal is to grab all the data from the totals table with the type of: 'tips' and compare my current month of entries to my previous month of entries and calculate a percentage to show either a gain/loss. I've got everything except actually segregating the data by current & previous month.

This is the code for my totals widget so far. The part I'm stuck on is Comparing the months where I have it just console logging the res data.(The current data was dummy data to test my percentages)

   name: "TotalsWidget",
    props: ['type'],
    data() {
        return {
            desc: 'Tips',
            percentage: 0,
            thisMonth: 100,
            lastMonth: 500,
            total: 5477,
            state: null,
        }
    },
    methods: {
        getData(type){
            axios.get('/api/totals/'+ type).then((res) => {      
                /* Adding totals together */
                let total = [];
                Object.entries(res.data).forEach(([key, val]) => {
                    total.push(val.value)
                });
                this.total = total.reduce((total, num) => {return total + num}, 0);

                /* Compare Months */ 
                let months = [];
                console.log(res.data)
            });           
        }
    },
    computed:{
        getPercentage(thisMonth, lastMonth){
            this.percentage = Math.floor((this.thisMonth - this.lastMonth) / this.lastMonth * 100);
            if(Math.sign(this.percentage) == 1){
              return this.state = 'mdi mdi-arrow-up-drop-circle text-success mr-1'
            } else {
              return this.state = 'mdi mdi-arrow-down-drop-circle mr-1 text-danger'
            }
        },
    },
    mounted(){
        this.getData(this.type);
        console.log('Tips Widget Loaded');     
    }

Here is what's in my res.data:

[{…}, {…}]
0: {id: 1, type: "tips", desc: "Tips", value: 740, created_at: "2019-05-22 03:46:25", …}
1: {id: 2, type: "tips", desc: "Tips", value: 1105, created_at: "2019-04-22 03:46:25", …}

Theres going to be entries every monday this is just some dummy data to try to get it working. I'm unsure how to go about comparing the two and if I should use javascripts Date function or a third party like moment.js and how to go about doing so.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire