Calorie counting web application written in the Go language

profile.go 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. package controllers
  2. import (
  3. "fmt"
  4. "github.com/revel/revel"
  5. "github.com/revolvingcow/grassfed/app/models"
  6. "strings"
  7. "strconv"
  8. "time"
  9. )
  10. type Profile struct {
  11. Application
  12. }
  13. const formatSmallDate = "2006-01-02"
  14. func (c Profile) getGoals(account *models.Account, startDate time.Time) []*models.Goal {
  15. if account == nil {
  16. return nil
  17. }
  18. duration, _ := time.ParseDuration(fmt.Sprintf("%dh", 1*24))
  19. oneDayAhead := time.Now().Add(duration)
  20. results, err := c.Transaction.Select(
  21. models.Goal{},
  22. `select * from Goal where AccountId = ? and (Date between ? and ?) order by Date desc`,
  23. account.Id,
  24. startDate.Format(formatSmallDate),
  25. oneDayAhead.Format(formatSmallDate))
  26. if err != nil {
  27. return nil
  28. }
  29. rows := len(results)
  30. if rows == 0 {
  31. return nil
  32. }
  33. goals := make([]*models.Goal, 0)
  34. for i := 0; i < rows; i++ {
  35. goals = append(goals, results[i].(*models.Goal))
  36. }
  37. return goals
  38. }
  39. func (c Profile) getDaysIn(month time.Month, year int) int {
  40. return time.Date(year, month+1, 0, 0, 0, 0, 0, time.UTC).Day()
  41. }
  42. func (c Profile) getWeights(account *models.Account, startDate time.Time) []*models.Weight {
  43. if account == nil {
  44. return nil
  45. }
  46. duration, _ := time.ParseDuration(fmt.Sprintf("%dh", 1*24))
  47. oneDayAhead := time.Now().Add(duration)
  48. results, err := c.Transaction.Select(
  49. models.Weight{},
  50. `select * from Weight where AccountId = ? and (Date between ? and ?) order by Date desc`,
  51. account.Id,
  52. startDate.Format(formatSmallDate),
  53. oneDayAhead.Format(formatSmallDate))
  54. if err != nil {
  55. return nil
  56. }
  57. rows := len(results)
  58. if rows == 0 {
  59. return nil
  60. }
  61. weights := make([]*models.Weight, 0)
  62. for i := 0; i < rows; i++ {
  63. weights = append(weights, results[i].(*models.Weight))
  64. }
  65. return weights
  66. }
  67. func (c Profile) getHistory(account *models.Account, startDate time.Time) []*models.History {
  68. if account == nil {
  69. return nil
  70. }
  71. duration, _ := time.ParseDuration(fmt.Sprintf("%dh", 1*24))
  72. oneDayAhead := time.Now().Add(duration)
  73. results, err := c.Transaction.Select(
  74. models.History{},
  75. `select * from History where AccountId = ? and (Date between ? and ?) order by Date desc`,
  76. account.Id,
  77. startDate.Format(formatSmallDate),
  78. oneDayAhead.Format(formatSmallDate))
  79. if err != nil {
  80. return nil
  81. }
  82. rows := len(results)
  83. if rows == 0 {
  84. return nil
  85. }
  86. history := make([]*models.History, 0)
  87. for i := 0; i < rows; i++ {
  88. history = append(history, results[i].(*models.History))
  89. }
  90. return history
  91. }
  92. func (c Profile) getLatestGoal(account *models.Account) (goal int64) {
  93. goal = 2000
  94. if account == nil {
  95. return goal
  96. }
  97. results := models.Goal{}
  98. err := c.Transaction.SelectOne(
  99. &results,
  100. `select * from Goal where AccountId = ? order by Date desc limit 1`,
  101. account.Id)
  102. if err != nil {
  103. return goal
  104. }
  105. goal = results.Calories
  106. return goal
  107. }
  108. func (c Profile) setGoal(account *models.Account, calories int64) {
  109. goals, err := c.Transaction.Select(
  110. models.Goal{},
  111. `select * from Goal where AccountId = ? order by Date desc limit 1`,
  112. account.Id)
  113. if err != nil {
  114. revel.INFO.Println(err)
  115. return
  116. }
  117. now := time.Now().Local()
  118. if len(goals) > 0 {
  119. goal := goals[0].(*models.Goal)
  120. local := goal.Date.Local()
  121. if now.Day() == local.Day() && now.Month() == local.Month() && now.Year() == local.Year() {
  122. goal.Calories = calories
  123. c.Transaction.Update(goal)
  124. } else {
  125. newGoal := models.Goal{AccountId: account.Id, Calories: calories, Date: now}
  126. c.Transaction.Insert(&newGoal)
  127. }
  128. } else {
  129. newGoal := models.Goal{AccountId: account.Id, Calories: calories, Date: now}
  130. c.Transaction.Insert(&newGoal)
  131. }
  132. }
  133. func (c Profile) getLatestWeight(account *models.Account) (weight float64) {
  134. weight = 0
  135. if account == nil {
  136. return weight
  137. }
  138. results := models.Weight{}
  139. err := c.Transaction.SelectOne(
  140. &results,
  141. `select * from Weight where AccountId = ? order by Date desc limit 1`,
  142. account.Id)
  143. if err != nil {
  144. return weight
  145. }
  146. weight = results.Weight
  147. return weight
  148. }
  149. func (c Profile) setWeight(account *models.Account, weight float64) {
  150. weights, err := c.Transaction.Select(
  151. models.Weight{},
  152. `select * from Weight where AccountId = ? order by Date desc limit 1`,
  153. account.Id)
  154. if err != nil {
  155. revel.INFO.Println(err)
  156. return
  157. }
  158. now := time.Now().Local()
  159. if len(weights) > 0 {
  160. w := weights[0].(*models.Weight)
  161. local := w.Date.Local()
  162. if now.Day() == local.Day() && now.Month() == local.Month() && now.Year() == local.Year() {
  163. w.Weight = weight
  164. c.Transaction.Update(w)
  165. } else {
  166. newWeight := models.Weight{AccountId: account.Id, Weight: weight, Date: now}
  167. c.Transaction.Insert(&newWeight)
  168. }
  169. } else {
  170. newWeight := models.Weight{AccountId: account.Id, Weight: weight, Date: now}
  171. c.Transaction.Insert(&newWeight)
  172. }
  173. }
  174. func (c Profile) getCaloriesForDate(history []*models.History, date time.Time) (current int64) {
  175. current = 0
  176. if history != nil {
  177. for _, moment := range history {
  178. if moment != nil {
  179. local := moment.Date.Local()
  180. if local.Day() == date.Day() && local.Month() == date.Month() && local.Year() == date.Year() {
  181. current += moment.Calories
  182. }
  183. }
  184. }
  185. }
  186. return current
  187. }
  188. func (c Profile) getStreak(history []*models.History, ceiling int64) (streak int64) {
  189. now := time.Now()
  190. streak = 0
  191. if history != nil && len(history) > 0 {
  192. interval := 1
  193. for {
  194. s := fmt.Sprintf("-%dh", interval*24)
  195. duration, _ := time.ParseDuration(s)
  196. count := c.getCaloriesForDate(history, now.Add(duration))
  197. if count > 0 && ceiling > count {
  198. streak += 1
  199. interval += 1
  200. } else {
  201. break
  202. }
  203. }
  204. }
  205. return streak
  206. }
  207. func (c Profile) getMoment(id int64) *models.History {
  208. history, err := c.Transaction.Select(models.History{}, `select * from History where Id = ?`, id)
  209. if err != nil {
  210. panic(err)
  211. }
  212. if len(history) == 0 {
  213. return nil
  214. }
  215. return history[0].(*models.History)
  216. }
  217. func (c Profile) Index() revel.Result {
  218. account := c.Connected()
  219. return c.Render(account)
  220. }
  221. func (c Profile) Logon(id string) revel.Result {
  222. c.Response.ContentType = "application/json"
  223. c.Validation.Required(id).Message("You must be logged on.")
  224. if c.Validation.HasErrors() {
  225. revel.INFO.Println("Validation errors found.")
  226. c.Validation.Keep()
  227. c.FlashParams()
  228. return c.RenderJson(nil)
  229. }
  230. revel.INFO.Println("Setting up the variables for storage.")
  231. now := time.Now()
  232. account := c.getAccount(id)
  233. if account == nil {
  234. revel.INFO.Println("Creating account.")
  235. account = &models.Account{}
  236. account.Profile = id
  237. account.Created = now
  238. account.LastVisit = now
  239. c.Transaction.Insert(account)
  240. } else {
  241. revel.INFO.Println("Updating account.")
  242. account.LastVisit = now
  243. c.Transaction.Update(account)
  244. }
  245. c.Session["account"] = id
  246. c.Session.SetDefaultExpiration()
  247. return c.RenderJson(true)
  248. }
  249. func (c Profile) History() revel.Result {
  250. account := c.Connected()
  251. if account == nil {
  252. return c.RenderJson(nil)
  253. }
  254. duration, _ := time.ParseDuration(fmt.Sprintf("-%dh", 8*24))
  255. sevenDaysAgo := time.Now().Add(duration)
  256. history := c.getHistory(account, sevenDaysAgo)
  257. return c.RenderJson(history)
  258. }
  259. func (c Profile) Stats() revel.Result {
  260. account := c.Connected()
  261. if account == nil {
  262. return c.RenderJson(nil)
  263. }
  264. duration, _ := time.ParseDuration(fmt.Sprintf("-%dh", 8*24))
  265. sevenDaysAgo := time.Now().Add(duration)
  266. goal := c.getLatestGoal(account)
  267. history := c.getHistory(account, sevenDaysAgo)
  268. response := models.ResponseStatistics{
  269. Goal: goal,
  270. Current: c.getCaloriesForDate(history, time.Now()),
  271. Streak: c.getStreak(history, goal),
  272. }
  273. return c.RenderJson(response)
  274. }
  275. func (c Profile) Trends() revel.Result {
  276. account := c.Connected()
  277. if account == nil {
  278. return c.RenderJson(nil)
  279. }
  280. now := time.Now()
  281. duration, _ := time.ParseDuration(fmt.Sprintf("-%dh", 31*24))
  282. oneMonthAgo := now.Add(duration)
  283. labels := make([]int, 0)
  284. for i := 1; i < c.getDaysIn(now.Month(), now.Year()); i++ {
  285. labels = append(labels, i)
  286. }
  287. rawGoals := c.getGoals(account, oneMonthAgo)
  288. rawWeights := c.getWeights(account, oneMonthAgo)
  289. rawHistory := c.getHistory(account, oneMonthAgo)
  290. latestGoal := c.getLatestGoal(account)
  291. latestWeight := float64(0)
  292. goals := make(map[string]int64, 0)
  293. weights := make(map[string]float64, 0)
  294. calories := make(map[string]int64, 0)
  295. for _, day := range labels {
  296. dayAsString := strconv.Itoa(day)
  297. goals[dayAsString] = latestGoal
  298. weights[dayAsString] = latestWeight
  299. calories[dayAsString] = 0
  300. for _, goal := range rawGoals {
  301. if day == goal.Date.Day() {
  302. goals[dayAsString] = goal.Calories
  303. }
  304. }
  305. for _, weight := range rawWeights {
  306. if day == weight.Date.Day() {
  307. weights[dayAsString] = weight.Weight
  308. latestWeight = weight.Weight
  309. }
  310. }
  311. for _, moment := range rawHistory {
  312. if day == moment.Date.Day() {
  313. calories[dayAsString] += moment.Calories
  314. }
  315. }
  316. }
  317. response := models.ResponseTrends{
  318. Labels: labels,
  319. Goals: goals,
  320. Weights: weights,
  321. History: calories,
  322. }
  323. return c.RenderJson(response)
  324. }
  325. func (c Profile) Add(product string, calories int64) revel.Result {
  326. account := c.Connected()
  327. if account == nil || strings.TrimSpace(product) == "" {
  328. return c.RenderJson(nil)
  329. }
  330. c.Validation.Required(product).Message("You must include a product.")
  331. c.Validation.Required(calories).Message("You must provide the amount of calories")
  332. if c.Validation.HasErrors() {
  333. c.Validation.Keep()
  334. c.FlashParams()
  335. return c.RenderJson(nil)
  336. }
  337. moment := models.History{
  338. AccountId: account.Id,
  339. Product: product,
  340. Calories: calories,
  341. Date: time.Now(),
  342. }
  343. c.Transaction.Insert(&moment)
  344. return c.RenderJson(moment)
  345. }
  346. func (c Profile) Delete(id int64) revel.Result {
  347. account := c.Connected()
  348. if account == nil {
  349. return c.RenderJson(nil)
  350. }
  351. moment := c.getMoment(id)
  352. if moment == nil {
  353. return c.RenderJson(nil)
  354. }
  355. c.Transaction.Delete(moment)
  356. return c.RenderJson(true)
  357. }
  358. func (c Profile) Goal(calories int64) revel.Result {
  359. account := c.Connected()
  360. if account == nil {
  361. return c.RenderJson(nil)
  362. }
  363. c.setGoal(account, calories)
  364. return c.RenderJson(true)
  365. }
  366. func (c Profile) Weight(weight float64) revel.Result {
  367. account := c.Connected()
  368. if account == nil {
  369. return c.RenderJson(nil)
  370. }
  371. c.setWeight(account, weight)
  372. return c.RenderJson(true)
  373. }