graficas highcharts

This commit is contained in:
2021-07-30 23:56:33 -05:00
parent 2db1144834
commit 74b37c0dfe
16 changed files with 306 additions and 103 deletions

View File

@@ -10,7 +10,7 @@ export default {
type: Array, type: Array,
default: () => [ default: () => [
'rgba(72,72,176,0.2)', 'rgba(72,72,176,0.2)',
'rgba(72,72,176,0.0)', 'rgba(72,72,176,0.1)',
'rgba(119,52,169,0)' 'rgba(119,52,169,0)'
], ],
validator: val => { validator: val => {
@@ -35,14 +35,17 @@ export default {
if (!chartData) return; if (!chartData) return;
const ctx = const ctx =
this.ctx || document.getElementById(this.chartId).getContext('2d'); this.ctx || document.getElementById(this.chartId).getContext('2d');
const gradientStroke = ctx.createLinearGradient(0, 230, 0, 50); const gradientStroke = ctx.createLinearGradient(0, 230, 20, 50);
this.gradientStops.forEach((stop, index) => { this.gradientStops.forEach((stop, index) => {
gradientStroke.addColorStop(stop, this.gradientColors[index]); gradientStroke.addColorStop(stop, this.gradientColors[index]);
}); });
chartData.datasets.forEach(set => { chartData.datasets.forEach(set => {
if (!set.backgroundColor) { if (!set.backgroundColor) {
console.log(ctx)
set.backgroundColor = gradientStroke; set.backgroundColor = gradientStroke;
} }
}); });

View File

@@ -0,0 +1,59 @@
import { Pie, mixins } from 'vue-chartjs';
export default {
name: 'pie-chart',
extends: Pie,
mixins: [mixins.reactiveProp],
props: {
extraOptions: Object,
gradientColors: {
type: Array,
default: () => [
'rgba(72,72,176,0.2)',
'rgba(72,72,176,0.1)',
'rgba(119,52,169,0)'
],
validator: val => {
return val.length > 1;
}
},
gradientStops: {
type: Array,
default: () => [1, 0.4, 0],
validator: val => {
return val.length > 1;
}
}
},
data() {
return {
ctx: null
};
},
methods: {
updateGradients(chartData) {
if (!chartData) return;
const ctx =
this.ctx || document.getElementById(this.chartId).getContext('2d');
const colors=["0xFF0000","0xFFFF00"]
chartData.datasets.forEach(set => {
if (!set.backgroundColor) {
set.backgroundColor = "rgba(119,52,169,1)";
}
});
}
},
mounted() {
this.$watch(
'chartData',
(newVal, oldVal) => {
this.updateGradients(newVal);
if (!oldVal) {
this.renderChart(this.chartData, this.extraOptions);
}
},
{ immediate: true }
);
}
};

View File

@@ -342,7 +342,8 @@ export let barChartOptions = {
xPadding: 12, xPadding: 12,
mode: 'nearest', mode: 'nearest',
intersect: 0, intersect: 0,
position: 'nearest' position: 'nearest',
}, },
scales: { scales: {
yAxes: [ yAxes: [

View File

@@ -0,0 +1,83 @@
export var chartOptions = {
credits: {
enabled: false
},
chart: {
renderTo: "container",
defaultSeriesType: "column",
backgroundColor: "rgba(0,0,0,0)"
},
xAxis: {
categories: [],
crosshair: true
},
yAxis: {
title: {
text: ""
},
labels: {
style: {
color: "#d4d2d2",
font: "11px Trebuchet MS, Verdana, sans-serif"
}
}
},
legend: {
itemStyle: {
color: "#d4d2d2"
}
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat:
'<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y:.0f} pesos</b></td></tr>',
footerFormat: "</table>",
shared: true,
useHTML: true
},
responsive: {
rules: [
{
condition: {
maxWidth: 500
},
chartOptions: {
legend: {
layout: "horizontal",
align: "center",
verticalAlign: "bottom"
}
}
}
]
}
};
export var pieOptions={
chart: {
renderTo: "container",
defaultSeriesType: "pie",
backgroundColor: "rgba(0,0,0,0)"
},
xAxis: {
categories: [],
crosshair: true
},
credits: {
enabled: false
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %'
}
}
},
};

View File

@@ -1,7 +0,0 @@
# COMPONENTS
**This directory is not required, you can delete it if you don't want to use it.**
The components directory contains your Vue.js Components.
_Nuxt.js doesn't supercharge these components._

View File

@@ -61,8 +61,8 @@ export default {
// Axios module configuration (https://go.nuxtjs.dev/config-axios) // Axios module configuration (https://go.nuxtjs.dev/config-axios)
axios: { axios: {
//baseURL: "http://192.168.1.111:4000/api" //baseURL: "http://192.168.1.111:4000/api"
baseURL:"http://localhost:4000/api" //baseURL:"http://localhost:4000/api"
//baseURL:"https://finanzasm.herokuapp.com/api" baseURL:"https://finanzasm.herokuapp.com/api"
}, },
/* /*

8
APP/package-lock.json generated
View File

@@ -8004,12 +8004,12 @@
} }
}, },
"nuxt-highcharts": { "nuxt-highcharts": {
"version": "1.0.5", "version": "1.0.7",
"resolved": "https://registry.npmjs.org/nuxt-highcharts/-/nuxt-highcharts-1.0.5.tgz", "resolved": "https://registry.npmjs.org/nuxt-highcharts/-/nuxt-highcharts-1.0.7.tgz",
"integrity": "sha512-HSByt6Q7Ww3X0pRs4XLbtDBXwE55zBFK0KcPoUc58xF/n+sVNP9UMpTeNd2iJcd1dJqvq2vKB5PhySLpAq9bfg==", "integrity": "sha512-LJ3PrjnGwS0nAQ8vQYFncsRWQVL1D3QKadbSbruks+8U5uLk5deAcNF4+WNlUfCAXkVk+TKhI2J+MTZ+7ouPZw==",
"requires": { "requires": {
"@highcharts/map-collection": "^1.1.3", "@highcharts/map-collection": "^1.1.3",
"highcharts": "^8.1.0" "highcharts": "^8.2.2"
} }
}, },
"oauth-sign": { "oauth-sign": {

View File

@@ -13,7 +13,7 @@
"@nuxtjs/axios": "^5.12.2", "@nuxtjs/axios": "^5.12.2",
"@nuxtjs/pwa": "^3.2.2", "@nuxtjs/pwa": "^3.2.2",
"bootstrap": "4.3.1", "bootstrap": "4.3.1",
"chart.js": "^2.7.1", "chart.js": "^2.9.4",
"cookieparser": "^0.1.0", "cookieparser": "^0.1.0",
"core-js": "^3.7.0", "core-js": "^3.7.0",
"cors": "^2.8.5", "cors": "^2.8.5",
@@ -24,7 +24,7 @@
"fuse.js": "^3.2.0", "fuse.js": "^3.2.0",
"js-cookie": "^2.2.1", "js-cookie": "^2.2.1",
"nuxt": "^2.14.7", "nuxt": "^2.14.7",
"nuxt-highcharts": "^1.0.3", "nuxt-highcharts": "^1.0.7",
"perfect-scrollbar": "^1.3.0", "perfect-scrollbar": "^1.3.0",
"register-service-worker": "^1.5.2", "register-service-worker": "^1.5.2",
"tween.js": "^16.6.0", "tween.js": "^16.6.0",

View File

@@ -1,6 +0,0 @@
# PAGES
This directory contains your Application Views and Routes.
The framework reads all the `*.vue` files inside this directory and creates the router of your application.
More information about the usage of this directory in [the documentation](https://nuxtjs.org/guide/routing).

View File

@@ -111,18 +111,14 @@ export default {
mounted() { mounted() {
this.$store.dispatch("getCategorias");
// this.$store.dispatch("getCategorias"); this.$store.dispatch("getMetodos");
//this.$store.dispatch("getMetodos");
this.newCompra.fecha = this.$store.state.fecha; this.newCompra.fecha = this.$store.state.fecha;
this.categorias = this.$store.state.categorias; this.categorias = this.$store.state.categorias;
this.metodos_pago = this.$store.state.metodos_de_pago; this.metodos_pago = this.$store.state.metodos_de_pago;
this.getCompras(); this.getCompras();
}, },

View File

@@ -10,60 +10,66 @@
> >
</div> </div>
<card title="Compras por categorías" class="p-2 col-12"> <card>
<bar-chart <div class="chart-area" style="height: 300px">
class="col-12" <highchart style="height: 100%" v-if="isMounted" :options="comprasChart"/>
style="height: 10%"
ref="categorias"
:chart-data="categoriasBars.chartData"
:gradient-stops="categoriasBars.gradientStops"
:extra-options="categoriasBars.extraOptions"
>
</bar-chart>
</card>
</div> </div>
<div class="chart-area" style="height: 300px">
<highchart style="height: 100%" v-if="isMounted" :options="metodosChart"/>
</div>
</card>
</div>
</template> </template>
<script> <script>
import LineChart from "@/components/Charts/LineChart"; import * as configPlot from "@/components/Charts/config_plots";
import BarChart from "@/components/Charts/BarChart";
import * as chartConfigs from "@/components/Charts/config";
import config from "@/config"; import config from "@/config";
export default { export default {
name: "dashboard", name: "dashboard",
middleware: "authenticated", middleware: "authenticated",
components: {
LineChart,
BarChart,
},
data() { data() {
return { return {
isMounted: false,
comprasChart:{
...configPlot.chartOptions,
title: {
text: 'Compras por categorías'
},
series: [{
name: '',
data: [],
color: "#e14eca"
},],
},
metodosChart:{
...configPlot.pieOptions,
title: {
text: 'Métodos de pago'
},
series: [{
data: [],
},],
},
ingresos: 1000, ingresos: 1000,
compras: 1000, compras: 1000,
categoriasBars: {
extraOptions: chartConfigs.barChartOptions,
chartData: {
labels: ["USA", "GER", "AUS", "UK", "RO", "BR"],
datasets: [
{
label: "Countries",
fill: true,
borderColor: config.colors.info,
borderWidth: 2,
borderDash: [],
borderDashOffset: 0.0,
data: [530, 20, 10, 80, 100, 45],
},
],
},
gradientColors: config.colors.primaryGradient,
gradientStops: [1, 0.4, 0],
},
}; };
}, },
@@ -115,50 +121,74 @@ export default {
.catch((e) => console.log(e)); .catch((e) => console.log(e));
}, },
getResumenCategorias() { async getResumenCategorias() {
const axiosHeader = { const axiosHeader = {
headers: { headers: {
token: this.$store.state.auth.token, token: this.$store.state.auth.token,
filtro: this.$store.state.filtro.fechas, filtro: this.$store.state.filtro.fechas,
}, },
}; };
this.$axios await this.$axios
.get("/resumen_categorias", axiosHeader) .get("/resumen_categorias", axiosHeader)
.then((res) => { .then((res) => {
let categorias = res.data.labels; let categorias = res.data.labels;
let valores = res.data.datos; let valores = res.data.datos;
let chartData = { this.comprasChart.xAxis.categories =categorias;
label: "Categorias", this.comprasChart.series =[{name: '',
datasets: [
{
label: "Total",
fill: true,
borderColor: config.colors.info,
borderWidth: 2,
borderDash: [],
data: valores, data: valores,
}, }]
],
labels: categorias,
};
this.categoriasBars.labels = categorias;
this.categoriasBars.chartData.datasets.data = valores;
})
.catch((e) => console.log(e));
},
async getResumenMetodos() {
const axiosHeader = {
headers: {
token: this.$store.state.auth.token,
filtro: this.$store.state.filtro.fechas,
},
};
await this.$axios
.get("/resumen_metodos", axiosHeader)
.then((res) => {
let metodos = res.data.labels;
let valores = res.data.datos;
//this.metodosChart.xAxis.categories =metodos;
var series =[];
for (var i=0;i< metodos.length;i++){
var serie={
name:metodos[i],
y:valores[i]
}
series.push(serie)
}
console.log(series)
this.metodosChart.series = [{name: '',
data: series,
}];
this.$refs.categorias.renderChart(
chartData,
chartConfigs.barChartOptions
);
this.$refs.categorias.updateGradients(chartData);
}) })
.catch((e) => console.log(e)); .catch((e) => console.log(e));
}, },
}, },
mounted() { async mounted() {
this.getCompras(); await this.getCompras();
this.getIngresos(); await this.getIngresos();
this.getResumenCategorias(); await this.getResumenCategorias();
await this.getResumenMetodos();
this.isMounted = true;
}, },
}; };
</script> </script>

View File

@@ -51,14 +51,14 @@ export const actions = {
//saving auth in state //saving auth in state
this.commit("setAuth", auth); this.commit("setAuth", auth);
}, },
getCategorias() { async getCategorias() {
const axiosHeader = { const axiosHeader = {
headers: { headers: {
token: this.state.auth.token token: this.state.auth.token
} }
}; };
this.$axios await this.$axios
.get("/categoria", axiosHeader) .get("/categoria", axiosHeader)
.then(res => { .then(res => {
this.commit("setCategorias", res.data.data); this.commit("setCategorias", res.data.data);
@@ -68,13 +68,13 @@ export const actions = {
}); });
}, },
getMetodos() { async getMetodos() {
const axiosHeader = { const axiosHeader = {
headers: { headers: {
token: this.state.auth.token token: this.state.auth.token
} }
}; };
this.$axios await this.$axios
.get("/metodo", axiosHeader) .get("/metodo", axiosHeader)
.then(res => { .then(res => {
this.commit("setMetodos", res.data.data); this.commit("setMetodos", res.data.data);

View File

@@ -14,3 +14,5 @@ npx mongoku start
# Referencias # Referencias
[Element UI](http://element.eleme.io) [Element UI](http://element.eleme.io)
[highcharts](https://www.highcharts.com/demo)

View File

@@ -35,7 +35,7 @@ app.use('/api',require('./routes/metodos_pago'))
app.use("*",(req,res)=>{res.redirect("/")}) app.use("*",(req,res)=>{res.redirect("/")})
app.disable('x-powered-by'); app.disable('x-powered-by');
module.exports = app;
app.listen(app.get('port') ,() => console.log("service startes, listening on the port: ",app.get('port'))) app.listen(app.get('port') ,() => console.log("service startes, listening on the port: ",app.get('port')))

20
routes/index.js Normal file
View File

@@ -0,0 +1,20 @@
const router = require("express").Router()
const fs = require("fs");
const pathRoutes = `${__dirname}`
const removeExtension = (fileName) =>{
return fileName.split(".").shift()
}
fs.readdirSync(pathRoutes).filter(file =>{
const nameFile = removeExtension(file);
const skip = ['index'].includes(nameFile)
if(!skip){
console.log(nameFile)
}
})
module.exports= router

View File

@@ -73,6 +73,28 @@ router.get("/resumen_compras", checkAuth, async (req, res) => {
res.json({"labels":labels,"datos":datos}); res.json({"labels":labels,"datos":datos});
}); });
router.get('/resumen_metodos',checkAuth,async (req,res)=>{
var compras_;
var labels =[];
var datos =[];
let miFiltro = req.get('filtro');
const filtros = {
fecha: { $regex: miFiltro, $options: "i" },
};
compras_ = await Compras.aggregate([
{$match: { $and: [{ user:req.userData._id}, filtros] }},
{$group:{_id:{metodopago:"$metodopago"},total:{$sum:"$valor"}}}
]).sort({total:"desc"});
compras_.forEach(element => {
//console.log(element.total)
labels.push(element._id.metodopago)
datos.push(element.total)
});
res.json({"labels":labels,"datos":datos});
});
module.exports = router; module.exports = router;