akaunting/app/Traits/Charts.php

93 lines
2.4 KiB
PHP
Raw Normal View History

2019-12-29 03:01:19 +03:00
<?php
namespace App\Traits;
2022-06-16 17:57:43 +03:00
use Akaunting\Apexcharts\Chart;
2019-12-29 03:01:19 +03:00
trait Charts
{
2022-06-01 10:15:55 +03:00
public $bar = [
'colors' => [],
'labels' => [],
'values' => [],
];
2019-12-29 03:01:19 +03:00
public $donut = [
'colors' => [],
'labels' => [],
'values' => [],
];
public function addToDonut($color, $label, $value)
{
$this->donut['colors'][] = $color;
$this->donut['labels'][] = $label;
$this->donut['values'][] = (int) $value;
}
public function addMoneyToDonut($color, $amount, $description = '')
{
$label = money($amount, setting('default.currency'), true)->format();
if (!empty($description)) {
$label .= ' - ' . $description;
}
$this->addToDonut($color, $label, $amount);
}
2022-06-01 10:15:55 +03:00
public function getDonutChart($name, $width = '100%', $height = 300, $limit = 10)
2019-12-29 03:01:19 +03:00
{
// Show donut prorated if there is no value
if (array_sum($this->donut['values']) == 0) {
foreach ($this->donut['values'] as $key => $value) {
$this->donut['values'][$key] = 1;
}
}
// Get 6 categories by amount
$colors = $labels = [];
$values = collect($this->donut['values'])->sort()->reverse()->take($limit)->all();
foreach ($values as $id => $val) {
$colors[$id] = $this->donut['colors'][$id];
$labels[$id] = $this->donut['labels'][$id];
}
2022-06-16 17:57:43 +03:00
$chart = new Chart();
2019-12-29 03:01:19 +03:00
2022-06-01 10:15:55 +03:00
$chart->setType('donut')
->setWidth($width)
->setHeight($height)
->setLabels(array_values($labels))
->setColors(array_values($colors))
->setDataset($name, 'donut', array_values($values));
2019-12-29 03:01:19 +03:00
return $chart;
}
2022-06-01 10:15:55 +03:00
public function addToBar($color, $label, $value)
2019-12-29 03:01:19 +03:00
{
2022-06-01 10:15:55 +03:00
$this->bar['colors'][] = $color;
$this->bar['labels'][] = $label;
$this->bar['values'][] = (int) $value;
2019-12-29 03:01:19 +03:00
}
2022-06-01 10:15:55 +03:00
public function getBarChart($name, $width = '100%', $height = 160)
2019-12-29 03:01:19 +03:00
{
2022-06-16 17:57:43 +03:00
$chart = new Chart();
2021-09-02 19:17:19 +03:00
2022-06-01 10:15:55 +03:00
$chart->setType('bar')
->setWidth($width)
->setHeight($height)
->setLabels(array_values($this->bar['labels']))
->setColors($this->bar['colors']);
2021-09-02 19:17:19 +03:00
2022-06-01 10:15:55 +03:00
foreach ($this->bar['values'] as $key => $value) {
$chart->setDataset($this->bar['labels'][$key], 'bar', $value);
2021-09-03 00:14:26 +03:00
}
2022-06-01 10:15:55 +03:00
return $chart;
2019-12-29 03:01:19 +03:00
}
}