73 lines
2.1 KiB
TypeScript
73 lines
2.1 KiB
TypeScript
import { prisma } from "#lib/server/prisma";
|
|
import moment from "moment";
|
|
import csv from "csvtojson"
|
|
|
|
// Als erstes schauen wir, welches das letzte Jahr ist, für das wir einen Verbrauchsausweis haben.
|
|
// Das machen wir, indem wir die Ausweise nach Jahr und Monat sortieren und dann den letzten Eintrag nehmen.
|
|
const newestDate = await prisma.klimafaktoren.findFirst({
|
|
orderBy: [
|
|
{
|
|
year: "desc",
|
|
},
|
|
{
|
|
month: "desc",
|
|
}
|
|
]
|
|
})
|
|
|
|
if (!newestDate) {
|
|
console.error("No last year found!")
|
|
process.exit(1)
|
|
}
|
|
|
|
// Jetzt müssen wir abfragen, welche neuen Dateien es beim Deutschen Wetterdienst gibt.
|
|
// https://opendata.dwd.de/climate_environment/CDC/derived_germany/techn/monthly/climate_correction_factor/recent/
|
|
// Weil die Antwort in HTML ist und wir keinen Bock haben das alles zu parsen, versuchen wir einfach die neueste Datei abzufragen.
|
|
// Das format des DWD ist wie folgt: KF_20221101_20231031.csv
|
|
// Der Monat bei moment und in der Datenbank ist nullbasiert, also 0 = Januar, 11 = Dezember.
|
|
const currentDate = moment().set("month", newestDate.month).set("year", newestDate.year).set("date", 1);
|
|
|
|
|
|
const lastYearString = currentDate.clone().add(1, "month").startOf("month").format("YYYYMMDD");
|
|
const nextYearString = currentDate.clone().add(1, "year").endOf("month").format("YYYYMMDD");
|
|
|
|
const filename = `KF_${lastYearString}_${nextYearString}.csv`
|
|
|
|
const url = "https://opendata.dwd.de/climate_environment/CDC/derived_germany/techn/monthly/climate_correction_factor/recent/"
|
|
|
|
const response = await fetch(`${url}${filename}`)
|
|
|
|
if (response.status !== 200) {
|
|
console.error(`Could not fetch ${url}${filename}`)
|
|
process.exit(1)
|
|
}
|
|
|
|
const parser = csv({
|
|
noheader: false,
|
|
output: "json",
|
|
delimiter: ";",
|
|
})
|
|
|
|
const data: {
|
|
DatAnf: string,
|
|
DatEnd: string,
|
|
PLZ: string,
|
|
KF: string
|
|
}[] = await parser.fromString(await response.text())
|
|
|
|
const year = currentDate.clone().add(1, "month").year();
|
|
const month = currentDate.clone().add(1, "month").month();
|
|
|
|
const result = await prisma.klimafaktoren.createMany({
|
|
data: data.map((row) => {
|
|
return {
|
|
year,
|
|
month,
|
|
klimafaktor: parseFloat(row.KF),
|
|
plz: row.PLZ,
|
|
}
|
|
})
|
|
})
|
|
|
|
|
|
console.log(`Updated ${result.count} rows!`) |