Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { Component, Input, OnChanges, OnInit, ViewChild } from '@angular/core';
- import { ChartComponent as ApexChartComponent } from "ng-apexcharts";
- import {
- ApexOptions,
- ApexXAxis,
- ApexDataLabels,
- ApexTooltip,
- ApexStroke,
- ApexAxisChartSeries,
- ApexChart,
- ChartType,
- ChartComponent
- } from "ng-apexcharts";
- import { GraphData } from 'src/app/models/item.model';
- interface CustomApexChart extends ApexChart {
- type: ChartType;
- }
- export type ChartOptions = {
- series: ApexAxisChartSeries;
- chart: CustomApexChart;
- xaxis: Partial<ApexXAxis>;
- stroke: Partial<ApexStroke>;
- tooltip: Partial<ApexTooltip>;
- dataLabels: Partial<ApexDataLabels>;
- };
- @Component({
- selector: 'app-line-chart',
- template: '<div #lineChart><apx-chart [series]="chartOptions.series" [chart]="chartOptions.chart" [xaxis]="chartOptions.xaxis" [stroke]="chartOptions.stroke" [tooltip]="chartOptions.tooltip" [dataLabels]="chartOptions.dataLabels"></apx-chart></div>',
- })
- export class LineChartComponent implements OnChanges, OnInit {
- @ViewChild('lineChart', { static: true }) lineChart!: ApexChartComponent;
- public chartOptions: ChartOptions = {
- series: [
- {
- name: 'Revenus',
- data: [0, 0, 0, 0, 0, 0, 0]
- }
- ],
- chart: {
- height: 350,
- type: 'line' as ChartType,
- zoom: {
- enabled: false
- },
- toolbar: {
- show: false
- },
- animations: {
- enabled: false
- }
- },
- dataLabels: {
- enabled: false
- },
- stroke: {
- curve: 'smooth',
- width: 2
- },
- xaxis: {
- type: 'datetime',
- categories: ['01/01', '02/01', '03/01', '04/01', '05/01', '06/01', '07/01'],
- },
- tooltip: {
- enabled: true,
- x: {
- show: true,
- format: 'dd MMM'
- }
- }
- } as ChartOptions;
- @Input() data!: GraphData | null | undefined;
- @Input() graphScale!: string | null | undefined;
- ngOnChanges(): void {
- console.log(this.data);
- this.initializeChartOptions();
- }
- ngOnInit(): void {
- console.log(this.data);
- this.initializeChartOptions();
- }
- private initializeChartOptions(): void {
- if (!this.data || !this.data.data || !this.data.data.events) {
- return;
- }
- let { montants: revenues, dates: labels } = this.convertirListe(this.cleanData(this.data.data.events, this.graphScale || 'week'));
- revenues = this.smoothData(revenues);
- labels.sort(this.compareDates);
- labels = this.formatLabels(labels, this.graphScale || 'week');
- this.chartOptions.series = [
- {
- name: 'Revenus',
- data: revenues
- }
- ];
- this.chartOptions.xaxis.categories = labels;
- }
- constructor() {
- if (!this.data || !this.data.data || !this.data.data.events) {
- return;
- }
- let { montants: revenues, dates: labels } = this.convertirListe(this.cleanData(this.data.data.events, this.graphScale || 'week'));
- revenues = this.smoothData(revenues);
- labels.sort(this.compareDates);
- labels = this.formatLabels(labels, this.graphScale || 'week');
- this.chartOptions = {
- series: [
- {
- name: 'Revenus',
- data: revenues
- }
- ],
- chart: {
- height: 350,
- type: 'line',
- zoom: {
- enabled: false
- },
- toolbar: {
- show: false
- },
- animations: {
- enabled: false
- }
- },
- dataLabels: {
- enabled: false
- },
- stroke: {
- curve: 'smooth',
- width: 2
- },
- xaxis: {
- type: 'datetime',
- categories: labels,
- },
- tooltip: {
- enabled: true,
- x: {
- show: true,
- format: 'dd MMM'
- }
- }
- } as ChartOptions;
- }
- public cleanData(data: any, scale: string): any {
- if (scale == 'year') {
- return this.yearStats(data);
- } else if (scale == 'month') {
- return this.monthStats(data);
- } else if (scale == 'week') {
- return this.weekStats(data);
- }
- return data;
- }
- public monthToDay(month: number, year: number): number {
- if (month == 2) {
- if (year % 4 == 0) {
- return 29;
- } else {
- return 28;
- }
- }
- if (month == 4 || month == 6 || month == 9 || month == 11) {
- return 30;
- }
- return 31;
- }
- private yearStats(events: { amount: number; created_at: string }[]) {
- let monthlyTotals: { [key: string]: number } = {};
- for (const event of events) {
- const time = new Date(event.created_at);
- const formattedDate = `${time.getMonth() + 1}/${time.getFullYear()}`;
- if (!monthlyTotals[formattedDate]) {
- monthlyTotals[formattedDate] = 0;
- }
- monthlyTotals[formattedDate] = event.amount;
- }
- for (let i = 1; i <= 12; i++) {
- const monthYear = `${i}/${new Date().getFullYear()}`;
- if (!monthlyTotals[monthYear]) {
- if (this.getPreviousMonth(monthYear) in monthlyTotals) {
- monthlyTotals[monthYear] = monthlyTotals[this.getPreviousMonth(monthYear)];
- } else {
- monthlyTotals[monthYear] = 0;
- }
- }
- }
- const sortedMonths = Object.keys(monthlyTotals).map(key => {
- const [month, year] = key.split('/').map(Number);
- return new Date(year, month - 1);
- }).sort((a, b) => a.getTime() - b.getTime());
- //order by month
- let ordered: { [key: string]: number } = {};
- sortedMonths.forEach(date => {
- const monthYearKey = `${date.getMonth() + 1}/${date.getFullYear()}`;
- ordered[monthYearKey] = monthlyTotals[monthYearKey];
- });
- monthlyTotals = ordered;
- return Object.keys(monthlyTotals).map(key => {
- return { amount: monthlyTotals[key], created_at: key };
- });
- }
- public getPreviousMonth(monthYear: string): string {
- const [month, year] = monthYear.split('/').map(Number);
- if (month === 1) {
- return `12/${year - 1}`;
- } else {
- return `${month - 1}/${year}`;
- }
- }
- public getNextMonth(monthYear: string): string {
- const [month, year] = monthYear.split('/').map(Number);
- if (month === 12) {
- return `1/${year + 1}`;
- } else {
- return `${month + 1}/${year}`;
- }
- }
- public monthStats(events: { amount: number; created_at: string }[]) {
- const currentDate = new Date();
- const oneDayMilliseconds = 24 * 60 * 60 * 1000; // Milliseconds in a day
- // Create a dictionary to store daily amounts
- const dict: { [key: string]: number } = {};
- // Update dictionary with actual amounts from events
- for (const event of events) {
- const time = new Date(event.created_at);
- const formattedDate = `${time.getDate()}/${time.getMonth() + 1}/${time.getFullYear()}`;
- dict[formattedDate] = event.amount;
- }
- // Initialize dictionary with 0 values for the last 31 days
- for (let i = 30; i >= 0; i--) {
- const day = new Date(currentDate.getTime() - i * oneDayMilliseconds);
- const formattedDate = `${day.getDate()}/${day.getMonth() + 1}/${day.getFullYear()}`;
- if (!dict[formattedDate]) {
- dict[formattedDate] = 0;
- }
- }
- // Convert dictionary to array of objects
- const result = Object.keys(dict).map((key) => {
- return { amount: dict[key], created_at: key };
- });
- // Sort the array by date using timestamp for comparison
- result.sort((a, b) => {
- const partsA = a.created_at.split('/');
- const partsB = b.created_at.split('/');
- const dateA = new Date(parseInt(partsA[2]), parseInt(partsA[1]) - 1, parseInt(partsA[0])).getTime();
- const dateB = new Date(parseInt(partsB[2]), parseInt(partsB[1]) - 1, parseInt(partsB[0])).getTime();
- return dateB - dateA;
- });
- console.log(result);
- //invert the array, by using a loop
- const results = [];
- for (let i = result.length - 1; i >= 0; i--) {
- results.push(result[i]);
- }
- console.log(results);
- return results;
- }
- public weekStats(events: { amount: number; created_at: string }[]) {
- const currentDate = new Date();
- const oneDayMilliseconds = 24 * 60 * 60 * 1000;
- const dict: { [key: string]: number } = {};
- for (let i = 6; i >= 0; i--) {
- const day = new Date(currentDate.getTime() - i * oneDayMilliseconds);
- const formattedDate = `${day.getDate()}/${day.getMonth() + 1}`;
- dict[formattedDate] = 0;
- }
- for (const event of events) {
- const time = new Date(event.created_at);
- const formattedDate = `${time.getDate()}/${time.getMonth() + 1}`;
- dict[formattedDate] += event.amount;
- }
- let result = Object.keys(dict).map((key) => {
- return { amount: dict[key] || 0, created_at: key };
- });
- result.sort((a, b) => {
- const dateA = new Date(`${currentDate.getFullYear()}/${a.created_at}`).getTime();
- const dateB = new Date(`${currentDate.getFullYear()}/${b.created_at}`).getTime();
- return dateA - dateB;
- });
- result = result.slice(result.length - 1).concat(result.slice(0, result.length - 1));
- return result;
- }
- public convertirListe(liste: { amount: number; created_at: string }[]): { montants: number[]; dates: string[] } {
- const montants: number[] = [];
- const dates: string[] = [];
- for (const transaction of liste) {
- montants.push(transaction.amount);
- dates.push(transaction.created_at);
- }
- return { montants, dates };
- }
- public smoothData(data: any): any {
- const smoothData: any = [];
- for (let i = 0; i < data.length; i++) {
- if (data[i] == 0) {
- smoothData.push(smoothData[i - 1] || 0);
- } else {
- smoothData.push(data[i]);
- }
- }
- return smoothData;
- }
- public formatLabels(labels: string[], scale: string): string[] {
- if (scale == 'week') {
- return this.formatWeekLabels(labels);
- } else if (scale == 'month') {
- return this.formatMonthLabels(labels);
- } else if (scale == 'year') {
- return this.formatYearLabels(labels);
- }
- return labels;
- }
- public formatWeekLabels(dates: string[]): string[] {
- const jours = [
- 'Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'
- ];
- const datesFormatees: string[] = [];
- for (let i = 0; i < dates.length; i++) {
- const [jour, mois] = dates[i].split('/');
- const dateObj = new Date(`${mois}/${jour}/${new Date().getFullYear()}`);
- const dateFormatee = `${jours[dateObj.getDay()]} ${jour.padStart(2, '0')}`;
- datesFormatees.push(dateFormatee);
- }
- return datesFormatees;
- }
- public formatMonthLabels(dates: string[]): string[] {
- const mois = [
- 'Jan', 'Fév', 'Mar', 'Avr', 'Mai', 'Juin', 'Juil', 'Août', 'Sep', 'Oct', 'Nov', 'Déc'
- ];
- const datesFormatees: string[] = [];
- for (let i = 0; i < dates.length; i++) {
- const [jour, moisIndex, annee] = dates[i].split('/');
- const dateObj = new Date(`${annee}/${moisIndex}/${jour}`);
- const dateFormatee = `${jour.padStart(2, '0')} ${mois[dateObj.getMonth()]}.`;
- datesFormatees.push(dateFormatee);
- }
- return datesFormatees;
- }
- public formatYearLabels(dates: string[]): string[] {
- const listeMois = [
- 'Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet',
- 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'
- ];
- const datesFormatees: string[] = [];
- for (let i = 0; i < dates.length; i++) {
- const [mois, annee] = dates[i].split('/');
- const dateFormatee = `${listeMois[parseInt(mois) - 1]}`;
- datesFormatees.push(dateFormatee);
- }
- return datesFormatees.slice(0, 13)
- }
- public compareDates(date1: string, date2: string): number {
- const [jour1, mois1, annee1] = date1.split('/').map(Number);
- const [jour2, mois2, annee2] = date2.split('/').map(Number);
- if (annee1 < annee2) {
- return -1;
- } else if (annee1 > annee2) {
- return 1;
- } else {
- if (mois1 < mois2) {
- return -1;
- } else if (mois1 > mois2) {
- return 1;
- } else {
- if (jour1 < jour2) {
- return -1;
- } else if (jour1 > jour2) {
- return 1;
- } else {
- return 0;
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment