浏览代码

added more json feedback

bmallred 10 年之前
父节点
当前提交
1c9ece5284

+ 28 - 0
app/controllers/home.go

2
2
3
import (
3
import (
4
    "github.com/revel/revel"
4
    "github.com/revel/revel"
5
    "github.com/revolvingcow/grassfed/app/models"
5
)
6
)
6
7
7
type Home struct {
8
type Home struct {
8
    Application
9
    Application
9
}
10
}
10
11
12
func (c Home) getNumberOfAccounts() (count int64) {
13
    count, err := c.Transaction.SelectInt(`select count(*) from Account`)
14
    if err != nil {
15
        return 0
16
    }
17
18
    return count
19
}
20
21
func (c Home) getNumberOfCalories() (calories int64) {
22
    calories, err := c.Transaction.SelectInt(`select sum(Calories) from History`)
23
    if err != nil {
24
        return 0
25
    }
26
27
    return calories
28
}
29
11
func (c Home) Index() revel.Result {
30
func (c Home) Index() revel.Result {
12
	return c.Render()
31
	return c.Render()
13
}
32
}
15
func (c Home) About() revel.Result {
34
func (c Home) About() revel.Result {
16
    return c.Render()
35
    return c.Render()
17
}
36
}
37
38
func (c Home) Overview() revel.Result {
39
    model := models.Overview {
40
        Accounts: c.getNumberOfAccounts(),
41
        Calories: c.getNumberOfCalories(),
42
    }
43
44
    return c.RenderJson(model)
45
}

+ 44 - 16
app/controllers/profile.go

1
package controllers
1
package controllers
2
2
3
import (
3
import (
4
    "fmt"
4
    "strings"
5
    "strings"
5
    "time"
6
    "time"
6
    "github.com/revel/revel"
7
    "github.com/revel/revel"
38
    return history
39
    return history
39
}
40
}
40
41
42
func (c Profile) getCaloriesForDate(history []*models.History, date time.Time) (current int64) {
43
    current = 0
44
45
    if history != nil {
46
        for _, moment := range history {
47
            if moment != nil {
48
                local := moment.Date.Local()
49
                if local.Day() == date.Day() && local.Month() == date.Month() && local.Year() == date.Year() {
50
                    current += moment.Calories
51
                }
52
            }
53
        }
54
    }
55
56
    return current
57
}
58
59
func (c Profile) getStreak(history []*models.History, ceiling int64) (streak int64) {
60
    now := time.Now()
61
    streak = 0
62
63
    if history != nil && len(history) > 0 {
64
        interval := 1
65
66
        for {
67
            s := fmt.Sprintf("-%dh", interval * 24)
68
            duration, _ := time.ParseDuration(s)
69
            count := c.getCaloriesForDate(history, now.Add(duration))
70
71
            if count > 0 && ceiling > count {
72
                streak += 1
73
                interval += 1
74
            } else {
75
                break
76
            }
77
        }
78
    }
79
80
    return streak
81
}
82
41
func (c Profile) getMoment(id int64) *models.History {
83
func (c Profile) getMoment(id int64) *models.History {
42
    history, err := c.Transaction.Select(models.History{}, `select * from History where Id = ?`, id)
84
    history, err := c.Transaction.Select(models.History{}, `select * from History where Id = ?`, id)
43
    if err != nil {
85
    if err != nil {
106
        return c.RenderJson(nil)
148
        return c.RenderJson(nil)
107
    }
149
    }
108
150
109
    now := time.Now().Local()
110
    history := c.getHistory(account)
151
    history := c.getHistory(account)
111
    current := int64(0)
112
113
    if history != nil {
114
        for _, moment := range history {
115
            if moment != nil {
116
                utcMoment := moment.Date.Local()
117
                if utcMoment.Day() == now.Day() && utcMoment.Month() == now.Month() && utcMoment.Year() == now.Year() {
118
                    revel.INFO.Println(utcMoment)
119
                    revel.INFO.Println(now)
120
                    current += moment.Calories
121
                }
122
            }
123
        }
124
    }
125
152
126
    response := models.ResponseStatistics {
153
    response := models.ResponseStatistics {
127
        Goal: account.Goal,
154
        Goal: account.Goal,
128
        Current: current,
155
        Current: c.getCaloriesForDate(history, time.Now()),
156
        Streak: c.getStreak(history, account.Goal),
129
    }
157
    }
130
158
131
    return c.RenderJson(response)
159
    return c.RenderJson(response)

+ 4 - 2
app/init.go

33
// should probably also have a filter for CSRF
33
// should probably also have a filter for CSRF
34
// not sure if it can go in the same filter or not
34
// not sure if it can go in the same filter or not
35
var HeaderFilter = func(c *revel.Controller, fc []revel.Filter) {
35
var HeaderFilter = func(c *revel.Controller, fc []revel.Filter) {
36
	// Add some common security headers
37
	c.Response.Out.Header().Add("X-Frame-Options", "SAMEORIGIN")
36
    // This was commented out so I could mask the origins with DNS
37
    //c.Response.Out.Header().Add("X-Frame-Options", "SAMEORIGIN")
38
39
    // Add some common security headers
38
	c.Response.Out.Header().Add("X-XSS-Protection", "1; mode=block")
40
	c.Response.Out.Header().Add("X-XSS-Protection", "1; mode=block")
39
	c.Response.Out.Header().Add("X-Content-Type-Options", "nosniff")
41
	c.Response.Out.Header().Add("X-Content-Type-Options", "nosniff")
40
42

+ 6 - 0
app/models/overview.go

1
package models
2
3
type Overview struct {
4
    Accounts int64
5
    Calories int64
6
}

+ 1 - 0
app/models/statistics.go

3
type ResponseStatistics struct {
3
type ResponseStatistics struct {
4
    Goal int64
4
    Goal int64
5
    Current int64
5
    Current int64
6
    Streak int64
6
}
7
}

+ 7 - 0
app/routes/routes.go

176
	return revel.MainRouter.Reverse("Home.About", args).Url
176
	return revel.MainRouter.Reverse("Home.About", args).Url
177
}
177
}
178
178
179
func (_ tHome) Overview(
180
		) string {
181
	args := make(map[string]string)
182
	
183
	return revel.MainRouter.Reverse("Home.Overview", args).Url
184
}
185
179
186

+ 13 - 6
app/tmp/main.go

125
				Args: []*revel.MethodArg{ 
125
				Args: []*revel.MethodArg{ 
126
				},
126
				},
127
				RenderArgNames: map[int][]string{ 
127
				RenderArgNames: map[int][]string{ 
128
					55: []string{ 
128
					97: []string{ 
129
					},
129
					},
130
				},
130
				},
131
			},
131
			},
