chore: typescript, rewrite charging plans (#20036)

Co-authored-by: Michael Geers <michael@geers.tv>
This commit is contained in:
Maschga 2025-03-31 18:39:19 +02:00 • committed by GitHub
parent 958751027a
commit 9eb5e33652
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
25 changed files with 743 additions and 577 deletions

View file

@ -59,11 +59,13 @@
</div>
</template>
<script>
<script lang="ts">
import { distanceUnit } from "../../units.js";
import formatter from "../../mixins/formatter.js";
import type { SelectOption } from "../../types/evcc";
import { defineComponent } from "vue";
export default {
export default defineComponent({
name: "ChargingPlanArrival",
mixins: [formatter],
props: {
@ -79,13 +81,13 @@ export default {
return { selectedMinSoc: this.minSoc, selectedLimitSoc: this.limitSoc };
},
computed: {
minSocOptions() {
minSocOptions(): SelectOption<number>[] {
// a list of entries from 0 to 95 with a step of 5
return Array.from(Array(20).keys())
.map((i) => i * 5)
.map(this.socOption);
},
limitSocOptions() {
limitSocOptions(): SelectOption<number>[] {
// a list of entries from 0 to 100 with a step of 5
return Array.from(Array(21).keys())
.map((i) => i * 5)
@ -93,29 +95,29 @@ export default {
},
},
watch: {
minSoc(value) {
minSoc(value: number): void {
this.selectedMinSoc = value;
},
limitSoc(value) {
limitSoc(value: number): void {
this.selectedLimitSoc = value;
},
},
methods: {
socOption(soc) {
socOption(soc: number): SelectOption<number> {
return {
value: soc,
name: soc === 0 ? "---" : this.fmtSocOption(soc, this.rangePerSoc, distanceUnit()),
};
},
formId(name) {
formId(name: string): string {
return `chargingplan_${this.id}_${name}`;
},
changeMinSoc() {
changeMinSoc(): void {
this.$emit("minsoc-updated", this.selectedMinSoc);
},
changeLimitSoc() {
changeLimitSoc(): void {
this.$emit("limitsoc-updated", this.selectedLimitSoc);
},
},
};
});
</script>

View file

@ -1,55 +0,0 @@
import ChargingPlan from "./ChargingPlan.vue";
const hoursFromNow = (hours) => {
const now = new Date();
now.setHours(now.getHours() + hours);
return now.toISOString();
};
export default {
title: "ChargingPlans/ChargingPlan",
component: ChargingPlan,
parameters: {
layout: "centered",
},
argTypes: {
id: { control: "text" },
effectivePlanTime: { control: "text" },
effectivePlanSoc: { control: "number" },
planEnergy: { control: "number" },
socBasedCharging: { control: "boolean" },
socBasedPlanning: { control: "boolean" },
vehicleSoc: { control: "number" },
},
};
const Template = (args) => ({
components: { ChargingPlan },
setup() {
return { args };
},
template: '<ChargingPlan v-bind="args" />',
});
export const None = Template.bind({});
None.args = {
id: "1",
};
export const SocBasedCharging = Template.bind({});
SocBasedCharging.args = {
id: "1",
effectivePlanTime: hoursFromNow(4),
effectivePlanSoc: 77,
socBasedCharging: true,
socBasedPlanning: true,
};
export const EnergyBasedCharging = Template.bind({});
EnergyBasedCharging.args = {
id: "1",
effectivePlanTime: hoursFromNow(12),
planEnergy: 77,
socBasedCharging: false,
socBasedPlanning: false,
};

View file

@ -0,0 +1,56 @@
import ChargingPlan from "./ChargingPlan.vue";
import type { Meta, StoryFn } from "@storybook/vue3";
const hoursFromNow = (hours: number) => {
const now = new Date();
now.setHours(now.getHours() + hours);
return now.toISOString();
};
export default {
title: "ChargingPlans/ChargingPlan",
component: ChargingPlan,
parameters: {
layout: "centered",
},
argTypes: {
id: { control: "text" },
effectivePlanTime: { control: "text" },
effectivePlanSoc: { control: "number" },
planEnergy: { control: "number" },
socBasedCharging: { control: "boolean" },
socBasedPlanning: { control: "boolean" },
vehicleSoc: { control: "number" },
},
} as Meta<typeof ChargingPlan>;
const Template: StoryFn<typeof ChargingPlan> = (args) => ({
components: { ChargingPlan },
setup() {
return { args };
},
template: '<ChargingPlan v-bind="args" />',
});
export const None = Template.bind({});
None.args = {
id: "1",
};
export const SocBasedCharging = Template.bind({});
SocBasedCharging.args = {
id: "1",
effectivePlanTime: hoursFromNow(4),
effectivePlanSoc: 77,
socBasedCharging: true,
socBasedPlanning: true,
};
export const EnergyBasedCharging = Template.bind({});
EnergyBasedCharging.args = {
id: "1",
effectivePlanTime: hoursFromNow(12),
planEnergy: 77,
socBasedCharging: false,
socBasedPlanning: false,
};

View file

@ -102,7 +102,7 @@
</div>
</template>
<script>
<script lang="ts">
import Modal from "bootstrap/js/dist/modal";
import LabelAndValue from "../Helper/LabelAndValue.vue";
import PlansSettings from "./PlansSettings.vue";
@ -112,10 +112,13 @@ import formatter from "../../mixins/formatter.js";
import collector from "../../mixins/collector.js";
import api from "../../api.js";
import { optionStep, fmtEnergy } from "../../utils/energyOptions.js";
import { defineComponent, type PropType } from "vue";
import type { CURRENCY, Timeout, Vehicle } from "assets/js/types/evcc.js";
import type { StaticPlan, StaticSocPlan, StaticEnergyPlan, RepeatingPlan } from "./types.js";
const ONE_MINUTE = 60 * 1000;
export default {
export default defineComponent({
name: "ChargingPlan",
components: {
LabelAndValue,
@ -124,7 +127,7 @@ export default {
},
mixins: [formatter, collector],
props: {
currency: String,
currency: String as PropType<CURRENCY>,
disabled: Boolean,
effectiveLimitSoc: Number,
effectivePlanSoc: Number,
@ -142,22 +145,22 @@ export default {
socBasedPlanning: Boolean,
socBasedCharging: Boolean,
socPerKwh: Number,
vehicle: Object,
vehicle: Object as PropType<Vehicle>,
capacity: Number,
vehicleSoc: Number,
vehicleLimitSoc: Number,
},
data() {
return {
modal: null,
modal: null as Modal | null,
isModalVisible: false,
activeTab: "departure",
targetTimeLabel: "",
interval: null,
interval: null as Timeout,
};
},
computed: {
buttonColor() {
buttonColor(): string {
if (this.planTimeUnreachable) {
return "text-warning";
}
@ -166,47 +169,51 @@ export default {
}
return "evcc-default-text";
},
minSoc() {
minSoc(): number | undefined {
return this.vehicle?.minSoc;
},
limitSoc() {
limitSoc(): number | undefined {
return this.vehicle?.limitSoc;
},
staticPlan() {
staticPlan(): StaticPlan | null {
if (this.socBasedPlanning) {
return this.vehicle?.plan;
const plan = this.vehicle?.plan as StaticSocPlan;
if (plan) {
return { soc: plan.soc, time: new Date(plan.time) };
}
return null;
}
if (this.planEnergy && this.planTime) {
return { energy: this.planEnergy, time: this.planTime };
return { energy: this.planEnergy, time: new Date(this.planTime) };
}
return null;
},
repeatingPlans() {
if (this.vehicle?.repeatingPlans.length > 0) {
repeatingPlans(): RepeatingPlan[] {
if (this.vehicle && this.vehicle.repeatingPlans.length > 0) {
return [...this.vehicle.repeatingPlans];
}
return [];
},
enabled() {
return this.effectivePlanTime;
enabled(): boolean {
return !!this.effectivePlanTime;
},
modalId() {
modalId(): string {
return `chargingPlanModal_${this.id}`;
},
departureTabActive() {
departureTabActive(): boolean {
return this.activeTab === "departure";
},
arrivalTabActive() {
arrivalTabActive(): boolean {
return this.activeTab === "arrival";
},
chargingPlansSettingsProps() {
chargingPlansSettingsProps(): any {
return this.collectProps(PlansSettings);
},
chargingPlanArrival() {
chargingPlanArrival(): any {
return this.collectProps(Arrival);
},
targetSocLabel() {
if (this.socBasedPlanning) {
targetSocLabel(): string {
if (this.socBasedPlanning && this.effectivePlanSoc) {
return this.fmtPercentage(this.effectivePlanSoc);
}
return fmtEnergy(
@ -216,55 +223,65 @@ export default {
this.$t("main.targetEnergy.noLimit")
);
},
apiVehicle() {
apiVehicle(): string {
return `vehicles/${this.vehicle?.name}/`;
},
apiLoadpoint() {
apiLoadpoint(): string {
return `loadpoints/${this.id}/`;
},
},
watch: {
effectivePlanTime() {
effectivePlanTime(): void {
this.updateTargetTimeLabel();
},
"$i18n.locale": {
handler() {
handler(): void {
this.updateTargetTimeLabel();
},
},
},
mounted() {
this.modal = Modal.getOrCreateInstance(this.$refs.modal);
this.$refs.modal.addEventListener("show.bs.modal", this.modalVisible);
this.$refs.modal.addEventListener("hidden.bs.modal", this.modalInvisible);
this.$refs.modal.addEventListener("hide.bs.modal", this.checkUnsavedOnClose);
mounted(): void {
const ref = this.$refs["modal"];
if (ref) {
this.modal = Modal.getOrCreateInstance(ref);
ref.addEventListener("show.bs.modal", this.modalVisible);
ref.addEventListener("hidden.bs.modal", this.modalInvisible);
ref.addEventListener("hide.bs.modal", this.checkUnsavedOnClose);
}
this.interval = setInterval(this.updateTargetTimeLabel, ONE_MINUTE);
this.updateTargetTimeLabel();
},
unmounted() {
this.$refs.modal?.removeEventListener("show.bs.modal", this.modalVisible);
this.$refs.modal?.removeEventListener("hidden.bs.modal", this.modalInvisible);
this.$refs.modal?.removeEventListener("hide.bs.modal", this.checkUnsavedOnClose);
clearInterval(this.interval);
unmounted(): void {
const ref = this.$refs["modal"];
if (ref) {
ref.removeEventListener("show.bs.modal", this.modalVisible);
ref.removeEventListener("hidden.bs.modal", this.modalInvisible);
ref.removeEventListener("hide.bs.modal", this.checkUnsavedOnClose);
}
if (this.interval) {
clearInterval(this.interval);
}
},
methods: {
checkUnsavedOnClose() {
const $applyButton = this.$refs.modal.querySelector("[data-testid=plan-apply]");
if ($applyButton) {
checkUnsavedOnClose(): void {
const applyButton = this.$refs["modal"]?.querySelector<HTMLElement>(
"[data-testid=plan-apply]"
);
if (applyButton) {
if (confirm(this.$t("main.chargingPlan.unsavedChanges"))) {
$applyButton.click();
applyButton.click();
}
}
},
modalVisible() {
modalVisible(): void {
this.isModalVisible = true;
},
modalInvisible() {
modalInvisible(): void {
this.isModalVisible = false;
},
openModal() {
openModal(): void {
this.showDeatureTab();
this.modal.show();
this.modal?.show();
},
openPlanModal(arrivalTab = false) {
if (arrivalTab) {
@ -272,45 +289,47 @@ export default {
} else {
this.showDeatureTab();
}
this.modal.show();
this.modal?.show();
},
updateTargetTimeLabel() {
if (!this.effectivePlanTime) return "";
updateTargetTimeLabel(): void {
if (!this.effectivePlanTime) return;
const targetDate = new Date(this.effectivePlanTime);
this.targetTimeLabel = this.fmtAbsoluteDate(targetDate);
},
showDeatureTab() {
showDeatureTab(): void {
this.activeTab = "departure";
},
showArrivalTab() {
showArrivalTab(): void {
this.activeTab = "arrival";
},
updateStaticPlan({ soc, time, energy }) {
const timeISO = time.toISOString();
updateStaticPlan(plan: StaticPlan): void {
const timeISO = plan.time.toISOString();
if (this.socBasedPlanning) {
api.post(`${this.apiVehicle}plan/soc/${soc}/${timeISO}`);
const p = plan as StaticSocPlan;
api.post(`${this.apiVehicle}plan/soc/${p.soc}/${timeISO}`);
} else {
api.post(`${this.apiLoadpoint}plan/energy/${energy}/${timeISO}`);
const p = plan as StaticEnergyPlan;
api.post(`${this.apiLoadpoint}plan/energy/${p.energy}/${timeISO}`);
}
},
removeStaticPlan() {
removeStaticPlan(): void {
if (this.socBasedPlanning) {
api.delete(`${this.apiVehicle}plan/soc`);
} else {
api.delete(`${this.apiLoadpoint}plan/energy`);
}
},
updateRepeatingPlans(plans) {
updateRepeatingPlans(plans: RepeatingPlan[]): void {
api.post(`${this.apiVehicle}plan/repeating`, { plans });
},
setMinSoc(soc) {
setMinSoc(soc: number): void {
api.post(`${this.apiVehicle}minsoc/${soc}`);
},
setLimitSoc(soc) {
setLimitSoc(soc: number): void {
api.post(`${this.apiVehicle}limitsoc/${soc}`);
},
},
};
});
</script>
<style scoped>

View file

@ -126,7 +126,7 @@
class="btn btn-sm btn-outline-secondary border-0"
aria-label="Remove"
tabindex="0"
@click="$emit('removed', id)"
@click="$emit('removed', id())"
>
<shopicon-regular-trash size="s" class="flex-shrink-0"></shopicon-regular-trash>
</button>
@ -135,21 +135,22 @@
</div>
</template>
<script>
<script lang="ts">
import "@h2d2/shopicons/es/regular/trash";
import { distanceUnit } from "../../units.js";
import MultiSelect from "../Helper/MultiSelect.vue";
import formatter from "../../mixins/formatter.js";
import deepEqual from "../../utils/deepEqual.js";
export default {
import type { SelectOption } from "../../types/evcc";
import { defineComponent, type PropType } from "vue";
export default defineComponent({
name: "ChargingPlanRepeatingSettings",
components: {
MultiSelect,
},
components: { MultiSelect },
mixins: [formatter],
props: {
number: Number,
weekdays: { type: Array, default: () => [] },
weekdays: { type: Array as PropType<number[]>, default: () => [] },
time: String,
tz: String,
soc: Number,
@ -168,7 +169,7 @@ export default {
};
},
computed: {
dataChanged() {
dataChanged(): boolean {
return (
!deepEqual(this.weekdays, this.selectedWeekdays) ||
this.time !== this.selectedTime ||
@ -176,51 +177,54 @@ export default {
this.active !== this.selectedActive
);
},
showApply() {
showApply(): boolean {
return this.dataChanged && this.selectedActive;
},
weekdaysLabel() {
weekdaysLabel(): string {
return this.getShortenedWeekdaysLabel(this.selectedWeekdays);
},
socOptions() {
socOptions(): SelectOption<number>[] {
// a list of entries from 5 to 100 with a step of 5
return Array.from(Array(20).keys())
.map((i) => 5 + i * 5)
.map(this.socOption);
},
dayOptions() {
dayOptions(): SelectOption<number>[] {
return this.getWeekdaysList("long");
},
},
watch: {
weekdays(newValue, oldValue) {
weekdays(newValue: number[], oldValue: number[]) {
if (!deepEqual(newValue, oldValue)) {
this.selectedWeekdays = newValue;
}
},
time(newValue) {
time(newValue: string) {
this.selectedTime = newValue;
},
soc(newValue) {
soc(newValue: number) {
this.selectedSoc = newValue;
},
active(newValue) {
active(newValue: boolean) {
this.selectedActive = newValue;
},
},
methods: {
changeSelectedWeekdays(weekdays) {
id(): number {
return this.number || 0;
},
changeSelectedWeekdays(weekdays: number[]): void {
this.selectedWeekdays = weekdays;
this.update();
},
formId(name) {
formId(name: string): string {
return `${this.formIdPrefix}-${this.number}-${name}`;
},
socOption(value) {
socOption(value: number): SelectOption<number> {
const name = this.fmtSocOption(value, this.rangePerSoc, distanceUnit());
return { value, name };
},
update(forceSave = false) {
update(forceSave = false): void {
const plan = {
weekdays: this.selectedWeekdays,
time: this.selectedTime,
@ -234,7 +238,7 @@ export default {
}
},
},
};
});
</script>
<style scoped>
.plan-id {

View file

@ -146,26 +146,27 @@
</div>
</template>
<script>
<script lang="ts">
import "@h2d2/shopicons/es/regular/checkmark";
import { distanceUnit } from "../../units.js";
import formatter from "../../mixins/formatter.js";
import { energyOptions } from "../../utils/energyOptions.js";
import { defineComponent } from "vue";
const LAST_TARGET_TIME_KEY = "last_target_time";
const LAST_SOC_GOAL_KEY = "last_soc_goal";
const LAST_ENERGY_GOAL_KEY = "last_energy_goal";
const DEFAULT_TARGET_TIME = "7:00";
export default {
export default defineComponent({
name: "ChargingPlanStaticSettings",
mixins: [formatter],
props: {
id: String,
id: [String, Number],
soc: Number,
energy: Number,
time: String,
time: Date,
rangePerSoc: Number,
socPerKwh: Number,
capacity: Number,
@ -175,8 +176,8 @@ export default {
emits: ["static-plan-updated", "static-plan-removed", "plan-preview"],
data() {
return {
selectedDay: null,
selectedTime: null,
selectedDay: null as string | null,
selectedTime: null as string | null,
selectedSoc: this.soc,
selectedEnergy: this.energy,
active: false,
@ -208,11 +209,12 @@ export default {
if (this.isNew) {
return {};
}
const t = this.time || new Date();
return {
soc: this.soc,
energy: this.energy,
day: this.fmtDayString(new Date(this.time)),
time: this.fmtTimeString(new Date(this.time)),
day: this.fmtDayString(t),
time: this.fmtTimeString(t),
};
},
dataChanged() {
@ -255,10 +257,10 @@ export default {
this.preview();
},
methods: {
formId(name) {
formId(name: string) {
return `chargingplan-${this.id}-${name}`;
},
socOption(value) {
socOption(value: number) {
const name = this.fmtSocOption(value, this.rangePerSoc, distanceUnit());
return { value, name };
},
@ -271,15 +273,15 @@ export default {
window.localStorage[LAST_ENERGY_GOAL_KEY] || this.capacity || 10;
}
let time = this.time;
if (!time) {
let t = this.time;
if (!t) {
// no time but existing selection, keep it
if (this.selectedDay && this.selectedTime) {
return;
}
time = this.defaultTime();
t = this.defaultTime();
}
const date = new Date(time);
const date = new Date(t);
this.selectedDay = this.fmtDayString(date);
this.selectedTime = this.fmtTimeString(date);
},
@ -327,7 +329,7 @@ export default {
},
preview(force = false) {
if (!this.isNew && !force) {
return false;
return;
}
this.$emit("plan-preview", {
time: this.selectedDate,
@ -335,8 +337,8 @@ export default {
energy: this.selectedEnergy,
});
},
toggle(e) {
const { checked } = e.target;
toggle(e: Event) {
const { checked } = e.target as HTMLInputElement;
if (checked) {
this.update();
} else {
@ -362,7 +364,7 @@ export default {
return target;
},
},
};
});
</script>
<style scoped>
.plan-id {

View file

@ -9,7 +9,6 @@
v-bind="plan"
:rangePerSoc="rangePerSoc"
@updated="updatePlan(index, $event)"
@saved="savePlan(index, $event)"
@removed="removePlan(index)"
/>
</div>
@ -28,25 +27,27 @@
</div>
</template>
<script>
<script lang="ts">
import PlanRepeatingSettings from "./PlanRepeatingSettings.vue";
import deepEqual from "../../utils/deepEqual.js";
import formatter from "../../mixins/formatter.js";
import { defineComponent, type PropType } from "vue";
import type { RepeatingPlan } from "./types.js";
const DEFAULT_WEEKDAYS = [1, 2, 3, 4, 5]; // weekdays
const DEFAULT_WEEKDAYS = [1, 2, 3, 4, 5];
const DEFAULT_TARGET_TIME = "07:00";
const DEFAULT_TARGET_SOC = 80;
export default {
export default defineComponent({
name: "ChargingPlansRepeatingSettings",
components: {
ChargingPlanRepeatingSettings: PlanRepeatingSettings,
},
mixins: [formatter],
props: {
id: Number,
id: [Number, String],
rangePerSoc: Number,
plans: { type: Array, default: () => [] },
plans: { type: Array as PropType<RepeatingPlan[]>, default: () => [] },
},
emits: ["updated"],
computed: {
@ -56,7 +57,7 @@ export default {
},
methods: {
deepEqual,
addPlan() {
addPlan(): void {
const newPlan = {
weekdays: DEFAULT_WEEKDAYS,
time: DEFAULT_TARGET_TIME,
@ -70,21 +71,21 @@ export default {
plans.push(newPlan);
this.updatePlans(plans);
},
updatePlan(index, plan) {
updatePlan(index: number, plan: RepeatingPlan): void {
const plans = [...this.plans]; // clone array
plans.splice(index, 1, plan);
this.updatePlans(plans);
},
updatePlans(plans) {
updatePlans(plans: RepeatingPlan[]): void {
this.$emit("updated", plans);
},
removePlan(index) {
removePlan(index: number): void {
const plans = [...this.plans]; // clone array
plans.splice(index, 1);
this.updatePlans(plans);
},
},
};
});
</script>
<style scoped>

View file

@ -61,7 +61,7 @@
</div>
</template>
<script>
<script lang="ts">
import "@h2d2/shopicons/es/regular/plus";
import Preview from "./Preview.vue";
import PlanStaticSettings from "./PlanStaticSettings.vue";
@ -72,10 +72,21 @@ import collector from "../../mixins/collector.js";
import api, { allowClientError } from "../../api.js";
import CustomSelect from "../Helper/CustomSelect.vue";
import deepEqual from "../../utils/deepEqual.js";
import { defineComponent, type PropType } from "vue";
import type { Vehicle, PartialBy, Timeout, Tariff, SelectOption, CURRENCY } from "../../types/evcc";
import type {
StaticPlan,
RepeatingPlan,
PlanWrapper,
StaticSocPlan,
StaticEnergyPlan,
PlanResponse,
} from "./types.js";
const TARIFF_CACHE_TIME = 300000; // 5 minutes
export default {
export default defineComponent({
name: "ChargingPlansSettings",
components: {
ChargingPlanPreview: Preview,
@ -87,8 +98,8 @@ export default {
mixins: [formatter, collector],
props: {
id: [String, Number],
staticPlan: Object,
repeatingPlans: { type: Array, default: () => [] },
staticPlan: Object as PropType<StaticPlan>,
repeatingPlans: { type: Array as PropType<RepeatingPlan[]>, default: () => [] },
effectiveLimitSoc: Number,
effectivePlanTime: String,
effectivePlanSoc: Number,
@ -98,39 +109,39 @@ export default {
socPerKwh: Number,
rangePerSoc: Number,
smartCostType: String,
currency: String,
currency: String as PropType<CURRENCY>,
mode: String,
capacity: Number,
vehicle: Object,
vehicle: Object as PropType<Vehicle>,
vehicleLimitSoc: Number,
planOverrun: Number,
},
emits: ["static-plan-removed", "static-plan-updated", "repeating-plans-updated"],
data() {
return {
staticPlanPreview: {},
tariff: {},
plan: {},
staticPlanPreview: {} as StaticPlan,
tariff: {} as Tariff,
plan: {} as PlanWrapper,
activeTab: "time",
debounceTimer: null,
debounceTimer: null as Timeout,
selectedPreviewId: 1,
nextPlanId: 0,
};
},
computed: {
noActivePlan() {
noActivePlan(): boolean {
return !this.staticPlan && this.repeatingPlans.every((plan) => !plan.active);
},
multiplePlans() {
multiplePlans(): boolean {
return this.repeatingPlans.length !== 0;
},
selectedPreviewPlanTitle() {
selectedPreviewPlanTitle(): string {
return this.previewPlanOptions[this.selectedPreviewId - 1]?.name;
},
chargingPlanWarningsProps() {
chargingPlanWarningsProps(): any {
return this.collectProps(Warnings);
},
chargingPlanPreviewProps() {
chargingPlanPreviewProps(): any {
const { rates } = this.tariff;
const { duration, plan, power, planTime } = this.plan;
const targetTime = planTime ? new Date(planTime) : null;
@ -139,11 +150,11 @@ export default {
? { duration, plan, power, rates, targetTime, currency, smartCostType }
: null;
},
previewPlanOptions() {
const name = (number) => `${this.$t("main.targetCharge.preview")} #${number}`;
previewPlanOptions(): SelectOption<number>[] {
const name = (n: number) => `${this.$t("main.targetCharge.preview")} #${n}`;
// static plan
const options = [{ value: 1, name: name(1) }];
const options = [{ value: 1, name: name(1) }] as SelectOption<number>[];
// repeating plans
this.repeatingPlans.forEach((plan, index) => {
@ -157,19 +168,19 @@ export default {
return options;
},
nextPlanTitle() {
nextPlanTitle(): string {
return `${this.$t("main.targetCharge.nextPlan")} #${this.nextPlanId}`;
},
},
watch: {
effectivePlanTime(newValue) {
effectivePlanTime(newValue: string) {
if (null !== newValue) {
this.fetchPlanDebounced();
}
},
staticPlan: {
deep: true,
handler(vNew, vOld) {
handler(vNew: StaticPlan, vOld: StaticPlan) {
if (!deepEqual(vNew, vOld)) {
this.fetchPlanDebounced();
}
@ -177,7 +188,7 @@ export default {
},
repeatingPlans: {
deep: true,
handler(vNew, vOld) {
handler(vNew: RepeatingPlan[], vOld: RepeatingPlan[]) {
if (!deepEqual(vNew, vOld)) {
this.adjustPreviewId();
this.fetchPlanDebounced();
@ -185,80 +196,91 @@ export default {
},
},
},
mounted() {
mounted(): void {
this.fetchPlanDebounced();
},
methods: {
selectPreviewPlan(id) {
selectPreviewPlan(id: number): void {
this.selectedPreviewId = id;
this.fetchPlanPreviewDebounced();
this.updatePlanPreviewDebounced();
},
async fetchPlanDebounced() {
if (this.noActivePlan) {
await this.fetchPlanPreviewDebounced();
await this.updatePlanPreviewDebounced();
} else {
await this.fetchActivePlanDebounced();
await this.updateActivePlanDebounced();
}
},
adjustPreviewId() {
adjustPreviewId(): void {
if (this.selectedPreviewId > this.previewPlanOptions.length) {
this.selectedPreviewId = this.previewPlanOptions.length;
}
},
async fetchActivePlan() {
async updateActivePlan(): Promise<void> {
try {
const res = await this.apiFetchPlan(`loadpoints/${this.id}/plan`);
this.plan = res.data.result;
this.plan = res?.data.result ?? ({} as PlanWrapper);
this.nextPlanId = this.plan.planId;
} catch (e) {
console.error(e);
}
await this.updateTariff();
},
async fetchStaticPreviewSoc(soc, time) {
const timeISO = time.toISOString();
async fetchStaticPreviewSoc(plan: StaticSocPlan): Promise<PlanResponse | undefined> {
const timeISO = plan.time.toISOString();
return await this.apiFetchPlan(
`loadpoints/${this.id}/plan/static/preview/soc/${soc}/${timeISO}`
`loadpoints/${this.id}/plan/static/preview/soc/${plan.soc}/${timeISO}`
);
},
async fetchRepeatingPreview(weekdays, soc, time, tz) {
async fetchRepeatingPreview(
plan: PartialBy<RepeatingPlan, "active">
): Promise<PlanResponse | undefined> {
return await this.apiFetchPlan(
`loadpoints/${this.id}/plan/repeating/preview/${soc}/${weekdays}/${time}/${encodeURIComponent(tz)}`
`loadpoints/${this.id}/plan/repeating/preview/${plan.soc}/${plan.weekdays}/${plan.time}/${encodeURIComponent(plan.tz)}`
);
},
async fetchStaticPreviewEnergy(energy, time) {
const timeISO = time.toISOString();
async fetchStaticPreviewEnergy(plan: StaticEnergyPlan): Promise<PlanResponse | undefined> {
const timeISO = plan.time.toISOString();
return await this.apiFetchPlan(
`loadpoints/${this.id}/plan/static/preview/energy/${energy}/${timeISO}`
`loadpoints/${this.id}/plan/static/preview/energy/${plan.energy}/${timeISO}`
);
},
async apiFetchPlan(url) {
async apiFetchPlan(url: string): Promise<PlanResponse | undefined> {
try {
const res = await api.get(url, {
const res = (await api.get(url, {
validateStatus: (code) => [200, 404].includes(code),
});
})) as PlanResponse;
if (res.status === 404) {
return { data: { result: {} } };
return { data: { result: {} as PlanWrapper } } as PlanResponse;
}
return res;
} catch (e) {
console.error(e);
return;
}
},
async fetchPreviewPlan() {
async updatePreviewPlan(): Promise<void> {
// only show preview of no plan is active
if (!this.noActivePlan) return;
try {
let planRes = undefined;
let planRes: PlanResponse | undefined = undefined;
if (this.selectedPreviewId < 2 && this.staticPlanPreview) {
// static plan
const { soc, energy, time } = this.staticPlanPreview;
let plan = this.staticPlanPreview;
if (this.socBasedPlanning) {
planRes = await this.fetchStaticPreviewSoc(soc, new Date(time));
plan = plan as StaticSocPlan;
planRes = await this.fetchStaticPreviewSoc({
soc: plan.soc,
time: plan.time,
});
} else {
planRes = await this.fetchStaticPreviewEnergy(energy, new Date(time));
plan = plan as StaticEnergyPlan;
planRes = await this.fetchStaticPreviewEnergy({
energy: plan.energy,
time: plan.time,
});
}
} else {
// repeating plan
@ -270,15 +292,15 @@ export default {
if (weekdays.length === 0) {
return;
}
planRes = await this.fetchRepeatingPreview(weekdays, soc, time, tz);
planRes = await this.fetchRepeatingPreview({ weekdays, soc, time, tz });
}
this.plan = planRes.data.result;
this.plan = planRes?.data.result ?? ({} as PlanWrapper);
await this.updateTariff();
} catch (e) {
console.error(e);
}
},
async updateTariff() {
async updateTariff(): Promise<void> {
// cache tariff for 5 minutes
if (
this.tariff?.lastUpdate &&
@ -288,44 +310,43 @@ export default {
}
const tariffRes = await api.get(`tariff/planner`, allowClientError);
if (tariffRes.status === 404) {
this.tariff = { rates: [] };
} else {
this.tariff = tariffRes.data.result;
this.tariff.lastUpdate = new Date();
}
this.tariff = {
rates: tariffRes.status === 404 ? [] : tariffRes.data.result.rates,
lastUpdate: new Date(),
};
},
async fetchPlanPreviewDebounced() {
async updatePlanPreviewDebounced(): Promise<void> {
if (!this.debounceTimer) {
await this.fetchPreviewPlan();
await this.updatePreviewPlan();
return;
}
clearTimeout(this.debounceTimer);
this.debounceTimer = setTimeout(async () => await this.fetchPreviewPlan(), 1000);
this.debounceTimer = setTimeout(async () => await this.updatePreviewPlan(), 1000);
},
async fetchActivePlanDebounced() {
async updateActivePlanDebounced(): Promise<void> {
if (!this.debounceTimer) {
await this.fetchActivePlan();
await this.updateActivePlan();
return;
}
clearTimeout(this.debounceTimer);
this.debounceTimer = setTimeout(async () => await this.fetchActivePlan(), 1000);
this.debounceTimer = setTimeout(async () => await this.updateActivePlan(), 1000);
},
removeStaticPlan(index) {
removeStaticPlan(index: number): void {
this.$emit("static-plan-removed", index);
},
updateStaticPlan(data) {
this.$emit("static-plan-updated", data);
updateStaticPlan(plan: StaticPlan): void {
this.$emit("static-plan-updated", plan);
},
updateRepeatingPlans(plans) {
updateRepeatingPlans(plans: RepeatingPlan[]): void {
this.$emit("repeating-plans-updated", plans);
},
previewStaticPlan(plan) {
previewStaticPlan(plan: StaticPlan): void {
this.staticPlanPreview = plan;
this.fetchPlanPreviewDebounced();
this.updatePlanPreviewDebounced();
},
},
};
});
</script>
<style scoped>

View file

@ -1,114 +0,0 @@
import Preview from "./Preview.vue";
const now = new Date();
function createDate(hoursFromNow) {
const result = new Date(now.getTime());
result.setHours(result.getHours() + hoursFromNow);
return result;
}
function createRate(price, hoursFromNow, durationHours = 1) {
const start = new Date(now.getTime());
start.setHours(start.getHours() + hoursFromNow);
start.setMinutes(0);
start.setSeconds(0);
start.setMilliseconds(0);
const end = new Date(start.getTime());
end.setHours(start.getHours() + durationHours);
end.setMinutes(0);
end.setSeconds(0);
end.setMilliseconds(0);
return { start: start.toISOString(), end: end.toISOString(), price };
}
// Scenario data
const co2Data = {
rates: [
545, 518, 545, 518, 0, 545, 527, 527, 536, 518, 400, 336, 336, 339, 344, 336, 336, 336, 372,
400, 555, 555, 545, 555, 564, 545, 555, 545, 536, 545, 527, 536, 518, 545, 509, 336, 336, 336,
].map((price, i) => createRate(price, i)),
duration: 8695,
plan: [createRate(213, 4), createRate(336, 11), createRate(336, 12)],
smartCostType: "co2",
targetTime: createDate(14),
};
const fixedData = {
rates: [createRate(0.442, 0, 50)],
duration: 8695,
plan: [createRate(0.442, 12, 3)],
smartCostType: "price",
currency: "EUR",
targetTime: createDate(14),
};
const zonedData = {
rates: [
createRate(3.72, 0, 4),
createRate(2.39, 4, 12),
createRate(3.72, 16, 12),
createRate(2.39, 28, 12),
createRate(3.72, 40, 12),
],
duration: 8695,
plan: [createRate(2.39, 13, 3)],
smartCostType: "price",
currency: "DKK",
targetTime: createDate(17),
};
const unknownData = {
rates: co2Data.rates.slice(0, 16),
duration: 8695,
plan: [createRate(213, 4), createRate(336, 11), createRate(336, 12)],
smartCostType: "co2",
targetTime: createDate(14),
};
const dynamicData = {
rates: [0.12, 0.15, 0, -0.05, -0.11, -0.24, -0.08, 0.12, 0.25, 0.29, 0.22, 0.31, 0.31, 0.33].map(
(price, i) => createRate(price, i)
),
duration: 8695,
plan: [createRate(0.23, 2, 5)],
smartCostType: "price",
currency: "EUR",
targetTime: createDate(13),
};
export default {
title: "ChargingPlans/Preview",
component: Preview,
argTypes: {
rates: { control: "object" },
duration: { control: "number" },
plan: { control: "object" },
smartCostType: { control: "select", options: ["co2", "price"] },
currency: { control: "text" },
targetTime: { control: "text" },
},
};
const Template = (args) => ({
components: { Preview },
setup() {
return { args };
},
template: '<Preview v-bind="args" />',
});
export const Co2 = Template.bind({});
Co2.args = co2Data;
export const Fixed = Template.bind({});
Fixed.args = fixedData;
export const Zoned = Template.bind({});
Zoned.args = zonedData;
export const Unknown = Template.bind({});
Unknown.args = unknownData;
export const Dynamic = Template.bind({});
Dynamic.args = dynamicData;

View file

@ -0,0 +1,117 @@
import { CURRENCY, type Rate } from "assets/js/types/evcc";
import Preview from "./Preview.vue";
import type { StoryFn } from "@storybook/vue3";
const now = new Date();
function createDate(hoursFromNow: number) {
const result = new Date(now.getTime());
result.setHours(result.getHours() + hoursFromNow);
return result;
}
function createRate(price: number, hoursFromNow: number, durationHours = 1): Rate {
const start = new Date(now.getTime());
start.setHours(start.getHours() + hoursFromNow);
start.setMinutes(0);
start.setSeconds(0);
start.setMilliseconds(0);
const end = new Date(start.getTime());
end.setHours(start.getHours() + durationHours);
end.setMinutes(0);
end.setSeconds(0);
end.setMilliseconds(0);
return { start, end, price };
}
// Scenario data
const co2Data = {
rates: [
545, 518, 545, 518, 0, 545, 527, 527, 536, 518, 400, 336, 336, 339, 344, 336, 336, 336, 372,
400, 555, 555, 545, 555, 564, 545, 555, 545, 536, 545, 527, 536, 518, 545, 509, 336, 336,
336,
].map((price, i) => createRate(price, i)),
duration: 8695,
plan: [createRate(213, 4), createRate(336, 11), createRate(336, 12)],
smartCostType: "co2",
targetTime: createDate(14),
};
const fixedData = {
rates: [createRate(0.442, 0, 50)],
duration: 8695,
plan: [createRate(0.442, 12, 3)],
smartCostType: "price",
currency: CURRENCY.EUR,
targetTime: createDate(14),
};
const zonedData = {
rates: [
createRate(3.72, 0, 4),
createRate(2.39, 4, 12),
createRate(3.72, 16, 12),
createRate(2.39, 28, 12),
createRate(3.72, 40, 12),
],
duration: 8695,
plan: [createRate(2.39, 13, 3)],
smartCostType: "price",
currency: CURRENCY.DKK,
targetTime: createDate(17),
};
const unknownData = {
rates: co2Data.rates.slice(0, 16),
duration: 8695,
plan: [createRate(213, 4), createRate(336, 11), createRate(336, 12)],
smartCostType: "co2",
targetTime: createDate(14),
};
const dynamicData = {
rates: [
0.12, 0.15, 0, -0.05, -0.11, -0.24, -0.08, 0.12, 0.25, 0.29, 0.22, 0.31, 0.31, 0.33,
].map((price, i) => createRate(price, i)),
duration: 8695,
plan: [createRate(0.23, 2, 5)],
smartCostType: "price",
currency: CURRENCY.EUR,
targetTime: createDate(13),
};
export default {
title: "ChargingPlans/Preview",
component: Preview,
argTypes: {
rates: { control: "object" },
duration: { control: "number" },
plan: { control: "object" },
smartCostType: { control: "select", options: ["co2", "price"] },
currency: { control: "text" },
targetTime: { control: "text" },
},
};
const Template: StoryFn<typeof Preview> = (args) => ({
components: { Preview },
setup() {
return { args };
},
template: '<Preview v-bind="args" />',
});
export const Co2 = Template.bind({});
Co2.args = co2Data;
export const Fixed = Template.bind({});
Fixed.args = fixedData;
export const Zoned = Template.bind({});
Zoned.args = zonedData;
export const Unknown = Template.bind({});
Unknown.args = unknownData;
export const Dynamic = Template.bind({});
Dynamic.args = dynamicData;

View file

@ -1,136 +0,0 @@
import { mount, config } from "@vue/test-utils";
import { beforeAll, describe, expect, test } from "vitest";
import Preview from "./Preview.vue";
config.global.mocks["$i18n"] = { locale: "de-DE" };
config.global.mocks["$t"] = (a) => a;
describe("basics", () => {
const DATE_START = new Date("2023-01-11T11:00:00+01:00");
const DATE_TARGET = new Date("2023-01-11T13:00:00+01:00");
const TARIFF_FIXED = [
{
start: "2023-01-11T11:00:00+01:00",
end: "2023-01-22T00:00:00+01:00",
price: 0.4,
},
];
const PLAN = [
{
start: "2023-01-11T12:00:00+01:00",
end: "2023-01-11T13:00:00+01:00",
},
];
const wrapper = mount(Preview, {
props: {
plan: PLAN,
targetTime: DATE_TARGET,
rates: TARIFF_FIXED,
},
});
wrapper.setData({ startTime: DATE_START });
let result = null;
beforeAll(() => {
result = wrapper.vm.slots;
});
test("should return 39 slots", () => {
expect(result.length).eq(39);
});
test("slots should be an hour apart", () => {
expect(result[0].startHour).eq(11);
expect(result[0].endHour).eq(12);
expect(result[0].day).eq("Mi");
expect(result[1].startHour).eq(12);
expect(result[1].endHour).eq(13);
expect(result[1].day).eq("Mi");
expect(result[11].startHour).eq(22);
expect(result[11].endHour).eq(23);
expect(result[11].day).eq("Mi");
expect(result[24].startHour).eq(11);
expect(result[24].endHour).eq(12);
expect(result[24].day).eq("Do");
});
test("slots after target should be toLate", () => {
expect(result[0].toLate).eq(false);
expect(result[1].toLate).eq(false);
expect(result[2].toLate).eq(true);
expect(result[3].toLate).eq(true);
});
test("slots are marked if charging is happening in them", () => {
expect(result[0].charging).eq(false);
expect(result[1].charging).eq(true);
expect(result[2].charging).eq(false);
expect(result[3].charging).eq(false);
});
test("all slots have the same fixed price", () => {
result.forEach((slot) => expect(slot.price).eq(0.4));
});
});
describe("zoned tariffs", () => {
const DATE_START = new Date("2023-01-11T11:00:00+01:00");
const DATE_TARGET = new Date("2023-01-11T16:00:00+01:00");
const TARIFF_ZONED = [
{
start: "2023-01-11T11:00:00+01:00",
end: "2023-01-11T12:00:00+01:00",
price: 0.2,
},
{
start: "2023-01-11T12:00:00+01:00",
end: "2023-01-22T00:00:00+01:00",
price: 0.4,
},
];
const PLAN = [
{
start: "2023-01-11T11:30:00+01:00",
end: "2023-01-11T13:00:00+01:00",
},
{
start: "2023-01-11T14:30:00+01:00",
end: "2023-01-11T16:00:00+01:00",
},
];
let result = null;
const wrapper = mount(Preview, {
props: {
plan: PLAN,
targetTime: DATE_TARGET,
rates: TARIFF_ZONED,
},
});
wrapper.setData({ startTime: DATE_START });
beforeAll(() => {
result = wrapper.vm.slots;
});
test("handle multiple charging slots", () => {
expect(result[0].charging).eq(true);
expect(result[1].charging).eq(true);
expect(result[2].charging).eq(false);
expect(result[3].charging).eq(true);
expect(result[4].charging).eq(true);
expect(result[5].charging).eq(false);
});
test("first slot is cheap, others are expensive", () => {
const [first, ...others] = result;
expect(first.price).eq(0.2);
others.forEach((slot) => expect(slot.price).eq(0.4));
});
});

View file

@ -0,0 +1,140 @@
import { mount, config } from "@vue/test-utils";
import { beforeAll, describe, expect, test } from "vitest";
import Preview from "./Preview.vue";
import type { Slot } from "./types";
config.global.mocks["$i18n"] = { locale: "de-DE" };
config.global.mocks["$t"] = (a: any) => a;
describe("basics", () => {
const DATE_START = new Date("2023-01-11T11:00:00+01:00");
const DATE_TARGET = new Date("2023-01-11T13:00:00+01:00");
const TARIFF_FIXED = [
{
start: new Date("2023-01-11T11:00:00+01:00"),
end: new Date("2023-01-22T00:00:00+01:00"),
price: 0.4,
},
];
const PLAN = [
{
start: new Date("2023-01-11T12:00:00+01:00"),
end: new Date("2023-01-11T13:00:00+01:00"),
price: 0.2,
},
];
const wrapper = mount(Preview, {
props: {
plan: PLAN,
targetTime: DATE_TARGET,
rates: TARIFF_FIXED,
},
});
wrapper.setData({ startTime: DATE_START });
let result: Slot[];
beforeAll(() => {
result = wrapper.vm.slots;
});
test("should return 39 slots", () => {
expect(result.length).eq(39);
});
test("slots should be an hour apart", () => {
expect(result[0].startHour).eq(11);
expect(result[0].endHour).eq(12);
expect(result[0].day).eq("Mi");
expect(result[1].startHour).eq(12);
expect(result[1].endHour).eq(13);
expect(result[1].day).eq("Mi");
expect(result[11].startHour).eq(22);
expect(result[11].endHour).eq(23);
expect(result[11].day).eq("Mi");
expect(result[24].startHour).eq(11);
expect(result[24].endHour).eq(12);
expect(result[24].day).eq("Do");
});
test("slots after target should be toLate", () => {
expect(result[0].toLate).eq(false);
expect(result[1].toLate).eq(false);
expect(result[2].toLate).eq(true);
expect(result[3].toLate).eq(true);
});
test("slots are marked if charging is happening in them", () => {
expect(result[0].charging).eq(false);
expect(result[1].charging).eq(true);
expect(result[2].charging).eq(false);
expect(result[3].charging).eq(false);
});
test("all slots have the same fixed price", () => {
result.forEach((slot) => expect(slot.price).eq(0.4));
});
});
describe("zoned tariffs", () => {
const DATE_START = new Date("2023-01-11T11:00:00+01:00");
const DATE_TARGET = new Date("2023-01-11T16:00:00+01:00");
const TARIFF_ZONED = [
{
start: new Date("2023-01-11T11:00:00+01:00"),
end: new Date("2023-01-11T12:00:00+01:00"),
price: 0.2,
},
{
start: new Date("2023-01-11T12:00:00+01:00"),
end: new Date("2023-01-22T00:00:00+01:00"),
price: 0.4,
},
];
const PLAN = [
{
start: new Date("2023-01-11T11:30:00+01:00"),
end: new Date("2023-01-11T13:00:00+01:00"),
price: 0.3,
},
{
start: new Date("2023-01-11T14:30:00+01:00"),
end: new Date("2023-01-11T16:00:00+01:00"),
price: 0.2,
},
];
let result: Slot[];
const wrapper = mount(Preview, {
props: {
plan: PLAN,
targetTime: DATE_TARGET,
rates: TARIFF_ZONED,
},
});
wrapper.setData({ startTime: DATE_START });
beforeAll(() => {
result = wrapper.vm.slots;
});
test("handle multiple charging slots", () => {
expect(result[0].charging).eq(true);
expect(result[1].charging).eq(true);
expect(result[2].charging).eq(false);
expect(result[3].charging).eq(true);
expect(result[4].charging).eq(true);
expect(result[5].charging).eq(false);
});
test("first slot is cheap, others are expensive", () => {
const [first, ...others] = result;
expect(first.price).eq(0.2);
others.forEach((slot) => expect(slot.price).eq(0.4));
});
});

View file

@ -34,57 +34,60 @@
</div>
</template>
<script>
<script lang="ts">
import { defineComponent, type PropType } from "vue";
import formatter from "../../mixins/formatter.js";
import { CO2_TYPE } from "../../units.js";
import TariffChart from "../Tariff/TariffChart.vue";
import type { CURRENCY, Rate } from "assets/js/types/evcc.js";
import type { Slot } from "./types.js";
export default {
export default defineComponent({
name: "ChargingPlanPreview",
components: { TariffChart },
mixins: [formatter],
props: {
duration: Number,
power: Number,
rates: Array,
plan: Array,
rates: Array as PropType<Rate[]>,
plan: Array as PropType<Rate[]>,
smartCostType: String,
targetTime: Date,
currency: String,
targetTime: [Date, null],
currency: String as PropType<CURRENCY>,
},
data() {
return { activeIndex: null, startTime: new Date() };
return { activeIndex: null as number | null, startTime: new Date() };
},
computed: {
endTime() {
endTime(): Date | null {
if (!this.plan?.length) {
return null;
}
const end = this.plan[this.plan.length - 1].end;
return end ? new Date(end) : null;
},
timeWarning() {
timeWarning(): boolean {
if (this.targetTime && this.endTime) {
return this.targetTime < this.endTime;
}
return false;
},
planDuration() {
planDuration(): string {
return this.fmtDuration(this.duration);
},
fmtPower() {
if (this.duration > 0 && this.power > 0) {
fmtPower(): string | null {
if (this.duration && this.power && this.duration > 0 && this.power > 0) {
return `@ ${this.fmtW(this.power)}`;
}
return null;
},
isCo2() {
isCo2(): boolean {
return this.smartCostType === CO2_TYPE;
},
hasTariff() {
return this.rates?.length > 1;
hasTariff(): boolean {
return (this.rates?.length || 0) > 1;
},
avgPrice() {
avgPrice(): number | undefined {
let hourSum = 0;
let priceSum = 0;
this.convertDates(this.plan).forEach((slot) => {
@ -96,7 +99,7 @@ export default {
});
return hourSum ? priceSum / hourSum : undefined;
},
fmtAvgPrice() {
fmtAvgPrice(): string {
if (this.duration === 0) {
return "—";
}
@ -108,10 +111,10 @@ export default {
? this.fmtCo2Medium(price)
: this.fmtPricePerKWh(price, this.currency);
},
activeSlot() {
return this.slots[this.activeIndex];
activeSlot(): Slot | null {
return this.activeIndex ? this.slots[this.activeIndex] : null;
},
activeSlotName() {
activeSlotName(): string | null {
if (this.activeSlot) {
const { day, startHour, endHour } = this.activeSlot;
const range = `${startHour}–${endHour}`;
@ -119,7 +122,7 @@ export default {
}
return null;
},
targetHourOffset() {
targetHourOffset(): number | null {
if (!this.targetTime) {
return null;
}
@ -129,13 +132,13 @@ export default {
start.setMilliseconds(0);
return (this.targetTime.getTime() - start.getTime()) / (60 * 60 * 1000);
},
targetText() {
targetText(): string | null {
if (!this.targetTime) {
return null;
}
return this.fmtWeekdayTime(this.targetTime);
},
slots() {
slots(): Slot[] {
const result = [];
const rates = this.convertDates(this.rates);
const plan = this.convertDates(this.plan);
@ -153,11 +156,13 @@ export default {
const toLate = this.targetTime && this.targetTime <= start;
// TODO: handle multiple matching time slots
const price = this.findSlotInRange(start, end, rates)?.price;
const isTarget = start <= this.targetTime && end > this.targetTime;
const isTarget =
this.targetTime && start <= this.targetTime && end > this.targetTime;
const charging = this.findSlotInRange(start, end, plan) != null;
const warning =
charging &&
this.targetTime &&
this.endTime &&
end > this.targetTime &&
this.targetTime < this.endTime;
result.push({
@ -175,12 +180,12 @@ export default {
},
},
watch: {
rates() {
rates(): void {
this.startTime = new Date();
},
},
methods: {
convertDates(list) {
convertDates(list: Rate[] | undefined): Rate[] {
if (!list?.length) {
return [];
}
@ -192,7 +197,7 @@ export default {
};
});
},
findSlotInRange(start, end, slots) {
findSlotInRange(start: Date, end: Date, slots: Rate[]): Rate | undefined {
return slots.find((s) => {
if (s.start.getTime() < start.getTime()) {
return s.end.getTime() > start.getTime();
@ -200,11 +205,11 @@ export default {
return s.start.getTime() < end.getTime();
});
},
slotHovered(index) {
slotHovered(index: number): void {
this.activeIndex = index;
},
},
};
});
</script>
<style scoped>

View file

@ -3,7 +3,7 @@
<span v-if="targetIsAboveLimit" class="d-block evcc-gray mb-1">
{{ $t("main.targetCharge.targetIsAboveLimit", { limit: limitFmt }) }}
</span>
<span v-if="['off', 'now'].includes(mode)" class="d-block evcc-gray mb-1">
<span v-if="mode && ['off', 'now'].includes(mode)" class="d-block evcc-gray mb-1">
{{ $t("main.targetCharge.onlyInPvMode") }}
</span>
<span v-if="timeTooFarInTheFuture" class="d-block evcc-gray mb-1">
@ -18,10 +18,13 @@
</p>
</template>
<script>
<script lang="ts">
import { defineComponent, type PropType } from "vue";
import formatter from "../../mixins/formatter.js";
import type { PlanWrapper } from "./types.js";
import type { Tariff } from "assets/js/types/evcc.js";
export default {
export default defineComponent({
name: "ChargingPlanWarnings",
mixins: [formatter],
props: {
@ -35,26 +38,26 @@ export default {
socPerKwh: Number,
rangePerSoc: Number,
mode: String,
tariff: Object,
plan: Object,
tariff: Object as PropType<Tariff>,
plan: Object as PropType<PlanWrapper>,
vehicleLimitSoc: Number,
planOverrun: Number,
},
computed: {
endTime() {
endTime(): Date | null {
if (!this.plan?.plan?.length) {
return null;
}
const { plan } = this.plan;
return plan[plan.length - 1].end;
},
overrunFmt() {
overrunFmt(): string {
if (!this.planOverrun) {
return "";
}
return this.fmtDuration(this.planOverrun, true, "m");
},
timeTooFarInTheFuture() {
timeTooFarInTheFuture(): boolean {
if (!this.effectivePlanTime) {
return false;
}
@ -67,47 +70,44 @@ export default {
}
return false;
},
notReachableInTime() {
notReachableInTime(): boolean {
const { planTime } = this.plan || {};
if (planTime && this.endTime) {
const dateWanted = new Date(planTime);
const dateEstimated = new Date(this.endTime);
// 1 minute tolerance
return dateEstimated - dateWanted > 60 * 1e3;
return dateEstimated.getTime() - dateWanted.getTime() > 60 * 1e3;
}
return false;
},
targetIsAboveLimit() {
if (this.socBasedPlanning) {
targetIsAboveLimit(): boolean {
if (this.socBasedPlanning && this.effectivePlanSoc && this.effectiveLimitSoc) {
return this.effectivePlanSoc > this.effectiveLimitSoc;
}
return this.limitEnergy && this.planEnergy > this.limitEnergy;
return !!this.limitEnergy && !!this.planEnergy && this.planEnergy > this.limitEnergy;
},
targetIsAboveVehicleLimit() {
if (this.socBasedPlanning) {
targetIsAboveVehicleLimit(): boolean {
if (this.socBasedPlanning && this.effectivePlanSoc) {
return this.effectivePlanSoc > (this.vehicleLimitSoc || 100);
}
return false;
},
limitFmt() {
if (this.socBasedPlanning) {
limitFmt(): string {
if (this.socBasedPlanning && this.effectiveLimitSoc) {
return this.fmtSoc(this.effectiveLimitSoc);
} else if (this.limitEnergy) {
return this.fmtWh(this.limitEnergy * 1e3);
} else {
return "??";
}
return this.fmtWh(this.limitEnergy * 1e3);
},
goalFmt() {
if (this.socBasedPlanning) {
return this.fmtSoc(this.effectivePlanSoc);
}
return this.fmtWh(this.planEnergy * 1e3);
},
},
methods: {
fmtSoc(soc) {
fmtSoc(soc: number): string {
return this.fmtPercentage(soc);
},
},
};
});
</script>
<style scoped>

View file

@ -0,0 +1,45 @@
import type { Rate } from "assets/js/types/evcc";
export interface RepeatingPlan {
weekdays: number[];
time: string;
tz: string; // timezone like "Europe/Berlin"
soc: number;
active: boolean;
}
export interface PlanWrapper {
planId: number;
planTime: Date;
duration: number;
plan: Rate[];
power: number;
}
export interface PlanResponse {
status: number;
data: { result: PlanWrapper };
}
export type StaticPlan = StaticSocPlan | StaticEnergyPlan;
export interface StaticSocPlan {
soc: number;
time: Date;
}
export interface StaticEnergyPlan {
energy: number;
time: Date;
}
export interface Slot {
day: string;
price?: number;
startHour: number;
endHour: number;
charging: boolean;
toLate?: boolean | null;
warning?: boolean | null;
isTarget?: boolean | null;
}

View file

@ -67,7 +67,7 @@ import { defineComponent, type PropType } from "vue";
import { ForecastType, type PriceSlot, type SolarDetails } from "../../utils/forecast.ts";
import formatter, { POWER_UNIT } from "../../mixins/formatter.ts";
import AnimatedNumber from "../Helper/AnimatedNumber.vue";
import type { CURRENCY } from "assets/js/types/evcc.ts";
import type { CURRENCY, Timeout } from "assets/js/types/evcc.ts";
const LOCALES_WITHOUT_DAY_AFTER_TOMORROW = ["en", "tr"];
export interface Energy {
@ -97,7 +97,7 @@ export default defineComponent({
data() {
return {
now: new Date(),
interval: null as ReturnType<typeof setInterval> | null,
interval: null as Timeout,
};
},
computed: {

View file

@ -14,27 +14,30 @@
</label>
</template>
<script>
export default {
<script lang="ts">
import type { SelectOption } from "../../types/evcc";
import { defineComponent, type PropType } from "vue";
export default defineComponent({
name: "CustomSelect",
props: {
options: { type: Array },
options: { type: Array as PropType<SelectOption<number | string>[]> },
selected: { type: [String, Number] },
id: { type: String },
},
emits: ["change"],
methods: {
text(name, count) {
text(name: string, count?: number) {
if (count === undefined) {
return name;
}
return `${name} (${count})`;
},
change(event) {
change(event: Event) {
this.$emit("change", event);
},
},
};
});
</script>
<style scoped>
.custom-select {

View file

@ -68,8 +68,8 @@ export default {
mixins: [formatter],
props: {
slots: Array,
targetText: String,
targetOffset: Number,
targetText: [String, null],
targetOffset: [Number, null],
},
emits: ["slot-hovered", "slot-selected"],
data() {

View file

@ -14,7 +14,8 @@ const ENERGY_PRICE_IN_SUBUNIT = {
ILS: "ag", // Israeli agora
NZD: "c", // New Zealand cent
PLN: "gr", // Polish grosz
USD: "¢", // US cent
USD: "¢", // US cent,
DKK: "Ø", // Danish øre
};
export enum POWER_UNIT {
@ -252,7 +253,7 @@ export default defineComponent({
return withSymbol ? result : result.replace(currency, "").trim();
},
fmtCurrencySymbol(currency = CURRENCY.EUR) {
const symbols = { EUR: "€", USD: "$" };
const symbols = { EUR: "€", USD: "$", DKK: "dkr." };
return symbols[currency] || currency;
},
fmtPricePerKWh(amout = 0, currency = CURRENCY.EUR, short = false, withUnit = true) {
@ -307,7 +308,7 @@ export default defineComponent({
return "";
},
fmtSocOption(soc: number, rangePerSoc: number, distanceUnit: string, heating?: boolean) {
fmtSocOption(soc: number, rangePerSoc?: number, distanceUnit?: string, heating?: boolean) {
let result = heating ? this.fmtTemperature(soc) : `${this.fmtPercentage(soc)}`;
if (rangePerSoc && distanceUnit) {
const range = soc * rangePerSoc;
@ -330,7 +331,9 @@ export default defineComponent({
// TODO: handle fahrenheit
return this.fmtNumber(value, 1, "celsius");
},
getWeekdaysList(weekdayFormat: Intl.DateTimeFormatOptions["weekday"]) {
getWeekdaysList(
weekdayFormat: Intl.DateTimeFormatOptions["weekday"]
): { name: string; value: number }[] {
const { format } = new Intl.DateTimeFormat(this.$i18n?.locale, {
weekday: weekdayFormat,
});
@ -340,7 +343,7 @@ export default defineComponent({
const sunday = { name: format(new Date(Date.UTC(2021, 5, 6))), value: 0 };
return [...mondayToSaturday, sunday];
},
getShortenedWeekdaysLabel(selectedWeekdays: number[]) {
getShortenedWeekdaysLabel(selectedWeekdays: number[]): string {
if (0 === selectedWeekdays.length) {
return "–";
}

View file

@ -1,4 +1,5 @@
import { reactive } from "vue";
import type { State } from "./types/evcc";
function setProperty(obj: object, props: string[], value: any) {
const prop = props.shift();

View file

@ -1,17 +1,55 @@
declare global {
interface State {
offline: boolean;
loadpoints: [];
forecast?: any;
currency?: CURRENCY;
}
import type { StaticPlan, RepeatingPlan } from "../components/ChargingPlans/types";
declare global {
interface Window {
app: any;
}
}
export interface State {
offline: boolean;
loadpoints: [];
forecast?: any;
currency?: CURRENCY;
}
export enum CURRENCY {
EUR = "EUR",
USD = "USD",
DKK = "DKK",
}
export interface Vehicle {
name: string;
minSoc?: number;
limitSoc?: number;
plan?: StaticPlan;
repeatingPlans: RepeatingPlan[];
title: string;
}
export type Timeout = ReturnType<typeof setInterval> | null;
export interface Tariff {
rates: Rate[];
lastUpdate: Date;
}
export interface Rate {
start: Date;
end: Date;
price: number;
}
export interface SelectOption<T> {
name: string;
value: T;
count?: number;
disabled?: boolean;
}
// see https://stackoverflow.com/a/54178819
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
export type PartialBy<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
export type ValueOf<T> = T[keyof T];

View file

@ -6,5 +6,6 @@ declare module "vue" {
* Whether experimental UI features should be shown.
*/
$hiddenFeatures: () => boolean;
$refs: { [key: string]: HTMLElement | undefined };
}
}

View file

@ -1,13 +1,13 @@
import globals from "globals";
import js from "@eslint/js";
import pluginVue from "eslint-plugin-vue";
import vueTsEslintConfig from "@vue/eslint-config-typescript";
import { defineConfigWithVueTs, vueTsConfigs } from "@vue/eslint-config-typescript";
import skipFormattingConfig from "@vue/eslint-config-prettier/skip-formatting";
export default [
export default defineConfigWithVueTs(
js.configs.recommended,
...pluginVue.configs["flat/recommended"],
...vueTsEslintConfig(),
vueTsConfigs.recommended,
skipFormattingConfig,
{
languageOptions: {
@ -28,6 +28,7 @@ export default [
/*"vue/no-undef-properties": "warn",*/
"no-param-reassign": "error",
"vue/block-lang": "off",
"@typescript-eslint/no-explicit-any": "off",
},
},
];
}
);

10
package-lock.json generated
View file

@ -13,6 +13,7 @@
"@h2d2/shopicons": "^1.2.0",
"@playwright/test": "^1.46.1",
"@popperjs/core": "^2.11.5",
"@types/bootstrap": "^5.2.10",
"@unhead/vue": "^1.8.9",
"@vitejs/plugin-legacy": "^6.0.1",
"@vitejs/plugin-vue": "^5.0.4",
@ -3427,6 +3428,15 @@
"dev": true,
"license": "MIT"
},
"node_modules/@types/bootstrap": {
"version": "5.2.10",
"resolved": "https://registry.npmjs.org/@types/bootstrap/-/bootstrap-5.2.10.tgz",
"integrity": "sha512-F2X+cd6551tep0MvVZ6nM8v7XgGN/twpdNDjqS1TUM7YFNEtQYWk+dKAnH+T1gr6QgCoGMPl487xw/9hXooa2g==",
"license": "MIT",
"dependencies": {
"@popperjs/core": "^2.9.2"
}
},
"node_modules/@types/estree": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.7.tgz",

View file

@ -5,7 +5,8 @@
"scripts": {
"build": "vite build",
"test": "TZ=Europe/Berlin vitest",
"lint": "prettier assets './**/*.{yml,yaml,sh}' --write && eslint assets/**/*.js assets/**/*.vue --fix --max-warnings=0 && vue-tsc --noEmit",
"lint": "prettier assets './**/*.{yml,yaml,sh}' --write && eslint assets/**/*.js assets/**/*.vue --fix --max-warnings=0 && npm run tsc",
"tsc": "vue-tsc --noEmit",
"dev": "vite",
"playwright": "playwright test --ui",
"simulator": "vite tests/simulator",
@ -20,6 +21,7 @@
"@h2d2/shopicons": "^1.2.0",
"@playwright/test": "^1.46.1",
"@popperjs/core": "^2.11.5",
"@types/bootstrap": "^5.2.10",
"@unhead/vue": "^1.8.9",
"@vitejs/plugin-legacy": "^6.0.1",
"@vitejs/plugin-vue": "^5.0.4",