Newer
Older
package models
import (
"encoding/json"
"net/http"
"time"
"forge.grandlyon.com/web-et-numerique/llle_project/backoffice-server/internal/common"
)
type MonthlyReport struct {
Year int `json:"year"`
Month int `json:"month"`
Info string `json:"info"`
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
NewsTitle string `json:"newsTitle"`
NewsContent string `json:"newsContent"`
Question string `json:"question"`
Link string `json:"link"`
}
// GetMonthlyReport godoc
// @Summary Get details of a specific monthlyReport
// @Description Get details of a specific monthlyReport
// @Tags monthlyReport
// @Produce json
// @Success 200 {object} MonthlyReport
// @Failure 404 {string} string "Not found"
// @Param year path int true "Year of the monthlyReport"
// @Param month path int true "Month of the monthlyReport"
// @Router /api/common/monthlyReport/{year}/{month} [get]
func (dh *DataHandler) GetMonthlyReport(w http.ResponseWriter, r *http.Request) {
year, month, err := common.YearMonthFromRequest(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
monthlyReport, err := dh.getMonthlyReport(year, month)
if err != nil {
w.WriteHeader(http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(monthlyReport)
}
// GetCurrentMonthlyReport godoc
// @Summary Get details of the current monthlyReport
// @Description Find the MonthlyInfo of the current month and try to find the corresponding monthlyNews and poll
// @Tags monthlyReport
// @Produce json
// @Success 200 {object} MonthlyReport
// @Failure 404 {string} string "Not found"
// @Router /api/common/monthlyReport [get]
func (dh *DataHandler) GetCurrentMonthlyReport(w http.ResponseWriter, r *http.Request) {
year, month, _ := time.Now().Date()
monthlyReport, err := dh.getMonthlyReport(year, int(month))
if err != nil {
w.WriteHeader(http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(monthlyReport)
}
func (dh *DataHandler) getMonthlyReport(year int, month int) (monthlyReport MonthlyReport, err error) {
var monthlyInfo MonthlyInfo
err = dh.db.Where("year = ? AND month = ?", year, month).First(&monthlyInfo).Error
if err != nil {
return MonthlyReport{}, err
}
var monthlyNews MonthlyNews
dh.db.Where("year = ? AND month = ?", year, month).First(&monthlyNews)
var poll Poll
dh.db.Where("year = ? AND month = ?", year, month).First(&poll)
monthlyReport = MonthlyReport{
Year: year,
Month: month,
Info: monthlyInfo.Info,
NewsTitle: monthlyNews.Title,
NewsContent: monthlyNews.Content,
Question: poll.Question,
Link: poll.Link,
}
return monthlyReport, nil
}