186
				Args: []*revel.MethodArg{ 
186
				Args: []*revel.MethodArg{ 
187
				},
187
				},
188
				RenderArgNames: map[int][]string{ 
188
				RenderArgNames: map[int][]string{ 
189
					12: []string{ 
189
					31: []string{ 
190
					},
190
					},
191
				},
191
				},
192
			},
192
			},
195
				Args: []*revel.MethodArg{ 
195
				Args: []*revel.MethodArg{ 
196
				},
196
				},
197
				RenderArgNames: map[int][]string{ 
197
				RenderArgNames: map[int][]string{ 
198
					16: []string{ 
198
					35: []string{ 
199
					},
199
					},
200
				},
200
				},
201
			},
201
			},
202
			&revel.MethodType{
203
				Name: "Overview",
204
				Args: []*revel.MethodArg{ 
205
				},
206
				RenderArgNames: map[int][]string{ 
207
				},
208
			},
202
			
209
			
203
		})
210
		})
204
	
211
	
205
	revel.DefaultValidationKeys = map[string]map[int]string{ 
212
	revel.DefaultValidationKeys = map[string]map[int]string{ 
206
		"github.com/revolvingcow/grassfed/app/controllers.Profile.Add": { 
213
		"github.com/revolvingcow/grassfed/app/controllers.Profile.Add": { 
207
			140: "product",
208
			141: "calories",
214
			168: "product",
215
			169: "calories",
209
		},
216
		},
210
		"github.com/revolvingcow/grassfed/app/controllers.Profile.Logon": { 
217
		"github.com/revolvingcow/grassfed/app/controllers.Profile.Logon": { 
211
			60: "id",
218
			102: "id",
212
		},
219
		},
213
	}
220
	}
