forked from WinPooh32/supreme-octo-train
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserveui.go
168 lines (131 loc) · 3.46 KB
/
serveui.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
package main
import (
"encoding/csv"
"io"
"log"
"mime"
"os"
"path"
"strconv"
"strings"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)
func prepareForecast(data []float64, lacks []YearLacks) (forecast, upperLimit, filtered, restored []float64) {
smoothHistory := approximateByRegression(movingavg(data, 2))
upperLimit = confidenceUpperLimit(smoothHistory, 4)
filtered = approximateByRegression(smoothHistory)
coefs := calcYearCoefficient(data, filtered)
multCoefficient(filtered, coefs)
//Внутри восстанавливает filtered!
restored = restoreLacks(filtered, lacks)
forecast = buildForecast(approximateByRegression(filtered[0 : len(filtered)-weeksperyear]))
return
}
func app(r *gin.Engine) {
html := `<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>%s</title>
</head>
<body>
<div id="root"></div>
<!-- Dependencies -->
<script src="/static/react.development.js"></script>
<script src="/static/react-dom.development.js"></script>
<!-- Main -->
<script src="/static/bundle.js"></script>
</body>
</html>`
r.NoRoute(func(c *gin.Context) {
if strings.HasPrefix(c.Request.URL.Path, staticPath) {
c.Status(404)
return
}
c.Header("Content-Type", "text/html; charset=utf-8")
c.String(200, html, "Прогноз закупок")
})
}
func readItems(reader *csv.Reader) []gin.H {
response := make([]gin.H, 0, 10)
for i := 0; ; i++ {
record, err := reader.Read()
if err == io.EOF {
break
}
if err != nil {
log.Println(err)
}
//Парсим провалы
lacks := make([]YearLacks, 0, 4)
const yearsField = 1
years, _ := strconv.Atoi(record[yearsField])
rawLacks := record[2 : 2+years]
for _, v := range rawLacks {
lack := parseLackRange(v)
lacks = append(lacks, lack)
}
// реверс т.к. годы не в том порядке в файле
// так же для данных продаж
lacks = reverseLacks(lacks)
//Считываем название и статистику продаж
dataBegin := 2 + years
name := record[0]
row := reverse(toFloat64(record[dataBegin:]))
forecast, upperLimit, filtered, restored := prepareForecast(row, lacks)
response = append(response, gin.H{
"id": i,
"name": name,
"data": row,
"forecast": forecast,
"upperLimit": upperLimit,
"filtered": filtered,
"restored": restored,
})
}
return response
}
func api(r *gin.Engine) {
r.GET("/forecast", func(c *gin.Context) {
//Считываем товары
fileIn, _ := os.Open("продажи.csv")
defer fileIn.Close()
reader := csv.NewReader(fileIn)
items := readItems(reader)
c.JSON(200, items)
})
}
func detectMIME() gin.HandlerFunc {
return func(c *gin.Context) {
var contentType string
ext := path.Ext(c.Request.URL.EscapedPath())
switch ext {
case ".js":
contentType = "application/javascript"
case ".woff":
contentType = "application/font-woff"
case ".woff2":
contentType = "application/font-woff2"
default:
contentType = mime.TypeByExtension(ext)
}
if len(contentType) > 0 {
c.Header("Content-Type", contentType)
}
c.Next()
}
}
func serveui(dir string) {
r := gin.Default()
config := cors.DefaultConfig()
config.AllowAllOrigins = true
r.Use(cors.New(config))
r.Use(detectMIME())
app(r)
api(r)
r.StaticFS(staticPath, gin.Dir(dir, true))
r.StaticFile("/favicon.ico", dir+"/favicon.ico")
// r.Static(staticPath, dir)
r.Run() // listen and serve on 0.0.0.0:8080
}