Compare commits

..

No commits in common. "main" and "0.0.2" have entirely different histories.
main ... 0.0.2

9 changed files with 213 additions and 520 deletions

View File

@ -40,3 +40,83 @@ jobs:
with: with:
name: coverage.html name: coverage.html
path: ./cover.html path: ./cover.html
build:
needs: test
runs-on: ubuntu-22.04
env:
RUNNER_TOOL_CACHE: /toolcache # Runner Tool Cache
steps:
- uses: actions/checkout@v3
- uses: actions/setup-go@v4
with:
go-version: '1.24.4' # The Go version to download (if necessary) and use.
- uses: https://gitea.com/actions/go-hashfiles@v0.0.1
id: hash-go
with:
patterns: |
go.mod
go.sum
- name: Echo hash
run: echo ${{ steps.hash-go.outputs.hash }}
- name: Cache go
id: cache-go
uses: https://github.com/actions/cache@v3 # Action cache
with: # specify with your GOMODCACHE and GOCACHE
path: |-
/root/go/pkg/mod
/root/.cache/go-build
key: go_cache-${{ steps.hash-go.outputs.hash }}
restore-keys: |-
go_cache-${{ steps.hash-go.outputs.hash }}
# build all binaries
- name: build binaries
run: |
GOOS=darwin GOARCH=amd64 CGO_ENABLED=0 go build -o charmite_darwin_amd64 .
GOOS=darwin GOARCH=arm64 CGO_ENABLED=0 go build -o charmite_darwin_arm64 .
GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o charmite_linux_amd64 .
GOOS=windows GOARCH=amd64 CGO_ENABLED=0 go build -o charmite_windows_amd64.exe .
# upload
- name: Upload artifacts to Gitea package repository
env:
GITEA_API_URL: https://code.ppl.town/api
GITEA_TOKEN: ${{ secrets.PACKAGE_API_KEY }}
OWNER: justin
VERSION: 0.0.1
run: |
# charmite_darwin_amd64
curl -D- -s -X DELETE "$GITEA_API_URL/packages/$OWNER/generic/charmite/$VERSION/charmite_darwin_amd64" \
-H "Authorization: token $GITEA_TOKEN"
curl -D- -s -X PUT "$GITEA_API_URL/packages/$OWNER/generic/charmite/$VERSION/charmite_darwin_amd64" \
-H "Authorization: token $GITEA_TOKEN" \
-H "Content-Type: application/octet-stream" \
--data-binary @charmite_darwin_amd64
curl -D- -s -X DELETE "$GITEA_API_URL/packages/$OWNER/generic/charmite/$VERSION/charmite_darwin_arm64" \
-H "Authorization: token $GITEA_TOKEN"
curl -D- -s -X PUT "$GITEA_API_URL/packages/$OWNER/generic/charmite/$VERSION/charmite_darwin_arm64" \
-H "Authorization: token $GITEA_TOKEN" \
-H "Content-Type: application/octet-stream" \
--data-binary @charmite_darwin_arm64
curl -D- -s -X DELETE "$GITEA_API_URL/packages/$OWNER/generic/charmite/$VERSION/charmite_linux_amd64" \
-H "Authorization: token $GITEA_TOKEN"
curl -D- -s -X PUT "$GITEA_API_URL/packages/$OWNER/generic/charmite/$VERSION/charmite_linux_amd64" \
-H "Authorization: token $GITEA_TOKEN" \
-H "Content-Type: application/octet-stream" \
--data-binary @charmite_linux_amd64
curl -D- -s -X DELETE "$GITEA_API_URL/packages/$OWNER/generic/charmite/$VERSION/charmite_windows_amd64.exe" \
-H "Authorization: token $GITEA_TOKEN"
curl -D- -s -X PUT "$GITEA_API_URL/packages/$OWNER/generic/charmite/$VERSION/charmite_windows_amd64.exe" \
-H "Authorization: token $GITEA_TOKEN" \
-H "Content-Type: application/octet-stream" \
--data-binary @charmite_windows_amd64.exe

2
.gitignore vendored
View File

@ -1,2 +1,2 @@
# Added by goreleaser init:
dist/ dist/
.DS_Store

View File

@ -1,9 +1,6 @@
{ {
"cSpell.ignoreWords": [ "cSpell.ignoreWords": [
"FORMENTRY", "FORMENTRY",
"TIMEENTRIES",
"ancel",
"lipgloss",
"oday" "oday"
] ]
} }

View File

