RevenueReportChart.vue
2.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
<template>
<div class="flex justify-center w-full h-full overflow-hidden relative">
<canvas ref="canvas" style="max-width: 100%"></canvas>
</div>
</template>
<script lang="ts" setup>
import { ref, onMounted, nextTick } from 'vue'
import { Chart, registerables } from 'chart.js'
import type { Revenues } from '../../../../data/charts/revenueChartData'
import { earningsColor, expensesColor, formatMoney } from '../../../../data/charts/revenueChartData'
const { revenues, months } = defineProps<{
months: string[]
revenues: Revenues[]
}>()
Chart.register(...registerables)
const BR_THICKNESS = 4
Chart.register([
{
id: 'background-color',
beforeDatasetDraw: function (chart) {
const ctx = chart.ctx
const config = chart.config
config.data.datasets.forEach(function (dataset, datasetIndex) {
const meta = chart.getDatasetMeta(datasetIndex)
if (meta.type === 'bar') {
const bgColor = earningsColor
// Loop through each bar in the dataset
meta.data.forEach(function (bar) {
ctx.fillStyle = bgColor
ctx.fillRect(bar.x - BR_THICKNESS / 2, 0, BR_THICKNESS, chart.chartArea.bottom)
})
}
})
},
},
])
const canvas = ref<HTMLCanvasElement | null>(null)
const doShowChart = ref(false)
onMounted(() => {
if (canvas.value) {
const ctx = canvas.value.getContext('2d')
if (ctx) {
new Chart(ctx, {
type: 'bar',
data: {
labels: months,
datasets: [
{
// Show relative expenses ratio
data: revenues.map(({ earning, expenses }) => (expenses / earning) * 100),
backgroundColor: expensesColor,
barThickness: BR_THICKNESS,
},
],
},
options: {
maintainAspectRatio: false,
plugins: {
legend: {
display: false,
},
},
scales: {
x: {
stacked: true,
grid: {
display: false,
},
border: {
width: 0,
},
},
y: {
display: false,
beginAtZero: true,
ticks: {
callback: function (value) {
return formatMoney(Number(value))
},
},
},
},
},
})
}
}
nextTick(() => {
doShowChart.value = true
})
})
</script>
<style lang="scss" scoped>
canvas {
position: absolute;
height: 100%;
width: 100%;
}
</style>