Compare commits
21 Commits
Author | SHA1 | Date | |
---|---|---|---|
2586f0749f | |||
1387eecc96 | |||
32563d7d33 | |||
12b00e5147 | |||
0051ae71d9 | |||
0e64ff9eb2 | |||
8fd8d53cc3 | |||
a6626761e7 | |||
1983c6c932 | |||
6bfd5cc26a | |||
abb25c1357 | |||
e0eb7f9748 | |||
b291fec8a0 | |||
d290cae3f7 | |||
376201373e | |||
84002d1856 | |||
3118069297 | |||
80fb660677 | |||
de461cb031 | |||
6d684b34ef | |||
35ca7620f4 |
12
app.go
12
app.go
@@ -2,6 +2,7 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"os"
|
||||||
)
|
)
|
||||||
|
|
||||||
// App struct
|
// App struct
|
||||||
@@ -43,12 +44,12 @@ func (a *App) UpdateFood(food Food) WailsFood1 {
|
|||||||
return WailsFood1{Data: data, Success: true}
|
return WailsFood1{Data: data, Success: true}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *App) GetLastPer100(name string) WailsPer100 {
|
func (a *App) GetLastPer100(name string) WailsFoodSearch {
|
||||||
data, err := foodService.GetLastPer100(name)
|
data, err := foodService.GetLastPer100(name)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return WailsPer100{Success: false, Error: err.Error()}
|
return WailsFoodSearch{Success: false, Error: err.Error()}
|
||||||
}
|
}
|
||||||
return WailsPer100{Data: data, Success: true}
|
return WailsFoodSearch{Data: data, Success: true}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *App) GetDailyFood() WailsAggregateFood {
|
func (a *App) GetDailyFood() WailsAggregateFood {
|
||||||
@@ -135,3 +136,8 @@ func (a *App) SetSetting(key string, value int64) WailsGenericAck {
|
|||||||
}
|
}
|
||||||
return WailsGenericAck{Success: true}
|
return WailsGenericAck{Success: true}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//region other
|
||||||
|
func (a *App) Close() {
|
||||||
|
os.Exit(0)
|
||||||
|
}
|
85
db.go
85
db.go
@@ -3,9 +3,11 @@ package main
|
|||||||
import (
|
import (
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
_ "github.com/mattn/go-sqlite3"
|
"github.com/mattn/go-sqlite3"
|
||||||
)
|
)
|
||||||
|
|
||||||
type DB struct {
|
type DB struct {
|
||||||
@@ -20,7 +22,27 @@ func (db *DB) Open() error {
|
|||||||
return fmt.Errorf("database path not set")
|
return fmt.Errorf("database path not set")
|
||||||
}
|
}
|
||||||
|
|
||||||
writeConn, err := sql.Open("sqlite3", db.path+"?_journal=WAL&_synchronous=NORMAL")
|
file, err := os.Open(db.path)
|
||||||
|
if err != nil {
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
log.Printf("Database file does not exist at %s, creating", db.path)
|
||||||
|
file, err := os.Create(db.path)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to create database file: %v", err)
|
||||||
|
}
|
||||||
|
log.Printf("Database created at %s", db.path)
|
||||||
|
file.Close()
|
||||||
|
} else {
|
||||||
|
return fmt.Errorf("failed to open database file: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
file.Close()
|
||||||
|
|
||||||
|
sql.Register("spellfixlite", &sqlite3.SQLiteDriver{
|
||||||
|
Extensions: []string{"spellfix"},
|
||||||
|
})
|
||||||
|
|
||||||
|
writeConn, err := sql.Open("spellfixlite", db.path+"?_journal=WAL&_synchronous=NORMAL")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
Error.Printf("%++v", err)
|
Error.Printf("%++v", err)
|
||||||
return err
|
return err
|
||||||
@@ -30,7 +52,7 @@ func (db *DB) Open() error {
|
|||||||
writeConn.SetConnMaxLifetime(30 * time.Second)
|
writeConn.SetConnMaxLifetime(30 * time.Second)
|
||||||
db.writeConn = writeConn
|
db.writeConn = writeConn
|
||||||
|
|
||||||
readConn, err := sql.Open("sqlite3", db.path+"?mode=ro&_journal=WAL&_synchronous=NORMAL&_mode=ro")
|
readConn, err := sql.Open("spellfixlite", db.path+"?mode=ro&_journal=WAL&_synchronous=NORMAL&_mode=ro")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
Error.Printf("%++v", err)
|
Error.Printf("%++v", err)
|
||||||
return err
|
return err
|
||||||
@@ -44,6 +66,63 @@ func (db *DB) Open() error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (db *DB) Init(ddl string) error {
|
||||||
|
if !db.Ready {
|
||||||
|
return fmt.Errorf("database not ready")
|
||||||
|
}
|
||||||
|
|
||||||
|
var rows map[string]struct{} = make(map[string]struct{})
|
||||||
|
// TODO: Maybe make this better one day...
|
||||||
|
var expected = map[string]struct{}{
|
||||||
|
"food": {},
|
||||||
|
"weight": {},
|
||||||
|
"settings": {},
|
||||||
|
}
|
||||||
|
|
||||||
|
res, err := db.readConn.Query("SELECT name FROM sqlite_master WHERE type='table';")
|
||||||
|
if err != nil {
|
||||||
|
Error.Printf("%++v", err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer res.Close()
|
||||||
|
for res.Next() {
|
||||||
|
var name string
|
||||||
|
err := res.Scan(&name)
|
||||||
|
if err != nil {
|
||||||
|
Error.Printf("%++v", err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
rows[name] = struct{}{}
|
||||||
|
}
|
||||||
|
|
||||||
|
var needsInit bool
|
||||||
|
for table := range expected {
|
||||||
|
if _, ok := rows[table]; !ok {
|
||||||
|
log.Printf("Table %s not found, initializing", table)
|
||||||
|
needsInit = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !needsInit {
|
||||||
|
log.Printf("Database already initialized")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = db.writeConn.Exec(ddl)
|
||||||
|
if err != nil {
|
||||||
|
Error.Printf("%++v", err)
|
||||||
|
log.Printf("%#v", "Rolling back")
|
||||||
|
_, err2 := db.writeConn.Exec("ROLLBACK;")
|
||||||
|
if err2 != nil {
|
||||||
|
Error.Printf("Error rollingback! %++v", err)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func (db *DB) Close() error {
|
func (db *DB) Close() error {
|
||||||
err := db.writeConn.Close()
|
err := db.writeConn.Close()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
91
food.ddl
91
food.ddl
@@ -1,11 +1,10 @@
|
|||||||
begin transaction;
|
begin;
|
||||||
|
|
||||||
create table weight (
|
create table weight (
|
||||||
date datetime default (datetime('now', '+2 hours')),
|
date datetime default (datetime('now', '+2 hours')),
|
||||||
weight real not null
|
weight real not null
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
||||||
create index weightDateIdx on weight(date);
|
create index weightDateIdx on weight(date);
|
||||||
create index weightDailyIdx on weight(strftime('%Y-%m-%d', date));
|
create index weightDailyIdx on weight(strftime('%Y-%m-%d', date));
|
||||||
create index weightWeeklyIdx on weight(strftime('%Y-%W', date));
|
create index weightWeeklyIdx on weight(strftime('%Y-%W', date));
|
||||||
@@ -28,28 +27,28 @@ order by date desc;
|
|||||||
create view weightDaily as
|
create view weightDaily as
|
||||||
select strftime('%Y-%m-%d', date) as period,
|
select strftime('%Y-%m-%d', date) as period,
|
||||||
round(avg(weight), 2) as amount
|
round(avg(weight), 2) as amount
|
||||||
from weight
|
from weight
|
||||||
group by strftime('%Y-%m-%d', date)
|
group by strftime('%Y-%m-%d', date)
|
||||||
order by date desc;
|
order by date desc;
|
||||||
|
|
||||||
create view weightWeekly as
|
create view weightWeekly as
|
||||||
select strftime('%Y-%W', date) as period,
|
select strftime('%Y-%W', date) as period,
|
||||||
round(avg(weight), 2) as amount
|
round(avg(weight), 2) as amount
|
||||||
from weight
|
from weight
|
||||||
group by strftime('%Y-%W', date)
|
group by strftime('%Y-%W', date)
|
||||||
order by date desc;
|
order by date desc;
|
||||||
|
|
||||||
create view weightMonthly as
|
create view weightMonthly as
|
||||||
select strftime('%Y-%m', date) as period,
|
select strftime('%Y-%m', date) as period,
|
||||||
round(avg(weight), 2) as amount
|
round(avg(weight), 2) as amount
|
||||||
from weight
|
from weight
|
||||||
group by strftime('%Y-%m', date)
|
group by strftime('%Y-%m', date)
|
||||||
order by date desc;
|
order by date desc;
|
||||||
|
|
||||||
create view weightYearly as
|
create view weightYearly as
|
||||||
select strftime('%Y', date) as period,
|
select strftime('%Y', date) as period,
|
||||||
round(avg(weight), 2) as amount
|
round(avg(weight), 2) as amount
|
||||||
from weight
|
from weight
|
||||||
group by strftime('%Y', date)
|
group by strftime('%Y', date)
|
||||||
order by date desc;
|
order by date desc;
|
||||||
|
|
||||||
@@ -62,6 +61,80 @@ create table food(
|
|||||||
energy generated always as (coalesce(amount, 0) * coalesce(per100, 0) / 100) stored
|
energy generated always as (coalesce(amount, 0) * coalesce(per100, 0) / 100) stored
|
||||||
);
|
);
|
||||||
|
|
||||||
|
create virtual table foodfix using spellfix1;
|
||||||
|
insert into foodfix (word, rank)
|
||||||
|
select food as word,
|
||||||
|
count(*) as rank
|
||||||
|
from food
|
||||||
|
group by food;
|
||||||
|
|
||||||
|
drop trigger if exists food_foodfix_insert;
|
||||||
|
create trigger food_foodfix_insert AFTER
|
||||||
|
insert on food for EACH row
|
||||||
|
begin
|
||||||
|
update foodfix
|
||||||
|
set rank = rank + 1
|
||||||
|
where word = new.food;
|
||||||
|
insert into foodfix (word, rank)
|
||||||
|
select new.food,
|
||||||
|
1
|
||||||
|
where not exists (
|
||||||
|
select 1
|
||||||
|
from foodfix
|
||||||
|
where word = new.food
|
||||||
|
);
|
||||||
|
end;
|
||||||
|
|
||||||
|
drop trigger if exists food_foodfix_delete;
|
||||||
|
create trigger food_foodfix_delete AFTER
|
||||||
|
delete on food for EACH row
|
||||||
|
begin
|
||||||
|
update foodfix
|
||||||
|
set rank = rank - 1
|
||||||
|
where word = old.food;
|
||||||
|
|
||||||
|
delete from foodfix
|
||||||
|
where word = old.food
|
||||||
|
and rank <= 0;
|
||||||
|
end;
|
||||||
|
|
||||||
|
|
||||||
|
drop trigger if exists food_foodfix_update;
|
||||||
|
create trigger food_foodfix_update AFTER
|
||||||
|
update on food for EACH row
|
||||||
|
begin
|
||||||
|
update foodfix
|
||||||
|
set rank = rank - 1
|
||||||
|
where word = old.food;
|
||||||
|
|
||||||
|
delete from foodfix
|
||||||
|
where word = old.food
|
||||||
|
and rank <= 0;
|
||||||
|
update foodfix
|
||||||
|
set rank = rank + 1
|
||||||
|
where word = new.food;
|
||||||
|
|
||||||
|
insert into foodfix (word, rank)
|
||||||
|
select new.food,
|
||||||
|
1
|
||||||
|
where not exists (
|
||||||
|
select 1
|
||||||
|
from foodfix
|
||||||
|
where word = new.food
|
||||||
|
);
|
||||||
|
end;
|
||||||
|
|
||||||
|
with search_results as (
|
||||||
|
select word, score, f.rowid, f.*
|
||||||
|
from foodfix
|
||||||
|
inner join food f on f.food == word
|
||||||
|
where word match 'B'
|
||||||
|
)
|
||||||
|
select rowid, food, score, date, description, amount, per100, energy
|
||||||
|
from search_results
|
||||||
|
group by food
|
||||||
|
order by score asc, date desc;
|
||||||
|
|
||||||
create index dailyIdx on food(strftime('%Y-%m-%d', date));
|
create index dailyIdx on food(strftime('%Y-%m-%d', date));
|
||||||
create index weeklyIdx on food(strftime('%Y-%W', date));
|
create index weeklyIdx on food(strftime('%Y-%W', date));
|
||||||
create index monthlyIdx on food(strftime('%Y-%m', date));
|
create index monthlyIdx on food(strftime('%Y-%m', date));
|
||||||
@@ -135,17 +208,17 @@ insert on food
|
|||||||
begin
|
begin
|
||||||
update food
|
update food
|
||||||
set per100 = coalesce(
|
set per100 = coalesce(
|
||||||
new .per100,
|
new.per100,
|
||||||
(
|
(
|
||||||
select per100
|
select per100
|
||||||
from food
|
from food
|
||||||
where food = new .food
|
where food = new.food
|
||||||
and per100 is not null
|
and per100 is not null
|
||||||
order by date desc
|
order by date desc
|
||||||
limit 1
|
limit 1
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
where rowid = new .rowid;
|
where rowid = new.rowid;
|
||||||
end;
|
end;
|
||||||
|
|
||||||
create table settings(
|
create table settings(
|
||||||
|
@@ -19,6 +19,10 @@ type (
|
|||||||
Per100 float32 `json:"per100"`
|
Per100 float32 `json:"per100"`
|
||||||
Energy float32 `json:"energy"`
|
Energy float32 `json:"energy"`
|
||||||
}
|
}
|
||||||
|
FoodSearch struct {
|
||||||
|
Food
|
||||||
|
Score int64 `json:"score"`
|
||||||
|
}
|
||||||
AggregatedFood struct {
|
AggregatedFood struct {
|
||||||
Period string `json:"period"`
|
Period string `json:"period"`
|
||||||
Amount float32 `json:"amount"`
|
Amount float32 `json:"amount"`
|
||||||
@@ -31,7 +35,7 @@ const foodColumns = "rowid, date, food, description, amount, per100, energy"
|
|||||||
const foodAggregatedColumns = "period, amount, avgPer100, energy"
|
const foodAggregatedColumns = "period, amount, avgPer100, energy"
|
||||||
|
|
||||||
func (s *FoodService) GetRecent() ([]Food, error) {
|
func (s *FoodService) GetRecent() ([]Food, error) {
|
||||||
var res []Food
|
var res []Food = []Food{}
|
||||||
if s.db == nil || !s.db.Ready {
|
if s.db == nil || !s.db.Ready {
|
||||||
return res, fmt.Errorf("cannot get recent food, db is nil or is not ready")
|
return res, fmt.Errorf("cannot get recent food, db is nil or is not ready")
|
||||||
}
|
}
|
||||||
@@ -56,19 +60,47 @@ func (s *FoodService) GetRecent() ([]Food, error) {
|
|||||||
return res, nil
|
return res, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *FoodService) GetLastPer100(name string) (float32, error) {
|
func (s *FoodService) GetLastPer100(name string) ([]FoodSearch, error) {
|
||||||
|
res := []FoodSearch{}
|
||||||
if s.db == nil || !s.db.Ready {
|
if s.db == nil || !s.db.Ready {
|
||||||
return 0, fmt.Errorf("cannot get last per100, db is nil or is not ready")
|
return res, fmt.Errorf("cannot get last per100, db is nil or is not ready")
|
||||||
}
|
}
|
||||||
|
|
||||||
row := s.db.readConn.QueryRow("SELECT per100 FROM food WHERE food like ? ORDER BY rowid DESC LIMIT 1", name+"%")
|
query := fmt.Sprintf(`
|
||||||
var per100 float32
|
with search_results as (
|
||||||
err := row.Scan(&per100)
|
select word, score, f.rowid, f.*
|
||||||
|
from foodfix
|
||||||
|
inner join food f on f.food == word
|
||||||
|
where word MATCH ?
|
||||||
|
)
|
||||||
|
select %s, score
|
||||||
|
from search_results
|
||||||
|
group by food
|
||||||
|
order by score asc, date desc
|
||||||
|
limit %d
|
||||||
|
`, foodColumns, Settings.SearchLimit)
|
||||||
|
// log.Printf("%#v", query)
|
||||||
|
rows, err := s.db.readConn.Query(query, name)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, fmt.Errorf("error scanning row: %v", err)
|
log.Printf("error getting last per100: %v", err)
|
||||||
|
return res, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return per100, nil
|
for rows.Next() {
|
||||||
|
var f FoodSearch
|
||||||
|
err := rows.Scan(&f.Rowid, &f.Date, &f.Food.Food, &f.Descripton, &f.Amount, &f.Per100, &f.Energy, &f.Score)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("error scanning row: %v", err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
res = append(res, f)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(res) == 0 {
|
||||||
|
return nil, fmt.Errorf("no results found for %s", name)
|
||||||
|
}
|
||||||
|
|
||||||
|
return res, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *FoodService) Create(food Food) (Food, error) {
|
func (s *FoodService) Create(food Food) (Food, error) {
|
||||||
@@ -151,7 +183,7 @@ func (s *FoodService) GetByRowid(rowid int64) (Food, error) {
|
|||||||
// I could probably refactor this to be less of a disaster...
|
// I could probably refactor this to be less of a disaster...
|
||||||
// But I think it'll work for now
|
// But I think it'll work for now
|
||||||
func (s *FoodService) GetDaily() ([]AggregatedFood, error) {
|
func (s *FoodService) GetDaily() ([]AggregatedFood, error) {
|
||||||
var res []AggregatedFood
|
res := []AggregatedFood{}
|
||||||
if s.db == nil || !s.db.Ready {
|
if s.db == nil || !s.db.Ready {
|
||||||
return res, fmt.Errorf("cannot get daily food, db is nil or is not ready")
|
return res, fmt.Errorf("cannot get daily food, db is nil or is not ready")
|
||||||
}
|
}
|
||||||
@@ -177,7 +209,7 @@ func (s *FoodService) GetDaily() ([]AggregatedFood, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *FoodService) GetWeekly() ([]AggregatedFood, error) {
|
func (s *FoodService) GetWeekly() ([]AggregatedFood, error) {
|
||||||
var res []AggregatedFood
|
res := []AggregatedFood{}
|
||||||
if s.db == nil || !s.db.Ready {
|
if s.db == nil || !s.db.Ready {
|
||||||
return res, fmt.Errorf("cannot get weekly food, db is nil or is not ready")
|
return res, fmt.Errorf("cannot get weekly food, db is nil or is not ready")
|
||||||
}
|
}
|
||||||
@@ -203,7 +235,7 @@ func (s *FoodService) GetWeekly() ([]AggregatedFood, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *FoodService) GetMonthly() ([]AggregatedFood, error) {
|
func (s *FoodService) GetMonthly() ([]AggregatedFood, error) {
|
||||||
var res []AggregatedFood
|
res := []AggregatedFood{}
|
||||||
if s.db == nil || !s.db.Ready {
|
if s.db == nil || !s.db.Ready {
|
||||||
return res, fmt.Errorf("cannot get monthly food, db is nil or is not ready")
|
return res, fmt.Errorf("cannot get monthly food, db is nil or is not ready")
|
||||||
}
|
}
|
||||||
@@ -229,7 +261,7 @@ func (s *FoodService) GetMonthly() ([]AggregatedFood, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *FoodService) GetYearly() ([]AggregatedFood, error) {
|
func (s *FoodService) GetYearly() ([]AggregatedFood, error) {
|
||||||
var res []AggregatedFood
|
res := []AggregatedFood{}
|
||||||
if s.db == nil || !s.db.Ready {
|
if s.db == nil || !s.db.Ready {
|
||||||
return res, fmt.Errorf("cannot get yearly food, db is nil or is not ready")
|
return res, fmt.Errorf("cannot get yearly food, db is nil or is not ready")
|
||||||
}
|
}
|
||||||
|
@@ -1,12 +1,15 @@
|
|||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
|
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8"/>
|
<meta charset="UTF-8" />
|
||||||
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
|
<meta content="width=device-width, initial-scale=1.0" name="viewport" />
|
||||||
<title>calorie-counter</title>
|
<title>calorie-counter</title>
|
||||||
</head>
|
</head>
|
||||||
|
|
||||||
<body>
|
<body>
|
||||||
<div id="app"></div>
|
<div id="app"></div>
|
||||||
<script src="./src/main.ts" type="module"></script>
|
<script src="./src/main.ts" type="module"></script>
|
||||||
</body>
|
</body>
|
||||||
|
|
||||||
</html>
|
</html>
|
@@ -10,6 +10,10 @@
|
|||||||
"check": "svelte-check --tsconfig ./tsconfig.json"
|
"check": "svelte-check --tsconfig ./tsconfig.json"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@fortawesome/fontawesome-svg-core": "^6.5.2",
|
||||||
|
"@fortawesome/free-brands-svg-icons": "^6.5.2",
|
||||||
|
"@fortawesome/free-regular-svg-icons": "^6.5.2",
|
||||||
|
"@fortawesome/free-solid-svg-icons": "^6.5.2",
|
||||||
"@sveltejs/vite-plugin-svelte": "^1.0.1",
|
"@sveltejs/vite-plugin-svelte": "^1.0.1",
|
||||||
"@tsconfig/svelte": "^3.0.0",
|
"@tsconfig/svelte": "^3.0.0",
|
||||||
"svelte": "^3.49.0",
|
"svelte": "^3.49.0",
|
||||||
@@ -21,15 +25,12 @@
|
|||||||
"tailwindcss": "^3.4.3",
|
"tailwindcss": "^3.4.3",
|
||||||
"tslib": "^2.4.0",
|
"tslib": "^2.4.0",
|
||||||
"typescript": "^4.6.4",
|
"typescript": "^4.6.4",
|
||||||
"vite": "^3.0.7",
|
"vite": "^3.0.7"
|
||||||
"@fortawesome/fontawesome-svg-core": "^6.5.2",
|
|
||||||
"@fortawesome/free-brands-svg-icons": "^6.5.2",
|
|
||||||
"@fortawesome/free-regular-svg-icons": "^6.5.2",
|
|
||||||
"@fortawesome/free-solid-svg-icons": "^6.5.2"
|
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"autoprefixer": "^10.4.20",
|
"autoprefixer": "^10.4.20",
|
||||||
"chart.js": "^4.4.3",
|
"chart.js": "^4.4.3",
|
||||||
|
"regression": "^2.0.1",
|
||||||
"svelte-chartjs": "^3.1.5"
|
"svelte-chartjs": "^3.1.5"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -1 +1 @@
|
|||||||
bd9b801d4541f25052f0d4cb72b7d95a
|
23e2cc3e28f96f9d63ed35c0a34c1dcd
|
8
frontend/pnpm-lock.yaml
generated
8
frontend/pnpm-lock.yaml
generated
@@ -14,6 +14,9 @@ importers:
|
|||||||
chart.js:
|
chart.js:
|
||||||
specifier: ^4.4.3
|
specifier: ^4.4.3
|
||||||
version: 4.4.3
|
version: 4.4.3
|
||||||
|
regression:
|
||||||
|
specifier: ^2.0.1
|
||||||
|
version: 2.0.1
|
||||||
svelte-chartjs:
|
svelte-chartjs:
|
||||||
specifier: ^3.1.5
|
specifier: ^3.1.5
|
||||||
version: 3.1.5(chart.js@4.4.3)(svelte@3.59.2)
|
version: 3.1.5(chart.js@4.4.3)(svelte@3.59.2)
|
||||||
@@ -714,6 +717,9 @@ packages:
|
|||||||
resolution: {integrity: sha512-A1PeDEYMrkLrfyOwv2jwihXbo9qxdGD3atBYQA9JJgreAx8/7rC6IUkWOw2NQlOxLp2wL0ifQbh1HuidDfYA6w==}
|
resolution: {integrity: sha512-A1PeDEYMrkLrfyOwv2jwihXbo9qxdGD3atBYQA9JJgreAx8/7rC6IUkWOw2NQlOxLp2wL0ifQbh1HuidDfYA6w==}
|
||||||
engines: {node: '>=8'}
|
engines: {node: '>=8'}
|
||||||
|
|
||||||
|
regression@2.0.1:
|
||||||
|
resolution: {integrity: sha512-A4XYsc37dsBaNOgEjkJKzfJlE394IMmUPlI/p3TTI9u3T+2a+eox5Pr/CPUqF0eszeWZJPAc6QkroAhuUpWDJQ==}
|
||||||
|
|
||||||
resolve-from@4.0.0:
|
resolve-from@4.0.0:
|
||||||
resolution: {integrity: sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==}
|
resolution: {integrity: sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==}
|
||||||
engines: {node: '>=4'}
|
engines: {node: '>=4'}
|
||||||
@@ -1512,6 +1518,8 @@ snapshots:
|
|||||||
|
|
||||||
regexparam@2.0.2: {}
|
regexparam@2.0.2: {}
|
||||||
|
|
||||||
|
regression@2.0.1: {}
|
||||||
|
|
||||||
resolve-from@4.0.0: {}
|
resolve-from@4.0.0: {}
|
||||||
|
|
||||||
resolve@1.22.8:
|
resolve@1.22.8:
|
||||||
|
@@ -1,9 +1,32 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import Header from "$lib/components/Header.svelte";
|
import Header from "$lib/components/Header.svelte";
|
||||||
import Router from "$lib/router/Router.svelte";
|
import Router from "$lib/router/Router.svelte";
|
||||||
import { Toaster } from 'svelte-sonner'
|
import { Close } from "$wails/main/App";
|
||||||
|
import { Toaster } from "svelte-sonner";
|
||||||
|
import * as srouter from "svelte-spa-router";
|
||||||
|
import { location } from "svelte-spa-router";
|
||||||
|
|
||||||
|
const energyLocRegex = /^\/(?:Energy)?(?!Weight)/;
|
||||||
|
const weightLocRegex = /^\/(?:Weight)(?!Energy)/;
|
||||||
|
function keyDown(event: KeyboardEvent) {
|
||||||
|
if (event.ctrlKey && event.key == "r") {
|
||||||
|
window.location.reload();
|
||||||
|
}
|
||||||
|
if (event.ctrlKey && event.key == "w") {
|
||||||
|
Close();
|
||||||
|
}
|
||||||
|
if (event.ctrlKey && event.key == "Tab") {
|
||||||
|
if (energyLocRegex.test($location)) {
|
||||||
|
srouter.replace($location.replace(energyLocRegex, "/Weight"));
|
||||||
|
} else if (weightLocRegex.test($location)) {
|
||||||
|
srouter.replace($location.replace(weightLocRegex, "/Energy"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
<svelte:window on:keydown={keyDown} />
|
||||||
|
|
||||||
<Toaster />
|
<Toaster />
|
||||||
<template>
|
<template>
|
||||||
<Header />
|
<Header />
|
||||||
|
@@ -3,6 +3,7 @@
|
|||||||
import AggregatedFoodComp from "$lib/components/Energy/Aggregated/AggregatedFoodComp.svelte";
|
import AggregatedFoodComp from "$lib/components/Energy/Aggregated/AggregatedFoodComp.svelte";
|
||||||
import { main } from "$wails/models";
|
import { main } from "$wails/models";
|
||||||
import type { ChartData, Point } from "chart.js";
|
import type { ChartData, Point } from "chart.js";
|
||||||
|
import regression from "regression";
|
||||||
import {
|
import {
|
||||||
CategoryScale,
|
CategoryScale,
|
||||||
Chart as ChartJS,
|
Chart as ChartJS,
|
||||||
@@ -13,6 +14,7 @@
|
|||||||
Title,
|
Title,
|
||||||
Tooltip,
|
Tooltip,
|
||||||
} from "chart.js";
|
} from "chart.js";
|
||||||
|
import { CalculateR2 } from "$lib/utils";
|
||||||
|
|
||||||
ChartJS.register(Title, Tooltip, Legend, LineElement, LinearScale, PointElement, CategoryScale);
|
ChartJS.register(Title, Tooltip, Legend, LineElement, LinearScale, PointElement, CategoryScale);
|
||||||
|
|
||||||
@@ -32,7 +34,7 @@
|
|||||||
pointHoverBorderColor: "rgba(220, 220, 220, 1)",
|
pointHoverBorderColor: "rgba(220, 220, 220, 1)",
|
||||||
pointHoverBorderWidth: 2,
|
pointHoverBorderWidth: 2,
|
||||||
pointRadius: 1,
|
pointRadius: 1,
|
||||||
pointHitRadius: 10,
|
pointHitRadius: 20,
|
||||||
};
|
};
|
||||||
const data: ChartData<"line", (number | Point)[]> = {
|
const data: ChartData<"line", (number | Point)[]> = {
|
||||||
labels: reversedItems.map((f) => f.period),
|
labels: reversedItems.map((f) => f.period),
|
||||||
@@ -74,6 +76,14 @@
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
|
data.datasets.push({
|
||||||
|
...defaultOptions,
|
||||||
|
label: "R2",
|
||||||
|
data: CalculateR2(reversedItems.map((f, i) => [i, f.energy])),
|
||||||
|
borderColor: "#04d1d1",
|
||||||
|
pointBorderColor: "#04d1d1",
|
||||||
|
pointRadius: 0,
|
||||||
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
|
@@ -3,6 +3,7 @@
|
|||||||
import { main } from "$wails/models";
|
import { main } from "$wails/models";
|
||||||
import { CreateFood, GetLastPer100 } from "$wails/main/App";
|
import { CreateFood, GetLastPer100 } from "$wails/main/App";
|
||||||
import { foodStore } from "$lib/store/Energy/foodStore";
|
import { foodStore } from "$lib/store/Energy/foodStore";
|
||||||
|
import FoodSearchEntry from "./FoodSearchEntry.svelte";
|
||||||
|
|
||||||
let item: main.Food = {
|
let item: main.Food = {
|
||||||
food: "",
|
food: "",
|
||||||
@@ -19,6 +20,18 @@
|
|||||||
let per100: string = "";
|
let per100: string = "";
|
||||||
let per100Edited: boolean = false;
|
let per100Edited: boolean = false;
|
||||||
let per100Element: HTMLTableCellElement;
|
let per100Element: HTMLTableCellElement;
|
||||||
|
let nameElement: HTMLTableCellElement;
|
||||||
|
let autocompleteList: HTMLUListElement;
|
||||||
|
let foodSearch: main.Food[] = [];
|
||||||
|
|
||||||
|
// Maybe it would be a good idea to use $ instead of update down there...
|
||||||
|
// Maybe it's a topic for another day
|
||||||
|
$: {
|
||||||
|
name = name.trim();
|
||||||
|
if (!name) {
|
||||||
|
foodSearch = [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function update(event: KeyboardEvent & { currentTarget: EventTarget & HTMLTableCellElement }) {
|
async function update(event: KeyboardEvent & { currentTarget: EventTarget & HTMLTableCellElement }) {
|
||||||
name = name.trim();
|
name = name.trim();
|
||||||
@@ -26,7 +39,12 @@
|
|||||||
description = description.trim();
|
description = description.trim();
|
||||||
per100 = per100.trim();
|
per100 = per100.trim();
|
||||||
|
|
||||||
if (!per100Edited && event.currentTarget === per100Element) per100Edited = true;
|
if (!name) {
|
||||||
|
foodSearch = [];
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!per100Edited && event.currentTarget == per100Element) per100Edited = true;
|
||||||
|
|
||||||
if (event.key == "Enter") {
|
if (event.key == "Enter") {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
@@ -48,24 +66,63 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
foodStore.update((value) => [res.data, ...value]);
|
foodStore.update((value) => [res.data, ...value]);
|
||||||
|
nameElement.focus();
|
||||||
|
foodSearch = [];
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!per100Edited)
|
if (!per100Edited)
|
||||||
GetLastPer100(name.trim()).then((res) => {
|
GetLastPer100(name.trim()).then((res) => {
|
||||||
if (res.success) {
|
// Prevent search when there's nothing to search
|
||||||
per100 = res.data.toString();
|
// Sometimes we get search results after deleting name
|
||||||
|
if (res.success && res.data && name) {
|
||||||
|
foodSearch = res.data;
|
||||||
|
} else {
|
||||||
|
foodSearch = [];
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let hiLiteIndex: number | null = null;
|
||||||
|
// function navigateList(e: KeyboardEvent) {
|
||||||
|
// console.log(foodSearch, hiLiteIndex);
|
||||||
|
// // @ts-ignore shut the fuck up
|
||||||
|
// if (e.key == "ArrowDown" && hiLiteIndex <= foodSearch.length - 2) {
|
||||||
|
// hiLiteIndex == null ? (hiLiteIndex = 0) : (hiLiteIndex += 1);
|
||||||
|
// } else if (e.key == "ArrowUp" && hiLiteIndex !== null) {
|
||||||
|
// hiLiteIndex == 0 ? 0 : (hiLiteIndex -= 1);
|
||||||
|
// } else if (e.key == "Enter") {
|
||||||
|
// // @ts-ignore ITS NOT NULL YOU ASSHAT
|
||||||
|
// // WE CHECKED
|
||||||
|
// // ITS NOT
|
||||||
|
// setInputVal(foodSearch[hiLiteIndex]);
|
||||||
|
// } else {
|
||||||
|
// return;
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
function setInputVal(food: main.Food) {
|
||||||
|
name = food.food;
|
||||||
|
per100 = String(food.per100)
|
||||||
|
hiLiteIndex = null;
|
||||||
|
foodSearch = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
$: {
|
||||||
|
if (nameElement && autocompleteList) {
|
||||||
|
const { top, left, height } = nameElement.getBoundingClientRect();
|
||||||
|
autocompleteList.style.top = `${top + height}px`;
|
||||||
|
autocompleteList.style.left = `${left}px`;
|
||||||
|
}
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
<!-- <svelte:window on:keydown={navigateList} /> -->
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<tr class="border-b border-gray-200 dark:border-gray-700 text-lg font-bold">
|
<tr class="border-b border-gray-200 dark:border-gray-700 text-lg font-bold relative">
|
||||||
<th
|
<th
|
||||||
class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap bg-gray-50 dark:text-white dark:bg-gray-800"
|
class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap bg-gray-50 dark:text-white dark:bg-gray-800"
|
||||||
scope="row"
|
scope="row"
|
||||||
>
|
></th>
|
||||||
</th>
|
|
||||||
<!-- svelte-ignore a11y-autofocus -->
|
<!-- svelte-ignore a11y-autofocus -->
|
||||||
<td
|
<td
|
||||||
bind:innerText={name}
|
bind:innerText={name}
|
||||||
@@ -75,15 +132,14 @@
|
|||||||
contenteditable="true"
|
contenteditable="true"
|
||||||
autofocus
|
autofocus
|
||||||
on:keydown={update}
|
on:keydown={update}
|
||||||
>
|
bind:this={nameElement}
|
||||||
</td>
|
/>
|
||||||
<td
|
<td
|
||||||
bind:innerText={description}
|
bind:innerText={description}
|
||||||
class="px-6 py-4 bg-gray-50 dark:bg-gray-800 overflow-hidden"
|
class="px-6 py-4 bg-gray-50 dark:bg-gray-800 overflow-hidden"
|
||||||
contenteditable="true"
|
contenteditable="true"
|
||||||
on:keydown={update}
|
on:keydown={update}
|
||||||
>
|
/>
|
||||||
</td>
|
|
||||||
<td
|
<td
|
||||||
bind:innerText={amount}
|
bind:innerText={amount}
|
||||||
class:border-[3px]={!amount}
|
class:border-[3px]={!amount}
|
||||||
@@ -91,8 +147,7 @@
|
|||||||
class="px-6 py-4 overflow-hidden"
|
class="px-6 py-4 overflow-hidden"
|
||||||
contenteditable="true"
|
contenteditable="true"
|
||||||
on:keydown={update}
|
on:keydown={update}
|
||||||
>
|
/>
|
||||||
</td>
|
|
||||||
<td
|
<td
|
||||||
bind:this={per100Element}
|
bind:this={per100Element}
|
||||||
bind:innerText={per100}
|
bind:innerText={per100}
|
||||||
@@ -101,7 +156,17 @@
|
|||||||
class:border-orange-600={!per100}
|
class:border-orange-600={!per100}
|
||||||
contenteditable="true"
|
contenteditable="true"
|
||||||
on:keydown={update}
|
on:keydown={update}
|
||||||
>
|
/>
|
||||||
</td>
|
|
||||||
</tr>
|
</tr>
|
||||||
|
{#if foodSearch.length > 0}
|
||||||
|
<ul bind:this={autocompleteList} class="z-50 fixed top-0 left-0 w-3/12 border border-x-gray-800">
|
||||||
|
{#each foodSearch as f, i}
|
||||||
|
<FoodSearchEntry
|
||||||
|
itemLabel={f.food}
|
||||||
|
highlighted={i == hiLiteIndex}
|
||||||
|
on:click={() => setInputVal(f)}
|
||||||
|
/>
|
||||||
|
{/each}
|
||||||
|
</ul>
|
||||||
|
{/if}
|
||||||
</template>
|
</template>
|
||||||
|
@@ -34,16 +34,18 @@
|
|||||||
remainingToday = $settingsStore.target;
|
remainingToday = $settingsStore.target;
|
||||||
let now = new Date();
|
let now = new Date();
|
||||||
let todayDate = formatter.format(now);
|
let todayDate = formatter.format(now);
|
||||||
const [day, month, year] = todayDate.split('/');
|
const [day, month, year] = todayDate.split("/");
|
||||||
todayDate = `${year}-${month}-${day}`;
|
todayDate = `${year}-${month}-${day}`;
|
||||||
|
|
||||||
$foodStore.forEach((food) => {
|
if ($foodStore) {
|
||||||
if (food.date.split("T")[0] == todayDate) {
|
$foodStore.forEach((food) => {
|
||||||
remainingToday -= food.energy;
|
if (food.date.split("T")[0] == todayDate) {
|
||||||
} else {
|
remainingToday -= food.energy;
|
||||||
return;
|
} else {
|
||||||
}
|
return;
|
||||||
});
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
remainingToday = Math.round(remainingToday);
|
remainingToday = Math.round(remainingToday);
|
||||||
computeColor();
|
computeColor();
|
||||||
}
|
}
|
||||||
|
15
frontend/src/lib/components/Energy/FoodSearchEntry.svelte
Normal file
15
frontend/src/lib/components/Energy/FoodSearchEntry.svelte
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
<script>
|
||||||
|
// This doesn't update when navigating with arrows keys...
|
||||||
|
// Fucking svelte and reactivity again, here we fucking go
|
||||||
|
export let itemLabel;
|
||||||
|
export let highlighted;
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<!-- svelte-ignore a11y-click-events-have-key-events -->
|
||||||
|
<li
|
||||||
|
class="list-none border-b border-gray-800 z-50 px-2 py-2 cursor-pointer bg-[#1b2636] hover:bg-[#81921f] hover:text-white active:bg-DodgerBlue active:text-white text-lg"
|
||||||
|
class:bg-DodgerBlue={highlighted}
|
||||||
|
class:text-white={highlighted}
|
||||||
|
on:click>
|
||||||
|
{itemLabel}
|
||||||
|
</li>
|
@@ -1,10 +1,11 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { GenerateColor } from "$lib/utils";
|
import { GenerateColor, RemoveExistingColors } from "$lib/utils";
|
||||||
import { main } from "$wails/models";
|
import { main } from "$wails/models";
|
||||||
import EmptyFoodComp from "./EmptyFoodComp.svelte";
|
import EmptyFoodComp from "./EmptyFoodComp.svelte";
|
||||||
import FoodComp from "./FoodComp.svelte";
|
import FoodComp from "./FoodComp.svelte";
|
||||||
|
|
||||||
export let items: main.Food[] = [];
|
export let items: main.Food[] = [];
|
||||||
|
RemoveExistingColors();
|
||||||
|
|
||||||
let minCal = 1e5;
|
let minCal = 1e5;
|
||||||
let maxCal = 0;
|
let maxCal = 0;
|
||||||
|
@@ -1,9 +1,10 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { link, location } from "svelte-spa-router";
|
import { link, location } from "svelte-spa-router";
|
||||||
import { faGear } from "@fortawesome/free-solid-svg-icons";
|
import { faGear} from "@fortawesome/free-solid-svg-icons";
|
||||||
import Fa from "svelte-fa";
|
import Fa from "svelte-fa";
|
||||||
import Settings from "./Settings/Settings.svelte";
|
import Settings from "./Settings/Settings.svelte";
|
||||||
import EnergyToday from "./Energy/EnergyToday.svelte";
|
import EnergyToday from "./Energy/EnergyToday.svelte";
|
||||||
|
import RefreshComponent from "./RefreshComponent.svelte";
|
||||||
Fa;
|
Fa;
|
||||||
|
|
||||||
type Link = {
|
type Link = {
|
||||||
@@ -88,6 +89,7 @@
|
|||||||
<Fa icon={faGear} scale={2} />
|
<Fa icon={faGear} scale={2} />
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
<RefreshComponent />
|
||||||
<EnergyToday />
|
<EnergyToday />
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
|
42
frontend/src/lib/components/RefreshComponent.svelte
Normal file
42
frontend/src/lib/components/RefreshComponent.svelte
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { dailyFoodStore } from "$lib/store/Energy/dailyFoodStore";
|
||||||
|
import { monthlyFoodStore } from "$lib/store/Energy/monthlyFoodStore";
|
||||||
|
import { weeklyFoodStore } from "$lib/store/Energy/weeklyFoodStore";
|
||||||
|
import { yearlyFoodStore } from "$lib/store/Energy/yearlyFoodStore";
|
||||||
|
import { dailyWeightStore } from "$lib/store/Weight/dailyWeightStore";
|
||||||
|
import { monthlyWeightStore } from "$lib/store/Weight/monthlyWeightStore";
|
||||||
|
import { weeklyWeightStore } from "$lib/store/Weight/weeklyWeightStore";
|
||||||
|
import { yearlyWeightStore } from "$lib/store/Weight/yearlyWeightStore";
|
||||||
|
import { faRefresh } from "@fortawesome/free-solid-svg-icons";
|
||||||
|
import Fa from "svelte-fa";
|
||||||
|
Fa;
|
||||||
|
|
||||||
|
// YES refresh DOES exist FFS
|
||||||
|
function refreshStores() {
|
||||||
|
// @ts-ignore
|
||||||
|
dailyFoodStore.refresh();
|
||||||
|
// @ts-ignore
|
||||||
|
weeklyFoodStore.refresh();
|
||||||
|
// @ts-ignore
|
||||||
|
monthlyFoodStore.refresh();
|
||||||
|
// @ts-ignore
|
||||||
|
yearlyFoodStore.refresh();
|
||||||
|
// @ts-ignore
|
||||||
|
dailyWeightStore.refresh();
|
||||||
|
// @ts-ignore
|
||||||
|
weeklyWeightStore.refresh();
|
||||||
|
// @ts-ignore
|
||||||
|
monthlyWeightStore.refresh();
|
||||||
|
// @ts-ignore
|
||||||
|
yearlyWeightStore.refresh();
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<!-- svelte-ignore a11y-click-events-have-key-events -->
|
||||||
|
<div class="absolute right-20 pt-4 pb-4 pr-8 pl-8 cursor-pointer" on:click={refreshStores}>
|
||||||
|
<button>
|
||||||
|
<Fa icon={faRefresh} scale={2} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</template>
|
@@ -13,6 +13,7 @@
|
|||||||
Title,
|
Title,
|
||||||
Tooltip,
|
Tooltip,
|
||||||
} from "chart.js";
|
} from "chart.js";
|
||||||
|
import { CalculateR2 } from "$lib/utils";
|
||||||
|
|
||||||
ChartJS.register(Title, Tooltip, Legend, LineElement, LinearScale, PointElement, CategoryScale);
|
ChartJS.register(Title, Tooltip, Legend, LineElement, LinearScale, PointElement, CategoryScale);
|
||||||
|
|
||||||
@@ -44,6 +45,14 @@
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
|
data.datasets.push({
|
||||||
|
...defaultOptions,
|
||||||
|
label: "R2",
|
||||||
|
data: CalculateR2(reversedItems.map((f, i) => [i, f.amount])),
|
||||||
|
borderColor: "#04d1d1",
|
||||||
|
pointBorderColor: "#04d1d1",
|
||||||
|
pointRadius: 0,
|
||||||
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
|
@@ -1,10 +1,11 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { GenerateColor } from "$lib/utils";
|
import { GenerateColor, RemoveExistingColors } from "$lib/utils";
|
||||||
import EmptyWeightComp from "$components/Weight/EmptyWeightComp.svelte";
|
import EmptyWeightComp from "$components/Weight/EmptyWeightComp.svelte";
|
||||||
import WeightComp from "$components/Weight/WeightComp.svelte";
|
import WeightComp from "$components/Weight/WeightComp.svelte";
|
||||||
import { main } from "$wails/models";
|
import { main } from "$wails/models";
|
||||||
|
|
||||||
export let items: main.Weight[] = [];
|
export let items: main.Weight[] = [];
|
||||||
|
RemoveExistingColors();
|
||||||
|
|
||||||
const dateColors: Map<string, string> = new Map<string, string>();
|
const dateColors: Map<string, string> = new Map<string, string>();
|
||||||
|
|
||||||
|
@@ -13,6 +13,7 @@
|
|||||||
|
|
||||||
const routes = {
|
const routes = {
|
||||||
'/': Energy,
|
'/': Energy,
|
||||||
|
'/Energy': Energy,
|
||||||
'/Energy/daily': Daily,
|
'/Energy/daily': Daily,
|
||||||
'/Energy/weekly': Weekly,
|
'/Energy/weekly': Weekly,
|
||||||
'/Energy/monthly': Monthly,
|
'/Energy/monthly': Monthly,
|
||||||
|
@@ -1,5 +1,7 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import FoodTable from "$lib/components/Energy/FoodTable.svelte";
|
import FoodTable from "$lib/components/Energy/FoodTable.svelte";
|
||||||
|
import * as srouter from "svelte-spa-router";
|
||||||
|
import { location } from "svelte-spa-router";
|
||||||
import { foodStore } from "$lib/store/Energy/foodStore";
|
import { foodStore } from "$lib/store/Energy/foodStore";
|
||||||
|
|
||||||
// Fuck this hacky shit
|
// Fuck this hacky shit
|
||||||
|
@@ -4,7 +4,6 @@
|
|||||||
|
|
||||||
let forceUpdate = false;
|
let forceUpdate = false;
|
||||||
weightStore.subscribe(() => {
|
weightStore.subscribe(() => {
|
||||||
console.log("updte");
|
|
||||||
forceUpdate = !forceUpdate;
|
forceUpdate = !forceUpdate;
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
@@ -1,5 +1,7 @@
|
|||||||
import { cubicOut } from "svelte/easing";
|
import { cubicOut } from "svelte/easing";
|
||||||
import type { TransitionConfig } from "svelte/transition";
|
import type { TransitionConfig } from "svelte/transition";
|
||||||
|
import regression from "regression";
|
||||||
|
import type { ChartData, Point } from "chart.js";
|
||||||
|
|
||||||
type FlyAndScaleParams = {
|
type FlyAndScaleParams = {
|
||||||
y?: number;
|
y?: number;
|
||||||
@@ -68,8 +70,11 @@ function GenerateRandomHSL(): Color {
|
|||||||
|
|
||||||
const existingColors: Color[] = [];
|
const existingColors: Color[] = [];
|
||||||
|
|
||||||
|
function RemoveExistingColors() {
|
||||||
|
existingColors.length = 0;
|
||||||
|
}
|
||||||
function GenerateColor(): string {
|
function GenerateColor(): string {
|
||||||
const minDistance = 15;
|
const minDistance = 5;
|
||||||
|
|
||||||
let newColor: Color;
|
let newColor: Color;
|
||||||
let isDistinct = false;
|
let isDistinct = false;
|
||||||
@@ -89,7 +94,9 @@ function GenerateColor(): string {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
existingColors.push(newColor);
|
if (isDistinct) {
|
||||||
|
existingColors.push(newColor);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// We can not reach this point without having a color generated
|
// We can not reach this point without having a color generated
|
||||||
@@ -104,5 +111,10 @@ function LerpColor(color1: Color, color2: Color, t: number): Color {
|
|||||||
return { h, s, l };
|
return { h, s, l };
|
||||||
}
|
}
|
||||||
|
|
||||||
export { GenerateColor, LerpColor };
|
function CalculateR2(input: [number, number][]): number[] {
|
||||||
|
const reg = regression.linear(input);
|
||||||
|
return reg.points.map((point: [number, number]) => point[1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
export { GenerateColor, LerpColor, RemoveExistingColors, CalculateR2 };
|
||||||
export type { Color };
|
export type { Color };
|
||||||
|
4
frontend/wailsjs/go/main/App.d.ts
vendored
4
frontend/wailsjs/go/main/App.d.ts
vendored
@@ -2,6 +2,8 @@
|
|||||||
// This file is automatically generated. DO NOT EDIT
|
// This file is automatically generated. DO NOT EDIT
|
||||||
import {main} from '../models';
|
import {main} from '../models';
|
||||||
|
|
||||||
|
export function Close():Promise<void>;
|
||||||
|
|
||||||
export function CreateFood(arg1:main.Food):Promise<main.WailsFood1>;
|
export function CreateFood(arg1:main.Food):Promise<main.WailsFood1>;
|
||||||
|
|
||||||
export function CreateWeight(arg1:main.Weight):Promise<main.WailsWeight1>;
|
export function CreateWeight(arg1:main.Weight):Promise<main.WailsWeight1>;
|
||||||
@@ -12,7 +14,7 @@ export function GetDailyWeight():Promise<main.WailsAggregateWeight>;
|
|||||||
|
|
||||||
export function GetFood():Promise<main.WailsFood>;
|
export function GetFood():Promise<main.WailsFood>;
|
||||||
|
|
||||||
export function GetLastPer100(arg1:string):Promise<main.WailsPer100>;
|
export function GetLastPer100(arg1:string):Promise<main.WailsFoodSearch>;
|
||||||
|
|
||||||
export function GetMonthlyFood():Promise<main.WailsAggregateFood>;
|
export function GetMonthlyFood():Promise<main.WailsAggregateFood>;
|
||||||
|
|
||||||
|
@@ -2,6 +2,10 @@
|
|||||||
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
|
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
|
||||||
// This file is automatically generated. DO NOT EDIT
|
// This file is automatically generated. DO NOT EDIT
|
||||||
|
|
||||||
|
export function Close() {
|
||||||
|
return window['go']['main']['App']['Close']();
|
||||||
|
}
|
||||||
|
|
||||||
export function CreateFood(arg1) {
|
export function CreateFood(arg1) {
|
||||||
return window['go']['main']['App']['CreateFood'](arg1);
|
return window['go']['main']['App']['CreateFood'](arg1);
|
||||||
}
|
}
|
||||||
|
@@ -56,6 +56,32 @@ export namespace main {
|
|||||||
this.energy = source["energy"];
|
this.energy = source["energy"];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
export class FoodSearch {
|
||||||
|
rowid: number;
|
||||||
|
date: string;
|
||||||
|
food: string;
|
||||||
|
description: string;
|
||||||
|
amount: number;
|
||||||
|
per100: number;
|
||||||
|
energy: number;
|
||||||
|
score: number;
|
||||||
|
|
||||||
|
static createFrom(source: any = {}) {
|
||||||
|
return new FoodSearch(source);
|
||||||
|
}
|
||||||
|
|
||||||
|
constructor(source: any = {}) {
|
||||||
|
if ('string' === typeof source) source = JSON.parse(source);
|
||||||
|
this.rowid = source["rowid"];
|
||||||
|
this.date = source["date"];
|
||||||
|
this.food = source["food"];
|
||||||
|
this.description = source["description"];
|
||||||
|
this.amount = source["amount"];
|
||||||
|
this.per100 = source["per100"];
|
||||||
|
this.energy = source["energy"];
|
||||||
|
this.score = source["score"];
|
||||||
|
}
|
||||||
|
}
|
||||||
export class WailsAggregateFood {
|
export class WailsAggregateFood {
|
||||||
data: AggregatedFood[];
|
data: AggregatedFood[];
|
||||||
success: boolean;
|
success: boolean;
|
||||||
@@ -192,6 +218,40 @@ export namespace main {
|
|||||||
return a;
|
return a;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
export class WailsFoodSearch {
|
||||||
|
data: FoodSearch[];
|
||||||
|
success: boolean;
|
||||||
|
error?: string;
|
||||||
|
|
||||||
|
static createFrom(source: any = {}) {
|
||||||
|
return new WailsFoodSearch(source);
|
||||||
|
}
|
||||||
|
|
||||||
|
constructor(source: any = {}) {
|
||||||
|
if ('string' === typeof source) source = JSON.parse(source);
|
||||||
|
this.data = this.convertValues(source["data"], FoodSearch);
|
||||||
|
this.success = source["success"];
|
||||||
|
this.error = source["error"];
|
||||||
|
}
|
||||||
|
|
||||||
|
convertValues(a: any, classs: any, asMap: boolean = false): any {
|
||||||
|
if (!a) {
|
||||||
|
return a;
|
||||||
|
}
|
||||||
|
if (a.slice && a.map) {
|
||||||
|
return (a as any[]).map(elem => this.convertValues(elem, classs));
|
||||||
|
} else if ("object" === typeof a) {
|
||||||
|
if (asMap) {
|
||||||
|
for (const key of Object.keys(a)) {
|
||||||
|
a[key] = new classs(a[key]);
|
||||||
|
}
|
||||||
|
return a;
|
||||||
|
}
|
||||||
|
return new classs(a);
|
||||||
|
}
|
||||||
|
return a;
|
||||||
|
}
|
||||||
|
}
|
||||||
export class WailsGenericAck {
|
export class WailsGenericAck {
|
||||||
success: boolean;
|
success: boolean;
|
||||||
error?: string;
|
error?: string;
|
||||||
@@ -206,22 +266,6 @@ export namespace main {
|
|||||||
this.error = source["error"];
|
this.error = source["error"];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
export class WailsPer100 {
|
|
||||||
data: number;
|
|
||||||
success: boolean;
|
|
||||||
error?: string;
|
|
||||||
|
|
||||||
static createFrom(source: any = {}) {
|
|
||||||
return new WailsPer100(source);
|
|
||||||
}
|
|
||||||
|
|
||||||
constructor(source: any = {}) {
|
|
||||||
if ('string' === typeof source) source = JSON.parse(source);
|
|
||||||
this.data = source["data"];
|
|
||||||
this.success = source["success"];
|
|
||||||
this.error = source["error"];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
export class Weight {
|
export class Weight {
|
||||||
rowid: number;
|
rowid: number;
|
||||||
date: string;
|
date: string;
|
||||||
@@ -322,6 +366,7 @@ export namespace main {
|
|||||||
weightYearlyLookback: number;
|
weightYearlyLookback: number;
|
||||||
target: number;
|
target: number;
|
||||||
limit: number;
|
limit: number;
|
||||||
|
searchLimit: number;
|
||||||
|
|
||||||
static createFrom(source: any = {}) {
|
static createFrom(source: any = {}) {
|
||||||
return new settings(source);
|
return new settings(source);
|
||||||
@@ -343,6 +388,7 @@ export namespace main {
|
|||||||
this.weightYearlyLookback = source["weightYearlyLookback"];
|
this.weightYearlyLookback = source["weightYearlyLookback"];
|
||||||
this.target = source["target"];
|
this.target = source["target"];
|
||||||
this.limit = source["limit"];
|
this.limit = source["limit"];
|
||||||
|
this.searchLimit = source["searchLimit"];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
11
main.go
11
main.go
@@ -7,6 +7,7 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"log"
|
"log"
|
||||||
"os"
|
"os"
|
||||||
|
_ "embed"
|
||||||
|
|
||||||
"github.com/wailsapp/wails/v2"
|
"github.com/wailsapp/wails/v2"
|
||||||
"github.com/wailsapp/wails/v2/pkg/options"
|
"github.com/wailsapp/wails/v2/pkg/options"
|
||||||
@@ -39,7 +40,11 @@ var (
|
|||||||
weightService *WeightService
|
weightService *WeightService
|
||||||
)
|
)
|
||||||
|
|
||||||
|
//go:embed food.ddl
|
||||||
|
var foodDDL string
|
||||||
|
|
||||||
// TODO: Embed food.ddl and create DB if no exists
|
// TODO: Embed food.ddl and create DB if no exists
|
||||||
|
// TODO: Add averages to graphs (ie. R2) https://stackoverflow.com/questions/60622195/how-to-draw-a-linear-regression-line-in-chart-js
|
||||||
func main() {
|
func main() {
|
||||||
dbpath := flag.String("db", "food.db", "Path to the database file")
|
dbpath := flag.String("db", "food.db", "Path to the database file")
|
||||||
flag.Parse()
|
flag.Parse()
|
||||||
@@ -50,6 +55,12 @@ func main() {
|
|||||||
Error.Printf("%++v", err)
|
Error.Printf("%++v", err)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
defer db.Close()
|
||||||
|
err = db.Init(foodDDL)
|
||||||
|
if err != nil {
|
||||||
|
Error.Printf("Error initializing database: %++v", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
settingsService = &SettingsService{db: &db}
|
settingsService = &SettingsService{db: &db}
|
||||||
err = settingsService.LoadSettings()
|
err = settingsService.LoadSettings()
|
||||||
|
@@ -28,8 +28,9 @@ type settings struct {
|
|||||||
WeightMonthlyLookback int `default:"4" json:"weightMonthlyLookback"`
|
WeightMonthlyLookback int `default:"4" json:"weightMonthlyLookback"`
|
||||||
WeightYearlyLookback int `default:"2" json:"weightYearlyLookback"`
|
WeightYearlyLookback int `default:"2" json:"weightYearlyLookback"`
|
||||||
|
|
||||||
Target int `default:"2000" json:"target"`
|
Target int `default:"2000" json:"target"`
|
||||||
Limit int `default:"2500" json:"limit"`
|
Limit int `default:"2500" json:"limit"`
|
||||||
|
SearchLimit int `default:"5" json:"searchLimit"`
|
||||||
}
|
}
|
||||||
|
|
||||||
var Settings settings
|
var Settings settings
|
||||||
|
@@ -28,6 +28,11 @@ type (
|
|||||||
Success bool `json:"success"`
|
Success bool `json:"success"`
|
||||||
Error string `json:"error,omitempty"`
|
Error string `json:"error,omitempty"`
|
||||||
}
|
}
|
||||||
|
WailsFoodSearch struct {
|
||||||
|
Data []FoodSearch `json:"data"`
|
||||||
|
Success bool `json:"success"`
|
||||||
|
Error string `json:"error,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
WailsWeight struct {
|
WailsWeight struct {
|
||||||
Data []Weight `json:"data"`
|
Data []Weight `json:"data"`
|
||||||
|
@@ -24,7 +24,7 @@ const weightcolumns = "rowid, date, weight"
|
|||||||
const weightAggregatedColumns = "period, amount"
|
const weightAggregatedColumns = "period, amount"
|
||||||
|
|
||||||
func (w *WeightService) GetRecent() ([]Weight, error) {
|
func (w *WeightService) GetRecent() ([]Weight, error) {
|
||||||
var res []Weight
|
res := []Weight{}
|
||||||
if w.db == nil || !w.db.Ready {
|
if w.db == nil || !w.db.Ready {
|
||||||
return res, fmt.Errorf("cannot get recent weight, db is nil or is not ready")
|
return res, fmt.Errorf("cannot get recent weight, db is nil or is not ready")
|
||||||
}
|
}
|
||||||
@@ -88,7 +88,7 @@ func (w *WeightService) GetByRowid(rowid int64) (Weight, error) {
|
|||||||
// I could probably refactor this to be less of a disaster...
|
// I could probably refactor this to be less of a disaster...
|
||||||
// But I think it'll work for now
|
// But I think it'll work for now
|
||||||
func (w *WeightService) GetDaily() ([]AggregatedWeight, error) {
|
func (w *WeightService) GetDaily() ([]AggregatedWeight, error) {
|
||||||
var res []AggregatedWeight
|
res := []AggregatedWeight{}
|
||||||
if w.db == nil || !w.db.Ready {
|
if w.db == nil || !w.db.Ready {
|
||||||
return res, fmt.Errorf("cannot get daily weight, db is nil or is not ready")
|
return res, fmt.Errorf("cannot get daily weight, db is nil or is not ready")
|
||||||
}
|
}
|
||||||
@@ -114,7 +114,7 @@ func (w *WeightService) GetDaily() ([]AggregatedWeight, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (w *WeightService) GetWeekly() ([]AggregatedWeight, error) {
|
func (w *WeightService) GetWeekly() ([]AggregatedWeight, error) {
|
||||||
var res []AggregatedWeight
|
res := []AggregatedWeight{}
|
||||||
if w.db == nil || !w.db.Ready {
|
if w.db == nil || !w.db.Ready {
|
||||||
return res, fmt.Errorf("cannot get weekly weight, db is nil or is not ready")
|
return res, fmt.Errorf("cannot get weekly weight, db is nil or is not ready")
|
||||||
}
|
}
|
||||||
@@ -140,7 +140,7 @@ func (w *WeightService) GetWeekly() ([]AggregatedWeight, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (w *WeightService) GetMonthly() ([]AggregatedWeight, error) {
|
func (w *WeightService) GetMonthly() ([]AggregatedWeight, error) {
|
||||||
var res []AggregatedWeight
|
res := []AggregatedWeight{}
|
||||||
if w.db == nil || !w.db.Ready {
|
if w.db == nil || !w.db.Ready {
|
||||||
return res, fmt.Errorf("cannot get monthly weight, db is nil or is not ready")
|
return res, fmt.Errorf("cannot get monthly weight, db is nil or is not ready")
|
||||||
}
|
}
|
||||||
@@ -166,7 +166,7 @@ func (w *WeightService) GetMonthly() ([]AggregatedWeight, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (w *WeightService) GetYearly() ([]AggregatedWeight, error) {
|
func (w *WeightService) GetYearly() ([]AggregatedWeight, error) {
|
||||||
var res []AggregatedWeight
|
res := []AggregatedWeight{}
|
||||||
if w.db == nil || !w.db.Ready {
|
if w.db == nil || !w.db.Ready {
|
||||||
return res, fmt.Errorf("cannot get yearly weight, db is nil or is not ready")
|
return res, fmt.Errorf("cannot get yearly weight, db is nil or is not ready")
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user