12 Commits

33 changed files with 806 additions and 458 deletions

View File

@@ -1,7 +1,8 @@
begin; begin;
create table weight ( create table weight (
date datetime default (datetime('now', '+2 hours')), id integer primary key,
date datetime default (datetime('now')),
weight real not null weight real not null
); );
@@ -18,7 +19,7 @@ drop view if exists weightMonthly;
drop view if exists weightYearly; drop view if exists weightYearly;
create view weightView as create view weightView as
select rowid, select id,
date, date,
round(weight, 2) as weight round(weight, 2) as weight
from weight from weight
@@ -53,7 +54,8 @@ group by strftime('%Y', date)
order by date desc; order by date desc;
create table food( create table food(
date datetime default (datetime('now', '+2 hours')), id integer primary key,
date datetime default (datetime('now')),
food varchar not null, food varchar not null,
description varchar, description varchar,
amount real not null, amount real not null,
@@ -98,7 +100,6 @@ where word = old.food
and rank <= 0; and rank <= 0;
end; end;
drop trigger if exists food_foodfix_update; drop trigger if exists food_foodfix_update;
create trigger food_foodfix_update AFTER create trigger food_foodfix_update AFTER
update on food for EACH row update on food for EACH row
@@ -150,7 +151,7 @@ drop view if exists foodYearly;
drop view if exists foodRecent; drop view if exists foodRecent;
create view foodView as create view foodView as
select rowid, select id,
date, date,
food, food,
description, description,
@@ -196,8 +197,7 @@ group by strftime('%Y', date)
order by date desc; order by date desc;
create view foodRecent as create view foodRecent as
select rowid, select *
*
from food from food
order by date desc order by date desc
limit 10; limit 10;
@@ -218,7 +218,7 @@ set per100 = coalesce(
limit 1 limit 1
) )
) )
where rowid = new.rowid; where id = new.id;
end; end;
create table settings( create table settings(

View File

@@ -11,7 +11,7 @@ type (
db *DB db *DB
} }
Food struct { Food struct {
Rowid int64 `json:"rowid"` Id int64 `json:"id"`
Date string `json:"date"` Date string `json:"date"`
Food string `json:"food"` Food string `json:"food"`
Descripton string `json:"description"` Descripton string `json:"description"`
@@ -31,24 +31,23 @@ type (
} }
) )
const foodColumns = "rowid, date, food, description, amount, per100, energy" const foodColumns = "id, 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() (res []Food, err error) {
var res []Food = []Food{} log.Printf("Getting recent 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")
} }
row, err := s.db.readConn.Query(fmt.Sprintf("SELECT %s from foodView WHERE date > datetime('now', '-%d days') order by date desc;", foodColumns, Settings.FoodDaysLookback)) row, err := s.db.readConn.Query(fmt.Sprintf("SELECT %s from foodView WHERE date > datetime('now', '-%d days') order by date desc;", foodColumns, Settings.FoodDaysLookback))
if err != nil { if err != nil {
log.Printf("error getting daily food: %v", err) return res, fmt.Errorf("error getting recent food: %w", err)
return res, err
} }
for row.Next() { for row.Next() {
var food Food var food Food
err := row.Scan(&food.Rowid, &food.Date, &food.Food, &food.Descripton, &food.Amount, &food.Per100, &food.Energy) err = row.Scan(&food.Id, &food.Date, &food.Food, &food.Descripton, &food.Amount, &food.Per100, &food.Energy)
if err != nil { if err != nil {
log.Printf("error scanning row: %v", err) log.Printf("error scanning row: %v", err)
continue continue
@@ -57,38 +56,39 @@ func (s *FoodService) GetRecent() ([]Food, error) {
res = append(res, food) res = append(res, food)
} }
return res, nil log.Printf("Got %d recent foods", len(res))
return
} }
func (s *FoodService) GetLastPer100(name string) ([]FoodSearch, error) { func (s *FoodService) GetLastPer100(name string) (res []FoodSearch, err error) {
res := []FoodSearch{} log.Printf("Getting last per100 for %s", name)
if s.db == nil || !s.db.Ready { if s.db == nil || !s.db.Ready {
return res, 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")
} }
query := fmt.Sprintf(` query := fmt.Sprintf(`
with search_results as ( with search_results as (
select word, score, f.rowid, f.* select word, score, f.rowid, f.*,
row_number() over (partition by f.food order by score asc, date desc) as rn
from foodfix from foodfix
inner join food f on f.food == word inner join food f on f.food == word
where word MATCH ? where word MATCH ?
) )
select %s, score select %s, score
from search_results from search_results
group by food where rn = 1
order by score asc, date desc order by score asc, date desc
limit %d limit %d
`, foodColumns, Settings.SearchLimit) `, foodColumns, Settings.SearchLimit)
// log.Printf("%#v", query) // log.Printf("%#v", query)
rows, err := s.db.readConn.Query(query, name) rows, err := s.db.readConn.Query(query, name)
if err != nil { if err != nil {
log.Printf("error getting last per100: %v", err) return res, fmt.Errorf("error getting last per100: %w", err)
return res, err
} }
for rows.Next() { for rows.Next() {
var f FoodSearch var f FoodSearch
err := rows.Scan(&f.Rowid, &f.Date, &f.Food.Food, &f.Descripton, &f.Amount, &f.Per100, &f.Energy, &f.Score) err = rows.Scan(&f.Id, &f.Date, &f.Food.Food, &f.Descripton, &f.Amount, &f.Per100, &f.Energy, &f.Score)
if err != nil { if err != nil {
log.Printf("error scanning row: %v", err) log.Printf("error scanning row: %v", err)
continue continue
@@ -100,10 +100,12 @@ limit %d
return nil, fmt.Errorf("no results found for %s", name) return nil, fmt.Errorf("no results found for %s", name)
} }
log.Printf("Got %d last per100 foods for %s", len(res), name)
return res, nil return res, nil
} }
func (s *FoodService) Create(food Food) (Food, error) { func (s *FoodService) Create(food Food) (res Food, err error) {
log.Printf("Creating food %v", food)
if s.db == nil || !s.db.Ready { if s.db == nil || !s.db.Ready {
return food, fmt.Errorf("cannot create food, db is nil or is not ready") return food, fmt.Errorf("cannot create food, db is nil or is not ready")
} }
@@ -114,34 +116,35 @@ func (s *FoodService) Create(food Food) (Food, error) {
return food, fmt.Errorf("cannot create food, amount is less than or equal to 0") return food, fmt.Errorf("cannot create food, amount is less than or equal to 0")
} }
var res sql.Result var dbres sql.Result
var err error
if food.Per100 > 0 { if food.Per100 > 0 {
res, err = s.db.writeConn.Exec("INSERT INTO food (food, description, amount, per100) VALUES (?, ?, ?, ?)", food.Food, food.Descripton, food.Amount, food.Per100) dbres, err = s.db.writeConn.Exec("INSERT INTO food (food, description, amount, per100) VALUES (?, ?, ?, ?)", food.Food, food.Descripton, food.Amount, food.Per100)
if err != nil { if err != nil {
return food, fmt.Errorf("error inserting food: %v", err) return food, fmt.Errorf("error inserting food: %w", err)
} }
} else { } else {
res, err = s.db.writeConn.Exec("INSERT INTO food (food, description, amount) VALUES (?, ?, ?)", food.Food, food.Descripton, food.Amount) dbres, err = s.db.writeConn.Exec("INSERT INTO food (food, description, amount) VALUES (?, ?, ?)", food.Food, food.Descripton, food.Amount)
if err != nil { if err != nil {
return food, fmt.Errorf("error inserting food: %v", err) return food, fmt.Errorf("error inserting food: %w", err)
} }
} }
rowid, err := res.LastInsertId() id, err := dbres.LastInsertId()
if err != nil { if err != nil {
return food, fmt.Errorf("error getting last insert id: %v", err) return food, fmt.Errorf("error getting last insert id: %w", err)
} }
return s.GetByRowid(rowid) log.Printf("Created food %s with id %d", food.Food, id)
return s.GetById(id)
} }
func (s *FoodService) Update(food Food) (Food, error) { func (s *FoodService) Update(food Food) (res Food, err error) {
log.Printf("Updating food %s with id %d", food.Food, food.Id)
if s.db == nil || !s.db.Ready { if s.db == nil || !s.db.Ready {
return food, fmt.Errorf("cannot update food, db is nil or is not ready") return food, fmt.Errorf("cannot update food, db is nil or is not ready")
} }
if food.Rowid <= 0 { if food.Id <= 0 {
return food, fmt.Errorf("cannot update food, rowid is less than or equal to 0") return food, fmt.Errorf("cannot update food, id is less than or equal to 0")
} }
if food.Food == "" { if food.Food == "" {
return food, fmt.Errorf("cannot update food, food is empty") return food, fmt.Errorf("cannot update food, food is empty")
@@ -151,47 +154,48 @@ func (s *FoodService) Update(food Food) (Food, error) {
} }
if food.Per100 > 0 { if food.Per100 > 0 {
_, err := s.db.writeConn.Exec("UPDATE food SET food = ?, description = ?, amount = ?, per100 = ? WHERE rowid = ?", food.Food, food.Descripton, food.Amount, food.Per100, food.Rowid) _, err := s.db.writeConn.Exec("UPDATE food SET food = ?, description = ?, amount = ?, per100 = ? WHERE Id = ?", food.Food, food.Descripton, food.Amount, food.Per100, food.Id)
if err != nil { if err != nil {
return food, fmt.Errorf("error updating food: %v", err) return food, fmt.Errorf("error updating food: %w", err)
} }
} else { } else {
_, err := s.db.writeConn.Exec("UPDATE food SET food = ?, description = ?, amount = ? WHERE rowid = ?", food.Food, food.Descripton, food.Amount, food.Rowid) _, err := s.db.writeConn.Exec("UPDATE food SET food = ?, description = ?, amount = ? WHERE Id = ?", food.Food, food.Descripton, food.Amount, food.Id)
if err != nil { if err != nil {
return food, fmt.Errorf("error updating food: %v", err) return food, fmt.Errorf("error updating food: %w", err)
} }
} }
return s.GetByRowid(food.Rowid) log.Printf("Updated food %s with id %d", food.Food, food.Id)
return s.GetById(food.Id)
} }
func (s *FoodService) GetByRowid(rowid int64) (Food, error) { func (s *FoodService) GetById(id int64) (res Food, err error) {
var res Food log.Printf("Getting food by id %d", id)
if s.db == nil || !s.db.Ready { if s.db == nil || !s.db.Ready {
return res, fmt.Errorf("cannot get food by rowid, db is nil or is not ready") return res, fmt.Errorf("cannot get food by id, db is nil or is not ready")
} }
row := s.db.readConn.QueryRow(fmt.Sprintf("SELECT %s from foodView WHERE rowid = ?", foodColumns), rowid) row := s.db.readConn.QueryRow(fmt.Sprintf("SELECT %s from foodView WHERE id = ?", foodColumns), id)
err := row.Scan(&res.Rowid, &res.Date, &res.Food, &res.Descripton, &res.Amount, &res.Per100, &res.Energy) err = row.Scan(&res.Id, &res.Date, &res.Food, &res.Descripton, &res.Amount, &res.Per100, &res.Energy)
if err != nil { if err != nil {
return res, fmt.Errorf("error scanning row: %v", err) return res, fmt.Errorf("error scanning row: %w", err)
} }
log.Printf("Got food %s with id %d", res.Food, res.Id)
return res, nil return res, nil
} }
// 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() (res []AggregatedFood, err error) {
res := []AggregatedFood{} log.Printf("Getting daily food")
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")
} }
row, err := s.db.readConn.Query(fmt.Sprintf("SELECT %s from foodDaily LIMIT %d", foodAggregatedColumns, Settings.FoodDailyLookback)) row, err := s.db.readConn.Query(fmt.Sprintf("SELECT %s from foodDaily LIMIT %d", foodAggregatedColumns, Settings.FoodDailyLookback))
if err != nil { if err != nil {
log.Printf("error getting daily food: %v", err) return res, fmt.Errorf("error getting daily food: %w", err)
return res, err
} }
for row.Next() { for row.Next() {
@@ -205,24 +209,24 @@ func (s *FoodService) GetDaily() ([]AggregatedFood, error) {
res = append(res, food) res = append(res, food)
} }
log.Printf("Got %d daily foods", len(res))
return res, nil return res, nil
} }
func (s *FoodService) GetWeekly() ([]AggregatedFood, error) { func (s *FoodService) GetWeekly() (res []AggregatedFood, err error) {
res := []AggregatedFood{} log.Printf("Getting weekly food")
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")
} }
row, err := s.db.readConn.Query(fmt.Sprintf("SELECT %s from foodWeekly LIMIT %d", foodAggregatedColumns, Settings.FoodWeeklyLookback)) row, err := s.db.readConn.Query(fmt.Sprintf("SELECT %s from foodWeekly LIMIT %d", foodAggregatedColumns, Settings.FoodWeeklyLookback))
if err != nil { if err != nil {
log.Printf("error getting weekly food: %v", err) return res, fmt.Errorf("error getting weekly food: %w", err)
return res, err
} }
for row.Next() { for row.Next() {
var food AggregatedFood var food AggregatedFood
err := row.Scan(&food.Period, &food.Amount, &food.AvgPer100, &food.Energy) err = row.Scan(&food.Period, &food.Amount, &food.AvgPer100, &food.Energy)
if err != nil { if err != nil {
log.Printf("error scanning row: %v", err) log.Printf("error scanning row: %v", err)
continue continue
@@ -231,24 +235,24 @@ func (s *FoodService) GetWeekly() ([]AggregatedFood, error) {
res = append(res, food) res = append(res, food)
} }
log.Printf("Got %d weekly foods", len(res))
return res, nil return res, nil
} }
func (s *FoodService) GetMonthly() ([]AggregatedFood, error) { func (s *FoodService) GetMonthly() (res []AggregatedFood, err error) {
res := []AggregatedFood{} log.Printf("Getting monthly food")
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")
} }
row, err := s.db.readConn.Query(fmt.Sprintf("SELECT %s from foodMonthly LIMIT %d", foodAggregatedColumns, Settings.FoodMonthlyLookback)) row, err := s.db.readConn.Query(fmt.Sprintf("SELECT %s from foodMonthly LIMIT %d", foodAggregatedColumns, Settings.FoodMonthlyLookback))
if err != nil { if err != nil {
log.Printf("error getting monthly food: %v", err) return res, fmt.Errorf("error getting monthly food: %w", err)
return res, err
} }
for row.Next() { for row.Next() {
var food AggregatedFood var food AggregatedFood
err := row.Scan(&food.Period, &food.Amount, &food.AvgPer100, &food.Energy) err = row.Scan(&food.Period, &food.Amount, &food.AvgPer100, &food.Energy)
if err != nil { if err != nil {
log.Printf("error scanning row: %v", err) log.Printf("error scanning row: %v", err)
continue continue
@@ -257,24 +261,24 @@ func (s *FoodService) GetMonthly() ([]AggregatedFood, error) {
res = append(res, food) res = append(res, food)
} }
log.Printf("Got %d monthly foods", len(res))
return res, nil return res, nil
} }
func (s *FoodService) GetYearly() ([]AggregatedFood, error) { func (s *FoodService) GetYearly() (res []AggregatedFood, err error) {
res := []AggregatedFood{} log.Printf("Getting yearly food")
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")
} }
row, err := s.db.readConn.Query(fmt.Sprintf("SELECT %s from foodYearly LIMIT %d", foodAggregatedColumns, Settings.FoodYearlyLookback)) row, err := s.db.readConn.Query(fmt.Sprintf("SELECT %s from foodYearly LIMIT %d", foodAggregatedColumns, Settings.FoodYearlyLookback))
if err != nil { if err != nil {
log.Printf("error getting yearly food: %v", err) return res, fmt.Errorf("error getting yearly food: %w", err)
return res, err
} }
for row.Next() { for row.Next() {
var food AggregatedFood var food AggregatedFood
err := row.Scan(&food.Period, &food.Amount, &food.AvgPer100, &food.Energy) err = row.Scan(&food.Period, &food.Amount, &food.AvgPer100, &food.Energy)
if err != nil { if err != nil {
log.Printf("error scanning row: %v", err) log.Printf("error scanning row: %v", err)
continue continue
@@ -283,5 +287,6 @@ func (s *FoodService) GetYearly() ([]AggregatedFood, error) {
res = append(res, food) res = append(res, food)
} }
log.Printf("Got %d yearly foods", len(res))
return res, nil return res, nil
} }

View File

@@ -1,13 +1,15 @@
<script lang="ts"> <script lang="ts">
import { main } from "$wails/models"; import { main } from "$wails/models";
export let item: main.AggregatedFood export let item: main.AggregatedFood;
</script> </script>
<template> <template>
<tr class="border-b border-gray-200 dark:border-gray-700"> <tr class="border-b border-gray-200 dark:border-gray-700">
<th class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap bg-gray-50 dark:text-white dark:bg-gray-800" <th
scope="row"> class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap bg-gray-50 dark:text-white dark:bg-gray-800"
scope="row"
>
{item.period} {item.period}
</th> </th>
<td class="px-6 py-4"> <td class="px-6 py-4">

View File

@@ -24,17 +24,18 @@
let reversedItems = items.slice().reverse(); let reversedItems = items.slice().reverse();
const defaultOptions = { const defaultOptions = {
backgroundColor: "rgba(225, 204,230, .3)", backgroundColor: "rgba(59, 130, 246, 0.1)",
borderColor: "rgb(205, 130, 158)", borderColor: "rgb(59, 130, 246)",
pointBorderColor: "rgb(205, 130, 158)", pointBorderColor: "rgb(59, 130, 246)",
pointBackgroundColor: "rgb(255, 255, 255)", pointBackgroundColor: "rgb(255, 255, 255)",
pointBorderWidth: 10, pointBorderWidth: 2,
pointHoverRadius: 5, pointHoverRadius: 6,
pointHoverBackgroundColor: "rgb(0, 157, 123)", pointHoverBackgroundColor: "rgb(59, 130, 246)",
pointHoverBorderColor: "rgba(220, 220, 220, 1)", pointHoverBorderColor: "rgb(255, 255, 255)",
pointHoverBorderWidth: 2, pointHoverBorderWidth: 2,
pointRadius: 1, pointRadius: 3,
pointHitRadius: 20, pointHitRadius: 20,
tension: 0.4,
}; };
const data: ChartData<"line", (number | Point)[]> = { const data: ChartData<"line", (number | Point)[]> = {
labels: reversedItems.map((f) => f.period), labels: reversedItems.map((f) => f.period),
@@ -87,25 +88,72 @@
</script> </script>
<template> <template>
<Line {data} class="max-h-[50vh] h-[50vh]" /> <div class="flex flex-col gap-6 p-6 bg-gray-900 min-h-screen">
<div class="relative flex flex-col h-[43vh]" data-vaul-drawer-wrapper id="page"> <div class="bg-gray-800 rounded-lg p-6 shadow-lg border border-gray-700">
<div class="relative overflow-x-auto shadow-md sm:rounded-lg"> <Line
<table class="w-full text-sm text-left rtl:text-right text-gray-500 dark:text-gray-400"> {data}
<thead class="text-xs text-gray-700 uppercase dark:text-gray-400"> options={{
<tr> responsive: true,
<th class="px-6 py-3 bg-gray-50 dark:bg-gray-800 w-2/12" scope="col"> Period </th> maintainAspectRatio: false,
<th class="px-6 py-3" scope="col"> Amount </th> plugins: {
<th class="px-6 py-3 bg-gray-50 dark:bg-gray-800" scope="col"> AvgPer100 </th> legend: {
<th class="px-6 py-3" scope="col"> Energy </th> position: "top",
</tr> labels: {
</thead> padding: 20,
<tbody> color: "rgb(229, 231, 235)",
{#each items as f} font: {
<AggregatedFoodComp item={f} /> size: 12,
{/each} family: "'Nunito', sans-serif",
</tbody> },
</table> },
},
},
scales: {
y: {
grid: {
color: "rgba(75, 85, 99, 0.2)",
},
ticks: {
color: "rgb(229, 231, 235)",
font: {
family: "'Nunito', sans-serif",
},
},
},
x: {
grid: {
color: "rgba(75, 85, 99, 0.2)",
},
ticks: {
color: "rgb(229, 231, 235)",
font: {
family: "'Nunito', sans-serif",
},
},
},
},
}}
class="max-h-[50vh] h-[50vh]"
/>
</div>
<div class="relative flex flex-col h-[43vh]" data-vaul-drawer-wrapper id="page">
<div class="relative overflow-x-auto shadow-md rounded-lg">
<table class="w-full text-sm text-left text-gray-400">
<thead class="text-xs uppercase bg-gray-800 text-gray-200 sticky top-0">
<tr>
<th class="px-6 py-4 font-semibold" scope="col">Period</th>
<th class="px-6 py-4 font-semibold" scope="col">Amount</th>
<th class="px-6 py-4 font-semibold" scope="col">AvgPer100</th>
<th class="px-6 py-4 font-semibold" scope="col">Energy</th>
</tr>
</thead>
<tbody class="divide-y divide-gray-700">
{#each items as f}
<AggregatedFoodComp item={f} />
{/each}
</tbody>
</table>
</div>
</div> </div>
<div></div>
</div> </div>
</template> </template>

View File

@@ -9,7 +9,7 @@
food: "", food: "",
amount: 0, amount: 0,
description: "", description: "",
rowid: 0, id: 0,
date: "", date: "",
per100: 0, per100: 0,
energy: 0, energy: 0,
@@ -23,9 +23,8 @@
let nameElement: HTMLTableCellElement; let nameElement: HTMLTableCellElement;
let autocompleteList: HTMLUListElement; let autocompleteList: HTMLUListElement;
let foodSearch: main.Food[] = []; let foodSearch: main.Food[] = [];
let hiLiteIndex: number = -1;
// 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(); name = name.trim();
if (!name) { if (!name) {
@@ -38,16 +37,37 @@
function updateAutocomplete() { function updateAutocomplete() {
if (!per100Edited) if (!per100Edited)
GetLastPer100(name.trim()).then((res) => { GetLastPer100(name.trim()).then((res) => {
// Prevent search when there's nothing to search
// Sometimes we get search results after deleting name
if (res.success && res.data && name) { if (res.success && res.data && name) {
foodSearch = res.data; foodSearch = res.data;
hiLiteIndex = -1;
} else { } else {
foodSearch = []; foodSearch = [];
} }
}); });
} }
async function handleSubmit() {
item.food = name;
item.description = description;
item.amount = parseInt(amount);
item.per100 = parseInt(per100);
const res = await CreateFood(item);
name = "";
amount = "";
per100 = "";
per100Edited = false;
if (!res.success) {
toast.error(`failed to create item with error ${res.error}`);
return;
}
foodStore.update((value) => [res.data, ...value]);
nameElement.focus();
foodSearch = [];
}
async function update(event: KeyboardEvent & { currentTarget: EventTarget & HTMLTableCellElement }) { async function update(event: KeyboardEvent & { currentTarget: EventTarget & HTMLTableCellElement }) {
name = name.trim(); name = name.trim();
amount = amount.trim(); amount = amount.trim();
@@ -61,52 +81,48 @@
if (!per100Edited && event.currentTarget == per100Element) per100Edited = true; if (!per100Edited && event.currentTarget == per100Element) per100Edited = true;
if (event.key == "Enter") { if (event.key === "Enter") {
event.preventDefault(); event.preventDefault();
item.food = name;
item.description = description;
item.amount = parseInt(amount);
item.per100 = parseInt(per100);
const res = await CreateFood(item); // If suggestions are visible and we have a highlighted item or at least one suggestion
name = ""; if (foodSearch.length > 0) {
amount = ""; const selectedFood = hiLiteIndex >= 0 ? foodSearch[hiLiteIndex] : foodSearch[0];
// description = '' setInputVal(selectedFood);
per100 = "";
per100Edited = false;
if (!res.success) {
toast.error(`failed to create item with error ${res.error}`);
return; return;
} }
foodStore.update((value) => [res.data, ...value]); // Only submit if we have no suggestions visible
nameElement.focus(); if (name && amount && per100) {
foodSearch = []; await handleSubmit();
}
}
}
function navigateList(e: KeyboardEvent) {
if (!foodSearch.length) return;
switch (e.key) {
case "ArrowDown":
e.preventDefault();
hiLiteIndex = Math.min(hiLiteIndex + 1, foodSearch.length - 1);
break;
case "ArrowUp":
e.preventDefault();
hiLiteIndex = Math.max(hiLiteIndex - 1, -1);
break;
case "Escape":
e.preventDefault();
foodSearch = [];
hiLiteIndex = -1;
break;
} }
} }
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) { function setInputVal(food: main.Food) {
name = food.food; name = food.food;
per100 = String(food.per100); per100 = String(food.per100);
hiLiteIndex = null; amount = String(food.amount);
hiLiteIndex = -1;
foodSearch = []; foodSearch = [];
} }
@@ -122,6 +138,7 @@
function handleFocusOut() { function handleFocusOut() {
timeout = setTimeout(() => { timeout = setTimeout(() => {
foodSearch = []; foodSearch = [];
hiLiteIndex = -1;
}, 100); }, 100);
} }
@@ -131,20 +148,16 @@
} }
</script> </script>
<!-- <svelte:window on:keydown={navigateList} /> --> <svelte:window on:keydown={navigateList} />
<template> <template>
<tr class="border-b border-gray-200 dark:border-gray-700 text-lg font-bold relative"> <tr class="border-b border-gray-700 text-lg font-medium hover:bg-gray-800/50 transition-colors">
<th <th class="px-6 py-4 font-medium text-gray-200 whitespace-nowrap" scope="row" />
class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap bg-gray-50 dark:text-white dark:bg-gray-800"
scope="row"
></th>
<!-- svelte-ignore a11y-autofocus -->
<td <td
bind:innerText={name} bind:innerText={name}
class:border-[3px]={!name} class="px-6 py-4 overflow-hidden focus:outline-none focus:ring-2 focus:ring-blue-500 rounded transition-all"
class:border-red-600={!name} class:ring-2={!name}
class="px-6 py-4 overflow-hidden" class:ring-red-500={!name}
contenteditable="true" contenteditable="true"
autofocus autofocus
on:keydown={update} on:keydown={update}
@@ -179,7 +192,7 @@
{#if foodSearch.length > 0} {#if foodSearch.length > 0}
<ul bind:this={autocompleteList} class="z-50 fixed top-0 left-0 w-3/12 border border-x-gray-800"> <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} {#each foodSearch as f, i}
<FoodSearchEntry itemLabel={f.food} highlighted={i == hiLiteIndex} on:click={() => setInputVal(f)} /> <FoodSearchEntry itemLabel={f.food} highlighted={i === hiLiteIndex} on:click={() => setInputVal(f)} />
{/each} {/each}
</ul> </ul>
{/if} {/if}

View File

@@ -57,5 +57,11 @@
</script> </script>
<template> <template>
<div class="px-4 text-bold text-3xl" style="color: {color}">{remainingToday}</div> <div
class="px-6 py-3 text-3xl font-bold rounded-lg bg-gray-800/50 shadow-lg border border-gray-700"
style="color: {color}"
>
<span class="mr-2">{remainingToday}</span>
<span class="text-lg text-gray-400">kcal remaining</span>
</div>
</template> </template>

View File

@@ -1,84 +1,105 @@
<script lang="ts"> <script lang="ts">
import { UpdateFood } from '$wails/main/App'; import { UpdateFood } from "$wails/main/App";
import {main} from '$wails/models' import { main } from "$wails/models";
import { toast } from 'svelte-sonner' import { toast } from "svelte-sonner";
export let item: main.Food export let item: main.Food;
export let energyColor: string export let energyColor: string;
export let nameColor: string export let nameColor: string;
export let dateColor: string export let dateColor: string;
let amount: string = item.amount.toString() let date = new Date(item.date);
let per100: string = item.per100?.toString() ?? '' let dateString = new Intl.DateTimeFormat("en-CA", {
let description: string = item.description ?? '' year: "numeric",
let name: string = item.food month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hour12: false,
}).format(date);
async function update(event: KeyboardEvent & { currentTarget: (EventTarget & HTMLTableCellElement) }) { let amount: string = item.amount.toString();
if (event.key == 'Enter') { let per100: string = item.per100?.toString() ?? "";
event.preventDefault() let description: string = item.description ?? "";
await updateItem() let name: string = item.food;
async function update(event: KeyboardEvent & { currentTarget: EventTarget & HTMLTableCellElement }) {
if (event.key == "Enter") {
event.preventDefault();
await updateItem();
} }
} }
async function focusOutUpdate() { async function focusOutUpdate() {
await updateItem() await updateItem();
} }
async function updateItem() { async function updateItem() {
amount = amount.trim() amount = amount.trim();
per100 = per100.trim() per100 = per100.trim();
description = description.trim() description = description.trim();
name = name.trim() name = name.trim();
item.food = name item.food = name;
item.description = description item.description = description;
item.amount = parseInt(amount) item.amount = parseInt(amount);
item.per100 = parseInt(per100) item.per100 = parseInt(per100);
const res = await UpdateFood(item) const res = await UpdateFood(item);
if (!res.success) { if (!res.success) {
toast.error(`failed to update food item with error ${res.error}`) toast.error(`failed to update food item with error ${res.error}`);
} else { } else {
item = res.data item = res.data;
} }
name = item.food name = item.food;
description = item.description ?? '' description = item.description ?? "";
amount = item.amount.toString() amount = item.amount.toString();
per100 = item.per100?.toString() ?? '' per100 = item.per100?.toString() ?? "";
} }
</script> </script>
<template> <template>
<tr class="border-b border-gray-200 dark:border-gray-700 font-bold text-lg"> <tr class="border-b border-gray-200 dark:border-gray-700 font-bold text-lg">
<th class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap bg-gray-50 dark:text-white dark:bg-gray-800" <th
style="color: {dateColor}" class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap bg-gray-50 dark:text-white dark:bg-gray-800"
scope="row"> style="color: {dateColor}"
{item.date} scope="row"
>
{dateString}
</th> </th>
<td class="px-6 py-4" <td
style="color: {nameColor}" class="px-6 py-4"
contenteditable="true" style="color: {nameColor}"
bind:innerText={name} contenteditable="true"
on:focusout={focusOutUpdate} bind:innerText={name}
on:keydown={update}> on:focusout={focusOutUpdate}
on:keydown={update}
>
</td> </td>
<td class="px-6 py-4 bg-gray-50 dark:bg-gray-800" <td
contenteditable="true" class="px-6 py-4 bg-gray-50 dark:bg-gray-800"
bind:innerText={description} contenteditable="true"
on:focusout={focusOutUpdate} bind:innerText={description}
on:keydown={update}> on:focusout={focusOutUpdate}
on:keydown={update}
>
</td> </td>
<td class="px-6 py-4" <td
contenteditable="true" class="px-6 py-4"
bind:innerText={amount} contenteditable="true"
on:focusout={focusOutUpdate} bind:innerText={amount}
on:keydown={update}> on:focusout={focusOutUpdate}
on:keydown={update}
>
</td> </td>
<td class="px-6 py-4 bg-gray-50 dark:bg-gray-800" <td
contenteditable="true" class="px-6 py-4 bg-gray-50 dark:bg-gray-800"
bind:innerText={per100} contenteditable="true"
on:focusout={focusOutUpdate} bind:innerText={per100}
on:keydown={update}> on:focusout={focusOutUpdate}
on:keydown={update}
>
</td> </td>
<td class="px-6 py-4" style="color: {energyColor}"> <td class="px-6 py-4" style="color: {energyColor}">
{item.energy} {item.energy}

View File

@@ -1,15 +1,13 @@
<script> <script lang="ts">
// This doesn't update when navigating with arrows keys... export let itemLabel: string;
// Fucking svelte and reactivity again, here we fucking go export let highlighted: boolean;
export let itemLabel;
export let highlighted;
</script> </script>
<!-- svelte-ignore a11y-click-events-have-key-events -->
<li <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="list-none px-4 py-3 cursor-pointer bg-gray-800 text-gray-200 text-base border-b border-gray-700 transition-colors"
class:bg-DodgerBlue={highlighted} class:bg-blue-600={highlighted}
class:text-white={highlighted} class:text-white={highlighted}
on:click> on:click
>
{itemLabel} {itemLabel}
</li> </li>

View File

@@ -59,20 +59,20 @@
</script> </script>
<template> <template>
<div class="relative flex flex-col flex-grow h-[93vh] select-none" data-vaul-drawer-wrapper id="page"> <div class="relative flex flex-col flex-grow h-[93vh] select-none bg-gray-900" data-vaul-drawer-wrapper id="page">
<div class="relative overflow-auto h-full shadow-md sm:rounded-lg"> <div class="relative overflow-auto h-full shadow-md rounded-lg">
<table class="w-full text-sm text-left rtl:text-right text-gray-500 dark:text-gray-400"> <table class="w-full text-sm text-left text-gray-400">
<thead class="text-xs text-gray-700 uppercase dark:text-gray-400"> <thead class="text-xs uppercase bg-gray-800 text-gray-200 sticky top-0">
<tr> <tr>
<th class="px-6 py-3 bg-gray-50 dark:bg-gray-800 w-2/12" scope="col"> Date </th> <th class="px-6 py-4 font-semibold w-2/12" scope="col">Date</th>
<th class="px-6 py-3 w-3/12" scope="col"> Food </th> <th class="px-6 py-4 font-semibold" scope="col">Food</th>
<th class="px-6 py-3 bg-gray-50 dark:bg-gray-800 w-4/12" scope="col"> Description </th> <th class="px-6 py-4 font-semibold" scope="col">Description</th>
<th class="px-6 py-3 w-1/12" scope="col"> Amount </th> <th class="px-6 py-4 font-semibold" scope="col">Amount</th>
<th class="px-6 py-3 bg-gray-50 dark:bg-gray-800 w-1/12" scope="col"> Cal Per 100 </th> <th class="px-6 py-4 font-semibold" scope="col">Cal Per 100</th>
<th class="px-6 py-3 w-1/12" scope="col"> Energy </th> <th class="px-6 py-4 font-semibold" scope="col">Energy</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody class="divide-y divide-gray-700">
<EmptyFoodComp /> <EmptyFoodComp />
{#each items as f} {#each items as f}
<FoodComp <FoodComp
@@ -85,6 +85,5 @@
</tbody> </tbody>
</table> </table>
</div> </div>
<div></div>
</div> </div>
</template> </template>

View File

@@ -1,6 +1,6 @@
<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";
@@ -49,48 +49,40 @@
</script> </script>
<header <header
class="flex h-22 items-center justify-center bg-base-100 shadow-lg sticky top-0 z-50 border-b class="flex h-24 items-center justify-between bg-gray-900 shadow-lg sticky top-0 z-50 border-b border-gray-700/40 backdrop-blur supports-[backdrop-filter]:bg-gray-900/60 px-6"
border-border/40 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60"
> >
<div> <div class="flex flex-col gap-2">
<nav class="flex space-x-4 text-2xl font-bold select-none justify-center"> <nav class="flex space-x-6 text-2xl font-bold select-none">
<a <a
use:link use:link
class={"/" == $location class="transition-colors hover:text-gray-200 {$location === '/' ? 'text-white' : 'text-gray-400'}"
? "transition-colors hover:text-foreground/80"
: "transition-colors hover:text-foreground/80 text-foreground/60"}
href="/" href="/"
on:click={(e) => (selected = "Energy")}>Energy</a on:click={() => (selected = "Energy")}>Energy</a
> >
<a <a
use:link use:link
class={"/Weight" == $location class="transition-colors hover:text-gray-200 {$location === '/Weight' ? 'text-white' : 'text-gray-400'}"
? "transition-colors hover:text-foreground/80"
: "transition-colors hover:text-foreground/80 text-foreground/60"}
href="/Weight" href="/Weight"
on:click={(e) => (selected = "Weight")}>Weight</a on:click={() => (selected = "Weight")}>Weight</a
> >
</nav> </nav>
<nav class="flex space-x-4 text-2xl font-bold select-none justify-center"> <nav class="flex space-x-6 text-xl font-medium select-none">
{#each sublinks as { label, href }} {#each sublinks as { label, href }}
<a <a
use:link use:link
{href} {href}
class={href == $location class="transition-colors hover:text-gray-200 {href === $location ? 'text-white' : 'text-gray-400'}"
? "transition-colors hover:text-foreground/80" >{label}</a
: "transition-colors hover:text-foreground/80 text-foreground/60"}>{label}</a
> >
{/each} {/each}
</nav> </nav>
</div> </div>
<!-- svelte-ignore a11y-click-events-have-key-events --> <div class="flex items-center gap-6">
<div class="absolute right-0 pt-4 pb-4 pr-8 pl-8 cursor-pointer" on:click={() => (showModal = true)}> <EnergyToday />
<button> <button class="p-3 hover:bg-gray-800 rounded-lg transition-colors" on:click={() => (showModal = true)}>
<Fa icon={faGear} scale={2} /> <Fa icon={faGear} scale={2} />
</button> </button>
</div> </div>
<RefreshComponent />
<EnergyToday />
</header> </header>
<Settings bind:showModal /> <Settings bind:showModal />

View File

@@ -35,7 +35,7 @@
<template> <template>
<!-- svelte-ignore a11y-click-events-have-key-events --> <!-- 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}> <div class="absolute right-20 pt-4 pb-4 pr-8 pl-8 cursor-pointer" on:click={refreshStores}>
<button> <button class="p-3 hover:bg-gray-800 rounded-lg transition-colors">
<Fa icon={faRefresh} scale={2} /> <Fa icon={faRefresh} scale={2} />
</button> </button>
</div> </div>

View File

@@ -18,7 +18,7 @@
if (!res.success) { if (!res.success) {
toast.error(`Failed to set setting with error ${res.error}`); toast.error(`Failed to set setting with error ${res.error}`);
editSetting = String(setting); editSetting = String(setting);
return return;
} }
setting = numSetting; setting = numSetting;
settingsStore.update((store) => { settingsStore.update((store) => {

View File

@@ -11,7 +11,7 @@
<div class="flex flex-2 flex-col gap-4 text-left text-xl"> <div class="flex flex-2 flex-col gap-4 text-left text-xl">
{#each Object.keys($settingsStore) as key} {#each Object.keys($settingsStore) as key}
<Setting key={key} setting={$settingsStore[key]} /> <Setting {key} setting={$settingsStore[key]} />
{/each} {/each}
</div> </div>
</Modal> </Modal>

View File

@@ -1,13 +1,15 @@
<script lang="ts"> <script lang="ts">
import {main} from '$wails/models' import { main } from "$wails/models";
export let item: main.AggregatedWeight export let item: main.AggregatedWeight;
</script> </script>
<template> <template>
<tr class="border-b border-gray-200 dark:border-gray-700"> <tr class="border-b border-gray-200 dark:border-gray-700">
<th class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap bg-gray-50 dark:text-white dark:bg-gray-800" <th
scope="row"> class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap bg-gray-50 dark:text-white dark:bg-gray-800"
scope="row"
>
{item.period} {item.period}
</th> </th>
<td class="px-6 py-4"> <td class="px-6 py-4">

View File

@@ -21,17 +21,18 @@
let reversedItems = items.slice().reverse(); let reversedItems = items.slice().reverse();
const defaultOptions = { const defaultOptions = {
backgroundColor: "rgba(225, 204,230, .3)", backgroundColor: "rgba(59, 130, 246, 0.1)",
borderColor: "rgb(205, 130, 158)", borderColor: "rgb(59, 130, 246)",
pointBorderColor: "rgb(205, 130, 158)", pointBorderColor: "rgb(59, 130, 246)",
pointBackgroundColor: "rgb(255, 255, 255)", pointBackgroundColor: "rgb(255, 255, 255)",
pointBorderWidth: 10, pointBorderWidth: 2,
pointHoverRadius: 5, pointHoverRadius: 6,
pointHoverBackgroundColor: "rgb(0, 157, 123)", pointHoverBackgroundColor: "rgb(59, 130, 246)",
pointHoverBorderColor: "rgba(220, 220, 220, 1)", pointHoverBorderColor: "rgb(255, 255, 255)",
pointHoverBorderWidth: 2, pointHoverBorderWidth: 2,
pointRadius: 1, pointRadius: 3,
pointHitRadius: 10, pointHitRadius: 20,
tension: 0.4,
}; };
const data: ChartData<"line", (number | Point)[]> = { const data: ChartData<"line", (number | Point)[]> = {
labels: reversedItems.map((f) => f.period), labels: reversedItems.map((f) => f.period),
@@ -56,23 +57,70 @@
</script> </script>
<template> <template>
<Line {data} class="max-h-[50vh] h-[50vh]" /> <div class="flex flex-col gap-6 p-6 bg-gray-900 min-h-screen">
<div class="relative flex flex-col h-[43vh]" data-vaul-drawer-wrapper id="page"> <div class="bg-gray-800 rounded-lg p-6 shadow-lg border border-gray-700">
<div class="relative overflow-x-auto shadow-md sm:rounded-lg"> <Line
<table class="w-full text-sm text-left rtl:text-right text-gray-500 dark:text-gray-400"> {data}
<thead class="text-xs text-gray-700 uppercase dark:text-gray-400"> options={{
<tr> responsive: true,
<th class="px-6 py-3 bg-gray-50 dark:bg-gray-800 w-2/12" scope="col"> Period </th> maintainAspectRatio: false,
<th class="px-6 py-3" scope="col"> Amount </th> plugins: {
</tr> legend: {
</thead> position: "top",
<tbody> labels: {
{#each items as f} padding: 20,
<AggregatedWeightComp item={f} /> color: "rgb(229, 231, 235)",
{/each} font: {
</tbody> size: 12,
</table> family: "'Nunito', sans-serif",
},
},
},
},
scales: {
y: {
grid: {
color: "rgba(75, 85, 99, 0.2)",
},
ticks: {
color: "rgb(229, 231, 235)",
font: {
family: "'Nunito', sans-serif",
},
},
},
x: {
grid: {
color: "rgba(75, 85, 99, 0.2)",
},
ticks: {
color: "rgb(229, 231, 235)",
font: {
family: "'Nunito', sans-serif",
},
},
},
},
}}
class="max-h-[50vh] h-[50vh]"
/>
</div>
<div class="relative flex flex-col h-[43vh]" data-vaul-drawer-wrapper id="page">
<div class="relative overflow-x-auto shadow-md rounded-lg">
<table class="w-full text-sm text-left text-gray-400">
<thead class="text-xs uppercase bg-gray-800 text-gray-200 sticky top-0">
<tr>
<th class="px-6 py-4 font-semibold" scope="col">Period</th>
<th class="px-6 py-4 font-semibold" scope="col">Amount</th>
</tr>
</thead>
<tbody>
{#each items as f}
<AggregatedWeightComp item={f} />
{/each}
</tbody>
</table>
</div>
</div> </div>
<div></div>
</div> </div>
</template> </template>

View File

@@ -1,34 +1,34 @@
<script lang="ts"> <script lang="ts">
import { toast } from 'svelte-sonner' import { toast } from "svelte-sonner";
import { main } from "$wails/models"; import { main } from "$wails/models";
import { CreateWeight } from '$wails/main/App'; import { CreateWeight } from "$wails/main/App";
import { weightStore } from '$lib/store/Weight/weightStore'; import { weightStore } from "$lib/store/Weight/weightStore";
let item: main.Weight = { let item: main.Weight = {
weight: 0, weight: 0,
rowid: 0, id: 0,
date: '' date: "",
} };
let weight: string | null = null let weight: string | null = null;
async function update(event: KeyboardEvent & { currentTarget: (EventTarget & HTMLTableCellElement) }) { async function update(event: KeyboardEvent & { currentTarget: EventTarget & HTMLTableCellElement }) {
if (!weight) return if (!weight) return;
weight = weight.trim() weight = weight.trim();
if (event.key == 'Enter') { if (event.key == "Enter") {
event.preventDefault() event.preventDefault();
item.weight = parseFloat(weight) item.weight = parseFloat(weight);
if (isNaN(item.weight)) { if (isNaN(item.weight)) {
toast.error('Weight must be a number') toast.error("Weight must be a number");
return return;
} }
const res = await CreateWeight(item) const res = await CreateWeight(item);
weight = '' weight = "";
if (!res.success) { if (!res.success) {
toast.error(`failed to create weight with error ${res.error}`) toast.error(`failed to create weight with error ${res.error}`);
return return;
} }
console.log("update"); console.log("update");
@@ -39,16 +39,20 @@
<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">
<th class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap bg-gray-50 dark:text-white dark:bg-gray-800" <th
scope="row"> class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap bg-gray-50 dark:text-white dark:bg-gray-800"
scope="row"
>
</th> </th>
<td bind:innerText={weight} <td
class:border-[3px]={!weight} bind:innerText={weight}
class:border-red-600={!weight} class:border-[3px]={!weight}
class="px-6 py-4 overflow-hidden" class:border-red-600={!weight}
contenteditable="true" class="px-6 py-4 overflow-hidden"
autofocus contenteditable="true"
on:keydown={update}> autofocus
on:keydown={update}
>
</td> </td>
</tr> </tr>
</template> </template>

View File

@@ -1,16 +1,29 @@
<script lang="ts"> <script lang="ts">
import { main } from "$wails/models"; import { main } from "$wails/models";
export let item: main.Weight export let item: main.Weight;
export let dateColor: string export let dateColor: string;
let date = new Date(item.date);
let dateString = new Intl.DateTimeFormat("en-CA", {
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hour12: false,
}).format(date);
</script> </script>
<template> <template>
<tr class="border-b border-gray-200 dark:border-gray-700 font-bold text-lg"> <tr class="border-b border-gray-200 dark:border-gray-700 font-bold text-lg">
<th class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap bg-gray-50 dark:text-white dark:bg-gray-800" <th
style="color: {dateColor}" class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap bg-gray-50 dark:text-white dark:bg-gray-800"
scope="row"> style="color: {dateColor}"
{item.date} scope="row"
>
{dateString}
</th> </th>
<td class="px-6 py-4"> <td class="px-6 py-4">
{item.weight} {item.weight}

View File

@@ -15,25 +15,22 @@
const date = item.date.toString().split("T")[0]; const date = item.date.toString().split("T")[0];
if (!date) return GenerateColor(); if (!date) return GenerateColor();
if (!dateColors.has(date)) dateColors.set(date, GenerateColor()); if (!dateColors.has(date)) dateColors.set(date, GenerateColor());
// THERE'S NOTHING UNDEFINED HERE
// WE GOT RID OF UNDEFINED ON LINE 33
// ASSHOLE
// @ts-ignore // @ts-ignore
return dateColors.get(date); return dateColors.get(date);
} }
</script> </script>
<template> <template>
<div class="relative flex flex-col flex-grow h-[93vh]" data-vaul-drawer-wrapper id="page"> <div class="relative flex flex-col flex-grow h-[93vh] select-none bg-gray-900" data-vaul-drawer-wrapper id="page">
<div class="relative overflow-auto h-full shadow-md sm:rounded-lg"> <div class="relative overflow-auto h-full shadow-md rounded-lg">
<table class="w-full text-sm text-left rtl:text-right text-gray-500 dark:text-gray-400"> <table class="w-full text-sm text-left text-gray-400">
<thead class="text-xs text-gray-700 uppercase dark:text-gray-400"> <thead class="text-xs uppercase bg-gray-800 text-gray-200 sticky top-0">
<tr> <tr>
<th class="px-6 py-3 bg-gray-50 dark:bg-gray-800 w-2/12" scope="col"> Date </th> <th class="px-6 py-4 font-semibold w-2/12" scope="col">Date</th>
<th class="px-6 py-3 w-10/12" scope="col"> Weight </th> <th class="px-6 py-4 font-semibold" scope="col">Weight</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody class="divide-y divide-gray-700">
<EmptyWeightComp /> <EmptyWeightComp />
{#each items as f} {#each items as f}
<WeightComp item={f} dateColor={getDateColor(f)} /> <WeightComp item={f} dateColor={getDateColor(f)} />
@@ -41,6 +38,5 @@
</tbody> </tbody>
</table> </table>
</div> </div>
<div></div>
</div> </div>
</template> </template>

View File

@@ -1,29 +1,29 @@
<script lang="ts"> <script lang="ts">
import Router from 'svelte-spa-router' import Router from "svelte-spa-router";
import Energy from './routes/Energy/Energy.svelte' import Energy from "./routes/Energy/Energy.svelte";
import Daily from './routes/Energy/Daily.svelte' import Daily from "./routes/Energy/Daily.svelte";
import Weekly from './routes/Energy/Weekly.svelte' import Weekly from "./routes/Energy/Weekly.svelte";
import Monthly from './routes/Energy/Monthly.svelte' import Monthly from "./routes/Energy/Monthly.svelte";
import Yearly from './routes/Energy/Yearly.svelte' import Yearly from "./routes/Energy/Yearly.svelte";
import Weight from './routes/Weight/Weight.svelte' import Weight from "./routes/Weight/Weight.svelte";
import WDaily from './routes/Weight/WDaily.svelte' import WDaily from "./routes/Weight/WDaily.svelte";
import WWeekly from './routes/Weight/WWeekly.svelte' import WWeekly from "./routes/Weight/WWeekly.svelte";
import WMonthly from './routes/Weight/WMonthly.svelte' import WMonthly from "./routes/Weight/WMonthly.svelte";
import WYearly from './routes/Weight/WYearly.svelte' import WYearly from "./routes/Weight/WYearly.svelte";
const routes = { const routes = {
'/': Energy, "/": Energy,
'/Energy': Energy, "/Energy": Energy,
'/Energy/daily': Daily, "/Energy/daily": Daily,
'/Energy/weekly': Weekly, "/Energy/weekly": Weekly,
'/Energy/monthly': Monthly, "/Energy/monthly": Monthly,
'/Energy/yearly': Yearly, "/Energy/yearly": Yearly,
'/Weight': Weight, "/Weight": Weight,
'/Weight/daily': WDaily, "/Weight/daily": WDaily,
'/Weight/weekly': WWeekly, "/Weight/weekly": WWeekly,
'/Weight/monthly': WMonthly, "/Weight/monthly": WMonthly,
'/Weight/yearly': WYearly "/Weight/yearly": WYearly,
} };
</script> </script>
<Router {routes} /> <Router {routes} />

View File

@@ -11,16 +11,16 @@
// Not when pushing unshifting the store // Not when pushing unshifting the store
// This is the only thing that works // This is the only thing that works
// Hacky ass shit // Hacky ass shit
let forceUpdate = false; let forceUpdate = false;
foodStore.subscribe(() => { foodStore.subscribe(() => {
forceUpdate = !forceUpdate; forceUpdate = !forceUpdate;
}); });
</script> </script>
<template> <template>
{#if forceUpdate} {#if forceUpdate}
<FoodTable items={$foodStore} /> <FoodTable items={$foodStore} />
{:else} {:else}
<FoodTable items={$foodStore} /> <FoodTable items={$foodStore} />
{/if} {/if}
</template> </template>

View File

@@ -1,8 +1,8 @@
<script lang="ts"> <script lang="ts">
import AggregatedWeightTable from '$components/Weight/Aggregated/AggregatedWeightTable.svelte' import AggregatedWeightTable from "$components/Weight/Aggregated/AggregatedWeightTable.svelte";
import { dailyWeightStore } from '$lib/store/Weight/dailyWeightStore' import { dailyWeightStore } from "$lib/store/Weight/dailyWeightStore";
</script> </script>
<template> <template>
<AggregatedWeightTable items="{$dailyWeightStore}" /> <AggregatedWeightTable items={$dailyWeightStore} />
</template> </template>

View File

@@ -1,8 +1,8 @@
<script lang="ts"> <script lang="ts">
import { monthlyWeightStore } from '$lib/store/Weight/monthlyWeightStore' import { monthlyWeightStore } from "$lib/store/Weight/monthlyWeightStore";
import AggregatedWeightTable from '$components/Weight/Aggregated/AggregatedWeightTable.svelte' import AggregatedWeightTable from "$components/Weight/Aggregated/AggregatedWeightTable.svelte";
</script> </script>
<template> <template>
<AggregatedWeightTable items="{$monthlyWeightStore}" /> <AggregatedWeightTable items={$monthlyWeightStore} />
</template> </template>

View File

@@ -1,8 +1,8 @@
<script lang="ts"> <script lang="ts">
import { weeklyWeightStore } from '$lib/store/Weight/weeklyWeightStore' import { weeklyWeightStore } from "$lib/store/Weight/weeklyWeightStore";
import AggregatedWeightTable from '$components/Weight/Aggregated/AggregatedWeightTable.svelte' import AggregatedWeightTable from "$components/Weight/Aggregated/AggregatedWeightTable.svelte";
</script> </script>
<template> <template>
<AggregatedWeightTable items="{$weeklyWeightStore}" /> <AggregatedWeightTable items={$weeklyWeightStore} />
</template> </template>

View File

@@ -1,8 +1,8 @@
<script lang="ts"> <script lang="ts">
import AggregatedWeightTable from '$components/Weight/Aggregated/AggregatedWeightTable.svelte' import AggregatedWeightTable from "$components/Weight/Aggregated/AggregatedWeightTable.svelte";
import { yearlyWeightStore } from '$lib/store/Weight/yearlyWeightStore' import { yearlyWeightStore } from "$lib/store/Weight/yearlyWeightStore";
</script> </script>
<template> <template>
<AggregatedWeightTable items="{$yearlyWeightStore}" /> <AggregatedWeightTable items={$yearlyWeightStore} />
</template> </template>

View File

@@ -1,7 +1,6 @@
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 regression from "regression";
import type { ChartData, Point } from "chart.js";
type FlyAndScaleParams = { type FlyAndScaleParams = {
y?: number; y?: number;

View File

@@ -1,8 +1,8 @@
import './style.css' import "./style.css";
import App from './App.svelte' import App from "./App.svelte";
const app = new App({ const app = new App({
target: document.getElementById('app') target: document.getElementById("app"),
}) });
export default app export default app;

View File

@@ -3,28 +3,26 @@
@tailwind utilities; @tailwind utilities;
html { html {
background-color: rgba(27, 38, 54, 1); background-color: rgba(27, 38, 54, 1);
text-align: center; text-align: center;
color: white; color: white;
} }
body { body {
margin: 0; margin: 0;
color: white; color: white;
font-family: "Nunito", -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", font-family: "Nunito", -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell",
"Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", "Fira Sans", "Droid Sans", "Helvetica Neue", sans-serif;
sans-serif;
} }
@font-face { @font-face {
font-family: "Nunito"; font-family: "Nunito";
font-style: normal; font-style: normal;
font-weight: 400; font-weight: 400;
src: local(""), src: local(""), url("assets/fonts/nunito-v16-latin-regular.woff2") format("woff2");
url("assets/fonts/nunito-v16-latin-regular.woff2") format("woff2");
} }
#app { #app {
height: 100vh; height: 100vh;
text-align: center; text-align: center;
} }

View File

@@ -33,7 +33,7 @@ export namespace main {
} }
} }
export class Food { export class Food {
rowid: number; id: number;
date: string; date: string;
food: string; food: string;
description: string; description: string;
@@ -47,7 +47,7 @@ export namespace main {
constructor(source: any = {}) { constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source); if ('string' === typeof source) source = JSON.parse(source);
this.rowid = source["rowid"]; this.id = source["id"];
this.date = source["date"]; this.date = source["date"];
this.food = source["food"]; this.food = source["food"];
this.description = source["description"]; this.description = source["description"];
@@ -57,7 +57,7 @@ export namespace main {
} }
} }
export class FoodSearch { export class FoodSearch {
rowid: number; id: number;
date: string; date: string;
food: string; food: string;
description: string; description: string;
@@ -72,7 +72,7 @@ export namespace main {
constructor(source: any = {}) { constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source); if ('string' === typeof source) source = JSON.parse(source);
this.rowid = source["rowid"]; this.id = source["id"];
this.date = source["date"]; this.date = source["date"];
this.food = source["food"]; this.food = source["food"];
this.description = source["description"]; this.description = source["description"];
@@ -267,7 +267,7 @@ export namespace main {
} }
} }
export class Weight { export class Weight {
rowid: number; id: number;
date: string; date: string;
weight: number; weight: number;
@@ -277,7 +277,7 @@ export namespace main {
constructor(source: any = {}) { constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source); if ('string' === typeof source) source = JSON.parse(source);
this.rowid = source["rowid"]; this.id = source["id"];
this.date = source["date"]; this.date = source["date"];
this.weight = source["weight"]; this.weight = source["weight"];
} }

4
go.mod
View File

@@ -6,7 +6,7 @@ toolchain go1.22.4
require ( require (
github.com/mattn/go-sqlite3 v1.14.22 github.com/mattn/go-sqlite3 v1.14.22
github.com/wailsapp/wails/v2 v2.9.1 github.com/wailsapp/wails/v2 v2.9.2
) )
require ( require (
@@ -30,7 +30,7 @@ require (
github.com/tkrajina/go-reflector v0.5.6 // indirect github.com/tkrajina/go-reflector v0.5.6 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasttemplate v1.2.2 // indirect github.com/valyala/fasttemplate v1.2.2 // indirect
github.com/wailsapp/go-webview2 v1.0.10 // indirect github.com/wailsapp/go-webview2 v1.0.16 // indirect
github.com/wailsapp/mimetype v1.4.1 // indirect github.com/wailsapp/mimetype v1.4.1 // indirect
golang.org/x/crypto v0.23.0 // indirect golang.org/x/crypto v0.23.0 // indirect
golang.org/x/exp v0.0.0-20230522175609-2e198f4a06a1 // indirect golang.org/x/exp v0.0.0-20230522175609-2e198f4a06a1 // indirect

8
go.sum
View File

@@ -59,12 +59,12 @@ github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyC
github.com/valyala/fasttemplate v1.2.1/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ= github.com/valyala/fasttemplate v1.2.1/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo= github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo=
github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ= github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
github.com/wailsapp/go-webview2 v1.0.10 h1:PP5Hug6pnQEAhfRzLCoOh2jJaPdrqeRgJKZhyYyDV/w= github.com/wailsapp/go-webview2 v1.0.16 h1:wffnvnkkLvhRex/aOrA3R7FP7rkvOqL/bir1br7BekU=
github.com/wailsapp/go-webview2 v1.0.10/go.mod h1:Uk2BePfCRzttBBjFrBmqKGJd41P6QIHeV9kTgIeOZNo= github.com/wailsapp/go-webview2 v1.0.16/go.mod h1:Uk2BePfCRzttBBjFrBmqKGJd41P6QIHeV9kTgIeOZNo=
github.com/wailsapp/mimetype v1.4.1 h1:pQN9ycO7uo4vsUUuPeHEYoUkLVkaRntMnHJxVwYhwHs= github.com/wailsapp/mimetype v1.4.1 h1:pQN9ycO7uo4vsUUuPeHEYoUkLVkaRntMnHJxVwYhwHs=
github.com/wailsapp/mimetype v1.4.1/go.mod h1:9aV5k31bBOv5z6u+QP8TltzvNGJPmNJD4XlAL3U+j3o= github.com/wailsapp/mimetype v1.4.1/go.mod h1:9aV5k31bBOv5z6u+QP8TltzvNGJPmNJD4XlAL3U+j3o=
github.com/wailsapp/wails/v2 v2.9.1 h1:irsXnoQrCpeKzKTYZ2SUVlRRyeMR6I0vCO9Q1cvlEdc= github.com/wailsapp/wails/v2 v2.9.2 h1:Xb5YRTos1w5N7DTMyYegWaGukCP2fIaX9WF21kPPF2k=
github.com/wailsapp/wails/v2 v2.9.1/go.mod h1:7maJV2h+Egl11Ak8QZN/jlGLj2wg05bsQS+ywJPT0gI= github.com/wailsapp/wails/v2 v2.9.2/go.mod h1:uehvlCwJSFcBq7rMCGfk4rxca67QQGsbg5Nm4m9UnBs=
golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI= golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI=
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8= golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
golang.org/x/exp v0.0.0-20230522175609-2e198f4a06a1 h1:k/i9J1pBpvlfR+9QsetwPyERsqu1GIbi967PQMq3Ivc= golang.org/x/exp v0.0.0-20230522175609-2e198f4a06a1 h1:k/i9J1pBpvlfR+9QsetwPyERsqu1GIbi967PQMq3Ivc=

32
main.go
View File

@@ -24,7 +24,7 @@ func init() {
logFile, err := os.Create("main.log") logFile, err := os.Create("main.log")
if err != nil { if err != nil {
log.Printf("Error creating log file: %v", err) log.Printf("Error creating log file: %v", err)
os.Exit(1) return
} }
logger := io.MultiWriter(os.Stdout, logFile) logger := io.MultiWriter(os.Stdout, logFile)
log.SetOutput(logger) log.SetOutput(logger)
@@ -42,31 +42,53 @@ var (
//go:embed food.ddl //go:embed food.ddl
var foodDDL string var foodDDL string
//go:embed spellfix.dll
var spellfixDll []byte
// 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 // 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() {
_, err := os.Open("spellfix.dll")
if err != nil && !os.IsNotExist(err) {
Error.Printf("Error looking for spellfix.dll: %v", err)
return
}
if err != nil && os.IsNotExist(err) {
log.Printf("No spellfix.dll found, creating...")
file, err := os.Create("spellfix.dll")
if err != nil {
Error.Printf("Error creating spellfix.dll: %v", err)
return
}
_, err = file.Write(spellfixDll)
if err != nil {
Error.Printf("Error writing spellfix.dll: %v", err)
return
}
file.Close()
}
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()
db := DB{path: *dbpath} db := DB{path: *dbpath}
err := db.Open() err = db.Open()
if err != nil { if err != nil {
Error.Printf("%++v", err) Error.Printf("%++v", err)
os.Exit(1) return
} }
defer db.Close() defer db.Close()
err = db.Init(foodDDL) err = db.Init(foodDDL)
if err != nil { if err != nil {
Error.Printf("Error initializing database: %++v", err) Error.Printf("Error initializing database: %++v", err)
os.Exit(1) return
} }
settingsService = &SettingsService{db: &db} settingsService = &SettingsService{db: &db}
err = settingsService.LoadSettings() err = settingsService.LoadSettings()
if err != nil { if err != nil {
Error.Printf("%++v", err) Error.Printf("%++v", err)
os.Exit(1) return
} }
log.Printf("Loaded settings as: %++v", Settings) log.Printf("Loaded settings as: %++v", Settings)

189
migratev2.sql Normal file
View File

@@ -0,0 +1,189 @@
drop index weightDateIdx;
drop index weightDailyIdx;
drop index weightWeeklyIdx;
drop index weightMonthlyIdx;
drop index weightYearlyIdx;
create table weight2 (
id integer primary key,
date datetime default (datetime('now')),
weight real not null
);
insert into weight2 select * from weight;
drop table weight;
drop view if exists weightView;
drop view if exists weightDaily;
drop view if exists weightWeekly;
drop view if exists weightMonthly;
drop view if exists weightYearly;
alter table weight2 rename to weight;
create index weightDateIdx on weight(date);
create index weightDailyIdx on weight(strftime('%Y-%m-%d', date));
create index weightWeeklyIdx on weight(strftime('%Y-%W', date));
create index weightMonthlyIdx on weight(strftime('%Y-%m', date));
create index weightYearlyIdx on weight(strftime('%Y', date));
create view weightDaily as
select strftime('%Y-%m-%d', date) as period,
round(avg(weight), 2) as amount
from weight
group by strftime('%Y-%m-%d', date)
order by date desc;
create view weightWeekly as
select strftime('%Y-%W', date) as period,
round(avg(weight), 2) as amount
from weight
group by strftime('%Y-%W', date)
order by date desc;
create view weightMonthly as
select strftime('%Y-%m', date) as period,
round(avg(weight), 2) as amount
from weight
group by strftime('%Y-%m', date)
order by date desc;
create view weightYearly as
select strftime('%Y', date) as period,
round(avg(weight), 2) as amount
from weight
group by strftime('%Y', date)
order by date desc;
create table food2 (
id integer primary key,
date datetime default (datetime('now')),
food varchar not null,
description varchar,
amount real not null,
per100 real default 0,
energy generated always as (coalesce(amount, 0) * coalesce(per100, 0) / 100) stored
);
drop index dailyIdx;
drop index weeklyIdx;
drop index monthlyIdx;
drop index yearlyIdx;
drop index dateIdx;
drop index foodIdx;
drop view if exists foodView;
drop view if exists foodDaily;
drop view if exists foodWeekly;
drop view if exists foodMonthly;
drop view if exists foodYearly;
drop view if exists foodRecent;
insert into food2(date, food, description, amount) select date, food, description, amount from food;
drop table food;
alter table food2 rename to food;
create index dailyIdx on food(strftime('%Y-%m-%d', date));
create index weeklyIdx on food(strftime('%Y-%W', date));
create index monthlyIdx on food(strftime('%Y-%m', date));
create index yearlyIdx on food(strftime('%Y', date));
create index dateIdx on food(date);
create index foodIdx on food(food);
create view foodView as
select id,
date,
food,
description,
round(amount, 2) as amount,
round(per100, 2) as per100,
round(energy, 2) as energy
from food;
create view foodDaily as
select strftime('%Y-%m-%d', date) as period,
round(sum(amount), 2) as amount,
round(avg(per100), 2) as avgPer100,
round(sum(energy), 2) as energy
from food
group by strftime('%Y-%m-%d', date)
order by date desc;
create view foodWeekly as
select strftime('%Y-%W', date) as period,
round(sum(amount), 2) as amount,
round(avg(per100), 2) as avgPer100,
round(sum(energy), 2) as energy
from food
group by strftime('%Y-%W', date)
order by date desc;
create view foodMonthly as
select strftime('%Y-%m', date) as period,
round(sum(amount), 2) as amount,
round(avg(per100), 2) as avgPer100,
round(sum(energy), 2) as energy
from food
group by strftime('%Y-%m', date)
order by date desc;
create view foodYearly as
select strftime('%Y', date) as period,
round(sum(amount), 2) as amount,
round(avg(per100), 2) as avgPer100,
round(sum(energy), 2) as energy
from food
group by strftime('%Y', date)
order by date desc;
create view foodRecent as
select *
from food
order by date desc
limit 10;
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;
end;
delete from foodfix;
insert into foodfix (word, rank)
select food as word,
count(*) as rank
from food
group by food;

View File

@@ -10,7 +10,7 @@ type (
db *DB db *DB
} }
Weight struct { Weight struct {
Rowid int64 `json:"rowid"` Id int64 `json:"id"`
Date string `json:"date"` Date string `json:"date"`
Weight float32 `json:"weight"` Weight float32 `json:"weight"`
} }
@@ -20,24 +20,23 @@ type (
} }
) )
const weightcolumns = "rowid, date, weight" const weightcolumns = "id, date, weight"
const weightAggregatedColumns = "period, amount" const weightAggregatedColumns = "period, amount"
func (w *WeightService) GetRecent() ([]Weight, error) { func (w *WeightService) GetRecent() (res []Weight, err error) {
res := []Weight{} log.Printf("Getting recent 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")
} }
row, err := w.db.readConn.Query(fmt.Sprintf("SELECT %s from weightView WHERE date > datetime('now', '-%d days') order by date desc;", weightcolumns, Settings.WeightDaysLookback)) row, err := w.db.readConn.Query(fmt.Sprintf("SELECT %s from weightView WHERE date > datetime('now', '-%d days') order by date desc;", weightcolumns, Settings.WeightDaysLookback))
if err != nil { if err != nil {
log.Printf("error getting daily weight: %v", err) return res, fmt.Errorf("error getting recent weight: %w", err)
return res, err
} }
for row.Next() { for row.Next() {
var weight Weight var weight Weight
err := row.Scan(&weight.Rowid, &weight.Date, &weight.Weight) err = row.Scan(&weight.Id, &weight.Date, &weight.Weight)
if err != nil { if err != nil {
log.Printf("error scanning row: %v", err) log.Printf("error scanning row: %v", err)
continue continue
@@ -45,11 +44,12 @@ func (w *WeightService) GetRecent() ([]Weight, error) {
res = append(res, weight) res = append(res, weight)
} }
log.Printf("Got %d recent weights", len(res))
return res, nil return
} }
func (w *WeightService) Create(weight Weight) (Weight, error) { func (w *WeightService) Create(weight Weight) (res Weight, err error) {
log.Printf("Creating weight: %v", weight)
if w.db == nil || !w.db.Ready { if w.db == nil || !w.db.Ready {
return weight, fmt.Errorf("cannot create weight, db is nil or is not ready") return weight, fmt.Errorf("cannot create weight, db is nil or is not ready")
} }
@@ -57,46 +57,44 @@ func (w *WeightService) Create(weight Weight) (Weight, error) {
return weight, fmt.Errorf("cannot create weight, weight is empty") return weight, fmt.Errorf("cannot create weight, weight is empty")
} }
res, err := w.db.writeConn.Exec("INSERT INTO weight (weight) VALUES (?)", weight.Weight) dbres, err := w.db.writeConn.Exec("INSERT INTO weight (weight) VALUES (?)", weight.Weight)
if err != nil { if err != nil {
return weight, fmt.Errorf("error inserting weight: %v", err) return weight, fmt.Errorf("error inserting weight: %w", err)
} }
rowid, err := res.LastInsertId() id, err := dbres.LastInsertId()
if err != nil { if err != nil {
return weight, fmt.Errorf("error getting last insert id: %v", err) return weight, fmt.Errorf("error getting last insert id: %w", err)
} }
return w.GetByRowid(rowid) return w.GetById(id)
} }
func (w *WeightService) GetByRowid(rowid int64) (Weight, error) { func (w *WeightService) GetById(id int64) (res Weight, err error) {
var res Weight log.Printf("Getting weight by id: %d", id)
if w.db == nil || !w.db.Ready { if w.db == nil || !w.db.Ready {
return res, fmt.Errorf("cannot get weight by rowid, db is nil or is not ready") return res, fmt.Errorf("cannot get weight by id, db is nil or is not ready")
} }
row := w.db.readConn.QueryRow(fmt.Sprintf("SELECT %s from weightView WHERE rowid = ?", weightcolumns), rowid) row := w.db.readConn.QueryRow(fmt.Sprintf("SELECT %s from weightView WHERE id = ?", weightcolumns), id)
err := row.Scan(&res.Rowid, &res.Date, &res.Weight) err = row.Scan(&res.Id, &res.Date, &res.Weight)
if err != nil { if err != nil {
return res, fmt.Errorf("error scanning row: %v", err) return res, fmt.Errorf("error scanning row: %w", err)
} }
return
return res, nil
} }
// 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() (res []AggregatedWeight, err error) {
res := []AggregatedWeight{} log.Printf("Getting daily weight")
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")
} }
row, err := w.db.readConn.Query(fmt.Sprintf("SELECT %s from weightDaily LIMIT %d", weightAggregatedColumns, Settings.WeightDailyLookback)) row, err := w.db.readConn.Query(fmt.Sprintf("SELECT %s from weightDaily LIMIT %d", weightAggregatedColumns, Settings.WeightDailyLookback))
if err != nil { if err != nil {
log.Printf("error getting daily weight: %v", err) return res, fmt.Errorf("error getting daily weight: %w", err)
return res, err
} }
for row.Next() { for row.Next() {
@@ -109,25 +107,23 @@ func (w *WeightService) GetDaily() ([]AggregatedWeight, error) {
res = append(res, weight) res = append(res, weight)
} }
log.Printf("Got %d daily weights", len(res))
return res, nil return
} }
func (w *WeightService) GetWeekly() ([]AggregatedWeight, error) { func (w *WeightService) GetWeekly() (res []AggregatedWeight, err error) {
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")
} }
row, err := w.db.readConn.Query(fmt.Sprintf("SELECT %s from weightWeekly LIMIT %d", weightAggregatedColumns, Settings.WeightWeeklyLookback)) row, err := w.db.readConn.Query(fmt.Sprintf("SELECT %s from weightWeekly LIMIT %d", weightAggregatedColumns, Settings.WeightWeeklyLookback))
if err != nil { if err != nil {
log.Printf("error getting weekly weight: %v", err) return res, fmt.Errorf("error getting weekly weight: %w", err)
return res, err
} }
for row.Next() { for row.Next() {
var weight AggregatedWeight var weight AggregatedWeight
err := row.Scan(&weight.Period, &weight.Amount) err = row.Scan(&weight.Period, &weight.Amount)
if err != nil { if err != nil {
log.Printf("error scanning row: %v", err) log.Printf("error scanning row: %v", err)
continue continue
@@ -135,20 +131,18 @@ func (w *WeightService) GetWeekly() ([]AggregatedWeight, error) {
res = append(res, weight) res = append(res, weight)
} }
log.Printf("Got %d weekly weights", len(res))
return res, nil return
} }
func (w *WeightService) GetMonthly() ([]AggregatedWeight, error) { func (w *WeightService) GetMonthly() (res []AggregatedWeight, err error) {
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")
} }
row, err := w.db.readConn.Query(fmt.Sprintf("SELECT %s from weightMonthly LIMIT %d", weightAggregatedColumns, Settings.WeightMonthlyLookback)) row, err := w.db.readConn.Query(fmt.Sprintf("SELECT %s from weightMonthly LIMIT %d", weightAggregatedColumns, Settings.WeightMonthlyLookback))
if err != nil { if err != nil {
log.Printf("error getting monthly weight: %v", err) return res, fmt.Errorf("error getting monthly weight: %w", err)
return res, err
} }
for row.Next() { for row.Next() {
@@ -161,25 +155,23 @@ func (w *WeightService) GetMonthly() ([]AggregatedWeight, error) {
res = append(res, weight) res = append(res, weight)
} }
log.Printf("Got %d monthly weights", len(res))
return res, nil return
} }
func (w *WeightService) GetYearly() ([]AggregatedWeight, error) { func (w *WeightService) GetYearly() (res []AggregatedWeight, err error) {
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")
} }
row, err := w.db.readConn.Query(fmt.Sprintf("SELECT %s from weightYearly LIMIT %d", weightAggregatedColumns, Settings.WeightYearlyLookback)) row, err := w.db.readConn.Query(fmt.Sprintf("SELECT %s from weightYearly LIMIT %d", weightAggregatedColumns, Settings.WeightYearlyLookback))
if err != nil { if err != nil {
log.Printf("error getting yearly weight: %v", err) return res, fmt.Errorf("error getting yearly weight: %w", err)
return res, err
} }
for row.Next() { for row.Next() {
var weight AggregatedWeight var weight AggregatedWeight
err := row.Scan(&weight.Period, &weight.Amount) err = row.Scan(&weight.Period, &weight.Amount)
if err != nil { if err != nil {
log.Printf("error scanning row: %v", err) log.Printf("error scanning row: %v", err)
continue continue
@@ -188,5 +180,6 @@ func (w *WeightService) GetYearly() ([]AggregatedWeight, error) {
res = append(res, weight) res = append(res, weight)
} }
return res, nil log.Printf("Got %d yearly weights", len(res))
return
} }