@ -1,23 +0,0 @@
# charmite
Charmite is a simple TUI to add/view time entries in the [Mite](https://mite.de/en/)
time tracking tool.
## Installation
Download the appropriate binary from https://code.ppl.town/justin/charmite/releases
Or compile from the source code with:
go build .
## Using
You'll need to set the environment variables:
* MITE_API
* MITE_DOMAIN
To appropriate values.
See the [Mite FAQ](https://mite.de/en/faq.html) under "How do I allow API access for my account? Where can I get an API key?" for details on how to obtain your API key.

10
build.sh Executable file
View File

@ -0,0 +1,10 @@
#!/bin/sh
GOOS=linux GOARCH=amd64 go build -o cal_linux_amd64
GOOS=darwin GOARCH=arm64 go build -o cal_darwin_arm64
GOOS=windows GOARCH=amd64 go build -o cal_windows_lol_amd64
zip cal.zip cal_linux_amd64 cal_darwin_arm64 cal_windows_lol_amd64
open .

View File

@ -3,7 +3,6 @@ package mite
import ( import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"net/http" "net/http"
"time" "time"
@ -51,15 +50,13 @@ type Project struct {
func (p Project) String() string { func (p Project) String() string {
return fmt.Sprintf("%d: %s (%s)", p.ID, p.Name, p.CustomerName) return fmt.Sprintf("%d: %s (%s)", p.ID, p.Name, p.CustomerName)
} }
func (p Project) GetID() int { return p.ID } func (p Project) GetID() int { return p.ID }
func (p Project) GetName() string { func (p Project) GetName() string { return p.Name }
return p.Name + " (" + p.CustomerName + ")"
}
func (a APIClient) GetProjects() (Projects, error) { func (a APIClient) GetProjects() (Projects, error) {
// GET /projects.json // GET /projects.json
p := APIProjects{} p := APIProjects{}
err := a.get("/projects.json", &p) err := get(a.domain, a.apiKey, "/projects.json", &p)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -101,7 +98,7 @@ func (c Customer) GetName() string { return c.Name }
func (a APIClient) GetCustomers() (Customers, error) { func (a APIClient) GetCustomers() (Customers, error) {
// GET /customers.json // GET /customers.json
p := apiCustomers{} p := apiCustomers{}
err := a.get("/customers.json", &p) err := get(a.domain, a.apiKey, "/customers.json", &p)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -145,7 +142,7 @@ func (s Service) GetName() string {
func (a APIClient) GetServices() (Services, error) { func (a APIClient) GetServices() (Services, error) {
// GET /services.json // GET /services.json
p := apiServices{} p := apiServices{}
err := a.get("/services.json", &p) err := get(a.domain, a.apiKey, "/services.json", &p)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -218,7 +215,7 @@ func (a APIClient) GetTimeEntries(from, to time.Time) (TimeEntries, error) {
p := apiTimeEntry{} p := apiTimeEntry{}
u := fmt.Sprintf("/time_entries.json?from=%s&to=%s", from.Format(time.DateOnly), to.Format(time.DateOnly)) u := fmt.Sprintf("/time_entries.json?from=%s&to=%s", from.Format(time.DateOnly), to.Format(time.DateOnly))
err := a.get(u, &p) err := get(a.domain, a.apiKey, u, &p)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -234,15 +231,13 @@ type requestAddTimeEntry struct {
RequestTimeEntryHolder struct { RequestTimeEntryHolder struct {
DateAt string `json:"date_at"` DateAt string `json:"date_at"`
Minutes int `json:"minutes"` Minutes int `json:"minutes"`
ProjectID int `json:"project_id,omitempty"` ProjectID int `json:"project_id,omit_empty"`
ServiceID int `json:"service_id,omitempty"` ServiceID int `json:"service_id,omit_empty"`
Note string `json:"note"` Note string `json:"note"`
} `json:"time_entry"` } `json:"time_entry"`
} }
type apiPostTimeEntry timeEntryHolder func (a APIClient) AddTimeEntry(date string, minutes int, notes string, projectId, serviceId int) error {
func (a APIClient) AddTimeEntry(date string, minutes int, notes string, projectId, serviceId int) (int, error) {
// POST /time_entries.json // POST /time_entries.json
// { // {
// "time_entry": { // "time_entry": {
@ -258,164 +253,23 @@ func (a APIClient) AddTimeEntry(date string, minutes int, notes string, projectI
req.RequestTimeEntryHolder.ProjectID = projectId req.RequestTimeEntryHolder.ProjectID = projectId
req.RequestTimeEntryHolder.ServiceID = serviceId req.RequestTimeEntryHolder.ServiceID = serviceId
res := apiPostTimeEntry{} err := post(a.domain, a.apiKey, "/time_entries.json", req)
return err
err := a.post("/time_entries.json", req, &res)
return res.TimeEntry.ID, err
} }
type apiTimeTrackerEntry struct { func post(domain, apiKey, path string, data any) error {
TimeTrackerHolder timeTrackerHolder `json:"tracker"`
}
type timeTrackerHolder struct { b, err := json.Marshal(data)
TrackingTimeEntry *TrackingTimeEntry `json:"tracking_time_entry"`
StoppedTimeEntry *StoppedTimeEntry `json:"stopped_time_entry"`
}
type TrackingTimeEntry struct {
ID int `json:"id"`
Minutes int `json:"minutes"`
Since time.Time `json:"since"`
}
type StoppedTimeEntry struct {
ID int `json:"id"`
Minutes int `json:"minutes"`
}
// {
// "tracker": {
// "tracking_time_entry": {
// "id": 36135322,
// "minutes": 0,
// "since": "2015-10-15T17:33:52+02:00"
// },
// "stopped_time_entry": {
// "id": 36134329,
// "minutes": 46
// }
// }
// }
// {
// "tracker": {
// "tracking_time_entry": {
// "id": 36135321,
// "minutes": 247,
// "since": "2015-10-15T17:05:04+02:00"
// }
// }
// }
var ErrNoTracker = errors.New("no time tracker running")
// GetTimeTracker gets the current running time tracker. If no tracker is
// running, the error returned will be ErrNoTracker
func (a APIClient) GetTimeTracker() (TrackingTimeEntry, error) {
r := apiTimeTrackerEntry{}
err := a.get("/tracker.json", &r)
if err != nil {
return TrackingTimeEntry{}, err
}
if r.TimeTrackerHolder.TrackingTimeEntry == nil {
return TrackingTimeEntry{}, ErrNoTracker
}
return *r.TimeTrackerHolder.TrackingTimeEntry, nil
}
func (a APIClient) StartTimeTracker(id int) (TrackingTimeEntry, *StoppedTimeEntry, error) {
url := fmt.Sprintf("/tracker/%d.json", id)
r := apiTimeTrackerEntry{}
err := a.patch(url, &r)
if err != nil {
return TrackingTimeEntry{}, nil, err
}
if r.TimeTrackerHolder.TrackingTimeEntry == nil {
// I don't think this should happen, the patch should have been a 404?
panic(fmt.Sprintf("unexpected failure to find a tracking entry in a successful PATCH\n%#v", r.TimeTrackerHolder))
}
return *r.TimeTrackerHolder.TrackingTimeEntry, r.TimeTrackerHolder.StoppedTimeEntry, nil
}
func (a APIClient) StopTimeTracker(id int) (StoppedTimeEntry, error) {
url := fmt.Sprintf("/tracker/%d.json", id)
r := apiTimeTrackerEntry{}
err := a.delete(url, &r)
if err != nil {
return StoppedTimeEntry{}, err
}
if r.TimeTrackerHolder.StoppedTimeEntry == nil {
// I don't think this should happen, the patch should have been a 404?
panic(fmt.Sprintf("unexpected failure to find a tracking entry in a successful DELETE\n%#v", r.TimeTrackerHolder))
}
return *r.TimeTrackerHolder.StoppedTimeEntry, nil
}
func (a APIClient) delete(path string, data any) error {
req, err := http.NewRequest("DELETE", baseurl(a.domain, path), nil)
if err != nil {
return err
}
req.Header.Add("X-MiteApiKey", a.apiKey)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
return fmt.Errorf("expected 2XX, got %d", resp.StatusCode)
}
err = json.NewDecoder(resp.Body).Decode(&data)
if err != nil {
return err
}
return nil
}
func (a APIClient) patch(path string, data any) error {
req, err := http.NewRequest("PATCH", baseurl(a.domain, path), nil)
if err != nil {
return err
}
req.Header.Add("X-MiteApiKey", a.apiKey)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
return fmt.Errorf("expected 2XX, got %d", resp.StatusCode)
}
err = json.NewDecoder(resp.Body).Decode(&data)
if err != nil {
return err
}
return nil
}
func (a APIClient) post(path string, dataIn any, dataOut any) error {
b, err := json.Marshal(dataIn)
if err != nil { if err != nil {
return err return err
} }
req, err := http.NewRequest("POST", baseurl(a.domain, path), bytes.NewBuffer(b)) req, err := http.NewRequest("POST", baseurl(domain, path), bytes.NewBuffer(b))
if err != nil { if err != nil {
return err return err
} }
req.Header.Add("X-MiteApiKey", a.apiKey) req.Header.Add("X-MiteApiKey", apiKey)
req.Header.Add("Content-Type", "application/json") req.Header.Add("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req) resp, err := http.DefaultClient.Do(req)
@ -427,21 +281,16 @@ func (a APIClient) post(path string, dataIn any, dataOut any) error {
return fmt.Errorf("expected 2XX, got %d", resp.StatusCode) return fmt.Errorf("expected 2XX, got %d", resp.StatusCode)
} }
err = json.NewDecoder(resp.Body).Decode(&dataOut)
if err != nil {
return err
}
return nil return nil
} }
func (a APIClient) get(path string, data any) error { func get(domain, apiKey, path string, data any) error {
req, err := http.NewRequest("GET", baseurl(a.domain, path), nil) req, err := http.NewRequest("GET", baseurl(domain, path), nil)
if err != nil { if err != nil {
return err return err
} }
req.Header.Add("X-MiteApiKey", a.apiKey) req.Header.Add("X-MiteApiKey", apiKey)
resp, err := http.DefaultClient.Do(req) resp, err := http.DefaultClient.Do(req)
if err != nil { if err != nil {
@ -456,6 +305,7 @@ func (a APIClient) get(path string, data any) error {
return err return err
} }
return nil return nil
} }
func baseurl(domain, path string) string { func baseurl(domain, path string) string {

View File

@ -1,82 +0,0 @@
package mite
import (
"encoding/json"
"testing"
)
func TestUnmarshalTimeTracking(t *testing.T) {
trackerOff := []byte(`{
"tracker": {}
}`)
off := apiTimeTrackerEntry{}
err := json.Unmarshal(trackerOff, &off)
if err != nil {
t.Error(err)
} else {
if off.TimeTrackerHolder.TrackingTimeEntry != nil {
t.Error("expected nil, but is not")
}
}
trackerOn := []byte(`
{
"tracker": {
"tracking_time_entry": {
"id": 36135321,
"minutes": 247,
"since": "2015-10-15T17:05:04+02:00"
}
}
}`)
on := apiTimeTrackerEntry{}
err = json.Unmarshal(trackerOn, &on)
if err != nil {
t.Error(err)
} else {
if on.TimeTrackerHolder.TrackingTimeEntry == nil {
t.Error("expected not nil, but is not")
} else {
if on.TimeTrackerHolder.TrackingTimeEntry.ID != 36135321 {
t.Error("bad unmarshal?")
}
}
}
trackerStart := []byte(`{
"tracker": {
"tracking_time_entry": {
"id": 36135322,
"minutes": 0,
"since": "2015-10-15T17:33:52+02:00"
},
"stopped_time_entry": {
"id": 36134329,
"minutes": 46
}
}
}`)
start := apiTimeTrackerEntry{}
err = json.Unmarshal(trackerStart, &start)
if err != nil {
t.Error(err)
} else {
if start.TimeTrackerHolder.TrackingTimeEntry == nil {
t.Error("expected not nil, but is not")
} else {
if start.TimeTrackerHolder.TrackingTimeEntry.ID != 36135322 {
t.Error("bad unmarshal?")
}
}
if start.TimeTrackerHolder.StoppedTimeEntry == nil {
t.Error("expected not nil, but is nil")
} else {
if start.TimeTrackerHolder.StoppedTimeEntry.ID != 36134329 {
t.Error("bad unmarshal")
}
}
}
}

220
model.go
View File

@ -4,7 +4,7 @@ import (
"charmcal/mite" "charmcal/mite"
"errors" "errors"
"fmt" "fmt"
"slices" "strconv"
"strings" "strings"
"time" "time"
@ -32,19 +32,7 @@ const MODE_CAL tuiMode = "MODE_CAL"
const MODE_TIMEENTRIES tuiMode = "MODE_TIMEENTRIES" const MODE_TIMEENTRIES tuiMode = "MODE_TIMEENTRIES"
const MODE_FORMENTRY tuiMode = "MODE_FORMENTRY" const MODE_FORMENTRY tuiMode = "MODE_FORMENTRY"
var version = "dev"
type tickMsg time.Time
func tick() tea.Cmd {
return tea.Tick(time.Second, func(t time.Time) tea.Msg {
return tickMsg(t)
})
}
type model struct { type model struct {
currentTime time.Time
miteAPI mite.APIClient miteAPI mite.APIClient
start calendarTime start calendarTime
dest calendarTime dest calendarTime
@ -63,11 +51,9 @@ type model struct {
timeData struct { timeData struct {
entries mite.TimeEntries entries mite.TimeEntries
table table.Model table table.Model
tracker *mite.TrackingTimeEntry
} }
statusBarMessage string statusBarMessage string
windowWidth int windowWidth int
windowHeight int
} }
func initialModel(miteDomain, miteApiKey string) model { func initialModel(miteDomain, miteApiKey string) model {
@ -87,10 +73,10 @@ func initialModel(miteDomain, miteApiKey string) model {
tab.SetStyles(s) tab.SetStyles(s)
tab.SetColumns([]table.Column{ tab.SetColumns([]table.Column{
{Title: " min", Width: 4}, table.Column{Title: "min", Width: 5},
{Title: "🔐", Width: 2}, table.Column{Title: "lck", Width: 4},
{Title: "customer", Width: 10}, table.Column{Title: "customer", Width: 10},
{Title: "description", Width: 40}, table.Column{Title: "description", Width: 40},
}) })
m.start = calendarTime{time.Now()} m.start = calendarTime{time.Now()}
@ -106,12 +92,88 @@ func initialModel(miteDomain, miteApiKey string) model {
return m return m
} }
func (m model) Init() tea.Cmd { func (m model) buildForm() *huh.Form {
return tea.Batch( clOptions := []huh.Option[string]{}
m.fetchMiteData(), for _, cust := range m.formData.customers {
tick(), op := miteToHuhOption(cust)
clOptions = append(clOptions, op)
}
svcOptions := []huh.Option[string]{}
for _, svc := range m.formData.services {
op := miteToHuhOption(svc)
svcOptions = append(svcOptions, op)
}
cl := huh.NewSelect[string]().
Key("client").
Options(clOptions...).
Title("Client").Height(5).Value(&m.formData.selected.customer)
sl := huh.NewSelect[string]().
Key("service").
Options(svcOptions...).
Title("Service").Height(5)
pl := huh.NewSelect[string]().
Key("project").
Title("Project").Height(3).
OptionsFunc(func() []huh.Option[string] {
out := []huh.Option[string]{}
for _, proj := range m.formData.projects {
if fmt.Sprint(proj.CustomerID) == m.formData.selected.customer {
out = append(out, miteToHuhOption(proj))
}
}
return out
}, &m.formData.selected.customer)
form := huh.NewForm(
huh.NewGroup(
cl,
sl,
pl,
),
huh.NewGroup(
huh.NewText().
Key("description").
Title("description").
Validate(func(s string) error {
if s == "" {
return errors.New("must enter a description")
}
return nil
}),
huh.NewInput().
Key("minutes").
CharLimit(5).
Validate(
func(s string) error {
h, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return err
}
if h < 0 {
return errors.New("must be positive")
}
return err
}).
Title("Minutes"),
),
) )
return form
}
func miteToHuhOption[T mite.APIObject](i T) huh.Option[string] {
return huh.Option[string]{
Key: i.GetName(),
Value: fmt.Sprint(i.GetID()),
}
}
func (m model) Init() tea.Cmd {
return m.fetchMiteData()
} }
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
@ -120,28 +182,19 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) { switch msg := msg.(type) {
case tickMsg:
m.currentTime = time.Time(msg)
return m, tick() // schedule next tick
case miteDataFetchedMsg: case miteDataFetchedMsg:
if msg.Error != nil { if msg.Error != nil {
m.statusBarMessage = fmt.Sprintf("Error fetching: %s", msg.Error.Error()) m.statusBarMessage = fmt.Sprintf("Error fetching: %s", msg.Error.Error())
m.fetchedData = false m.fetchedData = false
} else { } else {
m.statusBarMessage = fmt.Sprintf("Fetched %d time entries in %s", len(msg.TimeEntries), time.Since(msg.start).Truncate(time.Millisecond)) m.statusBarMessage = fmt.Sprintf("Fetched %d time entries", len(msg.TimeEntries))
m.timeData.entries = msg.TimeEntries m.timeData.entries = msg.TimeEntries
m.formData.customers = msg.Customers m.formData.customers = msg.Customers
m.formData.services = msg.Services m.formData.services = msg.Services
m.formData.projects = msg.Projects m.formData.projects = msg.Projects
m.timeData.tracker = msg.Tracker
m.fetchedData = true m.fetchedData = true
slices.SortFunc(m.formData.customers, func(a, b mite.Customer) int { return strings.Compare(a.GetName(), b.GetName()) })
slices.SortFunc(m.formData.services, func(a, b mite.Service) int { return strings.Compare(a.GetName(), b.GetName()) })
slices.SortFunc(m.formData.projects, func(a, b mite.Project) int { return strings.Compare(a.GetName(), b.GetName()) })
// just in case there is data for the currently focused day // just in case there is data for the currently focused day
m.timeData.table.SetRows(m.tableDataForDate(m.dest.Time)) m.timeData.table.SetRows(m.tableDataForDate(m.dest.Time))
} }
@ -153,14 +206,13 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
} }
m.debug = append(m.debug, fmt.Sprintf("Got a %#v", msg)) m.debug = append(m.debug, fmt.Sprintf("Got a %#v", msg))
switch m.tuiMode { if m.tuiMode == MODE_TIMEENTRIES {
case MODE_TIMEENTRIES:
return m.updateEntries(msg) return m.updateEntries(msg)
case MODE_CAL: } else if m.tuiMode == MODE_CAL {
return m.updateCal(msg) return m.updateCal(msg)
case MODE_FORMENTRY: } else if m.tuiMode == MODE_FORMENTRY {
return m.updateForm(msg) return m.updateForm(msg)
default: } else {
panic(m.tuiMode) panic(m.tuiMode)
} }
} }
@ -209,29 +261,13 @@ func (m model) updateEntries(msg tea.Msg) (tea.Model, tea.Cmd) {
m.formData.form = m.buildForm() m.formData.form = m.buildForm()
m.formData.form.Init() m.formData.form.Init()
return m, nil return m, nil
case "c":
if m.timeData.tracker != nil {
m, msg := m.cancelTracker()
return m, msg
}
} }
} }
newTable, tableCmd := m.timeData.table.Update(msg) newTable, tableCmd := m.timeData.table.Update(msg)
m.timeData.table = newTable m.timeData.table = newTable
return m, tableCmd return m, tableCmd
}
func (m model) cancelTracker() (model, tea.Cmd) {
stopped, err := m.miteAPI.StopTimeTracker(m.timeData.tracker.ID)
if err != nil {
m.statusBarMessage = err.Error()
return m, nil
} else {
m.statusBarMessage = fmt.Sprintf("Stopped tracking: %d", stopped.ID)
m.timeData.tracker = nil
return m, m.fetchMiteData()
}
} }
func (m model) updateCal(msg tea.Msg) (tea.Model, tea.Cmd) { func (m model) updateCal(msg tea.Msg) (tea.Model, tea.Cmd) {
@ -239,7 +275,6 @@ func (m model) updateCal(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) { switch msg := msg.(type) {
case tea.WindowSizeMsg: case tea.WindowSizeMsg:
m.windowWidth = msg.Width m.windowWidth = msg.Width
m.windowHeight = msg.Height
// Is it a key press? // Is it a key press?
case tea.KeyMsg: case tea.KeyMsg:
@ -271,12 +306,6 @@ func (m model) updateCal(msg tea.Msg) (tea.Model, tea.Cmd) {
m.statusBarMessage = "Fetching data from API" m.statusBarMessage = "Fetching data from API"
return m, m.fetchMiteData() return m, m.fetchMiteData()
// cancel tracker
case "c":
if m.timeData.tracker != nil {
return m.cancelTracker()
}
// // The "up" and "k" keys move the cursor up // // The "up" and "k" keys move the cursor up
// case "up", "k": // case "up", "k":
// if m.cursor > 0 { // if m.cursor > 0 {
@ -318,7 +347,7 @@ func (m model) updateCal(msg tea.Msg) (tea.Model, tea.Cmd) {
m.timeData.table.SetRows(m.tableDataForDate(m.dest.Time)) m.timeData.table.SetRows(m.tableDataForDate(m.dest.Time))
return m, nil return m, nil
} }
// The "enter" key and the space bar (a literal space) toggle // The "enter" key and the spacebar (a literal space) toggle
// the selected state for the item that the cursor is pointing at. // the selected state for the item that the cursor is pointing at.
// case "enter", " ": // case "enter", " ":
// _, ok := m.selected[m.cursor] // _, ok := m.selected[m.cursor]
@ -347,46 +376,34 @@ func (m model) tableDataForDate(t time.Time) []table.Row {
if entry.Locked { if entry.Locked {
lock = "🔐" lock = "🔐"
} }
rows = append(rows, table.Row{fmt.Sprintf("%4d", entry.Minutes), lock, entry.CustomerName, entry.Note}) rows = append(rows, table.Row{fmt.Sprint(entry.Minutes), lock, entry.CustomerName, entry.Note})
} }
return rows return rows
} }
type miteDataFetchedMsg struct { type miteDataFetchedMsg struct {
start time.Time
TimeEntries mite.TimeEntries TimeEntries mite.TimeEntries
Customers mite.Customers Customers mite.Customers
Services mite.Services Services mite.Services
Projects mite.Projects Projects mite.Projects
Tracker *mite.TrackingTimeEntry
Error error Error error
} }
func (m model) fetchMiteData() tea.Cmd { func (m model) fetchMiteData() tea.Cmd {
return func() tea.Msg { return func() tea.Msg {
t0 := time.Now()
from := time.Now().Add(-time.Hour * 24 * 30 * 6) // about 6 months from := time.Now().Add(-time.Hour * 24 * 30 * 6) // about 6 months
to := time.Now().Add(time.Hour * 20 * 30) // about 1 month to := time.Now().Add(time.Hour * 20 * 30) // about 1 month
te, err1 := m.miteAPI.GetTimeEntries(from, to) te, err1 := m.miteAPI.GetTimeEntries(from, to)
cst, err2 := m.miteAPI.GetCustomers() cst, err2 := m.miteAPI.GetCustomers()
svc, err3 := m.miteAPI.GetServices() svc, err3 := m.miteAPI.GetServices()
pjt, err4 := m.miteAPI.GetProjects() pjt, err4 := m.miteAPI.GetProjects()
tt, err5 := m.miteAPI.GetTimeTracker()
var msgTT = &tt
if err5 == mite.ErrNoTracker {
err5 = nil
msgTT = nil
}
return miteDataFetchedMsg{ return miteDataFetchedMsg{
TimeEntries: te, TimeEntries: te,
Customers: cst, Customers: cst,
Services: svc, Services: svc,
Projects: pjt, Projects: pjt,
Tracker: msgTT,
Error: errors.Join(err1, err2, err3, err4), Error: errors.Join(err1, err2, err3, err4),
start: t0,
} }
} }
} }
@ -398,12 +415,6 @@ func (m model) View() string {
lhs := strings.Builder{} lhs := strings.Builder{}
rhs := strings.Builder{} rhs := strings.Builder{}
nb := lipgloss.NewStyle().Border(lipgloss.NormalBorder())
db := lipgloss.NewStyle().Border(lipgloss.DoubleBorder())
lhsS := nb
rhsS := nb
// if any entries are not "locked", we always use that // if any entries are not "locked", we always use that
// regular colour in preference // regular colour in preference
styles := map[string]lipgloss.Style{} styles := map[string]lipgloss.Style{}
@ -425,49 +436,29 @@ func (m model) View() string {
if m.tuiMode == MODE_CAL { if m.tuiMode == MODE_CAL {
lhs.WriteString("(f)etch time data\n") lhs.WriteString("(f)etch time data\n")
lhsS = db
} else { } else {
lhs.WriteString("\n") lhs.WriteString("\n")
} }
if m.globalKeyMode() { if m.tuiMode != MODE_FORMENTRY {
lhs.WriteString("(a)dd time entry\n") lhs.WriteString("(a)dd time entry\n")
} else { } else {
lhs.WriteString("\n") lhs.WriteString("\n")
} }
if m.tuiMode == MODE_FORMENTRY { if m.tuiMode == MODE_FORMENTRY {
lhs.WriteString("(esc) abort form\n") lhs.WriteString("(esc) abort form\n")
lhs.WriteString("\n") lhs.WriteString("\n")
rhsS = db
} else { } else {
lhs.WriteString("(tab) switch panes\n") lhs.WriteString("(tab) switch panes\n")
lhs.WriteString("(q)uit\n") lhs.WriteString("(q)uit\n")
} }
if m.timeData.tracker != nil { calendarWidth := 25
activeTime := time.Since(m.timeData.tracker.Since).Truncate(time.Second).String() tableWidth := m.windowWidth - calendarWidth
activeTime = strings.Replace(activeTime, "0ms", "", 1)
lhs.WriteString("\nTracker active: " + activeTime + "\n")
if m.globalKeyMode() {
lhs.WriteString("(c)ancel\n")
} else {
lhs.WriteString("\n")
}
}
if m.tuiMode == MODE_TIMEENTRIES {
rhsS = db
}
lhsWidth := 25
rhsWidth := m.windowWidth - lhsWidth - 4
if m.tuiMode == MODE_FORMENTRY { if m.tuiMode == MODE_FORMENTRY {
rhs.WriteString(m.formData.form.View()) rhs.WriteString(m.formData.form.View())
} else { } else {
if m.fetchedData { if m.fetchedData {
m.timeData.table.Columns()[3].Width = rhsWidth - 30
m.timeData.table.SetHeight(14)
rhs.WriteString(m.timeData.table.View()) rhs.WriteString(m.timeData.table.View())
rhs.WriteString("\n") rhs.WriteString("\n")
} }
@ -475,29 +466,14 @@ func (m model) View() string {
out := lipgloss.JoinHorizontal( out := lipgloss.JoinHorizontal(
lipgloss.Top, lipgloss.Top,
lhsS.Render(lipgloss.NewStyle().Width(lhsWidth).Render(lhs.String())), lipgloss.NewStyle().Width(calendarWidth).Render(lhs.String()),
rhsS.Render(lipgloss.NewStyle().Width(rhsWidth).Render(rhs.String())), lipgloss.NewStyle().Width(tableWidth).Render(rhs.String()),
) )
sofar := lipgloss.Height(out) sofar := lipgloss.Height(out)
statusMsg := strings.ReplaceAll(m.statusBarMessage, "\n", " ") statusMsg := strings.ReplaceAll(m.statusBarMessage, "\n", " ")
out += styleStatusBar.MarginTop(19 - sofar).Width(m.windowWidth).Render(statusMsg)
mainMsg := styleStatusBar.Width(m.windowWidth - len(version)).MarginTop(m.windowHeight - sofar).Render(statusMsg)
versionMsg := styleStatusBar.MarginTop(m.windowHeight - sofar).Render(version)
bar := lipgloss.JoinHorizontal(lipgloss.Top,
mainMsg,
versionMsg,
)
out += bar
return out return out
} }
// globalKeyMode indicates when the UI can receive most keystrokes for global operations -
// mostly this means the form is not active
func (m model) globalKeyMode() bool {
return m.tuiMode != MODE_FORMENTRY
}

View File

@ -1,9 +1,7 @@
package main package main
import ( import (
"charmcal/mite"
"errors" "errors"
"fmt"
"strconv" "strconv"
"time" "time"
@ -20,8 +18,6 @@ func (m model) updateForm(msg tea.Msg) (tea.Model, tea.Cmd) {
case "esc": case "esc":
m.tuiMode = MODE_CAL m.tuiMode = MODE_CAL
return m, nil return m, nil
case "ctrl+c":
return m, tea.Quit
} }
} }
@ -35,7 +31,6 @@ func (m model) updateForm(msg tea.Msg) (tea.Model, tea.Cmd) {
projectID := m.formData.form.GetString("project") projectID := m.formData.form.GetString("project")
description := m.formData.form.GetString("description") description := m.formData.form.GetString("description")
minutes := m.formData.form.GetString("minutes") minutes := m.formData.form.GetString("minutes")
tracker := m.formData.form.GetBool("tracker")
minutesInt, err1 := strconv.ParseInt(minutes, 10, 64) minutesInt, err1 := strconv.ParseInt(minutes, 10, 64)
serviceIDInt, err2 := strconv.ParseInt(serviceID, 10, 64) serviceIDInt, err2 := strconv.ParseInt(serviceID, 10, 64)
@ -46,27 +41,14 @@ func (m model) updateForm(msg tea.Msg) (tea.Model, tea.Cmd) {
m.tuiMode = MODE_CAL m.tuiMode = MODE_CAL
} else { } else {
id, err := m.miteAPI.AddTimeEntry(m.dest.Format(time.DateOnly), int(minutesInt), description, int(projectIDInt), int(serviceIDInt)) err := m.miteAPI.AddTimeEntry(m.dest.Format(time.DateOnly), int(minutesInt), description, int(projectIDInt), int(serviceIDInt))
if err != nil { if err != nil {
m.statusBarMessage = err.Error() m.statusBarMessage = errors.Join(err1, err2, err3).Error()
m.tuiMode = MODE_CAL m.tuiMode = MODE_CAL
} else { } else {
if tracker { m.statusBarMessage = "Successfully logged time"
_, _, err = m.miteAPI.StartTimeTracker(id) m.tuiMode = MODE_CAL
if err != nil { return m, m.fetchMiteData()
m.statusBarMessage = err.Error()
m.tuiMode = MODE_CAL
} else {
m.statusBarMessage = "Successfully logged time and started tracker"
m.tuiMode = MODE_CAL
return m, m.fetchMiteData()
}
} else {
m.statusBarMessage = "Successfully logged time"
m.tuiMode = MODE_CAL
return m, m.fetchMiteData()
}
} }
} }
@ -74,100 +56,3 @@ func (m model) updateForm(msg tea.Msg) (tea.Model, tea.Cmd) {
return m, formCmd return m, formCmd
} }
func (m model) buildForm() *huh.Form {
clOptions := []huh.Option[string]{}
for _, cust := range m.formData.customers {
op := miteToHuhOption(cust)
clOptions = append(clOptions, op)
}
svcOptions := []huh.Option[string]{}
for _, svc := range m.formData.services {
op := miteToHuhOption(svc)
svcOptions = append(svcOptions, op)
}
projOptions := []huh.Option[string]{
{
Key: "[no project]",
Value: "0",
},
}
for _, proj := range m.formData.projects {
op := miteToHuhOption(proj)
projOptions = append(projOptions, op)
}
// cl := huh.NewSelect[string]().
// Key("client").
// Options(clOptions...).
// Title("Client").Height(5).Value(&m.formData.selected.customer)
sl := huh.NewSelect[string]().
Key("service").
Options(svcOptions...).
Title("Service").
Height(6)
pl := huh.NewSelect[string]().
Key("project").
Title("Project").
Options(projOptions...).
Height(6)
description := huh.NewText().
Key("description").
Title("description").
Validate(func(s string) error {
if s == "" {
return errors.New("must enter a description")
}
return nil
})
defMinutes := "0"
minutes := huh.NewInput().
Key("minutes").
CharLimit(5).
Validate(
func(s string) error {
h, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return err
}
if h < 0 {
return errors.New("must be positive")
}
return err
}).
Title("Minutes").
Value(&defMinutes)
confirmTracker := huh.NewConfirm().
Key("tracker").
Affirmative("Yes").
Negative("No").
Title("Start tracker")
form := huh.NewForm(
huh.NewGroup(
pl,
sl,
description,
),
huh.NewGroup(
minutes,
confirmTracker,
),
)
return form
}
func miteToHuhOption[T mite.APIObject](i T) huh.Option[string] {
return huh.Option[string]{
Key: i.GetName(),
Value: fmt.Sprint(i.GetID()),
}
}