chore: Typescript: Rewrite Sessions (#21047)

Co-authored-by: Michael Geers <michael@geers.tv>
This commit is contained in:
Maschga 2025-06-03 00:40:49 +02:00 • committed by GitHub
parent b1d0cebfd1
commit 1b1f637c14
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
20 changed files with 534 additions and 377 deletions

View file

@ -9,33 +9,38 @@
</div>
</template>
<script>
<script lang="ts">
import { PolarArea } from "vue-chartjs";
import { RadialLinearScale, ArcElement, Legend, Tooltip } from "chart.js";
import { registerChartComponents, commonOptions, tooltipLabelColor } from "./chartConfig";
import { RadialLinearScale, ArcElement, Legend, Tooltip, type TooltipItem } from "chart.js";
import { registerChartComponents, commonOptions, tooltipLabelColor } from "./chartConfig.ts";
import formatter from "@/mixins/formatter";
import colors, { dimColor } from "@/colors";
import { TYPES, GROUPS } from "./types";
import LegendList from "./LegendList.vue";
import { defineComponent, type PropType } from "vue";
import type { CURRENCY } from "@/types/evcc";
import { TYPES, GROUPS, type Session } from "./types.ts";
registerChartComponents([RadialLinearScale, ArcElement, Legend, Tooltip]);
export default {
export default defineComponent({
name: "AvgCostGroupedChart",
components: { PolarArea, LegendList },
mixins: [formatter],
props: {
sessions: { type: Array, default: () => [] },
currency: { type: String, default: "EUR" },
groupBy: { type: String, default: GROUPS.LOADPOINT },
sessions: { type: Array as PropType<Session[]>, default: () => [] },
currency: { type: String as PropType<CURRENCY>, default: "EUR" },
groupBy: {
type: String as PropType<Exclude<GROUPS, GROUPS.NONE>>,
default: GROUPS.LOADPOINT,
},
colorMappings: { type: Object, default: () => ({ loadpoint: {}, vehicle: {} }) },
suggestedMax: { type: Number, default: 0 },
costType: { type: String, default: TYPES.PRICE },
costType: { type: String as PropType<TYPES>, default: TYPES.PRICE },
},
computed: {
chartData() {
console.log(`update ${this.costType} grouped data`);
const aggregatedData = {};
const aggregatedData: Record<string, { energy: number; cost: number }> = {};
this.sessions.forEach((session) => {
const groupKey = session[this.groupBy];
@ -45,10 +50,10 @@ export default {
const chargedEnergy = session.chargedEnergy;
if (this.costType === TYPES.CO2) {
aggregatedData[groupKey].energy += chargedEnergy;
aggregatedData[groupKey].cost += session.co2PerKWh * chargedEnergy;
aggregatedData[groupKey].cost += (session.co2PerKWh || 0) * chargedEnergy;
} else if (this.costType === TYPES.PRICE) {
aggregatedData[groupKey].energy += chargedEnergy;
aggregatedData[groupKey].cost += session.price;
aggregatedData[groupKey].cost += session.price || 0;
}
});
@ -85,7 +90,7 @@ export default {
aspectRatio: 1,
borderRadius: 8,
borderWidth: 3,
color: colors.text,
color: colors.text || "",
spacing: 0,
radius: "100%",
plugins: {
@ -96,19 +101,21 @@ export default {
position: "topBottomCenter",
callbacks: {
title: () => null,
label: (tooltipItem) => {
const { label, raw = 0 } = tooltipItem;
label: (tooltipItem: TooltipItem<"polarArea">) => {
const { label, dataset, dataIndex } = tooltipItem;
const d = dataset.data[dataIndex];
return (
label +
": " +
(this.costType === TYPES.CO2
? this.fmtCo2Long(raw)
: this.fmtPricePerKWh(raw, this.currency))
? this.fmtCo2Long(d)
: this.fmtPricePerKWh(d, this.currency))
);
},
labelColor: tooltipLabelColor(true),
},
},
} as any,
},
scales: {
r: {
@ -116,25 +123,25 @@ export default {
suggestedMax: this.suggestedMax,
beginAtZero: false,
ticks: {
color: colors.muted,
backdropColor: colors.background,
color: colors.muted || "",
backdropColor: colors.background || "",
font: { size: 10 },
callback: this.formatValue,
maxTicksLimit: 6,
},
angleLines: { display: false },
grid: { color: colors.border },
},
grid: { color: colors.border || "" },
} as any,
},
};
},
},
methods: {
formatValue(value) {
formatValue(value: number) {
return this.costType === TYPES.CO2
? this.fmtCo2Medium(value)
: this.fmtPricePerKWh(value, this.currency);
},
},
};
});
</script>

View file

@ -9,32 +9,44 @@
</div>
</template>
<script>
<script lang="ts">
import { Doughnut } from "vue-chartjs";
import { DoughnutController, ArcElement, LinearScale, Legend, Tooltip } from "chart.js";
import {
DoughnutController,
ArcElement,
LinearScale,
Legend,
Tooltip,
type TooltipItem,
} from "chart.js";
import LegendList from "./LegendList.vue";
import { registerChartComponents, commonOptions, tooltipLabelColor } from "./chartConfig";
import formatter from "@/mixins/formatter";
import colors from "@/colors";
import { TYPES, GROUPS } from "./types";
import { TYPES, GROUPS, type Session } from "./types";
import { defineComponent, type PropType } from "vue";
import { CURRENCY } from "@/types/evcc";
registerChartComponents([DoughnutController, ArcElement, LinearScale, Legend, Tooltip]);
export default {
export default defineComponent({
name: "CostGroupedChart",
components: { Doughnut, LegendList },
mixins: [formatter],
props: {
sessions: { type: Array, default: () => [] },
groupBy: { type: String, default: GROUPS.LOADPOINT },
sessions: { type: Array as PropType<Session[]>, default: () => [] },
groupBy: {
type: String as PropType<Exclude<GROUPS, GROUPS.NONE>>,
default: GROUPS.LOADPOINT,
},
colorMappings: { type: Object, default: () => ({ loadpoint: {}, vehicle: {} }) },
currency: { type: String, default: "EUR" },
costType: { type: String, default: TYPES.PRICE },
currency: { type: String as PropType<CURRENCY>, default: CURRENCY.EUR },
costType: { type: String as PropType<TYPES>, default: TYPES.PRICE },
},
computed: {
chartData() {
console.log(`update ${this.costType} grouped data`);
const aggregatedData = {};
const aggregatedData: Record<string, number> = {};
this.sessions.forEach((session) => {
const groupKey = session[this.groupBy];
@ -42,9 +54,10 @@ export default {
aggregatedData[groupKey] = 0;
}
if (this.costType === TYPES.PRICE) {
aggregatedData[groupKey] += session.price;
aggregatedData[groupKey] += session.price || 0;
} else if (this.costType === TYPES.CO2) {
aggregatedData[groupKey] += session.co2PerKWh * session.chargedEnergy;
aggregatedData[groupKey] +=
(session.co2PerKWh || 0) * (session.chargedEnergy || 0);
}
});
@ -60,7 +73,7 @@ export default {
},
legends() {
const total = this.chartData.datasets[0].data.reduce((acc, curr) => acc + curr, 0);
const fmtShare = (value) => this.fmtPercentage((100 / total) * value, 1);
const fmtShare = (value: number) => this.fmtPercentage((100 / total) * value, 1);
return this.chartData.labels.map((label, index) => ({
label: label,
color: this.chartData.datasets[0].backgroundColor[index],
@ -76,9 +89,9 @@ export default {
locale: this.$i18n?.locale,
aspectRatio: 1,
borderRadius: 10,
color: colors.text,
color: colors.text || "",
borderWidth: 3,
borderColor: colors.background,
borderColor: colors.background || "",
cutout: "70%",
radius: "95%",
animation: { duration: 250 },
@ -89,21 +102,24 @@ export default {
axis: "r",
position: "center",
callbacks: {
label: (tooltipItem) => this.formatValue(tooltipItem.raw || 0),
label: (tooltipItem: TooltipItem<"doughnut">) =>
this.formatValue(
tooltipItem.dataset.data[tooltipItem.dataIndex] || 0
),
labelColor: tooltipLabelColor(false),
},
},
},
};
} as any;
},
},
methods: {
formatValue(value) {
formatValue(value: number) {
if (this.costType === TYPES.PRICE) {
return this.fmtMoney(value, this.currency, true, true);
}
return this.fmtGrams(value);
},
},
};
});
</script>

View file

@ -7,7 +7,8 @@
</div>
</template>
<script>
<script lang="ts">
import { defineComponent, type PropType } from "vue";
import { Bar } from "vue-chartjs";
import {
BarController,
@ -18,12 +19,16 @@ import {
LineController,
LineElement,
Tooltip,
type ChartData,
type TooltipItem,
} from "chart.js";
import { registerChartComponents, commonOptions, tooltipLabelColor } from "./chartConfig";
import LegendList from "./LegendList.vue";
import formatter from "@/mixins/formatter";
import colors from "@/colors";
import { TYPES, GROUPS, PERIODS } from "./types";
import { TYPES, GROUPS, PERIODS, type Session } from "./types";
import { CURRENCY } from "@/types/evcc";
import type { Context } from "chartjs-plugin-datalabels";
registerChartComponents([
BarController,
@ -36,16 +41,16 @@ registerChartComponents([
Tooltip,
]);
export default {
export default defineComponent({
name: "CostHistoryChart",
components: { Bar, LegendList },
mixins: [formatter],
props: {
sessions: { type: Array, default: () => [] },
groupBy: { type: String, default: GROUPS.NONE },
costType: { type: String, default: TYPES.PRICE },
period: { type: String, default: PERIODS.TOTAL },
currency: { type: String, default: "EUR" },
sessions: { type: Array as PropType<Session[]>, default: () => [] },
groupBy: { type: String as PropType<GROUPS>, default: GROUPS.NONE },
costType: { type: String as PropType<TYPES>, default: TYPES.PRICE },
period: { type: String as PropType<PERIODS>, default: PERIODS.TOTAL },
currency: { type: String as PropType<CURRENCY>, default: CURRENCY.EUR },
colorMappings: { type: Object, default: () => ({ loadpoint: {}, vehicle: {} }) },
suggestedMaxAvgCost: { type: Number, default: 0 },
suggestedMaxCost: { type: Number, default: 0 },
@ -58,10 +63,10 @@ export default {
return new Date(this.sessions[0].created);
},
month() {
return this.firstDay?.getMonth() + 1;
return (this.firstDay?.getMonth() || 0) + 1;
},
year() {
return this.firstDay?.getFullYear();
return this.firstDay?.getFullYear() || 0;
},
lastDay() {
if (this.sessions.length === 0) {
@ -69,10 +74,19 @@ export default {
}
return new Date(this.sessions[this.sessions.length - 1].created);
},
chartData() {
chartData(): ChartData<"bar", number[], unknown> {
console.log("update cost history data");
const result = {};
const groups = new Set();
const result: Array<{
[key: string]: number;
totalCost: number;
totalKWh: number;
avgCost: number;
}> = [];
const groups: Set<string> = new Set();
if (!this.firstDay || !this.lastDay) {
return { labels: [], datasets: [] };
}
if (this.sessions.length > 0) {
//const lastDay = new Date(this.year, this.month, 0);
@ -95,7 +109,7 @@ export default {
// initialize result with empty arrays
for (let i = xFrom; i <= xTo; i++) {
result[i] = {};
result[i] = { totalCost: 0, totalKWh: 0, avgCost: 0 };
}
// Populate with actual data
@ -116,8 +130,8 @@ export default {
const value =
this.costType === TYPES.PRICE
? session.price
: session.co2PerKWh * session.chargedEnergy;
? session.price || 0
: (session.co2PerKWh || 0) * (session.chargedEnergy || 0);
result[index][groupKey] = (result[index][groupKey] || 0) + value;
@ -134,21 +148,23 @@ export default {
this.groupBy === GROUPS.NONE ? this.$t(`sessions.group.${group}`) : group;
return {
type: "bar",
type: "bar" as const,
backgroundColor,
label,
data: Object.values(result).map((index) => index[group] || 0),
borderRadius: (context) => {
borderRadius: (context: Context) => {
const threshold = 0.04; // 400 Wh
const { dataIndex, datasetIndex } = context;
const currentValue = context.dataset.data[dataIndex];
const currentValue = context.dataset.data[dataIndex] as number;
const previousValuesExist = context.chart.data.datasets
.filter((dataset) => dataset.type === "bar")
.slice(datasetIndex + 1)
.some((dataset) => (dataset?.data[dataIndex] || 0) > threshold);
return currentValue > threshold && !previousValuesExist
? { topLeft: 10, topRight: 10 }
: { topLeft: 0, topRight: 0 };
.some((dataset: any) => (dataset?.data[dataIndex] || 0) > threshold);
return (
currentValue > threshold && !previousValuesExist
? { topLeft: 10, topRight: 10 }
: { topLeft: 0, topRight: 0 }
) as any;
},
};
});
@ -156,12 +172,12 @@ export default {
// add average price line
const costColor = this.costType === TYPES.PRICE ? colors.pricePerKWh : colors.co2PerKWh;
datasets.push({
type: "line",
type: "line" as const,
label:
this.costType === TYPES.PRICE
? this.$t("sessions.avgPrice")
: this.$t("sessions.co2"),
data: Object.values(result).map((index) => index.avgCost || null),
data: Object.values(result).map((index) => index.avgCost),
yAxisID: "y1",
tension: 0.25,
pointRadius: 0,
@ -170,7 +186,7 @@ export default {
backgroundColor: costColor,
borderWidth: 2,
spanGaps: true,
});
} as any);
return {
labels: Object.keys(result),
@ -182,11 +198,11 @@ export default {
let value = null;
// line chart handling
if (dataset.type === "line") {
if ((dataset as any).type === "line") {
const items = dataset.data.filter((v) => v !== null);
const min = Math.min(...items);
const max = Math.max(...items);
const format = (value, withUnit) => {
const format = (value: number, withUnit: boolean) => {
return this.costType === TYPES.PRICE
? this.fmtPricePerKWh(value, this.currency, false, withUnit)
: withUnit
@ -202,7 +218,7 @@ export default {
: this.fmtGrams(total);
}
return {
label: dataset.label,
label: dataset.label || "",
color: dataset.backgroundColor,
value,
};
@ -215,16 +231,16 @@ export default {
return {
...commonOptions,
locale: this.$i18n?.locale,
color: colors.text,
color: colors.text || "",
borderSkipped: false,
maxBarThickness: 40,
animation: false,
animation: false as const,
plugins: {
...commonOptions.plugins,
tooltip: {
...commonOptions.plugins.tooltip,
axis: "x",
positioner: (context) => {
positioner: (context: any) => {
const { chart, tooltipPosition } = context;
const { tooltip } = chart;
const { width, height } = tooltip;
@ -237,28 +253,28 @@ export default {
};
},
callbacks: {
title: (tooltipItem) => {
title: (tooltipItem: TooltipItem<"bar">[]) => {
const { label } = tooltipItem[0];
if (this.period === PERIODS.TOTAL) {
return label;
} else if (this.period === PERIODS.YEAR) {
const date = new Date(this.year, label - 1, 1);
return this.fmtMonth(date);
const date = new Date(this.year, Number(label) - 1, 1);
return this.fmtMonth(date, false);
} else {
const date = new Date(this.year, this.month - 1, label);
const date = new Date(this.year, this.month - 1, Number(label));
return this.fmtDayMonth(date);
}
},
label: (tooltipItem) => {
label: (tooltipItem: TooltipItem<"bar" | "line">) => {
const datasetLabel = tooltipItem.dataset.label || "";
const value = tooltipItem.raw;
const value = tooltipItem.dataset.data[tooltipItem.dataIndex];
if (typeof value !== "number") {
return undefined;
}
// line datasets have null values
if (tooltipItem.dataset.type === "line") {
if (value === null) {
return null;
}
const valueFmt =
this.costType === TYPES.PRICE
? this.fmtPricePerKWh(value, this.currency, false)
@ -272,11 +288,11 @@ export default {
? this.fmtMoney(value, this.currency, true, true)
: this.fmtGrams(value)
}`
: null;
: undefined;
},
labelColor: tooltipLabelColor(false),
},
itemSort(a, b) {
itemSort(a: TooltipItem<"bar">, b: TooltipItem<"bar">) {
return b.datasetIndex - a.datasetIndex;
},
},
@ -288,10 +304,10 @@ export default {
grid: { display: false },
ticks: {
color: colors.muted,
callback(value) {
callback(value: number): string {
return vThis.period === PERIODS.YEAR
? vThis.fmtMonth(new Date(vThis.year, value, 1), true)
: this.getLabelForValue(value);
: (this as any).getLabelForValue(value);
},
},
},
@ -306,7 +322,7 @@ export default {
color: colors.muted,
},
ticks: {
callback: (value) =>
callback: (value: number) =>
this.costType === TYPES.PRICE
? this.fmtMoney(value, this.currency, false, true)
: this.fmtNumber(value / 1e3, 0),
@ -332,7 +348,7 @@ export default {
color: colors.muted,
},
ticks: {
callback: (value) =>
callback: (value: number) =>
this.costType === TYPES.PRICE
? this.fmtPricePerKWh(value, this.currency, false, false)
: this.fmtNumber(value, 0),
@ -341,8 +357,8 @@ export default {
},
},
},
};
} as any;
},
},
};
});
</script>

View file

@ -93,12 +93,14 @@
</div>
</template>
<script>
<script lang="ts">
import { defineComponent } from "vue";
import CustomSelect from "../Helper/CustomSelect.vue";
import DateNavigatorButton from "./DateNavigatorButton.vue";
import formatter from "@/mixins/formatter";
import type { SelectOption } from "@/types/evcc";
export default {
export default defineComponent({
name: "DateNavigator",
components: {
CustomSelect,
@ -106,9 +108,9 @@ export default {
},
mixins: [formatter],
props: {
month: Number,
year: Number,
startDate: Date,
month: { type: Number, required: true },
year: { type: Number, required: true },
startDate: { type: Date, required: true },
showMonth: Boolean,
showYear: Boolean,
},
@ -132,7 +134,7 @@ export default {
},
monthOptions() {
return Array.from({ length: 12 }, (_, i) => i + 1).map((month) => ({
name: this.fmtMonth(new Date(this.year, month - 1, 1)),
name: this.fmtMonth(new Date(this.year, month - 1, 1), false),
value: month,
}));
},
@ -152,19 +154,19 @@ export default {
}
return yearMonths;
},
yearOptions() {
yearOptions(): SelectOption<number>[] {
const first = this.startDate;
const last = new Date();
const years = [];
for (let year = first.getFullYear(); year <= last.getFullYear(); year++) {
years.push({ name: year, value: year });
years.push({ name: year.toString(), value: year });
}
return years;
},
monthName() {
const date = new Date();
date.setMonth(this.month - 1, 1);
return this.fmtMonth(date);
return this.fmtMonth(date, false);
},
monthYearName() {
const date = new Date();
@ -194,18 +196,18 @@ export default {
emitNextYear() {
this.$emit("update-date", { year: this.year + 1, month: undefined });
},
emitMonth(month) {
emitMonth(month: number) {
this.$emit("update-date", { year: this.year, month });
},
emitMonthYear(monthYear) {
emitMonthYear(monthYear: string) {
const [year, month] = monthYear.split("-");
this.$emit("update-date", { year: parseInt(year), month: parseInt(month) });
},
emitYear(year) {
emitYear(year: number) {
this.$emit("update-date", { year, month: undefined });
},
},
};
});
</script>
<style scoped>

View file

@ -4,17 +4,18 @@
</button>
</template>
<script>
<script lang="ts">
import { defineComponent, type PropType } from "vue";
import "@h2d2/shopicons/es/regular/angledoubleleftsmall";
import "@h2d2/shopicons/es/regular/angledoublerightsmall";
export default {
export default defineComponent({
name: "DateNavigatorButton",
props: {
disabled: Boolean,
prev: Boolean,
next: Boolean,
onClick: Function,
onClick: { type: Function as PropType<(event: MouseEvent) => void> },
},
computed: {
icon() {
@ -29,7 +30,7 @@ export default {
return this.prev ? "me-1" : this.next ? "ms-1" : "";
},
},
};
});
</script>
<style scoped>

View file

@ -9,30 +9,38 @@
</div>
</template>
<script>
<script lang="ts">
import { defineComponent, type PropType } from "vue";
import { Doughnut } from "vue-chartjs";
import { DoughnutController, ArcElement, LinearScale, Legend, Tooltip } from "chart.js";
import {
DoughnutController,
ArcElement,
LinearScale,
Legend,
Tooltip,
type TooltipItem,
} from "chart.js";
import LegendList from "./LegendList.vue";
import { registerChartComponents, commonOptions, tooltipLabelColor } from "./chartConfig";
import formatter, { POWER_UNIT } from "@/mixins/formatter";
import colors from "@/colors";
import { GROUPS } from "./types";
import { GROUPS, type Session } from "./types";
registerChartComponents([DoughnutController, ArcElement, LinearScale, Legend, Tooltip]);
export default {
export default defineComponent({
name: "EnergyGroupedChart",
components: { Doughnut, LegendList },
mixins: [formatter],
props: {
sessions: { type: Array, default: () => [] },
groupBy: { type: String, default: GROUPS.NONE },
sessions: { type: Array as PropType<Session[]>, default: () => [] },
groupBy: { type: String as PropType<GROUPS>, default: GROUPS.NONE },
colorMappings: { type: Object, default: () => ({ loadpoint: {}, vehicle: {}, solar: {} }) },
},
computed: {
chartData() {
console.log("update energy aggregate data");
const aggregatedData = {};
const aggregatedData: { [key: string]: number } = {};
if (this.groupBy === GROUPS.NONE) {
const total = this.sessions.reduce((acc, s) => acc + s.chargedEnergy, 0);
@ -40,11 +48,11 @@ export default {
(acc, s) => acc + (s.chargedEnergy / 100) * s.solarPercentage,
0
);
aggregatedData.self = self;
aggregatedData.grid = total - self;
aggregatedData["self"] = self;
aggregatedData["grid"] = total - self;
} else {
this.sessions.forEach((session) => {
const groupKey = session[this.groupBy];
const groupKey = session[this.groupBy as "loadpoint" | "vehicle"];
if (!aggregatedData[groupKey]) {
aggregatedData[groupKey] = 0;
}
@ -75,8 +83,8 @@ export default {
// sync energy units for label grid view
const unit =
maxEnergy < 1 ? POWER_UNIT.W : maxEnergy > 1e4 ? POWER_UNIT.MW : POWER_UNIT.KW;
const fmtShare = (value) => this.fmtPercentage((100 / total) * value, 1);
const fmtValue = (value) => this.fmtWh(value * 1e3, unit);
const fmtShare = (value: number) => this.fmtPercentage((100 / total) * value, 1);
const fmtValue = (value: number) => this.fmtWh(value * 1e3, unit);
return this.chartData.labels.map((label, index) => ({
label: label,
color: this.chartData.datasets[0].backgroundColor[index],
@ -105,18 +113,19 @@ export default {
axis: "r",
position: "center",
callbacks: {
label: (tooltipItem) => this.formatValue(tooltipItem.raw || 0),
label: (tooltipItem: TooltipItem<"doughnut">) =>
this.formatValue(tooltipItem.raw as number),
labelColor: tooltipLabelColor(false),
},
},
},
};
} as any;
},
},
methods: {
formatValue(value) {
formatValue(value: number) {
return this.fmtWh(value * 1e3, POWER_UNIT.AUTO);
},
},
};
});
</script>

View file

@ -7,25 +7,37 @@
</div>
</template>
<script>
<script lang="ts">
import { defineComponent, type PropType } from "vue";
import { Bar } from "vue-chartjs";
import { BarController, BarElement, CategoryScale, LinearScale, Legend, Tooltip } from "chart.js";
import {
BarController,
BarElement,
CategoryScale,
LinearScale,
Legend,
Tooltip,
type ChartData,
type TooltipModel,
type TooltipItem,
} from "chart.js";
import { registerChartComponents, commonOptions, tooltipLabelColor } from "./chartConfig";
import LegendList from "./LegendList.vue";
import formatter, { POWER_UNIT } from "@/mixins/formatter";
import colors from "@/colors";
import { GROUPS, PERIODS } from "./types";
import { GROUPS, PERIODS, type Session } from "./types";
import type { Context } from "chartjs-plugin-datalabels";
registerChartComponents([BarController, BarElement, CategoryScale, LinearScale, Legend, Tooltip]);
export default {
export default defineComponent({
name: "EnergyHistoryChart",
components: { Bar, LegendList },
mixins: [formatter],
props: {
sessions: { type: Array, default: () => [] },
groupBy: { type: String, default: GROUPS.NONE },
period: { type: String, default: PERIODS.TOTAL },
sessions: { type: Array as PropType<Session[]>, default: () => [] },
groupBy: { type: String as PropType<GROUPS>, default: GROUPS.NONE },
period: { type: String as PropType<PERIODS>, default: PERIODS.TOTAL },
colorMappings: { type: Object, default: () => ({ loadpoint: {}, vehicle: {} }) },
},
computed: {
@ -36,10 +48,10 @@ export default {
return new Date(this.sessions[0].created);
},
month() {
return this.firstDay?.getMonth() + 1;
return (this.firstDay?.getMonth() || 0) + 1;
},
year() {
return this.firstDay?.getFullYear();
return this.firstDay?.getFullYear() || 0;
},
lastDay() {
if (this.sessions.length === 0) {
@ -47,12 +59,12 @@ export default {
}
return new Date(this.sessions[this.sessions.length - 1].created);
},
chartData() {
chartData(): ChartData<"bar", number[], unknown> {
console.log("update energy history data");
const result = {};
const groups = new Set();
const result: Record<number, Record<string, number>> = {};
const groups: Set<string> = new Set();
if (this.sessions.length > 0) {
if (this.firstDay && this.lastDay) {
//const lastDay = new Date(this.year, this.month, 0);
//const daysInMonth = this.lastDay.getDate();
let xFrom, xTo;
@ -94,8 +106,8 @@ export default {
const charged = session.chargedEnergy;
const self = (charged / 100) * session.solarPercentage;
const grid = charged - self;
result[index].self = (result[index].self || 0) + self;
result[index].grid = (result[index].grid || 0) + grid;
result[index]["self"] = (result[index]["self"] || 0) + self;
result[index]["grid"] = (result[index]["grid"] || 0) + grid;
} else {
const groupKey = session[this.groupBy];
groups.add(groupKey);
@ -115,16 +127,16 @@ export default {
backgroundColor,
label,
data: Object.values(result).map((day) => day[group] || 0),
borderRadius: (context) => {
borderRadius: (context: Context) => {
const threshold = 0.04; // 400 Wh
const { dataIndex, datasetIndex } = context;
const currentValue = context.dataset.data[dataIndex];
const currentValue = context.dataset.data[dataIndex] as number;
const previousValuesExist = context.chart.data.datasets
.slice(datasetIndex + 1)
.some((dataset) => (dataset?.data[dataIndex] || 0) > threshold);
.some((dataset: any) => (dataset?.data[dataIndex] || 0) > threshold);
return currentValue > threshold && !previousValuesExist
? { topLeft: 10, topRight: 10 }
: { topLeft: 0, topRight: 0 };
? { topLeft: 10, topRight: 10, bottomLeft: 0, bottomRight: 0 }
: { topLeft: 0, topRight: 0, bottomLeft: 0, bottomRight: 0 };
},
};
});
@ -136,7 +148,7 @@ export default {
},
legends() {
return this.chartData.datasets.map((dataset) => ({
label: dataset.label,
label: dataset.label || "",
color: dataset.backgroundColor,
value: this.fmtWh(
dataset.data.reduce((acc, curr) => acc + curr, 0) * 1e3,
@ -160,34 +172,36 @@ export default {
tooltip: {
...commonOptions.plugins.tooltip,
axis: "x",
positioner: (context) => {
positioner: (context: TooltipModel<"bar">) => {
const { chart, tooltipPosition } = context;
const { tooltip } = chart;
const { width, height } = tooltip;
const { x, y } = tooltipPosition();
const { width, height } = tooltip || {};
const { x, y } = tooltipPosition(false);
const { innerWidth, innerHeight } = window;
return {
x: Math.min(x, innerWidth - width),
y: Math.min(y, innerHeight - height),
x: Math.min(x, innerWidth - (width || 0)),
y: Math.min(y, innerHeight - (height || 0)),
};
},
callbacks: {
title: (tooltipItem) => {
title: (tooltipItem: TooltipItem<"bar">[]) => {
const { label } = tooltipItem[0];
if (this.period === PERIODS.TOTAL) {
return label;
} else if (this.period === PERIODS.YEAR) {
const date = new Date(this.year, label - 1, 1);
return this.fmtMonth(date);
const date = new Date(this.year, Number(label) - 1, 1);
return this.fmtMonth(date, false);
} else {
const date = new Date(this.year, this.month - 1, label);
const date = new Date(this.year, this.month - 1, Number(label));
return this.fmtDayMonth(date);
}
},
label: (tooltipItem) => {
label: (tooltipItem: TooltipItem<"bar">) => {
const datasetLabel = tooltipItem.dataset.label || "";
const value = tooltipItem.raw || 0;
const value =
(tooltipItem.dataset.data[tooltipItem.dataIndex] as number) ||
0;
return value
? `${datasetLabel}: ${this.fmtWh(value * 1e3, POWER_UNIT.AUTO)}`
: null;
@ -199,7 +213,7 @@ export default {
};
},
},
itemSort(a, b) {
itemSort(a: TooltipItem<"bar">, b: TooltipItem<"bar">) {
return b.datasetIndex - a.datasetIndex;
},
},
@ -211,10 +225,10 @@ export default {
grid: { display: false },
ticks: {
color: colors.muted,
callback(value) {
callback(value: number) {
return vThis.period === PERIODS.YEAR
? vThis.fmtMonth(new Date(vThis.year, value, 1), true)
: this.getLabelForValue(value);
: (this as any).getLabelForValue(value);
},
},
},
@ -228,7 +242,8 @@ export default {
color: colors.muted,
},
ticks: {
callback: (value) => this.fmtWh(value * 1e3, POWER_UNIT.KW, false, 0),
callback: (value: number) =>
this.fmtWh(value * 1e3, POWER_UNIT.KW, false, 0),
color: colors.muted,
maxTicksLimit: 6,
},
@ -236,8 +251,8 @@ export default {
min: 0,
},
},
};
} as any;
},
},
};
});
</script>

View file

@ -28,21 +28,24 @@
</ul>
</template>
<script>
export default {
<script lang="ts">
import { defineComponent, type PropType } from "vue";
import type { Legend } from "./types";
export default defineComponent({
name: "LegendList",
props: {
legends: Array,
legends: Array as PropType<Legend[]>,
grid: Boolean,
smallEqualWidths: Boolean,
},
methods: {
valueList(value) {
valueList(value: Legend["value"]) {
if (!value) return [];
return Array.isArray(value) ? value : [value];
},
},
};
});
</script>
<style scoped>

View file

@ -16,23 +16,26 @@
/>
</template>
<script>
<script lang="ts">
import { defineComponent, type PropType } from "vue";
import SelectGroup from "../Helper/SelectGroup.vue";
import type { SelectOption } from "@/types/evcc";
import type { PERIODS } from "./types";
export default {
export default defineComponent({
name: "PeriodSelector",
components: {
SelectGroup,
},
props: {
period: { type: String, required: true },
periodOptions: { type: Array, required: true },
periodOptions: { type: Array as PropType<SelectOption<PERIODS>[]>, required: true },
},
emits: ["update:period"],
methods: {
changePeriod(newPeriod) {
changePeriod(newPeriod: PERIODS) {
this.$emit("update:period", newPeriod);
},
},
};
});
</script>

View file

@ -72,9 +72,9 @@
{{ $t("session.date") }}
</th>
<td>
{{ fmtFullDateTime(new Date(session.created), false) }}
{{ fmtFullDateTime(session.created, false) }}
<br />
{{ fmtFullDateTime(new Date(session.finished), false) }}
{{ fmtFullDateTime(session.finished, false) }}
</td>
</tr>
<tr>
@ -112,7 +112,7 @@
<td>
{{ fmtMoney(session.price, currency) }}
{{ fmtCurrencySymbol(currency) }}<br />
{{ fmtPricePerKWh(session.pricePerKWh, currency) }}
{{ fmtPricePerKWh(session.pricePerKWh || 0, currency) }}
</td>
</tr>
<tr v-if="session.co2PerKWh != null">
@ -194,7 +194,7 @@
</Teleport>
</template>
<script>
<script lang="ts">
import "@h2d2/shopicons/es/regular/checkmark";
import Modal from "bootstrap/js/dist/modal";
import formatter from "@/mixins/formatter";
@ -202,16 +202,19 @@ import Options from "../Vehicles/Options.vue";
import CustomSelect from "../Helper/CustomSelect.vue";
import { distanceUnit, distanceValue } from "@/units";
import api from "@/api";
import { defineComponent, type PropType } from "vue";
import type { Session } from "./types";
import type { CURRENCY, LoadpointCompact, SelectOption, Vehicle } from "@/types/evcc";
export default {
export default defineComponent({
name: "SessionDetailsModal",
components: { VehicleOptions: Options, CustomSelect },
mixins: [formatter],
props: {
session: Object,
currency: String,
vehicles: Array,
loadpoints: Array,
session: { type: Object as PropType<Session>, default: () => ({}) },
currency: { type: String as PropType<CURRENCY> },
vehicles: { type: Array as PropType<Vehicle[]>, default: () => [] },
loadpoints: { type: Array as PropType<LoadpointCompact[]>, default: () => [] },
},
emits: ["session-changed"],
computed: {
@ -231,37 +234,39 @@ export default {
title: v.title,
}));
},
loadpointOptions() {
loadpointOptions(): SelectOption<string>[] {
return this.loadpoints.map((loadpoint) => ({
value: loadpoint,
name: loadpoint,
value: loadpoint.title,
name: loadpoint.title,
}));
},
},
methods: {
openSessionDetailsModal() {
const modal = Modal.getOrCreateInstance(document.getElementById("sessionDetailsModal"));
const modal = Modal.getOrCreateInstance(
document.getElementById("sessionDetailsModal") as HTMLElement
);
modal.show();
},
openRemoveConfirmationModal() {
const modal = Modal.getOrCreateInstance(
document.getElementById("deleteSessionConfirmationModal")
document.getElementById("deleteSessionConfirmationModal") as HTMLElement
);
modal.show();
},
formatKm(value) {
formatKm(value: number) {
return `${this.fmtNumber(distanceValue(value), 0)} ${distanceUnit()}`;
},
async changeVehicle(title) {
async changeVehicle(title: string) {
await this.updateSession({ vehicle: title });
},
async removeVehicle() {
await this.updateSession({ vehicle: null });
},
async changeLoadpoint(title) {
async changeLoadpoint(title: string) {
await this.updateSession({ loadpoint: title });
},
async updateSession(data) {
async updateSession(data: Partial<Session> | { vehicle: null }) {
try {
await api.put("session/" + this.session.id, data);
this.$emit("session-changed");
@ -278,7 +283,7 @@ export default {
}
},
},
};
});
</script>
<style scoped>

View file

@ -121,7 +121,7 @@
scope="col"
class="align-top text-end"
>
{{ column.format(column.total) }}
{{ column.format(column.total || 0) }}
</th>
</tr>
</tfoot>
@ -148,7 +148,7 @@
</td>
<td v-for="column in columnsPerBreakpoint" :key="column.name" class="text-end">
<span v-if="column.value(session) === null" class="text-gray"> - </span>
<span v-else>{{ column.format(column.value(session)) }}</span>
<span v-else>{{ column.format(column.value(session) || 0) }}</span>
</td>
</tr>
</tbody>
@ -156,11 +156,14 @@
</div>
</template>
<script>
<script lang="ts">
import { defineComponent, type PropType } from "vue";
import CustomSelect from "../Helper/CustomSelect.vue";
import formatter, { POWER_UNIT } from "@/mixins/formatter";
import breakpoint from "@/mixins/breakpoint";
import breakpoint from "@/mixins/breakpoint.ts";
import settings from "@/settings";
import type { CURRENCY } from "@/types/evcc";
import type { Session, Column } from "./types";
const COLUMNS_PER_BREAKPOINT = {
xs: 1,
@ -171,15 +174,15 @@ const COLUMNS_PER_BREAKPOINT = {
xxl: 6,
};
export default {
export default defineComponent({
name: "SessionTable",
components: { CustomSelect },
mixins: [formatter, breakpoint],
props: {
sessions: { type: Array, default: () => [] },
sessions: { type: Array as PropType<Session[]>, default: () => [] },
loadpointFilter: { type: String, default: "" },
vehicleFilter: { type: String, default: "" },
currency: { type: String },
currency: { type: String as PropType<CURRENCY> },
},
emits: ["show-session"],
data() {
@ -192,13 +195,13 @@ export default {
return this.sessions
.filter(this.filterByLoadpoint)
.filter(this.filterByVehicle)
.sort((a, b) => new Date(b.created) - new Date(a.created));
.sort((a, b) => new Date(b.created).getTime() - new Date(a.created).getTime());
},
maxColumns() {
return COLUMNS_PER_BREAKPOINT[this.breakpoint] || 1;
},
columns() {
const columns = [
const columns: Column[] = [
{
name: "energy",
unit: "kWh",
@ -231,7 +234,7 @@ export default {
name: "co2",
unit: "g/kWh",
total: this.co2PerKWh,
value: (session) => session.co2PerKWh,
value: (session) => session.co2PerKWh || null,
format: (value) => this.fmtNumber(value, 0),
},
{
@ -266,15 +269,17 @@ export default {
},
sortedColumns() {
const columns = [...this.columns];
const sorted = [];
const sorted = [] as Column[];
for (const name of this.selectedColumns) {
if (!name && columns.length) {
sorted.push(columns.shift());
sorted.push(columns.shift() as Column);
} else if (columns.some((c) => c.name === name)) {
const column = columns.find((c) => c.name === name);
sorted.push(column);
const index = columns.indexOf(column);
columns.splice(index, 1);
if (column) {
sorted.push(column);
const index = columns.indexOf(column);
columns.splice(index, 1);
}
}
}
return sorted.concat(columns);
@ -287,7 +292,7 @@ export default {
return {
name: this.$t(`sessions.${column.name}`),
value: column.name,
disabled: this.columnsPerBreakpoint.find((c) => c.name === column.name),
disabled: this.columnsPerBreakpoint.some((c) => c.name === column.name),
};
});
},
@ -296,7 +301,7 @@ export default {
{
name: this.$t("sessions.filter.allVehicles"),
value: "",
count: this.filterCountForVehicle(),
count: this.filterCountForVehicle(""),
},
];
this.vehicles.forEach((name) => {
@ -310,7 +315,7 @@ export default {
{
name: this.$t("sessions.filter.allLoadpoints"),
value: "",
count: this.filterCountForLoadpoint(),
count: this.filterCountForLoadpoint(""),
},
];
this.loadpoints.forEach((name) => {
@ -326,7 +331,7 @@ export default {
return this.filteredSessions.reduce((total, s) => total + s.chargeDuration, 0);
},
price() {
return this.filteredSessions.reduce((total, s) => total + s.price, 0);
return this.filteredSessions.reduce((total, s) => total + (s.price || 0), 0);
},
avgPower() {
const { energy, hours } = this.filteredSessions
@ -349,7 +354,7 @@ export default {
.filter((s) => s.price !== null)
.reduce(
(total, s) => ({
price: total.price + s.price,
price: total.price + (s.price || 0),
chargedEnergy: total.chargedEnergy + s.chargedEnergy,
}),
{ price: 0, chargedEnergy: 0 }
@ -361,7 +366,7 @@ export default {
.filter((s) => s.co2PerKWh !== null)
.reduce(
(total, s) => ({
emittedCo2: total.emittedCo2 + s.chargedEnergy * s.co2PerKWh,
emittedCo2: total.emittedCo2 + s.chargedEnergy * (s.co2PerKWh || 0),
chargedEnergy: total.chargedEnergy + s.chargedEnergy,
}),
{ emittedCo2: 0, chargedEnergy: 0 }
@ -393,42 +398,42 @@ export default {
},
},
methods: {
nsToHours(ns) {
nsToHours(ns: number) {
return ns / 1e9 / 3600;
},
filterByLoadpoint(session) {
filterByLoadpoint(session: Session) {
return !this.loadpointFilter || session.loadpoint === this.loadpointFilter;
},
filterByVehicle(session) {
filterByVehicle(session: Session) {
return !this.vehicleFilter || session.vehicle === this.vehicleFilter;
},
filterCountForVehicle(vehicle) {
filterCountForVehicle(vehicle: string) {
return this.sessions
.filter(this.filterByLoadpoint)
.filter((s) => !vehicle || s.vehicle === vehicle).length;
},
filterCountForLoadpoint(loadpoint) {
filterCountForLoadpoint(loadpoint: string) {
return this.sessions
.filter(this.filterByVehicle)
.filter((s) => !loadpoint || s.loadpoint === loadpoint).length;
},
selectColumnPosition(index, value) {
selectColumnPosition(index: number, value: Column) {
this.selectedColumns[index] = value;
settings.sessionColumns = [...this.selectedColumns];
},
changeLoadpointFilter(event) {
const loadpoint = event.target.value || undefined;
changeLoadpointFilter(event: Event) {
const loadpoint = (event.target as HTMLSelectElement).value || undefined;
this.$router.push({ query: { ...this.$route.query, loadpoint } });
},
changeVehicleFilter(event) {
const vehicle = event.target.value || undefined;
changeVehicleFilter(event: Event) {
const vehicle = (event.target as HTMLSelectElement).value || undefined;
this.$router.push({ query: { ...this.$route.query, vehicle } });
},
showDetails(sessionId) {
showDetails(sessionId: number) {
this.$emit("show-session", sessionId);
},
},
};
});
</script>
<style scoped>
.table {

View file

@ -9,30 +9,34 @@
</div>
</template>
<script>
<script lang="ts">
import { defineComponent, type PropType } from "vue";
import { PolarArea } from "vue-chartjs";
import { RadialLinearScale, ArcElement, Legend, Tooltip } from "chart.js";
import { registerChartComponents, commonOptions, tooltipLabelColor } from "./chartConfig";
import { RadialLinearScale, ArcElement, Legend, Tooltip, type TooltipItem } from "chart.js";
import { registerChartComponents, commonOptions, tooltipLabelColor } from "./chartConfig.ts";
import formatter from "@/mixins/formatter";
import colors, { dimColor } from "@/colors";
import LegendList from "./LegendList.vue";
import { GROUPS } from "./types";
import { GROUPS, type Session } from "./types.ts";
registerChartComponents([RadialLinearScale, ArcElement, Legend, Tooltip]);
export default {
export default defineComponent({
name: "SolarGroupedChart",
components: { PolarArea, LegendList },
mixins: [formatter],
props: {
sessions: { type: Array, default: () => [] },
groupBy: { type: String, default: GROUPS.LOADPOINT },
sessions: { type: Array as PropType<Session[]>, default: () => [] },
groupBy: {
type: String as PropType<Exclude<GROUPS, GROUPS.NONE>>,
default: GROUPS.LOADPOINT,
},
colorMappings: { type: Object, default: () => ({ loadpoint: {}, vehicle: {} }) },
},
computed: {
chartData() {
console.log("update solar grouped data");
const aggregatedData = {};
const aggregatedData: Record<string, { grid: number; self: number }> = {};
this.sessions.forEach((session) => {
const groupKey = session[this.groupBy];
@ -57,8 +61,7 @@ export default {
return selfPercentage;
});
const colorGroup = this.groupBy === GROUPS.NONE ? "solar" : this.groupBy;
const borderColors = labels.map((label) => this.colorMappings[colorGroup][label]);
const borderColors = labels.map((label) => this.colorMappings[this.groupBy][label]);
const backgroundColors = borderColors.map((color) => dimColor(color));
return {
labels: labels,
@ -96,9 +99,11 @@ export default {
position: "topBottomCenter",
callbacks: {
title: () => null,
label: (tooltipItem) => {
const { label, raw = 0 } = tooltipItem;
return label + ": " + this.fmtPercentage(raw, 1);
label: (tooltipItem: TooltipItem<"polarArea">) => {
const { label, dataset, dataIndex } = tooltipItem;
const d = dataset.data[dataIndex];
return label + ": " + this.fmtPercentage(d, 1);
},
labelColor: tooltipLabelColor(true),
},
@ -116,8 +121,8 @@ export default {
grid: { color: colors.border },
},
},
};
} as any;
},
},
};
});
</script>

View file

@ -9,23 +9,32 @@
</div>
</template>
<script>
<script lang="ts">
import { defineComponent, type PropType } from "vue";
import { Radar } from "vue-chartjs";
import { RadialLinearScale, PointElement, LineElement, Filler, Tooltip } from "chart.js";
import { registerChartComponents, commonOptions, tooltipLabelColor } from "./chartConfig";
import {
RadialLinearScale,
PointElement,
LineElement,
Filler,
Tooltip,
type TooltipItem,
} from "chart.js";
import { registerChartComponents, commonOptions, tooltipLabelColor } from "./chartConfig.ts";
import formatter from "@/mixins/formatter";
import colors, { dimColor } from "@/colors";
import LegendList from "./LegendList.vue";
import type { Legend, PERIODS, Session } from "./types.ts";
registerChartComponents([RadialLinearScale, PointElement, LineElement, Filler, Tooltip]);
export default {
export default defineComponent({
name: "SolarYearChart",
components: { Radar, LegendList },
mixins: [formatter],
props: {
sessions: { type: Array, default: () => [] },
period: { type: String, default: "total" },
sessions: { type: Array as PropType<Session[]>, default: () => [] },
period: { type: String as PropType<PERIODS>, default: "total" },
},
computed: {
firstDay() {
@ -43,14 +52,16 @@ export default {
chartData() {
console.log("update solar month data");
if (!this.sessions.length > 0) return { labels: [], datasets: [] };
if (!this.firstDay || !this.lastDay) {
return { labels: [], datasets: [] };
}
const firstYear = this.firstDay.getFullYear();
const lastYear = this.lastDay.getFullYear();
const result = {};
const result: Record<string, Record<string, { self: number; grid: number }>> = {};
const years = [];
const years: string[] = [];
// initialize result for years and months
for (let year = lastYear; year >= firstYear; year--) {
@ -60,7 +71,7 @@ export default {
console.log("year", yearString);
for (let month = 1; month <= 12; month++) {
result[yearString][month] = {};
result[yearString][month] = { self: 0, grid: 0 };
}
}
@ -73,8 +84,8 @@ export default {
const charged = session.chargedEnergy;
const self = (charged / 100) * session.solarPercentage;
const grid = charged - self;
result[year][month].self = (result[year][month].self || 0) + self;
result[year][month].grid = (result[year][month].grid || 0) + grid;
result[year][month].self += self;
result[year][month].grid += grid;
});
const datasets = years.map((year) => {
@ -99,7 +110,7 @@ export default {
});
const labels = Object.keys(result[firstYear]).map((month) =>
this.fmtMonth(new Date(firstYear, month - 1, 1), true)
this.fmtMonth(new Date(firstYear, parseInt(month) - 1, 1), true)
);
return {
@ -107,7 +118,7 @@ export default {
datasets,
};
},
legends() {
legends(): Legend[] {
if (this.period === "total") {
return this.chartData.datasets.map((dataset) => {
const label = dataset.label;
@ -125,10 +136,14 @@ export default {
const value = this.chartData.datasets[0].data[index];
return {
label,
color: null,
value:
value === null
? "- %"
: this.fmtPercentage(this.chartData.datasets[0].data[index], 1),
: this.fmtPercentage(
this.chartData.datasets[0].data[index] || 0,
1
),
};
});
}
@ -139,7 +154,7 @@ export default {
locale: this.$i18n?.locale,
aspectRatio: 1,
borderWidth: 4,
color: colors.text,
color: colors.text || "",
spacing: 0,
radius: "100%",
elements: { line: { tension: 0.05 } },
@ -150,14 +165,14 @@ export default {
axis: "xy",
position: "topBottomCenter",
callbacks: {
label: (tooltipItem) => {
const value = tooltipItem.raw || 0;
label: (tooltipItem: TooltipItem<"radar">) => {
const value = tooltipItem.dataset.data[tooltipItem.dataIndex] || 0;
const datasetLabel = tooltipItem.dataset.label || "";
return datasetLabel + ": " + this.fmtPercentage(value, 1);
},
labelColor: tooltipLabelColor(true),
},
},
} as any,
},
scales: {
r: {
@ -169,14 +184,14 @@ export default {
color: colors.muted,
backdropColor: colors.background,
font: { size: 10 },
callback: (value) => this.fmtPercentage(value, 0),
callback: (value: number) => this.fmtPercentage(value, 0),
},
angleLines: { display: false },
grid: { color: colors.border },
},
},
};
} as any;
},
},
};
});
</script>

View file

@ -1,65 +0,0 @@
import { Chart, Tooltip } from "chart.js";
import colors from "@/colors";
// Register common components
export function registerChartComponents(components) {
Chart.register(...components);
}
// Set default configurations immediately
Chart.defaults.font.family = window
.getComputedStyle(document.documentElement)
.getPropertyValue("--bs-font-sans-serif");
Chart.defaults.font.size = 14;
Chart.defaults.layout.padding = 0;
// Custom tooltip positioners
Tooltip.positioners.center = function () {
const { chart } = this;
return {
x: chart.width / 2,
y: chart.height / 2,
xAlign: "center",
yAlign: "center",
};
};
Tooltip.positioners.topBottomCenter = function (context, eventPosition) {
const { chart } = this;
const { height, width } = chart;
const isTop = eventPosition.y > height / 2;
const yPadding = height / 5;
const y = isTop ? yPadding : height - yPadding;
const x = width / 2;
return { x, y, xAlign: "center", yAlign: "center" };
};
export const commonOptions = {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: { display: false },
datalabels: { display: false },
tooltip: {
backgroundColor: "#000000cc",
boxPadding: 5,
usePointStyle: false,
borderWidth: 0.00001,
mode: "index",
intersect: false,
},
},
};
export function tooltipLabelColor(useBorder = false) {
return function (item) {
const { backgroundColor, borderColor } = item.element.options;
const color = useBorder ? borderColor : backgroundColor;
return {
borderColor: !item.raw ? colors.muted : "#fff",
borderWidth: 1,
backgroundColor: color,
};
};
}

View file

@ -0,0 +1,76 @@
import {
Chart,
Tooltip,
type ChartComponentLike,
type ChartType,
type Point,
type TooltipItem,
} from "chart.js";
import colors from "@/colors";
import type { Context } from "chartjs-plugin-datalabels";
// Register common components
export function registerChartComponents(components: ChartComponentLike[]) {
Chart.register(...components);
}
// Set default configurations immediately
Chart.defaults.font.family = window
.getComputedStyle(document.documentElement)
.getPropertyValue("--bs-font-sans-serif");
Chart.defaults.font.size = 14;
Chart.defaults.layout.padding = 0;
// Custom tooltip positioners
(Tooltip.positioners as any)["center"] = function () {
const { chart } = this;
return {
x: chart.width / 2,
y: chart.height / 2,
xAlign: "center",
yAlign: "center",
};
};
(Tooltip.positioners as any)["topBottomCenter"] = function (
_context: Context,
eventPosition: Point
) {
const { chart } = this;
const { height, width } = chart;
const isTop = eventPosition.y > height / 2;
const yPadding = height / 5;
const y = isTop ? yPadding : height - yPadding;
const x = width / 2;
return { x, y, xAlign: "center", yAlign: "center" };
};
export const commonOptions = {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: { display: false },
datalabels: { display: false },
tooltip: {
backgroundColor: "#000000cc",
boxPadding: 5,
usePointStyle: false,
borderWidth: 0.00001,
mode: "index",
intersect: false,
},
},
};
export function tooltipLabelColor(useBorder = false) {
return function (item: TooltipItem<ChartType>) {
const { backgroundColor, borderColor } = item.element.options;
const color = useBorder ? borderColor : backgroundColor;
return {
borderColor: !item.raw ? colors.muted : "#fff",
borderWidth: 1,
backgroundColor: color,
};
};
}

View file

@ -1,17 +0,0 @@
export const TYPES = {
SOLAR: "solar",
PRICE: "price",
CO2: "co2",
};
export const GROUPS = {
NONE: "none",
LOADPOINT: "loadpoint",
VEHICLE: "vehicle",
};
export const PERIODS = {
MONTH: "month",
YEAR: "year",
TOTAL: "total",
};

View file

@ -0,0 +1,49 @@
export interface Session {
id: number;
created: Date;
finished: Date;
loadpoint: string;
identifier: string;
vehicle: string;
odometer: number;
meterStart: number;
meterStop: number;
chargedEnergy: number;
chargeDuration: number;
solarPercentage: number;
price: number | null;
pricePerKWh: number | null;
co2PerKWh?: number | null;
}
export interface Legend {
label: string;
color: any;
value: string | string[];
}
export interface Column {
name: string;
unit: string;
total: number | null;
value: (session: Session) => number | null;
format: (value: number) => string | undefined;
}
export enum TYPES {
SOLAR = "solar",
PRICE = "price",
CO2 = "co2",
}
export enum GROUPS {
NONE = "none",
LOADPOINT = "loadpoint",
VEHICLE = "vehicle",
}
export enum PERIODS {
MONTH = "month",
YEAR = "year",
TOTAL = "total",
}

View file

@ -1,33 +0,0 @@
export default {
data() {
return {
breakpoint: "md",
};
},
methods: {
updateBreakpoint() {
const width = window.innerWidth;
if (width <= 575) {
this.breakpoint = "xs";
} else if (width <= 767) {
this.breakpoint = "sm";
} else if (width <= 991) {
this.breakpoint = "md";
} else if (width <= 1199) {
this.breakpoint = "lg";
} else if (width <= 1399) {
this.breakpoint = "xl";
} else {
this.breakpoint = "xxl";
}
},
},
mounted() {
this.updateBreakpoint();
window.addEventListener("resize", this.updateBreakpoint);
},
beforeDestroy() {
window.removeEventListener("resize", this.updateBreakpoint);
},
};

View file

@ -0,0 +1,44 @@
export type Breakpoint = "xs" | "sm" | "md" | "lg" | "xl" | "xxl";
interface BreakpointDef {
name: Breakpoint;
maxWidth: number;
}
const BREAKPOINTS: BreakpointDef[] = [
{ name: "xs", maxWidth: 575 },
{ name: "sm", maxWidth: 767 },
{ name: "md", maxWidth: 991 },
{ name: "lg", maxWidth: 1199 },
{ name: "xl", maxWidth: 1399 },
{ name: "xxl", maxWidth: Infinity },
];
export default {
data() {
return {
breakpoint: "md" as Breakpoint,
};
},
methods: {
updateBreakpoint(): void {
const width: number = window.innerWidth;
const self = this as any;
for (const bp of BREAKPOINTS) {
if (width <= bp.maxWidth) {
self.breakpoint = bp.name;
return;
}
}
},
},
mounted() {
const self = this as any;
self.updateBreakpoint();
window.addEventListener("resize", self.updateBreakpoint);
},
beforeDestroy() {
const self = this as any;
window.removeEventListener("resize", self.updateBreakpoint);
},
};

View file

@ -206,6 +206,7 @@ import DateNavigator from "../components/Sessions/DateNavigator.vue";
import DynamicPriceIcon from "../components/MaterialIcon/DynamicPrice.vue";
import TotalIcon from "../components/MaterialIcon/Total.vue";
import { TYPES, GROUPS, PERIODS } from "../components/Sessions/types";
export default {
name: "Sessions",
components: {