src

Go monorepo.
git clone git://code.dwrz.net/src
Log | Files | Refs

entry.go (1728B)


      1 package entry
      2 
      3 import (
      4 	"fmt"
      5 	"strings"
      6 	"time"
      7 
      8 	"code.dwrz.net/src/pkg/dqs/category"
      9 	"code.dwrz.net/src/pkg/dqs/diet"
     10 	"code.dwrz.net/src/pkg/dqs/user"
     11 )
     12 
     13 const (
     14 	DateFormat        = "20060102"
     15 	dateDisplayFormat = "2006-01-02"
     16 )
     17 
     18 type Entry struct {
     19 	BodyFat    float64                      `json:"bodyFat"`
     20 	Categories map[string]category.Category `json:"categories"`
     21 	Date       time.Time                    `json:"date"`
     22 	Diet       diet.Diet                    `json:"diet"`
     23 	Height     float64                      `json:"height"`
     24 	Note       string                       `json:"note"`
     25 	Weight     float64                      `json:"weight"`
     26 }
     27 
     28 func New(date time.Time, u *user.User) *Entry {
     29 	var e = &Entry{
     30 		Categories: u.Diet.Template(),
     31 		Date:       date,
     32 		Diet:       u.Diet,
     33 	}
     34 
     35 	var currentDate = time.Now().Format(DateFormat)
     36 	if currentDate == date.Format(DateFormat) {
     37 		e.BodyFat = u.BodyFat
     38 		e.Height = u.Height
     39 		e.Weight = u.Weight
     40 	}
     41 
     42 	return e
     43 }
     44 
     45 // Key returns the key used to retrieve an entry from the store.
     46 func (e *Entry) Key() string {
     47 	return e.Date.Format(DateFormat)
     48 }
     49 
     50 func (e *Entry) Score() (total float64) {
     51 	for _, c := range e.Categories {
     52 		total += c.Score()
     53 	}
     54 
     55 	return total
     56 }
     57 
     58 func (e *Entry) Category(c string) (*category.Category, error) {
     59 	// Try expanding an abbreviation.
     60 	category, exists := e.Categories[category.Abbreviations[c]]
     61 	if !exists {
     62 		// Check if a lowercase full category name was used.
     63 		category, exists = e.Categories[strings.Title(c)]
     64 		if !exists {
     65 			// Check the full, capitalized name.
     66 			category, exists = e.Categories[c]
     67 			if !exists {
     68 				return nil, fmt.Errorf(
     69 					"category %s not found", c,
     70 				)
     71 			}
     72 		}
     73 	}
     74 
     75 	return &category, nil
     76 }