214
	revel.TestSuites = []interface{}{ 
221
	revel.TestSuites = []interface{}{ 

+ 6 - 18
app/views/Home/Index.html

1
{{set . "title" "Home"}}
1
{{set . "title" "Home"}}
2
{{template "header.html" .}}
2
{{template "header.html" .}}
3
3
4
{{append . "moreScripts" "/public/js/overview.js"}}
5
4
<div class="jumbotron">
6
<div class="jumbotron">
5
    <h1></h1>
7
    <h1></h1>
6
    
8
    
7
    <div class="row">
9
    <div class="row">
8
        <div class="col-md-4 text-center">
10
        <div class="col-md-4 text-center">
9
            <h3>0</h3>
10
            <h3>Users</h3>
11
        </div>
12
        <div class="col-md-4 text-center">
13
            <h3>0</h3>
14
            <h3>Something else</h3>
11
            <h3 class="accounts">0</h3>
12
            <h3>Accounts</h3>
15
        </div>
13
        </div>
16
        <div class="col-md-4 text-center">
14
        <div class="col-md-4 text-center">
17
            <h3>0</h3>
18
            <h3>And then...</h3>
15
            <h3 class="calories">0</h3>
16
            <h3>Calories</h3>
19
        </div>
17
        </div>
20
    </div>
18
    </div>
21
</div>
19
</div>
22
<!--<span id="signinButton">
23
    <span
24
        class="g-signin"
25
        data-callback="onAuthentication"
26
        data-clientid="903785837828-lfsps917vkth7c88em9ieq0l0d0p35kb.apps.googleusercontent.com"
27
        data-cookiepolicy="single_host_origin"
28
        data-requestvisibleactions=""
29
        data-scope="profile">
30
    </span>
31
</span>-->
32
20
33
{{template "footer.html" .}}
21
{{template "footer.html" .}}

+ 2 - 2
app/views/Profile/Index.html

70
        </form>
70
        </form>
71
71
72
        <h3>Streak</h3>
72
        <h3>Streak</h3>
73
        <p class="text-center">0 days</p>
74
73
        <h3 class="streak text-center">0</h3>
74
        <h3 class="streak-units text-center">days</h3>
75
    </div>
75
    </div>
76
</div>
76
</div>
77
77

+ 15 - 0
app/views/footer.html

4
    {{range .moreScripts}}
4
    {{range .moreScripts}}
5
        <script type="text/javascript" charset="utf-8" src="{{.}}"></script>
5
        <script type="text/javascript" charset="utf-8" src="{{.}}"></script>
6
    {{end}}
6
    {{end}}
7
8
    <script type="text/javascript">
9
        $(function () {
10
            var loc = window.location.href;
11
            var menuItems = $('.nav.navbar-nav').find('li > a');
12
13
            for (var i = 0 ; i < menuItems.length; i++) {
14
                var href = $(menuItems[i]).attr('href');
15
16
                if (loc.indexOf(href, loc.length - href.length) !== -1) {
17
                    $(menuItems[i]).parents('li').addClass('active');
18
                }
19
            }
20
        });
21
    </script>
7
  
22
  
8
    {{if eq .RunMode "dev"}}
23
    {{if eq .RunMode "dev"}}
9
        {{template "debug.html" .}}
24
        {{template "debug.html" .}}

+ 1 - 1
app/views/header.html

31
            </div>
31
            </div>
32
            <div class="navbar-collapse collapse">
32
            <div class="navbar-collapse collapse">
33
                <ul class="nav navbar-nav">
33
                <ul class="nav navbar-nav">
34
                    <li class="active"><a href="/">Overview</a></li>
34
                    <li><a href="/">Overview</a></li>
35
                    <li><a href="/about">About</a></li>
35
                    <li><a href="/about">About</a></li>
36
                    <li><a href="//github.com/revolvingcow/grassfed">Get The Code!</a></li>
36
                    <li><a href="//github.com/revolvingcow/grassfed">Get The Code!</a></li>
37
                </ul>
37
                </ul>

+ 1 - 0
conf/routes

6
6
7
GET     /                                       Home.Index
7
GET     /                                       Home.Index
8
GET     /about                                  Home.About
8
GET     /about                                  Home.About
9
POST    /overview                               Home.Overview
9
GET     /me                                     Profile.Index
10
GET     /me                                     Profile.Index
10
POST    /me/logon                               Profile.Logon
11
POST    /me/logon                               Profile.Logon
11
GET     /me/history                             Profile.History
12
GET     /me/history                             Profile.History

+ 8 - 0
public/js/grassfed.js

20
        // Pull the information we need first.
20
        // Pull the information we need first.
21
        loadStatistics();
21
        loadStatistics();
22
        loadHistory();
22
        loadHistory();
23
24
        // Set focus.
25
        $('input[name="products"][type="text"]').focus();
23
    }
26
    }
24
27
25
    $('div#profile').on('show', function () {
28
    $('div#profile').on('show', function () {
47
                    var previousCalories = parseInt($('input[name="current"][type="hidden"]').val());
50
                    var previousCalories = parseInt($('input[name="current"][type="hidden"]').val());
48
                    $('input[name="current"][type="hidden"]').val(previousCalories + response.Calories);
51
                    $('input[name="current"][type="hidden"]').val(previousCalories + response.Calories);
49
                    updateChart();
52
                    updateChart();
53
54
                    // Reset focus.
55
                    $('input[name="products"][type="text"]').focus();
50
                }
56
                }
51
            });
57
            });
52
58
139
                    $('input[name="calories"][type="range"]').val(response.Goal);
145
                    $('input[name="calories"][type="range"]').val(response.Goal);
140
                    $('span.goal').text(response.Goal);
146
                    $('span.goal').text(response.Goal);
141
                    $('input[name="current"][type="hidden"]').val(response.Current);
147
                    $('input[name="current"][type="hidden"]').val(response.Current);
148
                    $('.streak').text(response.Streak);
149
                    $('.streak-unit').text('days');
142
                }
150
                }
143
151
144
                updateChart();
152
                updateChart();

+ 9 - 0
public/js/overview.js

1
$(function () {
2
    $.post('/overview')
3
    .done(function (response) {
4
        if (response) {
5
            $('.accounts').text(response.Accounts);
6
            $('.calories').text(response.Calories);
7
        }
8
    });
9
});