Format codebase with cljstyle
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -2,8 +2,10 @@
|
||||
(:require
|
||||
[kit.config :as config]))
|
||||
|
||||
|
||||
(def ^:const system-filename "system.edn")
|
||||
|
||||
|
||||
(defn system-config
|
||||
[options]
|
||||
(config/read-config system-filename options))
|
||||
|
||||
@@ -1,21 +1,20 @@
|
||||
(ns pmagnus.elprice.core
|
||||
(:gen-class)
|
||||
(:require
|
||||
[clojure.tools.logging :as log]
|
||||
[integrant.core :as ig]
|
||||
[pmagnus.elprice.config :as config]
|
||||
[pmagnus.elprice.env :refer [defaults]]
|
||||
|
||||
[kit.edge.db.postgres]
|
||||
;; Edges
|
||||
[kit.edge.db.sql.conman]
|
||||
[kit.edge.db.sql.migratus]
|
||||
[kit.edge.db.postgres]
|
||||
[kit.edge.server.undertow]
|
||||
[pmagnus.elprice.config :as config]
|
||||
[pmagnus.elprice.env :refer [defaults]]
|
||||
[pmagnus.elprice.web.handler]
|
||||
|
||||
;; Routes
|
||||
[pmagnus.elprice.web.routes.api]
|
||||
[pmagnus.elprice.web.routes.ui])
|
||||
(:gen-class))
|
||||
[pmagnus.elprice.web.routes.ui]))
|
||||
|
||||
|
||||
;; log uncaught exceptions in threads
|
||||
(Thread/setDefaultUncaughtExceptionHandler
|
||||
@@ -24,19 +23,26 @@
|
||||
:exception ex
|
||||
:where (str "Uncaught exception on" (.getName thread))})))
|
||||
|
||||
|
||||
(defonce system (atom nil))
|
||||
|
||||
(defn stop-app []
|
||||
|
||||
(defn stop-app
|
||||
[]
|
||||
((or (:stop defaults) (fn [])))
|
||||
(some-> (deref system) (ig/halt!)))
|
||||
|
||||
(defn start-app [& [params]]
|
||||
|
||||
(defn start-app
|
||||
[& [params]]
|
||||
((or (:start params) (:start defaults) (fn [])))
|
||||
(->> (config/system-config (or (:opts params) (:opts defaults) {}))
|
||||
(ig/expand)
|
||||
(ig/init)
|
||||
(reset! system)))
|
||||
|
||||
(defn -main [& _]
|
||||
|
||||
(defn -main
|
||||
[& _]
|
||||
(start-app)
|
||||
(.addShutdownHook (Runtime/getRuntime) (Thread. (fn [] (stop-app) (shutdown-agents)))))
|
||||
|
||||
@@ -4,21 +4,36 @@
|
||||
[clojure.string :as str]
|
||||
[clojure.tools.logging :as log])
|
||||
(:import
|
||||
[java.net URI]
|
||||
[java.net.http HttpClient HttpRequest HttpRequest$BodyPublishers HttpResponse$BodyHandlers]
|
||||
[java.time LocalDate LocalDateTime ZoneId]
|
||||
[java.time.format DateTimeFormatter]
|
||||
[java.sql Timestamp Date]))
|
||||
(java.net
|
||||
URI)
|
||||
(java.net.http
|
||||
HttpClient
|
||||
HttpRequest
|
||||
HttpRequest$BodyPublishers
|
||||
HttpResponse$BodyHandlers)
|
||||
(java.sql
|
||||
Date
|
||||
Timestamp)
|
||||
(java.time
|
||||
LocalDate
|
||||
LocalDateTime
|
||||
ZoneId)
|
||||
(java.time.format
|
||||
DateTimeFormatter)))
|
||||
|
||||
|
||||
(def ^:private base-url "https://api.eloverblik.dk/customerapi")
|
||||
(def ^:private dk-zone (ZoneId/of "Europe/Copenhagen"))
|
||||
(def ^:private date-fmt (DateTimeFormatter/ofPattern "yyyy-MM-dd"))
|
||||
|
||||
|
||||
;; --- Auth ---
|
||||
|
||||
(defn- read-refresh-token []
|
||||
(defn- read-refresh-token
|
||||
[]
|
||||
(str/trim (slurp ".token")))
|
||||
|
||||
|
||||
(defn- get-access-token
|
||||
"Exchange refresh token for a short-lived access token."
|
||||
[refresh-token]
|
||||
@@ -34,6 +49,7 @@
|
||||
(let [body (json/read-str (.body response) :key-fn keyword)]
|
||||
(:result body)))))
|
||||
|
||||
|
||||
;; --- HTTP helpers ---
|
||||
|
||||
(defn- api-get
|
||||
@@ -51,6 +67,7 @@
|
||||
(when (= 200 (.statusCode response))
|
||||
(json/read-str (.body response) :key-fn keyword))))
|
||||
|
||||
|
||||
(defn- api-post
|
||||
"POST with Bearer access token + JSON body, returns parsed JSON."
|
||||
[access-token path body]
|
||||
@@ -68,17 +85,23 @@
|
||||
(when (= 200 (.statusCode response))
|
||||
(json/read-str (.body response) :key-fn keyword))))
|
||||
|
||||
|
||||
;; --- Metering Points ---
|
||||
|
||||
(defn- fetch-metering-points [access-token]
|
||||
(defn- fetch-metering-points
|
||||
[access-token]
|
||||
(let [data (api-get access-token "/api/meteringpoints/meteringpoints?includeAll=true")]
|
||||
(:result data)))
|
||||
|
||||
(defn- parse-date [s]
|
||||
|
||||
(defn- parse-date
|
||||
[s]
|
||||
(when (and s (not (str/blank? s)))
|
||||
(Date/valueOf (LocalDate/parse (subs s 0 10)))))
|
||||
|
||||
(defn- upsert-mp! [query-fn mp]
|
||||
|
||||
(defn- upsert-mp!
|
||||
[query-fn mp]
|
||||
(query-fn :upsert-metering-point!
|
||||
{:metering-point-id (:meteringPointId mp)
|
||||
:type-of-mp (:typeOfMP mp)
|
||||
@@ -93,7 +116,9 @@
|
||||
:consumer-start-date (parse-date (:consumerStartDate mp))
|
||||
:first-consumer-name (:firstConsumerPartyName mp)}))
|
||||
|
||||
(defn- save-metering-points! [query-fn metering-points]
|
||||
|
||||
(defn- save-metering-points!
|
||||
[query-fn metering-points]
|
||||
(let [all-mps (mapcat (fn [mp]
|
||||
(cons mp (:childMeteringPoints mp)))
|
||||
metering-points)]
|
||||
@@ -101,15 +126,18 @@
|
||||
(upsert-mp! query-fn mp))
|
||||
(log/info "Saved" (count all-mps) "metering points")))
|
||||
|
||||
|
||||
;; --- Time Series ---
|
||||
|
||||
(defn- fetch-time-series [access-token metering-point-ids from to]
|
||||
(defn- fetch-time-series
|
||||
[access-token metering-point-ids from to]
|
||||
(api-post access-token
|
||||
(str "/api/meterdata/gettimeseries/"
|
||||
(.format from date-fmt) "/"
|
||||
(.format to date-fmt) "/Hour")
|
||||
{:meteringPoints {:meteringPoint metering-point-ids}}))
|
||||
|
||||
|
||||
(defn- parse-time-series
|
||||
"Parse the nested time series response into flat reading maps."
|
||||
[response metering-point-ids]
|
||||
@@ -145,9 +173,11 @@
|
||||
results
|
||||
metering-point-ids)))
|
||||
|
||||
|
||||
(def ^:private production-mp-id "571313113163368491")
|
||||
(def ^:private consumption-mp-id "571313113163368507")
|
||||
|
||||
|
||||
(defn- utc-start-for-date
|
||||
"Compute the UTC start of a Danish date (midnight DK -> UTC)."
|
||||
[^LocalDate date]
|
||||
@@ -156,7 +186,9 @@
|
||||
(.toInstant)
|
||||
(Timestamp/from)))
|
||||
|
||||
(defn- save-time-series! [query-fn readings from]
|
||||
|
||||
(defn- save-time-series!
|
||||
[query-fn readings from]
|
||||
(doseq [r readings]
|
||||
(query-fn :insert-meter-reading! r))
|
||||
(let [time-start (utc-start-for-date from)]
|
||||
@@ -170,14 +202,18 @@
|
||||
{:time-start time-start :hour hour :kwh (:quantity-kwh r)}))))
|
||||
(log/info "Saved" (count readings) "meter readings + production/consumption"))
|
||||
|
||||
|
||||
;; --- Charges ---
|
||||
|
||||
(defn- fetch-charges [access-token metering-point-ids]
|
||||
(defn- fetch-charges
|
||||
[access-token metering-point-ids]
|
||||
(api-post access-token
|
||||
"/api/meteringpoints/meteringpoint/getcharges"
|
||||
{:meteringPoints {:meteringPoint metering-point-ids}}))
|
||||
|
||||
(defn- save-charges! [query-fn charges-response]
|
||||
|
||||
(defn- save-charges!
|
||||
[query-fn charges-response]
|
||||
(let [results (:result charges-response)]
|
||||
(doseq [result results]
|
||||
(let [mp-id (:id result)
|
||||
@@ -240,6 +276,7 @@
|
||||
:quantity (:quantity fee)
|
||||
:position 0}))))))
|
||||
|
||||
|
||||
;; --- Orchestrator ---
|
||||
|
||||
(defn fetch-and-save-all!
|
||||
@@ -286,4 +323,3 @@
|
||||
{:metering-points (count all-ids)
|
||||
:from (.format from date-fmt)
|
||||
:to (.format to date-fmt)})))))))
|
||||
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
(:require
|
||||
[ring.util.http-response :as http-response])
|
||||
(:import
|
||||
[java.util Date]))
|
||||
(java.util
|
||||
Date)))
|
||||
|
||||
|
||||
(defn healthcheck!
|
||||
[req]
|
||||
|
||||
@@ -3,16 +3,27 @@
|
||||
[clojure.data.json :as json]
|
||||
[clojure.tools.logging :as log])
|
||||
(:import
|
||||
[java.net URI URLEncoder]
|
||||
[java.net.http HttpClient HttpRequest HttpResponse$BodyHandlers]
|
||||
[java.time LocalDate ZoneId]
|
||||
[java.time.format DateTimeFormatter]
|
||||
[java.sql Timestamp]))
|
||||
(java.net
|
||||
URI
|
||||
URLEncoder)
|
||||
(java.net.http
|
||||
HttpClient
|
||||
HttpRequest
|
||||
HttpResponse$BodyHandlers)
|
||||
(java.sql
|
||||
Timestamp)
|
||||
(java.time
|
||||
LocalDate
|
||||
ZoneId)
|
||||
(java.time.format
|
||||
DateTimeFormatter)))
|
||||
|
||||
|
||||
(def ^:private dk-zone (ZoneId/of "Europe/Copenhagen"))
|
||||
|
||||
(def ^:private date-fmt (DateTimeFormatter/ofPattern "yyyy-MM-dd"))
|
||||
|
||||
|
||||
(defn- build-url
|
||||
"Build the Energi Data Service API URL for day-ahead prices."
|
||||
[start-date end-date price-area]
|
||||
@@ -23,6 +34,7 @@
|
||||
"&sort=TimeDK%20asc"
|
||||
"&limit=200"))
|
||||
|
||||
|
||||
(defn- fetch-json
|
||||
"Fetch JSON from a URL using JDK HttpClient."
|
||||
[url]
|
||||
@@ -36,6 +48,7 @@
|
||||
(when (= 200 (.statusCode response))
|
||||
(json/read-str (.body response) :key-fn keyword))))
|
||||
|
||||
|
||||
(defn- fetch-area
|
||||
"Fetch today's and tomorrow's prices for a single price area."
|
||||
[start end price-area]
|
||||
@@ -44,6 +57,7 @@
|
||||
(when-let [data (fetch-json url)]
|
||||
(:records data))))
|
||||
|
||||
|
||||
(defn fetch-prices-from-api
|
||||
"Fetch today's and tomorrow's prices from Energi Data Service for DK1 and DK2."
|
||||
[]
|
||||
@@ -53,6 +67,7 @@
|
||||
(concat (fetch-area start end "DK1")
|
||||
(fetch-area start end "DK2"))))
|
||||
|
||||
|
||||
(defn- parse-timestamp
|
||||
"Parse an ISO timestamp string to java.sql.Timestamp."
|
||||
[s]
|
||||
@@ -60,6 +75,7 @@
|
||||
(Timestamp/valueOf
|
||||
(.replace ^String s "T" " "))))
|
||||
|
||||
|
||||
(defn save-records!
|
||||
"Insert price records into the database, skipping existing ones."
|
||||
[query-fn records]
|
||||
@@ -71,6 +87,7 @@
|
||||
:price-dkk (:DayAheadPriceDKK rec)
|
||||
:price-eur (:DayAheadPriceEUR rec)})))
|
||||
|
||||
|
||||
(defn fetch-and-save!
|
||||
"Fetch prices from API and save to database."
|
||||
[query-fn]
|
||||
@@ -79,6 +96,7 @@
|
||||
(save-records! query-fn records)
|
||||
(count records)))
|
||||
|
||||
|
||||
(defn get-prices-for-date
|
||||
"Get prices for a given LocalDate and price area from the database."
|
||||
[query-fn date price-area]
|
||||
@@ -86,10 +104,12 @@
|
||||
{:date (java.sql.Date/valueOf date)
|
||||
:price-area price-area}))
|
||||
|
||||
|
||||
(defn get-today-prices
|
||||
[query-fn]
|
||||
(get-prices-for-date query-fn (LocalDate/now dk-zone) "DK1"))
|
||||
|
||||
|
||||
(defn get-tomorrow-prices
|
||||
[query-fn]
|
||||
(get-prices-for-date query-fn (.plusDays (LocalDate/now dk-zone) 1) "DK1"))
|
||||
|
||||
@@ -1,22 +1,26 @@
|
||||
(ns pmagnus.elprice.web.controllers.tariffs
|
||||
(:import
|
||||
[java.time LocalDateTime]))
|
||||
(java.time
|
||||
LocalDateTime)))
|
||||
|
||||
|
||||
(def n1-tariffs
|
||||
"N1 network tariffs in øre/kWh (incl. VAT), effective 2026-01-01.
|
||||
Source: https://n1.dk/elnetkunder/gaeldende-priser"
|
||||
{:summer {:low 10.98 ;; 00:00-06:00
|
||||
:high 16.47 ;; 06:00-17:00, 21:00-24:00
|
||||
:peak 42.83} ;; 17:00-21:00
|
||||
{:summer {:low 10.98 ; 00:00-06:00
|
||||
:high 16.47 ; 06:00-17:00, 21:00-24:00
|
||||
:peak 42.83} ; 17:00-21:00
|
||||
:winter {:low 10.98
|
||||
:high 32.95
|
||||
:peak 98.84}})
|
||||
|
||||
|
||||
(defn season
|
||||
"Returns :summer (Apr-Sep) or :winter (Oct-Mar) for a given month (1-12)."
|
||||
[month]
|
||||
(if (<= 4 month 9) :summer :winter))
|
||||
|
||||
|
||||
(defn load-level
|
||||
"Returns :low, :high, or :peak for a given hour (0-23).
|
||||
Low: 00:00-06:00
|
||||
@@ -29,6 +33,7 @@
|
||||
(and (<= 17 hour) (< hour 21)) :peak
|
||||
:else :high))
|
||||
|
||||
|
||||
(defn tariff-for-hour
|
||||
"Returns the applicable N1 tariff in øre/kWh.
|
||||
Can be called with (month, hour) or a LocalDateTime."
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
(ns pmagnus.elprice.web.handler
|
||||
(:require
|
||||
[pmagnus.elprice.web.middleware.core :as middleware]
|
||||
[integrant.core :as ig]
|
||||
[ring.util.http-response :as http-response]
|
||||
[pmagnus.elprice.web.middleware.core :as middleware]
|
||||
[reitit.ring :as ring]
|
||||
[reitit.swagger-ui :as swagger-ui]))
|
||||
[reitit.swagger-ui :as swagger-ui]
|
||||
[ring.util.http-response :as http-response]))
|
||||
|
||||
|
||||
(defmethod ig/init-key :handler/ring
|
||||
[_ {:keys [router api-path] :as opts}]
|
||||
@@ -30,6 +31,7 @@
|
||||
(http-response/content-type "text/plain")))}))
|
||||
{:middleware [(middleware/wrap-base opts)]}))
|
||||
|
||||
|
||||
(defmethod ig/init-key :router/routes
|
||||
[_ {:keys [routes]}]
|
||||
(mapv (fn [route]
|
||||
@@ -38,6 +40,7 @@
|
||||
route))
|
||||
routes))
|
||||
|
||||
|
||||
(defmethod ig/init-key :router/core
|
||||
[_ {:keys [routes env] :as opts}]
|
||||
(if (= env :dev)
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
(ns pmagnus.elprice.web.htmx
|
||||
(:require
|
||||
[ring.util.http-response :as http-response]
|
||||
[hiccup.core :as h]
|
||||
[hiccup.page :as p]))
|
||||
[hiccup.page :as p]
|
||||
[ring.util.http-response :as http-response]))
|
||||
|
||||
(defmacro page [opts & content]
|
||||
|
||||
(defmacro page
|
||||
[opts & content]
|
||||
`(-> (p/html5 ~opts
|
||||
[:head
|
||||
[:meta {:charset "UTF-8"}]
|
||||
@@ -19,7 +21,9 @@
|
||||
http-response/ok
|
||||
(http-response/content-type "text/html")))
|
||||
|
||||
(defmacro fragment [opts & content]
|
||||
|
||||
(defmacro fragment
|
||||
[opts & content]
|
||||
`(-> (str (h/html ~opts ~@content))
|
||||
http-response/ok
|
||||
(http-response/content-type "text/html")))
|
||||
|
||||
@@ -4,11 +4,11 @@
|
||||
[ring.middleware.defaults :as defaults]
|
||||
[ring.middleware.session.cookie :as cookie]))
|
||||
|
||||
|
||||
(defn wrap-base
|
||||
[{:keys [metrics site-defaults-config cookie-secret] :as opts}]
|
||||
(let [cookie-store (cookie/cookie-store {:key (.getBytes ^String cookie-secret)})]
|
||||
(fn [handler]
|
||||
(cond-> ((:middleware env/defaults) handler opts)
|
||||
true (defaults/wrap-defaults
|
||||
(assoc-in site-defaults-config [:session :store] cookie-store))
|
||||
))))
|
||||
(assoc-in site-defaults-config [:session :store] cookie-store))))))
|
||||
|
||||
@@ -3,7 +3,9 @@
|
||||
[clojure.tools.logging :as log]
|
||||
[reitit.ring.middleware.exception :as exception]))
|
||||
|
||||
(defn handler [message status exception request]
|
||||
|
||||
(defn handler
|
||||
[message status exception request]
|
||||
(when (>= status 500)
|
||||
;; You can optionally use this to report error to an external service
|
||||
(log/error exception))
|
||||
@@ -13,6 +15,7 @@
|
||||
:data (ex-data exception)
|
||||
:uri (:uri request)}})
|
||||
|
||||
|
||||
(def wrap-exception
|
||||
(exception/create-exception-middleware
|
||||
(merge
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
[luminus-transit.time :as time]
|
||||
[muuntaja.core :as m]))
|
||||
|
||||
|
||||
(def instance
|
||||
(m/create
|
||||
(-> m/default-options
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
(ns pmagnus.elprice.web.routes.api
|
||||
(:require
|
||||
[integrant.core :as ig]
|
||||
[pmagnus.elprice.web.controllers.health :as health]
|
||||
[pmagnus.elprice.web.middleware.exception :as exception]
|
||||
[pmagnus.elprice.web.middleware.formats :as formats]
|
||||
[integrant.core :as ig]
|
||||
[reitit.coercion.malli :as malli]
|
||||
[reitit.ring.coercion :as coercion]
|
||||
[reitit.ring.middleware.muuntaja :as muuntaja]
|
||||
[reitit.ring.middleware.parameters :as parameters]
|
||||
[reitit.swagger :as swagger]))
|
||||
|
||||
|
||||
(def route-data
|
||||
{:coercion malli/coercion
|
||||
:muuntaja formats/instance
|
||||
@@ -31,8 +32,10 @@
|
||||
;; exception handling
|
||||
exception/wrap-exception]})
|
||||
|
||||
|
||||
;; Routes
|
||||
(defn api-routes [_opts]
|
||||
(defn api-routes
|
||||
[_opts]
|
||||
[["/swagger.json"
|
||||
{:get {:no-doc true
|
||||
:swagger {:info {:title "pmagnus.elprice API"}}
|
||||
@@ -43,8 +46,10 @@
|
||||
;; restarting the system
|
||||
{:get #'health/healthcheck!}]])
|
||||
|
||||
|
||||
(derive :reitit.routes/api :reitit/routes)
|
||||
|
||||
|
||||
(defmethod ig/init-key :reitit.routes/api
|
||||
[_ {:keys [base-path]
|
||||
:or {base-path ""}
|
||||
|
||||
@@ -1,39 +1,49 @@
|
||||
(ns pmagnus.elprice.web.routes.ui
|
||||
(:require
|
||||
[integrant.core :as ig]
|
||||
[pmagnus.elprice.web.controllers.eloverblik :as eloverblik]
|
||||
[pmagnus.elprice.web.controllers.prices :as prices]
|
||||
[pmagnus.elprice.web.controllers.tariffs :as tariffs]
|
||||
[pmagnus.elprice.web.htmx :refer [page fragment]]
|
||||
[pmagnus.elprice.web.middleware.exception :as exception]
|
||||
[pmagnus.elprice.web.middleware.formats :as formats]
|
||||
[pmagnus.elprice.web.routes.utils :as utils]
|
||||
[pmagnus.elprice.web.htmx :refer [page fragment]]
|
||||
[pmagnus.elprice.web.controllers.prices :as prices]
|
||||
[pmagnus.elprice.web.controllers.tariffs :as tariffs]
|
||||
[pmagnus.elprice.web.controllers.eloverblik :as eloverblik]
|
||||
[integrant.core :as ig]
|
||||
[reitit.ring.middleware.muuntaja :as muuntaja]
|
||||
[reitit.ring.middleware.parameters :as parameters])
|
||||
(:import
|
||||
[java.time LocalDateTime ZoneId]
|
||||
[java.time.format DateTimeFormatter]))
|
||||
(java.time
|
||||
LocalDateTime
|
||||
ZoneId)
|
||||
(java.time.format
|
||||
DateTimeFormatter)))
|
||||
|
||||
|
||||
(def ^:private dk-zone (ZoneId/of "Europe/Copenhagen"))
|
||||
(def ^:private hour-fmt (DateTimeFormatter/ofPattern "HH:00"))
|
||||
(def ^:private date-fmt (DateTimeFormatter/ofPattern "yyyy-MM-dd"))
|
||||
|
||||
(defn- ->ldt [time-dk]
|
||||
|
||||
(defn- ->ldt
|
||||
[time-dk]
|
||||
(cond
|
||||
(instance? LocalDateTime time-dk) time-dk
|
||||
(instance? java.sql.Timestamp time-dk)
|
||||
(.toLocalDateTime ^java.sql.Timestamp time-dk)
|
||||
:else (LocalDateTime/parse (str time-dk))))
|
||||
|
||||
(defn- format-hour [time-dk]
|
||||
|
||||
(defn- format-hour
|
||||
[time-dk]
|
||||
(.format (->ldt time-dk) hour-fmt))
|
||||
|
||||
|
||||
(defn- dkk-mwh->ore-kwh
|
||||
"Convert DKK/MWh to øre/kWh (divide by 10)."
|
||||
[price-dkk]
|
||||
(when price-dkk
|
||||
(/ (double price-dkk) 10.0)))
|
||||
|
||||
|
||||
(defn- format-ore
|
||||
"Format price as total(net) where total = net + tariff, or just net if no tariff."
|
||||
([price-dkk]
|
||||
@@ -45,31 +55,41 @@
|
||||
(format "%.1f(%.1f)" (+ ore tariff) ore)
|
||||
"-")))
|
||||
|
||||
(defn- group-by-hour [prices]
|
||||
|
||||
(defn- group-by-hour
|
||||
[prices]
|
||||
(->> prices
|
||||
(group-by #(.getHour (->ldt (:time_dk %))))
|
||||
(sort-by key)))
|
||||
|
||||
(defn- avg-ore [quarters]
|
||||
|
||||
(defn- avg-ore
|
||||
[quarters]
|
||||
(let [vals (keep :price_dkk quarters)]
|
||||
(when (seq vals)
|
||||
(/ (reduce + 0.0 (map double vals)) (count vals) 10.0))))
|
||||
|
||||
|
||||
(def ^:private red-gradient
|
||||
["bg-red-50" "bg-red-100" "bg-red-200" "bg-red-300"
|
||||
"bg-red-400" "bg-red-500" "bg-red-600" "bg-red-700"])
|
||||
|
||||
|
||||
(def ^:private green-gradient
|
||||
["bg-green-700" "bg-green-600" "bg-green-500" "bg-green-400"
|
||||
"bg-green-300" "bg-green-200" "bg-green-100" "bg-green-50"])
|
||||
|
||||
(defn- rank-bg [rank total]
|
||||
|
||||
(defn- rank-bg
|
||||
[rank total]
|
||||
(cond
|
||||
(<= rank 8) (get green-gradient (dec rank))
|
||||
(> rank (- total 8)) (get red-gradient (- rank (- total 7)))
|
||||
:else nil))
|
||||
|
||||
(defn- hour-block [hour quarters rank total-hours]
|
||||
|
||||
(defn- hour-block
|
||||
[hour quarters rank total-hours]
|
||||
(let [sorted (sort-by #(.getMinute (->ldt (:time_dk %))) quarters)
|
||||
avg (avg-ore quarters)
|
||||
month (.getMonthValue (->ldt (:time_dk (first quarters))))
|
||||
@@ -90,6 +110,7 @@
|
||||
[:span (format "%02d:%02d" hour (.getMinute (->ldt (:time_dk q))))]
|
||||
[:span {:class "font-mono"} (format-ore (:price_dkk q) tariff)]])]]))
|
||||
|
||||
|
||||
(defn- hour-ranks
|
||||
"Compute a map of hour -> rank (1 = cheapest) based on total price (avg + tariff)."
|
||||
[grouped-hours]
|
||||
@@ -103,7 +124,9 @@
|
||||
(map-indexed (fn [i [hour _]] [hour (inc i)]))
|
||||
(into {}))))
|
||||
|
||||
(defn- price-table [prices]
|
||||
|
||||
(defn- price-table
|
||||
[prices]
|
||||
[:div
|
||||
(if (seq prices)
|
||||
(let [grouped (group-by-hour prices)
|
||||
@@ -114,16 +137,21 @@
|
||||
(hour-block hour quarters (get ranks hour) total-hours))])
|
||||
[:p {:class "mt-2 text-sm text-gray-400"} "Not available yet"])])
|
||||
|
||||
|
||||
(def ^:private tab-base
|
||||
"px-4 py-2 font-medium text-sm rounded-t-lg border-2 border-b-0 ")
|
||||
|
||||
|
||||
(def ^:private tab-active
|
||||
(str tab-base "border-blue-400 bg-white text-gray-900"))
|
||||
|
||||
|
||||
(def ^:private tab-inactive
|
||||
(str tab-base "border-gray-200 bg-gray-100 text-gray-500 hover:text-gray-700 cursor-pointer"))
|
||||
|
||||
(defn- tabs [active-tab has-tomorrow?]
|
||||
|
||||
(defn- tabs
|
||||
[active-tab has-tomorrow?]
|
||||
(let [today (java.time.LocalDate/now dk-zone)
|
||||
tomorrow (.plusDays today 1)]
|
||||
[:div {:class "flex gap-1 mt-4"}
|
||||
@@ -139,17 +167,23 @@
|
||||
:hx-swap "innerHTML"}
|
||||
(str "Tomorrow " (.format tomorrow date-fmt))])]))
|
||||
|
||||
(defn- price-content [tab prices has-tomorrow?]
|
||||
|
||||
(defn- price-content
|
||||
[tab prices has-tomorrow?]
|
||||
[:div
|
||||
(tabs tab has-tomorrow?)
|
||||
[:div {:id "price-content"
|
||||
:class "border-2 border-blue-400 rounded-b-lg rounded-tr-lg p-4 bg-white"}
|
||||
(price-table prices)]])
|
||||
|
||||
(defn- has-tomorrow? [query-fn]
|
||||
|
||||
(defn- has-tomorrow?
|
||||
[query-fn]
|
||||
(seq (prices/get-tomorrow-prices query-fn)))
|
||||
|
||||
(defn home [query-fn request]
|
||||
|
||||
(defn home
|
||||
[query-fn request]
|
||||
(prices/fetch-and-save! query-fn)
|
||||
(page {:lang "en"}
|
||||
[:h1 {:class "text-2xl font-bold text-gray-900 cursor-pointer hover:text-blue-600 transition-colors"
|
||||
@@ -162,20 +196,28 @@
|
||||
[:div {:id "price-panel"}
|
||||
(price-content :today (prices/get-today-prices query-fn) (has-tomorrow? query-fn))]))
|
||||
|
||||
(defn prices-today [query-fn request]
|
||||
|
||||
(defn prices-today
|
||||
[query-fn request]
|
||||
(fragment
|
||||
(price-content :today (prices/get-today-prices query-fn) (has-tomorrow? query-fn))))
|
||||
|
||||
(defn prices-tomorrow [query-fn request]
|
||||
|
||||
(defn prices-tomorrow
|
||||
[query-fn request]
|
||||
(fragment
|
||||
(price-content :tomorrow (prices/get-tomorrow-prices query-fn) (has-tomorrow? query-fn))))
|
||||
|
||||
(defn fetch-prices [query-fn request]
|
||||
|
||||
(defn fetch-prices
|
||||
[query-fn request]
|
||||
(prices/fetch-and-save! query-fn)
|
||||
(fragment
|
||||
(price-content :today (prices/get-today-prices query-fn) (has-tomorrow? query-fn))))
|
||||
|
||||
(defn sync-eloverblik [query-fn request]
|
||||
|
||||
(defn sync-eloverblik
|
||||
[query-fn request]
|
||||
(let [date-str (get-in request [:params :date])
|
||||
date (if date-str
|
||||
(java.time.LocalDate/parse date-str)
|
||||
@@ -194,14 +236,17 @@
|
||||
(str "Synced " (:metering-points result)
|
||||
" metering points (" (:from result) " to " (:to result) ")")]))))
|
||||
|
||||
|
||||
;; Routes
|
||||
(defn ui-routes [{:keys [query-fn]}]
|
||||
(defn ui-routes
|
||||
[{:keys [query-fn]}]
|
||||
[["/" {:get (partial home query-fn)}]
|
||||
["/prices/today" {:get (partial prices-today query-fn)}]
|
||||
["/prices/tomorrow" {:get (partial prices-tomorrow query-fn)}]
|
||||
["/prices/fetch" {:post (partial fetch-prices query-fn)}]
|
||||
["/eloverblik/sync" {:post (partial sync-eloverblik query-fn)}]])
|
||||
|
||||
|
||||
(def route-data
|
||||
{:muuntaja formats/instance
|
||||
:middleware
|
||||
@@ -213,8 +258,10 @@
|
||||
;; exception handling
|
||||
exception/wrap-exception]})
|
||||
|
||||
|
||||
(derive :reitit.routes/ui :reitit/routes)
|
||||
|
||||
|
||||
(defmethod ig/init-key :reitit.routes/ui
|
||||
[_ {:keys [base-path]
|
||||
:or {base-path ""}
|
||||
|
||||
@@ -2,10 +2,12 @@
|
||||
|
||||
(def route-data-path [:reitit.core/match :data])
|
||||
|
||||
|
||||
(defn route-data
|
||||
[req]
|
||||
(get-in req route-data-path))
|
||||
|
||||
|
||||
(defn route-data-key
|
||||
[req k]
|
||||
(get-in req (conj route-data-path k)))
|
||||
|
||||
Reference in New Issue
Block a user