Compare commits

...

4 Commits

Author SHA1 Message Date
Magnus Åhall
d935eb282b Managing of problems 2024-05-01 20:01:43 +02:00
Magnus Åhall
c746343dc0 Adding datapoints to triggers 2024-05-01 10:02:33 +02:00
Magnus Åhall
b0a0f9290e Trigger expression evaluated and problems managed 2024-04-30 21:23:05 +02:00
Magnus Åhall
ffe0c3def2 Wip problem 2024-04-30 20:10:05 +02:00
24 changed files with 980 additions and 148 deletions

View File

@ -36,6 +36,7 @@ type DatapointValue struct {
ValueInt sql.NullInt64 `db:"value_int"`
ValueString sql.NullString `db:"value_string"`
ValueDateTime sql.NullTime `db:"value_datetime"`
TemplateValue any
}
func (dp DatapointValue) Value() any { // {{{
@ -53,13 +54,13 @@ func (dp DatapointValue) Value() any { // {{{
return nil
} // }}}
func (dp DatapointValue) FormattedTime() string {
func (dp DatapointValue) FormattedTime() string {// {{{
if dp.ValueDateTime.Valid {
return dp.ValueDateTime.Time.Format("2006-01-02 15:04:05")
}
return "invalid time"
}
func (dp Datapoint) Update() (err error) {
}// }}}
func (dp Datapoint) Update() (err error) {// {{{
name := strings.TrimSpace(dp.Name)
if name == "" {
err = errors.New("Name can't be empty")
@ -82,7 +83,7 @@ func (dp Datapoint) Update() (err error) {
}
return
}
}// }}}
func DatapointAdd[T any](name string, value T) (err error) { // {{{
row := service.Db.Conn.QueryRow(`SELECT id, datatype FROM datapoint WHERE name=$1`, name)

156
main.go
View File

@ -95,21 +95,22 @@ func main() { // {{{
logger.Error("application", "error", err)
return
}
_, err = service.Db.Conn.Exec(`SET TIMEZONE TO 'Europe/Stockholm'`)
if err != nil {
logger.Error("application", "error", err)
return
}
service.Register("/", false, false, staticHandler)
service.Register("/problems", false, false, pageProblems)
service.Register("/problem/acknowledge/{id}", false, false, pageProblemAcknowledge)
service.Register("/problem/unacknowledge/{id}", false, false, pageProblemUnacknowledge)
service.Register("/datapoints", false, false, pageDatapoints)
service.Register("/datapoint/edit/{id}", false, false, pageDatapointEdit)
service.Register("/datapoint/update/{id}", false, false, pageDatapointUpdate)
service.Register("/triggers", false, false, pageTriggers)
service.Register("/trigger/edit/{id}", false, false, pageTriggerEdit)
service.Register("/trigger/edit/{id}/{sectionID}", false, false, pageTriggerEdit)
service.Register("/trigger/update/{id}", false, false, pageTriggerUpdate)
service.Register("/trigger/run/{id}", false, false, pageTriggerRun)
service.Register("/configuration", false, false, pageConfiguration)
service.Register("/entry/{datapoint}", false, false, entryDatapoint)
@ -170,6 +171,45 @@ func entryDatapoint(w http.ResponseWriter, r *http.Request, sess *session.T) { /
return
}
var triggers []Trigger
triggers, err = TriggersRetrieveByDatapoint(dpoint)
if err != nil {
logger.Error("entry", "error", err)
}
for _, trigger := range triggers {
var out any
out, err = trigger.Run()
if err != nil {
err = we.Wrap(err).Log()
logger.Error("entry", "error", err)
}
logger.Debug("entry", "datapoint", dpoint, "value", value, "trigger", trigger, "result", out)
switch v := out.(type) {
case bool:
// Trigger returning true - a problem occurred
if v {
err = ProblemStart(trigger)
if err != nil {
err = we.Wrap(err).Log()
logger.Error("entry", "error", err)
}
} else {
err = ProblemClose(trigger)
if err != nil {
err = we.Wrap(err).Log()
logger.Error("entry", "error", err)
}
}
default:
err := fmt.Errorf(`Expression for trigger %s not returning bool (%T)`, trigger.Name, v)
logger.Info("entry", "error", err)
we.Wrap(err).WithData(v).Log()
}
}
j, _ := json.Marshal(struct{ OK bool }{true})
w.Write(j)
} // }}}
@ -204,8 +244,10 @@ func getPage(layout, page string) (tmpl *template.Template, err error) { // {{{
}
funcMap := template.FuncMap{
"format_time": func(t time.Time) string {
return t.Local().Format("2006-01-02 15:04:05")
"format_time": func(t time.Time) template.HTML {
return template.HTML(
t.Local().Format(`<span class="date">2006-01-02</span> <span class="time">15:04<span class="seconds">:05</span></span>`),
)
},
}
@ -233,32 +275,65 @@ func pageIndex(w http.ResponseWriter, _ *http.Request, _ *session.T) { // {{{
}
page.Render(w)
} // }}}
func pageProblems(w http.ResponseWriter, _ *http.Request, _ *session.T) { // {{{
page := Page{
LAYOUT: "main",
PAGE: "problems",
}
/*
areas, err := ProblemsRetrieve()
problems, err := ProblemsRetrieve()
if err != nil {
httpError(w, we.Wrap(err).Log())
return
}
sort.SliceStable(areas, func(i, j int) bool {
return areas[i].Name < areas[j].Name
})
logger.Info("problems", "areas", areas)
*/
page.Data = map[string]any{
//"Areas": areas,
"Problems": problems,
}
page.Render(w)
return
} // }}}
func pageDatapoints(w http.ResponseWriter, _ *http.Request, _ *session.T) { // {{{
func pageProblemAcknowledge(w http.ResponseWriter, r *http.Request, _ *session.T) { // {{{
idStr := r.PathValue("id")
id, err := strconv.Atoi(idStr)
if err != nil {
httpError(w, we.Wrap(err).Log())
return
}
err = ProblemAcknowledge(id, true)
if err != nil {
httpError(w, we.Wrap(err).Log())
return
}
w.Header().Add("Location", "/problems")
w.WriteHeader(302)
return
} // }}}
func pageProblemUnacknowledge(w http.ResponseWriter, r *http.Request, _ *session.T) { // {{{
idStr := r.PathValue("id")
id, err := strconv.Atoi(idStr)
if err != nil {
httpError(w, we.Wrap(err).Log())
return
}
err = ProblemAcknowledge(id, false)
if err != nil {
httpError(w, we.Wrap(err).Log())
return
}
w.Header().Add("Location", "/problems")
w.WriteHeader(302)
return
} // }}}
func pageDatapoints(w http.ResponseWriter, r *http.Request, _ *session.T) { // {{{
page := Page{
LAYOUT: "main",
PAGE: "datapoints",
@ -269,7 +344,13 @@ func pageDatapoints(w http.ResponseWriter, _ *http.Request, _ *session.T) { // {
httpError(w, we.Wrap(err).Log())
return
}
logger.Info("FOO", "dps", datapoints)
// The datapoint selector in trigger edit wants the raw data in JSON.
if r.URL.Query().Get("format") == "json" {
j, _ := json.Marshal(datapoints)
w.Write(j)
return
}
page.Data = map[string]any{
"Datapoints": datapoints,
@ -332,6 +413,7 @@ func pageDatapointUpdate(w http.ResponseWriter, r *http.Request, _ *session.T) {
w.Header().Add("Location", "/datapoints")
w.WriteHeader(302)
} // }}}
func pageTriggers(w http.ResponseWriter, _ *http.Request, _ *session.T) { // {{{
areas, err := TriggersRetrieve()
if err != nil {
@ -361,12 +443,27 @@ func pageTriggerEdit(w http.ResponseWriter, r *http.Request, _ *session.T) { //
return
}
// Creating a new trigger uses the edit function.
// ID == 0 - create a new trigger.
// ID > 0 - edit existing trigger.
var trigger Trigger
if id > 0 {
trigger, err = TriggerRetrieve(id)
if err != nil {
httpError(w, we.Wrap(err).Log())
return
}
} else {
// A new trigger needs to know which section it belongs to.
sectionIDStr := r.PathValue("sectionID")
if sectionIDStr != "" {
trigger.SectionID, err = strconv.Atoi(sectionIDStr)
if err != nil {
httpError(w, we.Wrap(err).Log())
return
}
}
}
datapoints := make(map[string]Datapoint)
for _, dpname := range trigger.Datapoints {
@ -375,6 +472,7 @@ func pageTriggerEdit(w http.ResponseWriter, r *http.Request, _ *session.T) { //
httpError(w, we.Wrap(err).Log())
return
}
dp.LastDatapointValue.TemplateValue = dp.LastDatapointValue.Value()
datapoints[dpname] = dp
}
@ -401,14 +499,23 @@ func pageTriggerUpdate(w http.ResponseWriter, r *http.Request, _ *session.T) { /
}
var trigger Trigger
if id > 0 {
trigger, err = TriggerRetrieve(id)
if err != nil {
httpError(w, we.Wrap(err).Log())
return
}
} else {
trigger.SectionID, err = strconv.Atoi(r.FormValue("sectionID"))
if err != nil {
httpError(w, we.Wrap(err).Log())
return
}
}
trigger.Name = r.FormValue("name")
trigger.Expression = r.FormValue("expression")
trigger.Datapoints = r.Form["datapoints[]"]
err = trigger.Update()
if err != nil {
httpError(w, we.Wrap(err).Log())
@ -436,23 +543,13 @@ func pageTriggerRun(w http.ResponseWriter, r *http.Request, _ *session.T) { // {
expr, _ := io.ReadAll(r.Body)
trigger.Expression = string(expr)
datapoints := make(map[string]Datapoint)
for _, dpname := range trigger.Datapoints {
dp, err := DatapointRetrieve(0, dpname)
if err != nil {
httpError(w, we.Wrap(err).Log())
return
}
datapoints[dpname] = dp
}
resp := struct {
OK bool
Output any
}{
OK: true,
}
resp.Output, err = trigger.Run(datapoints)
resp.Output, err = trigger.Run()
if err != nil {
we.Wrap(err).Log()
httpError(w, err)
@ -463,6 +560,7 @@ func pageTriggerRun(w http.ResponseWriter, r *http.Request, _ *session.T) { // {
w.Header().Add("Content-Type", "application/json")
w.Write(j)
} // }}}
func pageConfiguration(w http.ResponseWriter, _ *http.Request, _ *session.T) { // {{{
areas, err := AreaRetrieve()
if err != nil {

View File

@ -52,7 +52,6 @@ func (p *Page) Render(w http.ResponseWriter) {
"Data": p.Data,
}
logger.Info("foo", "tmpl", tmpl)
err = tmpl.Execute(w, data)
if err != nil {
httpError(w, we.Wrap(err).Log())

View File

@ -2,19 +2,108 @@ package main
import (
// External
// we "git.gibonuddevalla.se/go/wrappederror"
we "git.gibonuddevalla.se/go/wrappederror"
// Standard
// "encoding/json"
"database/sql"
"encoding/json"
"time"
)
/*
type Problem struct {
ID int
Name string
SectionID int
Expression string
DatapointNames []string
Start time.Time
End sql.NullTime
Acknowledged bool
TriggerID int `json:"trigger_id"`
TriggerName string `json:"trigger_name"`
AreaName string `json:"area_name"`
SectionName string `json:"section_name"`
}
*/
func ProblemsRetrieve() (problems []Problem, err error) {
problems = []Problem{}
row := service.Db.Conn.QueryRow(`
SELECT
jsonb_agg(p.*)
FROM (
SELECT
p.id,
p.start,
p.end,
p.acknowledged,
t.id AS trigger_id,
t.name AS trigger_name,
a.name AS area_name,
s.name AS section_name
FROM problem p
INNER JOIN "trigger" t ON p.trigger_id = t.id
INNER JOIN section s ON t.section_id = s.id
INNER JOIN area a ON s.area_id = a.id
WHERE
p.end IS NULL
ORDER BY p.start DESC
) p
`)
var jsonBody []byte
err = row.Scan(&jsonBody)
if err != nil {
err = we.Wrap(err)
return
}
err = json.Unmarshal(jsonBody, &problems)
if err != nil {
err = we.Wrap(err)
}
return
}
func ProblemStart(trigger Trigger) (err error) {
row := service.Db.Conn.QueryRow(`
SELECT COUNT(id)
FROM problem
WHERE
trigger_id = $1 AND
"end" IS NULL
GROUP BY trigger_id
`,
trigger.ID,
)
var openProblems int
err = row.Scan(&openProblems)
if err != nil && err != sql.ErrNoRows {
err = we.Wrap(err).WithData(trigger.ID)
return
}
// Open up a new problem if no open exists.
if openProblems == 0 {
_, err = service.Db.Conn.Exec(`INSERT INTO problem(trigger_id) VALUES($1)`, trigger.ID)
if err != nil {
err = we.Wrap(err).WithData(trigger)
}
}
return
}
func ProblemClose(trigger Trigger) (err error) {
_, err = service.Db.Conn.Exec(`UPDATE problem SET "end"=NOW() WHERE trigger_id=$1 AND "end" IS NULL`, trigger.ID)
if err != nil {
err = we.Wrap(err).WithData(trigger)
return
}
return
}
func ProblemAcknowledge(id int, state bool) (err error) {
_, err = service.Db.Conn.Exec(`UPDATE problem SET "acknowledged"=$2 WHERE id=$1`, id, state)
if err != nil {
err = we.Wrap(err).WithData(id)
return
}
return
}

1
sql/00008.sql Normal file
View File

@ -0,0 +1 @@
ALTER TABLE public."trigger" ADD CONSTRAINT trigger_sectionname_unique UNIQUE (section_id,"name");

View File

@ -37,7 +37,7 @@ h2 {
font-size: 1.25em;
}
a {
color: #3f9da1;
color: #fabd2f;
text-decoration: none;
}
a:hover {
@ -70,13 +70,31 @@ button {
background: #202020;
color: #d5c4a1;
padding: 8px 32px;
border: 1px solid #3a3a3a;
border: 1px solid #535353;
font-size: 1em;
height: 3em;
}
button:focus {
background: #333;
}
.line {
grid-column: 1 / -1;
border-bottom: 1px solid #4e4e4e;
}
span.date {
color: #d5c4a1;
font-weight: 500;
}
span.time {
font-size: 0.9em;
color: #d5c4a1;
}
span.seconds {
display: none;
}
label {
user-select: none;
}
#datapoints {
display: grid;
grid-template-columns: repeat(4, min-content);
@ -102,10 +120,10 @@ button:focus {
width: 100%;
}
.widgets .datapoints {
font: "Roboto Mono", monospace;
display: grid;
grid-template-columns: min-content 1fr;
gap: 6px 8px;
font-family: "Roboto Mono", monospace;
margin-bottom: 8px;
}
.widgets .action {

View File

@ -37,7 +37,7 @@ h2 {
font-size: 1.25em;
}
a {
color: #3f9da1;
color: #fabd2f;
text-decoration: none;
}
a:hover {
@ -70,13 +70,31 @@ button {
background: #202020;
color: #d5c4a1;
padding: 8px 32px;
border: 1px solid #3a3a3a;
border: 1px solid #535353;
font-size: 1em;
height: 3em;
}
button:focus {
background: #333;
}
.line {
grid-column: 1 / -1;
border-bottom: 1px solid #4e4e4e;
}
span.date {
color: #d5c4a1;
font-weight: 500;
}
span.time {
font-size: 0.9em;
color: #d5c4a1;
}
span.seconds {
display: none;
}
label {
user-select: none;
}
#layout {
display: grid;
grid-template-areas: "menu content";
@ -137,12 +155,17 @@ button:focus {
#areas .area .section {
margin: 8px 16px;
}
#areas .area .section > .name {
#areas .area .section .create {
display: grid;
grid-template-columns: min-content min-content;
grid-gap: 8px;
white-space: nowrap;
}
#areas .area .section .create .new {
font-weight: 500;
}
#areas .area .section .triggers a {
color: inherit;
text-decoration: none;
#areas .area .section > .name {
font-weight: 500;
}
#areas .area .section .triggers .trigger {
display: grid;
@ -155,5 +178,11 @@ button:focus {
height: 16px;
}
#areas .area .section .triggers .trigger .label {
color: #3f9da1;
color: inherit;
}
dialog {
background: #202020;
border: 1px solid #606060;
color: #d5c4a1;
box-shadow: 10px 10px 15px 0px rgba(0, 0, 0, 0.25);
}

124
static/css/problems.css Normal file
View File

@ -0,0 +1,124 @@
html {
box-sizing: border-box;
}
*,
*:before,
*:after {
box-sizing: inherit;
}
*:focus {
outline: none;
}
[onClick] {
cursor: pointer;
}
html,
body {
margin: 0;
padding: 0;
}
body {
background: #282828;
font-family: "Roboto", sans-serif;
font-weight: 300;
color: #d5c4a1;
font-size: 11pt;
}
h1,
h2 {
margin-top: 0px;
margin-bottom: 4px;
}
h1 {
font-size: 1.5em;
color: #fb4934;
}
h2 {
font-size: 1.25em;
}
a {
color: #fabd2f;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
b {
font-weight: 500;
}
.roboto-light {
font-family: "Roboto", sans-serif;
font-weight: 300;
font-style: normal;
}
.roboto-medium {
font-family: "Roboto", sans-serif;
font-weight: 500;
font-style: normal;
}
input[type="text"],
textarea,
select {
font-family: "Roboto Mono", monospace;
background: #202020;
color: #d5c4a1;
padding: 4px 8px;
border: none;
font-size: 1em;
}
button {
background: #202020;
color: #d5c4a1;
padding: 8px 32px;
border: 1px solid #535353;
font-size: 1em;
height: 3em;
}
button:focus {
background: #333;
}
.line {
grid-column: 1 / -1;
border-bottom: 1px solid #4e4e4e;
}
span.date {
color: #d5c4a1;
font-weight: 500;
}
span.time {
font-size: 0.9em;
color: #d5c4a1;
}
span.seconds {
display: none;
}
label {
user-select: none;
}
#problems-list,
#acknowledged-list {
display: grid;
grid-template-columns: repeat(5, min-content);
grid-gap: 4px 16px;
margin-bottom: 32px;
}
#problems-list div,
#acknowledged-list div {
white-space: nowrap;
}
#problems-list .header,
#acknowledged-list .header {
font-weight: 500;
}
#problems-list .trigger,
#acknowledged-list .trigger {
color: #fb4934;
font-weight: 500;
}
#problems-list .acknowledge img,
#acknowledged-list .acknowledge img {
height: 16px;
}
#acknowledged-list.hidden {
display: none;
}

View File

@ -37,7 +37,7 @@ h2 {
font-size: 1.25em;
}
a {
color: #3f9da1;
color: #fabd2f;
text-decoration: none;
}
a:hover {
@ -70,10 +70,28 @@ button {
background: #202020;
color: #d5c4a1;
padding: 8px 32px;
border: 1px solid #3a3a3a;
border: 1px solid #535353;
font-size: 1em;
height: 3em;
}
button:focus {
background: #333;
}
.line {
grid-column: 1 / -1;
border-bottom: 1px solid #4e4e4e;
}
span.date {
color: #d5c4a1;
font-weight: 500;
}
span.time {
font-size: 0.9em;
color: #d5c4a1;
}
span.seconds {
display: none;
}
label {
user-select: none;
}

View File

@ -37,7 +37,7 @@ h2 {
font-size: 1.25em;
}
a {
color: #3f9da1;
color: #fabd2f;
text-decoration: none;
}
a:hover {
@ -70,13 +70,31 @@ button {
background: #202020;
color: #d5c4a1;
padding: 8px 32px;
border: 1px solid #3a3a3a;
border: 1px solid #535353;
font-size: 1em;
height: 3em;
}
button:focus {
background: #333;
}
.line {
grid-column: 1 / -1;
border-bottom: 1px solid #4e4e4e;
}
span.date {
color: #d5c4a1;
font-weight: 500;
}
span.time {
font-size: 0.9em;
color: #d5c4a1;
}
span.seconds {
display: none;
}
label {
user-select: none;
}
.widgets {
display: grid;
grid-template-columns: min-content 1fr;

View File

@ -0,0 +1,67 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
width="31.999987"
height="29.090721"
viewBox="0 0 8.4666629 7.6969202"
version="1.1"
id="svg8"
inkscape:version="1.3.2 (1:1.3.2+202311252150+091e20ef0f)"
sodipodi:docname="acknowledge-filled.svg"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:dc="http://purl.org/dc/elements/1.1/">
<defs
id="defs2" />
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="1"
inkscape:cx="11.5"
inkscape:cy="10"
inkscape:document-units="px"
inkscape:current-layer="layer1"
showgrid="false"
units="px"
inkscape:window-width="2190"
inkscape:window-height="1404"
inkscape:window-x="1463"
inkscape:window-y="16"
inkscape:window-maximized="0"
inkscape:showpageshadow="true"
inkscape:pagecheckerboard="0"
inkscape:deskcolor="#d6d6d6"
showborder="true" />
<metadata
id="metadata5">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
</cc:Work>
</rdf:RDF>
</metadata>
<g
inkscape:label="Layer 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(-89.958296,-148.43122)">
<title
id="title1">thumb-up</title>
<path
d="m 98.424959,151.89488 c 0,-0.42719 -0.346361,-0.7697 -0.769692,-0.7697 h -2.432224 l 0.369452,-1.75874 c 0.0077,-0.0385 0.01149,-0.0809 0.01149,-0.1232 0,-0.15778 -0.06542,-0.30402 -0.169332,-0.40794 l -0.407941,-0.40408 -2.532284,2.53229 c -0.142399,0.1424 -0.227059,0.33482 -0.227059,0.54648 v 3.84845 a 0.76969147,0.76969147 0 0 0 0.769691,0.7697 h 3.463611 c 0.319422,0 0.592664,-0.19242 0.708117,-0.46951 l 1.162234,-2.71317 c 0.03463,-0.0884 0.05388,-0.18087 0.05388,-0.28093 v -0.7697 m -8.466606,4.23331 h 1.539382 v -4.61815 h -1.539382 z"
id="path1"
style="stroke-width:0.384845;fill:#fb4934;fill-opacity:1" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.4 KiB

View File

@ -0,0 +1,69 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
width="31.999987"
height="29.090721"
viewBox="0 0 8.4666629 7.6969202"
version="1.1"
id="svg8"
inkscape:version="1.3.2 (1:1.3.2+202311252150+091e20ef0f)"
sodipodi:docname="acknowledge-outline.svg"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:dc="http://purl.org/dc/elements/1.1/">
<defs
id="defs2" />
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="1"
inkscape:cx="11.5"
inkscape:cy="10"
inkscape:document-units="px"
inkscape:current-layer="layer1"
showgrid="false"
units="px"
inkscape:window-width="2190"
inkscape:window-height="1404"
inkscape:window-x="1463"
inkscape:window-y="16"
inkscape:window-maximized="0"
inkscape:showpageshadow="true"
inkscape:pagecheckerboard="0"
inkscape:deskcolor="#d6d6d6"
showborder="true" />
<metadata
id="metadata5">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
</cc:Work>
</rdf:RDF>
</metadata>
<g
inkscape:label="Layer 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(-89.958296,-148.43122)">
<title
id="title1">thumb-up</title>
<title
id="title1-3">thumb-up-outline</title>
<path
d="m 91.497681,151.50999 v 4.61815 h -1.539385 v -4.61815 h 1.539385 m 1.539383,4.61815 a 0.76969186,0.76969186 0 0 1 -0.769692,-0.76969 v -3.84846 c 0,-0.21166 0.08467,-0.40408 0.22706,-0.54263 l 2.532286,-2.53614 0.407936,0.40794 c 0.103912,0.10385 0.169333,0.24631 0.169333,0.40408 l -0.01149,0.1232 -0.365604,1.75875 h 2.428378 c 0.42718,0 0.769693,0.34636 0.769693,0.76969 v 0.76969 c 0,0.10008 -0.01924,0.19242 -0.05388,0.28095 l -1.162236,2.71316 c -0.115446,0.27709 -0.388694,0.46951 -0.708116,0.46951 h -3.463613 m 0,-0.7697 h 3.47516 l 1.142991,-2.69392 v -0.76969 h -3.382795 l 0.434876,-2.04738 -1.670232,1.67408 z"
id="path1"
style="stroke-width:0.384845;fill:#fb4934;fill-opacity:1" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.6 KiB

23
static/js/problems.mjs Normal file
View File

@ -0,0 +1,23 @@
export class UI {
constructor() {
const showAcked = localStorage.getItem('show_acknowledged')
if (showAcked == 'true') {
document.getElementById('show-acked').checked = true
const list = document.getElementById('acknowledged-list')
list.classList.remove('hidden')
}
}
toggleAcknowledged(evt) {
const list = document.getElementById('acknowledged-list')
if (evt.target.checked) {
list.classList.remove('hidden')
localStorage.setItem('show_acknowledged', true)
} else {
list.classList.add('hidden')
localStorage.setItem('show_acknowledged', false)
}
}
}

View File

@ -1,17 +1,35 @@
export class UI {
constructor() {
constructor() {//{{{
document.getElementById('button-run').
addEventListener('click', evt=>evt.preventDefault())
addEventListener('click', evt => evt.preventDefault())
document.addEventListener('keydown', evt=>this.keyHandler(evt))
}
setTrigger(t) {
document.addEventListener('keydown', evt => this.keyHandler(evt))
document.querySelector('input[name="name"]').focus()
this.datapoints = []
}//}}}
render() {//{{{
document.querySelectorAll('.datapoints .datapoint').forEach(el => el.remove());
const datapoints = document.querySelector('.datapoints')
let html = Object.keys(this.trigger.datapoints).sort().map(dpName => {
const dp = this.trigger.datapoints[dpName]
return `
<div class="datapoint name"><b>${dp.Name}</b></div>
<div class="datapoint value">${dp.LastDatapointValue.TemplateValue}</div>
`
}).join('')
datapoints.innerHTML += html
}//}}}
setTrigger(t) {//{{{
this.trigger = t
}
run() {
}//}}}
run() {//{{{
this.trigger.run()
}
keyHandler(evt) {
}//}}}
keyHandler(evt) {//{{{
if (!(evt.altKey && evt.shiftKey))
return
@ -24,18 +42,72 @@ export class UI {
break
case 'S':
document.getElementById('form-trigger').submit()
this.update()
break
}
}//}}}
addDatapoint() {//{{{
const dlg = document.getElementById('dlg-datapoints')
const datalist = document.getElementById('list-datapoints')
dlg.showModal()
fetch('/datapoints?format=json')
.then(data => data.json())
.then(json => {
this.datapoints = json
let html = ''
this.datapoints.forEach(dp => {
html += `<option value="${dp.Name}">`
})
datalist.innerHTML = html
})
.catch(err => alert(err))
}//}}}
chooseDatapoint() {//{{{
const dlg = document.getElementById('dlg-datapoints')
const datapoint = document.getElementById('datapoint').value
const dp = this.datapoints.find(dp => dp.Name == datapoint)
if (dp === undefined) {
alert('Invalid datapoint')
return
}
this.trigger.addDatapoint(dp)
dlg.close()
this.render()
}//}}}
update() {//{{{
const form = document.getElementById('form-trigger')
var formData = new FormData(form)
Object.keys(this.trigger.datapoints).forEach(name => formData.append("datapoints[]", name))
fetch(form.action, {
method: 'POST',
body: formData,
})
.then(resp => {
if (resp.redirected) {
location.href = resp.url
return
}
return resp.json()
})
.then(json => {
if (json)
alert(json.Error)
})
.catch(err => alert(err))
}//}}}
}
export class Trigger {
constructor(id, name) {
constructor(id, name, datapoints) {//{{{
this.id = id
this.name = name
}
run() {
this.datapoints = datapoints
}//}}}
run() {//{{{
const result = document.getElementById('run-result')
const classes = result.classList
const expr = document.getElementById('expr').value
@ -59,5 +131,8 @@ export class Trigger {
result.innerText = json.Output
})
.catch(err => alert(err))
}
}//}}}
addDatapoint(dp) {//{{{
this.datapoints[dp.Name] = dp
}//}}}
}

View File

@ -29,10 +29,10 @@
}
.datapoints {
font: "Roboto Mono", monospace;
display: grid;
grid-template-columns: min-content 1fr;
gap: 6px 8px;
font-family: "Roboto Mono", monospace;
margin-bottom: 8px;
}

View File

@ -71,17 +71,22 @@
.section {
margin: 8px 16px;
.create {
display: grid;
grid-template-columns: min-content min-content;
grid-gap: 8px;
white-space: nowrap;
.new {
font-weight: @bold;
}
}
&>.name {
font-weight: 500;
font-weight: @bold;
}
.triggers {
a {
color: inherit;
text-decoration: none;
}
.trigger {
display: grid;
grid-template-columns: min-content 1fr;
@ -94,10 +99,17 @@
}
.label {
color: @color4;
color: inherit;
}
}
}
}
}
}
dialog {
background: @bg2;
border: 1px solid lighten(@bg2, 25%);
color: @text1;
box-shadow: 10px 10px 15px 0px rgba(0, 0, 0, 0.25);
}

31
static/less/problems.less Normal file
View File

@ -0,0 +1,31 @@
@import "theme.less";
#problems-list, #acknowledged-list {
display: grid;
grid-template-columns: repeat(5, min-content);
grid-gap: 4px 16px;
margin-bottom: 32px;
div {
white-space: nowrap;
}
.header {
font-weight: @bold;
}
.trigger {
color: @color1;
font-weight: @bold;
}
.acknowledge {
img {
height: 16px;
}
}
}
#acknowledged-list.hidden{
display: none;
}

View File

@ -14,11 +14,17 @@
@bold: 500;
.lighterOrDarker(@color, @amount) {
@result: lighten(@color, @amount);
}
html {
box-sizing: border-box;
}
*, *:before, *:after {
*,
*:before,
*:after {
box-sizing: inherit;
}
@ -44,7 +50,8 @@ body {
font-size: 11pt;
}
h1, h2 {
h1,
h2 {
margin-top: 0px;
margin-bottom: 4px;
}
@ -59,7 +66,7 @@ h2 {
}
a {
color: @color4;
color: @color2;
text-decoration: none;
&:hover {
@ -83,7 +90,9 @@ b {
font-style: normal;
}
input[type="text"], textarea, select {
input[type="text"],
textarea,
select {
font-family: "Roboto Mono", monospace;
background: @bg2;
color: @text1;
@ -96,7 +105,7 @@ button {
background: @bg2;
color: @text1;
padding: 8px 32px;
border: 1px solid lighten(@bg2, 10%);
border: 1px solid lighten(@bg2, 20%);
font-size: 1em;
height: 3em;
@ -104,3 +113,26 @@ button {
background: @bg3;
}
}
.line {
grid-column: 1 / -1;
border-bottom: 1px solid .lighterOrDarker(@bg1, 15%)[@result];
}
span.date {
color: @text1;
font-weight: @bold;
}
span.time {
font-size: 0.9em;
color: @text1;
}
span.seconds {
display: none;
}
label {
user-select: none;
}

View File

@ -1,5 +1,8 @@
@import "theme.less";
#dlg-datapoints {
}
.widgets {
display: grid;
grid-template-columns: min-content 1fr;

View File

@ -4,6 +4,7 @@ import (
// External
we "git.gibonuddevalla.se/go/wrappederror"
"github.com/expr-lang/expr"
"github.com/lib/pq"
// Standard
"encoding/json"
@ -19,9 +20,6 @@ type Trigger struct {
Datapoints []string
}
func Foo() {
}
func TriggersRetrieve() (areas []Area, err error) { // {{{
areas = []Area{}
@ -73,6 +71,32 @@ func TriggersRetrieve() (areas []Area, err error) { // {{{
return
} // }}}
func TriggersRetrieveByDatapoint(datapointName string) (triggers []Trigger, err error) { // {{{
triggers = []Trigger{}
row := service.Db.Conn.QueryRow(`
SELECT jsonb_agg(t.*)
FROM public."trigger" t
WHERE
datapoints @> $1
`,
fmt.Sprintf(`["%s"]`, datapointName),
)
var data []byte
err = row.Scan(&data)
if err != nil {
err = we.Wrap(err).WithData(datapointName)
return
}
err = json.Unmarshal(data, &triggers)
if err != nil {
err = we.Wrap(err).WithData(datapointName)
return
}
return
} // }}}
func TriggerRetrieve(id int) (trigger Trigger, err error) { // {{{
row := service.Db.Conn.QueryRow(`SELECT to_jsonb(t.*) FROM "trigger" t WHERE id=$1`, id)
var jsonData []byte
@ -85,7 +109,7 @@ func TriggerRetrieve(id int) (trigger Trigger, err error) { // {{{
err = json.Unmarshal(jsonData, &trigger)
return
} // }}}
func (t *Trigger) Validate() (ok bool, err error) {
func (t *Trigger) Validate() (ok bool, err error) { // {{{
if strings.TrimSpace(t.Name) == "" {
err = fmt.Errorf("Name can't be empty")
return
@ -97,33 +121,73 @@ func (t *Trigger) Validate() (ok bool, err error) {
}
return true, nil
}
func (t *Trigger) Update() (err error) {
} // }}}
func (t *Trigger) Update() (err error) { // {{{
var ok bool
if ok, err = t.Validate(); !ok {
return
}
logger.Info("FOO", "trigger", t)
if t.Datapoints == nil {
t.Datapoints = []string{}
}
jsonDatapoints, _ := json.Marshal(t.Datapoints)
if t.ID == 0 {
_, err = service.Db.Conn.Exec(`
INSERT INTO "trigger"(name, section_id, expression, datapoints)
VALUES($1, $2, $3, $4)
`,
t.Name,
t.SectionID,
t.Expression,
jsonDatapoints,
)
} else {
_, err = service.Db.Conn.Exec(`
UPDATE "trigger"
SET
name=$2,
expression=$3
expression=$3,
datapoints=$4
WHERE
id=$1
`,
t.ID,
t.Name,
t.Expression,
jsonDatapoints,
)
if err != nil {
err = we.Wrap(err)
}
if pqErr, ok := err.(*pq.Error); ok {
err = we.Wrap(err).WithData(
struct {
Trigger *Trigger
PostgresCode pq.ErrorCode
PostgresMsg string
}{
t,
pqErr.Code,
pqErr.Code.Name(),
})
} else if err != nil {
err = we.Wrap(err).WithData(t)
}
return
}
} // }}}
func (t *Trigger) Run() (output any, err error) { // {{{
datapoints := make(map[string]Datapoint)
for _, dpname := range t.Datapoints {
var dp Datapoint
dp, err = DatapointRetrieve(0, dpname)
if err != nil {
err = we.Wrap(err)
return
}
datapoints[dpname] = dp
}
func (t *Trigger) Run(datapoints map[string]Datapoint) (output any, err error) {
env := make(map[string]any)
for dpName, dp := range datapoints {
env[dpName] = dp.LastDatapointValue.Value()
@ -138,6 +202,5 @@ func (t *Trigger) Run(datapoints map[string]Datapoint) (output any, err error) {
if err != nil {
return
}
return
}
} // }}}

View File

@ -12,6 +12,7 @@
<div class="header">Value</div>
{{ range .Data.Datapoints }}
<div class="line"></div>
<div class="name"><a href="/datapoint/edit/{{ .ID }}">{{ .Name }}</a></div>
<div class="datatype">{{ .Datatype }}</div>
<div class="last-value">{{ format_time .LastValue }}</div>

View File

@ -1,6 +1,56 @@
{{ define "page" }}
{{ $version := .VERSION }}
<script type="module" defer>
import {UI} from "/js/{{ .VERSION }}/problems.mjs"
window._ui = new UI()
</script>
<link rel="stylesheet" type="text/css" href="/css/{{ .VERSION }}/problems.css">
{{ block "page_label" . }}{{end}}
<div id="problems-list">
<div style="grid-column: 1/-1; margin-top: 32px;"><h2>Current</h2></div>
<div class="header">Trigger</div>
<div class="header">Area</div>
<div class="header">Section</div>
<div class="header">Since</div>
{{ range .Data.Problems }}
{{ if .Acknowledged }}
{{ continue }}
{{ end }}
<div class="line"></div>
<div class="trigger"><a href="/trigger/edit/{{ .TriggerID }}">{{ .TriggerName }}</a></div>
<div class="area">{{ .AreaName }}</div>
<div class="section">{{ .SectionName }}</div>
<div class="start">{{ format_time .Start }}</div>
<div class="acknowledge"><a href="/problem/acknowledge/{{ .ID }}"><img src="/images/{{ $version }}/acknowledge-filled.svg"></a></div>
{{ end }}
</div>
<input type="checkbox" id="show-acked" onclick="_ui.toggleAcknowledged(event)"> <label for="show-acked">Show acknowledged</label>
<div id="acknowledged-list" class="hidden">
<div style="grid-column: 1/-1; margin-top: 32px;"><h2>Acknowledged</h2></div>
<div class="header">Trigger</div>
<div class="header">Area</div>
<div class="header">Section</div>
<div class="header">Since</div>
{{ range .Data.Problems }}
{{ if not .Acknowledged }}
{{ continue }}
{{ end }}
<div class="line"></div>
<div class="trigger"><a href="/trigger/edit/{{ .TriggerID }}">{{ .TriggerName }}</a></div>
<div class="area">{{ .AreaName }}</div>
<div class="section">{{ .SectionName }}</div>
<div class="start">{{ format_time .Start }}</div>
<div class="acknowledge"><a href="/problem/unacknowledge/{{ .ID }}"><img src="/images/{{ $version }}/acknowledge-outline.svg"></a></div>
{{ end }}
</div>
<div id="areas">
{{ range .Data.Areas }}
<div class="area">

View File

@ -6,24 +6,31 @@
let trigger = new Trigger(
{{ .Data.Trigger.ID }},
'{{ .Data.Trigger.Name }}',
{{ .Data.Datapoints }},
)
_ui.setTrigger(trigger)
_ui.render()
</script>
<link rel="stylesheet" type="text/css" href="/css/{{ .VERSION }}/trigger_edit.css">
{{ block "page_label" . }}{{end}}
<dialog id="dlg-datapoints">
<input list="list-datapoints" id="datapoint">
<datalist id="list-datapoints"></datalist>
<button onclick="_ui.chooseDatapoint()">OK</button>
</dialog>
<form id="form-trigger" action="/trigger/update/{{ .Data.Trigger.ID }}" method="post">
<input type="hidden" name="sectionID" value="{{ .Data.Trigger.SectionID }}">
<div id="widgets" class="widgets">
<div class="label">Name</div>
<div><input type="text" name="name" value="{{ .Data.Trigger.Name }}"></div>
<div class="label">Datapoints</div>
<div class="datapoints" style="margin-top: 4px">
{{ range .Data.Datapoints }}
<div class="datapoint name"><b>{{ .Name }}</b></div>
<div class="datapoint value">{{ .LastDatapointValue.Value }}</div>
{{ end }}
<div><a onclick="_ui.addDatapoint()">Add</a></div>
<div></div>
</div>
<div class="label">Expression</div>
@ -31,10 +38,11 @@
<div></div>
<div class="action">
<button id="button-update">Update</button>
<button id="button-update" onclick="_ui.update(); return false">{{ if eq .Data.Trigger.ID 0 }}Create{{ else }}Update{{ end }}</button>
<button id="button-run" onclick="window._ui.run(); return false">Test</button>
<div id="run-result"></div>
</div>
</div>
</form>
{{ end }}

View File

@ -9,7 +9,10 @@
<div class="name">{{ .Name }}</div>
{{ range .SortedSections }}
<div class="section">
<div class="create">
<div class="name">{{ .Name }}</div>
<div class="new"><a href="/trigger/edit/0/{{ .ID }}">+</a></div>
</div>
<div class="triggers">
{{ range .SortedTriggers }}