Commit b793e986 authored by jadtaphon chinnapan's avatar jadtaphon chinnapan

jadtaphon

parent e4aa5658
Pipeline #904 canceled with stages
package main
import (
"net/http"
"github.com/labstack/echo"
"gopkg.in/mgo.v2/bson"
)
//////////sssss///////////////////////////////////////
func (h *Handler) checkIn(c echo.Context) error {
u := new(Course)
id := c.Param("id")
stdid := c.FormValue("stdid")
week := c.FormValue("week")
//idactive := c.FormValue("id_active")
// Find user
db := h.DB.Clone()
defer db.Close()
query := bson.M{"_id": bson.ObjectIdHex(id), "students.id_student": stdid}
update := bson.M{}
switch week {
case "1":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week1.week": 1,
"students.$.weeks.week1.id_active": stdid,
},
}
case "2":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week2.week": 1,
"students.$.weeks.week2.id_active": stdid,
},
}
case "3":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week3.week": 1,
"students.$.weeks.week3.id_active": stdid,
},
}
case "4":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week4.week": 1,
"students.$.weeks.week4.id_active": stdid,
},
}
case "5":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week5.week": 1,
"students.$.weeks.week5.id_active": stdid,
},
}
case "6":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week6.week": 1,
"students.$.weeks.week6.id_active": stdid,
},
}
case "7":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week7.week": 1,
"students.$.weeks.week7.id_active": stdid,
},
}
case "8":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week8.week": 1,
"students.$.weeks.week8.id_active": stdid,
},
}
case "9":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week9.week": 1,
"students.$.weeks.week9.id_active": stdid,
},
}
case "10":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week10.week": 1,
"students.$.weeks.week10.id_active": stdid,
},
}
case "11":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week11.week": 1,
"students.$.weeks.week11.id_active": stdid,
},
}
case "12":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week12.week": 1,
"students.$.weeks.week12.id_active": stdid,
},
}
case "13":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week13.week": 1,
"students.$.weeks.week13.id_active": stdid,
},
}
case "14":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week14.week": 1,
"students.$.weeks.week14.id_active": stdid,
},
}
case "15":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week15.week": 1,
"students.$.weeks.week15.id_active": stdid,
},
}
case "16":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week16.week": 1,
"students.$.weeks.week16.id_active": stdid,
},
}
default:
return c.JSON(http.StatusBadRequest, "week invalid")
}
err := db.DB("test").C("course").Update(query, update)
if err != nil {
return c.JSON(http.StatusBadRequest, err.Error())
}
WsSendAction(c, WsMsg{
Action: string(checknameEvent),
Payload: map[string]interface{}{"item": u},
})
return c.JSON(http.StatusOK, u)
}
func (h *Handler) checknameT(c echo.Context) error {
u := new(Course)
id := c.Param("id")
stdid := c.FormValue("stdid")
week := c.FormValue("week")
//cont := c.FormValue("cont")
// Find user
db := h.DB.Clone()
defer db.Close()
query := bson.M{"_id": bson.ObjectIdHex(id), "students.id_student": stdid}
update := bson.M{}
switch week {
case "1":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week1.week": 0.5,
"students.$.weeks.week1.id_active": stdid,
},
}
case "2":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week2.week": 0.5,
"students.$.weeks.week2.id_active": stdid,
},
}
case "3":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week3.week": 0.5,
"students.$.weeks.week3.id_active": stdid,
},
}
case "4":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week4.week": 0.5,
"students.$.weeks.week4.id_active": stdid,
},
}
case "5":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week5.week": 0.5,
"students.$.weeks.week5.id_active": stdid,
},
}
case "6":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week6.week": 0.5,
"students.$.weeks.week6.id_active": stdid,
},
}
case "7":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week7.week": 0.5,
"students.$.weeks.week7.id_active": stdid,
},
}
case "8":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week8.week": 0.5,
"students.$.weeks.week8.id_active": stdid,
},
}
case "9":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week9.week": 0.5,
"students.$.weeks.week9.id_active": stdid,
},
}
case "10":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week10.week": 0.5,
"students.$.weeks.week10.id_active": stdid,
},
}
case "11":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week11.week": 0.5,
"students.$.weeks.week11.id_active": stdid,
},
}
case "12":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week12.week": 0.5,
"students.$.weeks.week12.id_active": stdid,
},
}
case "13":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week13.week": 0.5,
"students.$.weeks.week13.id_active": stdid,
},
}
case "14":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week14.week": 0.5,
"students.$.weeks.week14.id_active": stdid,
},
}
case "15":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week15.week": 0.5,
"students.$.weeks.week15.id_active": stdid,
},
}
case "16":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week16.week": 0.5,
"students.$.weeks.week16.id_active": stdid,
},
}
default:
return c.JSON(http.StatusBadRequest, "week invalid")
}
err := db.DB("test").C("course").Update(query, update)
if err != nil {
return c.JSON(http.StatusBadRequest, err.Error())
}
return c.JSON(http.StatusOK, u)
}
func (h *Handler) checknameO(c echo.Context) error {
u := new(Course)
id := c.Param("id")
stdid := c.FormValue("stdid")
week := c.FormValue("week")
//cont := c.FormValue("cont")
// Find user
db := h.DB.Clone()
defer db.Close()
query := bson.M{"_id": bson.ObjectIdHex(id), "students.id_student": stdid}
update := bson.M{}
switch week {
case "1":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week1.week": 0,
"students.$.weeks.week1.id_active": stdid,
},
}
case "2":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week2.week": 0,
"students.$.weeks.week2.id_active": stdid,
},
}
case "3":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week3.week": 0,
"students.$.weeks.week3.id_active": stdid,
},
}
case "4":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week4.week": 0,
"students.$.weeks.week4.id_active": stdid,
},
}
case "5":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week5.week": 0,
"students.$.weeks.week5.id_active": stdid,
},
}
case "6":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week6.week": 0,
"students.$.weeks.week6.id_active": stdid,
},
}
case "7":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week7.week": 0,
"students.$.weeks.week7.id_active": stdid,
},
}
case "8":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week8.week": 0,
"students.$.weeks.week8.id_active": stdid,
},
}
case "9":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week9.week": 0,
"students.$.weeks.week9.id_active": stdid,
},
}
case "10":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week10.week": 0,
"students.$.weeks.week10.id_active": stdid,
},
}
case "11":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week11.week": 0,
"students.$.weeks.week11.id_active": stdid,
},
}
case "12":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week12.week": 0,
"students.$.weeks.week12.id_active": stdid,
},
}
case "13":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week13.week": 0,
"students.$.weeks.week13.id_active": stdid,
},
}
case "14":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week14.week": 0,
"students.$.weeks.week14.id_active": stdid,
},
}
case "15":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week15.week": 0,
"students.$.weeks.week15.id_active": stdid,
},
}
case "16":
update = bson.M{
"$set": bson.M{
"students.$.weeks.week16.week": 0,
"students.$.weeks.week16.id_active": stdid,
},
}
default:
return c.JSON(http.StatusBadRequest, "week invalid")
}
err := db.DB("test").C("course").Update(query, update)
if err != nil {
return c.JSON(http.StatusBadRequest, err.Error())
}
return c.JSON(http.StatusOK, u)
}
// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"log"
"net/http"
"time"
"github.com/gorilla/websocket"
)
const (
// Time allowed to write a message to the peer.
writeWait = 10 * time.Second
// Time allowed to read the next pong message from the peer.
pongWait = 60 * time.Second
// Send pings to peer with this period. Must be less than pongWait.
pingPeriod = (pongWait * 9) / 10
// Maximum message size allowed from peer.
maxMessageSize = 512
)
var (
newline = []byte{'\n'}
space = []byte{' '}
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool { return true },
}
// Client is a middleman between the websocket connection and the hub.
type Client struct {
hub *Hub
// The websocket connection.
conn *websocket.Conn
// Buffered channel of outbound messages.
send chan []byte
}
// readPump pumps messages from the websocket connection to the hub.
//
// The application runs readPump in a per-connection goroutine. The application
// ensures that there is at most one reader on a connection by executing all
// reads from this goroutine.
func (c *Client) readPump() {
defer func() {
c.hub.unregister <- c
c.conn.Close()
}()
c.conn.SetReadLimit(maxMessageSize)
c.conn.SetReadDeadline(time.Now().Add(pongWait))
c.conn.SetPongHandler(func(string) error { c.conn.SetReadDeadline(time.Now().Add(pongWait)); return nil })
for {
_, message, err := c.conn.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
log.Printf("error: %v", err)
}
break
}
message = bytes.TrimSpace(bytes.Replace(message, newline, space, -1))
c.hub.broadcast <- message
}
}
// writePump pumps messages from the hub to the websocket connection.
//
// A goroutine running writePump is started for each connection. The
// application ensures that there is at most one writer to a connection by
// executing all writes from this goroutine.
func (c *Client) writePump() {
ticker := time.NewTicker(pingPeriod)
defer func() {
ticker.Stop()
c.conn.Close()
}()
for {
select {
case message, ok := <-c.send:
c.conn.SetWriteDeadline(time.Now().Add(writeWait))
if !ok {
// The hub closed the channel.
c.conn.WriteMessage(websocket.CloseMessage, []byte{})
return
}
w, err := c.conn.NextWriter(websocket.TextMessage)
if err != nil {
return
}
w.Write(message)
// Add queued chat messages to the current websocket message.
n := len(c.send)
for i := 0; i < n; i++ {
w.Write(newline)
w.Write(<-c.send)
}
if err := w.Close(); err != nil {
return
}
case <-ticker.C:
c.conn.SetWriteDeadline(time.Now().Add(writeWait))
if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
return
}
}
}
}
// serveWs handles websocket requests from the peer.
func serveWs(hub *Hub, w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
client := &Client{hub: hub, conn: conn, send: make(chan []byte, 256)}
client.hub.register <- client
// Allow collection of memory referenced by the caller by doing all work in
// new goroutines.
go client.writePump()
go client.readPump()
}
module server
go 1.13
require (
github.com/dgrijalva/jwt-go v3.2.0+incompatible // indirect
github.com/gorilla/websocket v1.4.1
github.com/kr/pretty v0.1.0 // indirect
github.com/labstack/echo v3.3.10+incompatible
github.com/labstack/gommon v0.3.0 // indirect
github.com/valyala/fasttemplate v1.1.0 // indirect
golang.org/x/crypto v0.0.0-20191227163750-53104e6ec876 // indirect
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 // indirect
gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22
gopkg.in/yaml.v2 v2.2.7 // indirect
)
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/gorilla/websocket v1.4.1 h1:q7AeDBpnBk8AogcD4DSag/Ukw/KV+YhzLj2bP5HvKCM=
github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/labstack/echo v3.3.10+incompatible h1:pGRcYk231ExFAyoAjAfD85kQzRJCRI8bbnE7CX5OEgg=
github.com/labstack/echo v3.3.10+incompatible/go.mod h1:0INS7j/VjnFxD4E2wkz67b8cVwCLbBmJyDaka6Cmk1s=
github.com/labstack/gommon v0.3.0 h1:JEeO0bvc78PKdyHxloTKiF8BD5iGrH8T6MSeGvSgob0=
github.com/labstack/gommon v0.3.0/go.mod h1:MULnywXg0yavhxWKc+lOruYdAhDwPK9wf0OL7NoOu+k=
github.com/mattn/go-colorable v0.1.2 h1:/bC9yWikZXAL9uJdulbSfyVNIR3n3trXl+v8+1sx8mU=
github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
github.com/mattn/go-isatty v0.0.9 h1:d5US/mDsogSGW37IV293h//ZFaeajb69h+EHFsv2xGg=
github.com/mattn/go-isatty v0.0.9/go.mod h1:YNRxwqDuOph6SZLI9vUUz6OYw3QyUt7WiY2yME+cCiQ=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasttemplate v1.0.1/go.mod h1:UQGH1tvbgY+Nz5t2n7tXsz52dQxojPUpymEIMZ47gx8=
github.com/valyala/fasttemplate v1.1.0 h1:RZqt0yGBsps8NGvLSGW804QQqCUYYLsaOjTVHy1Ocw4=
github.com/valyala/fasttemplate v1.1.0/go.mod h1:UQGH1tvbgY+Nz5t2n7tXsz52dQxojPUpymEIMZ47gx8=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191227163750-53104e6ec876 h1:sKJQZMuxjOAR/Uo2LBfU90onWEf1dF4C+0hPJCc9Mpc=
golang.org/x/crypto v0.0.0-20191227163750-53104e6ec876/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3 h1:0GoQqolDA55aaLxZyTzK/Y2ePZzZTUrRacwib7cNsYQ=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a h1:aYOabOQFp6Vj6W1F80affTUvO9UxmJRx8K0gsfABByQ=
golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22 h1:VpOs+IwYnYBaFnrNAeB8UUWtL3vEUnzSCL1nVjPhqrw=
gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.7 h1:VUgggvou5XRW9mHwD/yXxIYSMtY0zoKQf/v226p2nyo=
gopkg.in/yaml.v2 v2.2.7/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
package main
import (
"gopkg.in/mgo.v2"
)
type (
Handler struct {
DB *mgo.Session
}
)
const (
Key = "secret"
)
package main
// Msg type
type WsMsg struct {
Action string `json:"action"`
Payload map[string]interface{} `json:"payload"`
}
// Hub maintains the set of active clients and broadcasts messages to the
// clients.
type Hub struct {
// Registered clients.
clients map[*Client]bool
// Inbound messages from the clients.
broadcast chan []byte
// Register requests from the clients.
register chan *Client
// Unregister requests from clients.
unregister chan *Client
event chan WsMsg
}
type Event string
const (
checknameEvent Event = "[student][checkname]"
)
func newHub() *Hub {
return &Hub{
broadcast: make(chan []byte),
register: make(chan *Client),
unregister: make(chan *Client),
clients: make(map[*Client]bool),
}
}
func (h *Hub) run() {
for {
select {
case client := <-h.register:
h.clients[client] = true
case client := <-h.unregister:
if _, ok := h.clients[client]; ok {
delete(h.clients, client)
close(client.send)
}
case message := <-h.broadcast:
for client := range h.clients {
select {
case client.send <- message:
default:
close(client.send)
delete(h.clients, client)
}
}
}
}
}
package main
import (
"gopkg.in/mgo.v2/bson"
)
type (
Course struct {
ID bson.ObjectId `json:"id" bson:"_id,omitempty"`
CourseID string `json:"course_id" bson:"course_id"`
CourseName string `json:"course_name" bson:"course_name"`
Day_Time string `json:"time" bson:"time"`
Seson string `json:"seson" bson:"seson"`
Sutdents []Sutdent `json:"students" bson:"students"`
}
Sutdent struct {
NumberID int `json:"number_id" bson:"number_id"`
Idstudent string `json:"id_student" bson:"id_student"`
Name string `json:"name" bson:"name"`
Weeks Week `json:"weeks" bson:"weeks"`
}
Week struct {
Week1 Active `json:"week1" bson:"week1"`
Week2 Active `json:"week2" bson:"week2"`
Week3 Active `json:"week3" bson:"week3"`
Week4 Active `json:"week4" bson:"week4"`
Week5 Active `json:"week5" bson:"week5"`
Week6 Active `json:"week6" bson:"week6"`
Week7 Active `json:"week7" bson:"week7"`
Week8 Active `json:"week8" bson:"week8"`
Week9 Active `json:"week9" bson:"week9"`
Week10 Active `json:"week10" bson:"week10"`
Week11 Active `json:"week11" bson:"week11"`
Week12 Active `json:"week12" bson:"week12"`
Week13 Active `json:"week13" bson:"week13"`
Week14 Active `json:"week14" bson:"week14"`
Week15 Active `json:"week15" bson:"week15"`
Week16 Active `json:"week16" bson:"week16"`
}
Active struct {
Weeks float32 `json:"week" bson:"week"`
Idactive string `json:"id_active" bson:"id_active"`
}
)
package main
import (
"log"
"os"
"net"
"github.com/gorilla/websocket"
"github.com/labstack/echo"
)
func WsSendAction(e echo.Context, data WsMsg) error {
////////////get ip///////////
addrs, err := net.InterfaceAddrs()
if err != nil {
os.Stderr.WriteString("Oops: " + err.Error() + "\n")
os.Exit(1)
}
var ip string
for _, a := range addrs {
if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
ip = ipnet.IP.String()
}
}
}
/////////////////////////////////////////////
c, _, err := websocket.DefaultDialer.Dial("ws://"+ip+":443/ws", nil)
log.Println(ip+"test01")
if err != nil {
log.Println("dial:", err)
return err
}
defer c.Close()
err = c.WriteJSON(data)
if err != nil {
log.Println("write:", err)
return err
}
return nil
}
package main
import (
"log"
"net"
"net/http"
"os"
//"github.com/tealeg/xlsx"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
"gopkg.in/mgo.v2"
)
func main() {
e := echo.New()
e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
AllowOrigins: []string{"*"},
AllowMethods: []string{http.MethodGet, http.MethodPut, http.MethodPost, http.MethodDelete},
}))
//////get ip//////////
addrs, err := net.InterfaceAddrs()
if err != nil {
os.Stderr.WriteString("Oops: " + err.Error() + "\n")
os.Exit(1)
}
var ip string
for _, a := range addrs {
if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
ip = ipnet.IP.String()
}
}
}
log.Print(ip)
//////get ip//////////
// Database connection
db, err := mgo.Dial("localhost")
if err != nil {
e.Logger.Fatal(err)
}
hub := newHub()
go hub.run()
// Initialize handler
h := &Handler{DB: db}
e.GET("/getCourse", h.getAllCourse)
e.GET("/report/:id", h.report)
e.DELETE("/deleteCourse/:id", h.deleteCourse)
e.POST("/upload", h.uploadCourse)
e.POST("/chackname/:id", h.checkIn)
e.POST("/chacknameT/:id", h.checknameT)
e.POST("/checknameO/:id", h.checknameO)
e.GET("/getIP", h.getIP)
e.POST("/addupstudent/:id", h.addupstudent)
e.POST("/editstudent/:id", h.editstudent)
e.POST("/deletestudent/:id", h.deletestudent)
e.POST("/updatescore/:id", h.updatescore)
e.GET("/ws", func(c echo.Context) error {
serveWs(hub, c.Response(), c.Request())
return nil
})
//e.GET("/getMacAddr", h.getMacAddr)
e.Logger.Fatal(e.Start(ip + ":443"))
}
package main
import (
"bytes"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"github.com/labstack/echo"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
func (h *Handler) getIP(c echo.Context) (err error) {
addrs, err := net.InterfaceAddrs()
if err != nil {
os.Stderr.WriteString("Oops: " + err.Error() + "\n")
os.Exit(1)
}
var ip string
for _, a := range addrs {
if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
ip = ipnet.IP.String()
}
}
}
return c.JSON(http.StatusOK, ip)
}
/////////////////////////ssssss//////////////////////////////////////////
func (h *Handler) getAllCourse(c echo.Context) (err error) {
users := []*Course{}
db := h.DB.Clone()
if err = db.DB("test").C("course").Find(nil).All(&users); err != nil {
return c.JSON(http.StatusBadRequest, err)
}
defer db.Close()
return c.JSON(http.StatusOK, users)
}
///////////////////////////ssssss//////////////////////////////////////////
func (h *Handler) deleteCourse(c echo.Context) (err error) {
db := h.DB.Clone()
defer db.Close()
id := c.Param("id")
err = db.DB("test").C("course").Remove(bson.M{"_id": bson.ObjectIdHex(id)})
if err != nil {
return c.JSON(http.StatusBadRequest, err)
}
return c.NoContent(http.StatusNoContent)
}
///////////////////////////ssssss///////////////////////////////////////////////
func (h *Handler) uploadCourse(c echo.Context) (err error) {
var bodyBytes []byte
if c.Request().Body != nil {
bodyBytes, _ = ioutil.ReadAll(c.Request().Body)
}
c.Request().Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
user := new(Course)
err = c.Bind(user)
if err != nil {
log.Print(err)
return c.JSON(http.StatusBadRequest, err)
}
log.Print(user.CourseID)
db := h.DB.Clone()
defer db.Close()
if err = db.DB("test").C("course").Insert(user); err != nil {
return c.JSON(http.StatusBadRequest, err)
}
if err != nil {
if mgo.IsDup(err) {
log.Panicln(err)
}
}
return c.JSON(http.StatusOK, &user)
}
//////////////////////////ssssssss////////////////////////////////////////////////////
func (h *Handler) updatescore(c echo.Context) error {
var bodyBytes []byte
if c.Request().Body != nil {
bodyBytes, _ = ioutil.ReadAll(c.Request().Body)
}
id := c.Param("id")
log.Print(id)
c.Request().Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
user := new(Course)
err := c.Bind(user)
if err != nil {
log.Print(err)
return c.JSON(http.StatusBadRequest, err)
}
db := h.DB.Clone()
defer db.Close()
query := bson.M{"_id": bson.ObjectIdHex(id)}
update1 := bson.M{"$set": bson.M{"students": user.Sutdents}}
err = db.DB("test").C("course").Update(query, update1)
if err != nil {
return c.JSON(http.StatusBadRequest, err.Error())
}
return c.JSON(http.StatusOK, user)
}
/////////////////////////ssssss//////////////////////////////////////////////
func (h *Handler) addupstudent(c echo.Context) error {
u := new(Sutdent)
id := c.Param("id")
if err := c.Bind(u); err != nil {
return c.JSON(http.StatusBadRequest, err)
}
db := h.DB.Clone()
defer db.Close()
if err := db.DB("test").C("course").
UpdateId(bson.ObjectIdHex(id), bson.M{"$addToSet": bson.M{"students": u}}); err != nil {
if err == mgo.ErrNotFound {
return echo.ErrNotFound
}
return c.JSON(http.StatusBadRequest, err)
}
return c.JSON(http.StatusOK, u)
}
//////////////////////////sssss////////////////////////////////////////////
func (h *Handler) deletestudent(c echo.Context) error {
u := new(Sutdent)
if err := c.Bind(u); err != nil {
return c.JSON(http.StatusBadRequest, err)
}
db := h.DB.Clone()
defer db.Close()
id := c.Param("id")
query := bson.M{"_id": bson.ObjectIdHex(id)}
update := bson.M{"$pull": bson.M{"students": bson.M{"id_student": u.Idstudent}}}
err := db.DB("test").C("course").Update(query, update)
if err != nil {
return c.JSON(http.StatusBadRequest, err.Error())
}
return c.JSON(http.StatusOK, u)
}
////////////////////////////sssssssssss//////////////////////////////////////////
func (h *Handler) editstudent(c echo.Context) error {
u := new(Sutdent)
id := c.Param("id")
if err := c.Bind(u); err != nil {
return c.JSON(http.StatusBadRequest, err)
}
db := h.DB.Clone()
defer db.Close()
query := bson.M{"_id": bson.ObjectIdHex(id), "students.id_student": u.Idstudent}
update := bson.M{
"$set": bson.M{
"students.$": u,
},
}
err := db.DB("test").C("course").Update(query, update)
if err != nil {
return c.JSON(http.StatusBadRequest, err.Error())
}
return c.JSON(http.StatusOK, u.Idstudent)
}
///////////////////////////ssssss///////////////////////////////////////////
func (h *Handler) report(c echo.Context) error {
users := []*Course{}
db := h.DB.Clone()
defer db.Close()
id := c.Param("id")
err := db.DB("test").C("course").Find(bson.M{"_id": bson.ObjectIdHex(id)}).All(&users)
if err != nil {
return c.JSON(http.StatusBadRequest, err.Error())
}
return c.JSON(http.StatusOK, users)
}
/////////////////////////////////////////////////////////////////////
# Editor configuration, see https://editorconfig.org
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
max_line_length = off
trim_trailing_whitespace = false
# See http://help.github.com/ignore-files/ for more about ignoring files.
# compiled output
/dist
/tmp
/out-tsc
# Only exists if Bazel was run
/bazel-out
# dependencies
/node_modules
# profiling files
chrome-profiler-events*.json
speed-measure-plugin*.json
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history/*
# misc
/.sass-cache
/connect.lock
/coverage
/libpeerconnection.log
npm-debug.log
yarn-error.log
testem.log
/typings
# System Files
.DS_Store
Thumbs.db
# TestTeam
This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 9.0.3.
## Development server
Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files.
## Code scaffolding
Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`.
## Build
Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--prod` flag for a production build.
## Running unit tests
Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).
## Running end-to-end tests
Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/).
## Further help
To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md).
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"test-team": {
"projectType": "application",
"schematics": {},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/test-team",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.app.json",
"aot": true,
"assets": [
"src/favicon.ico",
"src/logo.ico",
"src/assets"
],
"styles": [
"./node_modules/@angular/material/prebuilt-themes/indigo-pink.css",
"./node_modules/bootstrap/dist/css/bootstrap.min.css",
"src/styles.css"
],
"scripts": [
"node_modules/jquery/dist/jquery.min.js",
"node_modules/bootstrap/dist/js/bootstrap.min.js",
"node_modules/popper.js/dist/popper.min.js",
"node_modules/angular/angular.min.js",
"node_modules/angular-js-xlsx/angular-js-xlsx.js",
"node_modules/xlsx/dist/xlsx.full.min.js"
]
},
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,
"budgets": [
{
"type": "initial",
"maximumWarning": "2mb",
"maximumError": "5mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "6kb",
"maximumError": "10kb"
}
]
}
}
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"port": 80,
"browserTarget": "test-team:build"
},
"configurations": {
"production": {
"browserTarget": "test-team:build:production"
}
}
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "test-team:build"
}
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.spec.json",
"karmaConfig": "karma.conf.js",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"./node_modules/@angular/material/prebuilt-themes/indigo-pink.css",
"src/styles.css"
],
"scripts": []
}
},
"lint": {
"builder": "@angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"tsconfig.app.json",
"tsconfig.spec.json",
"e2e/tsconfig.json"
],
"exclude": [
"**/node_modules/**"
]
}
},
"e2e": {
"builder": "@angular-devkit/build-angular:protractor",
"options": {
"protractorConfig": "e2e/protractor.conf.js",
"devServerTarget": "test-team:serve"
},
"configurations": {
"production": {
"devServerTarget": "test-team:serve:production"
}
}
}
}
}
},
"defaultProject": "test-team",
"cli": {
"analytics": "5c762fe8-e911-49ef-a2eb-c379615dbd0d"
}
}
\ No newline at end of file
# This file is used by the build system to adjust CSS and JS output to support the specified browsers below.
# For additional information regarding the format and rule options, please see:
# https://github.com/browserslist/browserslist#queries
# You can see what browsers were selected by your queries by running:
# npx browserslist
> 0.5%
last 2 versions
Firefox ESR
not dead
not IE 9-11 # For IE 9-11 support, remove 'not'.
\ No newline at end of file
// @ts-check
// Protractor configuration file, see link for more information
// https://github.com/angular/protractor/blob/master/lib/config.ts
const { SpecReporter } = require('jasmine-spec-reporter');
/**
* @type { import("protractor").Config }
*/
exports.config = {
allScriptsTimeout: 11000,
specs: [
'./src/**/*.e2e-spec.ts'
],
capabilities: {
browserName: 'chrome'
},
directConnect: true,
baseUrl: 'http://localhost:4200/',
framework: 'jasmine',
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000,
print: function() {}
},
onPrepare() {
require('ts-node').register({
project: require('path').join(__dirname, './tsconfig.json')
});
jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
}
};
\ No newline at end of file
import { AppPage } from './app.po';
import { browser, logging } from 'protractor';
describe('workspace-project App', () => {
let page: AppPage;
beforeEach(() => {
page = new AppPage();
});
it('should display welcome message', () => {
page.navigateTo();
expect(page.getTitleText()).toEqual('test-team app is running!');
});
afterEach(async () => {
// Assert that there are no errors emitted from the browser
const logs = await browser.manage().logs().get(logging.Type.BROWSER);
expect(logs).not.toContain(jasmine.objectContaining({
level: logging.Level.SEVERE,
} as logging.Entry));
});
});
import { browser, by, element } from 'protractor';
export class AppPage {
navigateTo(): Promise<unknown> {
return browser.get(browser.baseUrl) as Promise<unknown>;
}
getTitleText(): Promise<string> {
return element(by.css('app-root .content span')).getText() as Promise<string>;
}
}
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/e2e",
"module": "commonjs",
"target": "es5",
"types": [
"jasmine",
"jasminewd2",
"node"
]
}
}
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, './coverage/test-team'),
reports: ['html', 'lcovonly', 'text-summary'],
fixWebpackSourcePaths: true
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
restartOnFileChange: true
});
};
This source diff could not be displayed because it is too large. You can view the blob instead.
{
"name": "test-team",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"@angular/animations": "~9.0.2",
"@angular/cdk": "^9.1.0",
"@angular/common": "~9.0.2",
"@angular/compiler": "~9.0.2",
"@angular/core": "~9.0.2",
"@angular/forms": "~9.0.2",
"@angular/localize": "^9.0.3",
"@angular/material": "^9.1.0",
"@angular/platform-browser": "~9.0.2",
"@angular/platform-browser-dynamic": "~9.0.2",
"@angular/router": "~9.0.2",
"@ng-bootstrap/ng-bootstrap": "^6.0.0",
"@types/jquery": "^3.3.33",
"angular": "^1.7.9",
"angular-js-xlsx": "0.0.3",
"angular2-qrcode": "^2.0.3",
"bootstrap": "^4.4.1",
"file-saver": "^2.0.2",
"jquery": "^1.12.4",
"ngx-countdown": "^8.0.3",
"ngx-pagination": "^5.0.0",
"ngx-qrcode-all": "^1.2.1",
"ngx-qrcode2": "0.0.9",
"popper.js": "^1.16.1",
"rxjs": "~6.5.4",
"tslib": "^1.10.0",
"xlsx": "^0.15.5",
"zone.js": "~0.10.2"
},
"devDependencies": {
"@angular-devkit/build-angular": "~0.900.3",
"@angular/cli": "~9.0.3",
"@angular/compiler-cli": "~9.0.2",
"@angular/language-service": "~9.0.2",
"@types/node": "^12.11.1",
"@types/jasmine": "~3.5.0",
"@types/jasminewd2": "~2.0.3",
"codelyzer": "^5.1.2",
"jasmine-core": "~3.5.0",
"jasmine-spec-reporter": "~4.2.1",
"karma": "~4.3.0",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage-istanbul-reporter": "~2.1.0",
"karma-jasmine": "~2.0.1",
"karma-jasmine-html-reporter": "^1.4.2",
"protractor": "~5.4.3",
"ts-node": "~8.3.0",
"tslint": "~5.18.0",
"typescript": "~3.7.5"
}
}
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { CardComponent } from './card/card.component';
import { UploadfileComponent } from './uploadfile/uploadfile.component';
import { QrcodeComponent } from './qrcode/qrcode.component';
import { EditComponent } from './edit/edit.component';
import { InfoComponent } from './info/info.component';
import { FromstusentComponent } from './fromstusent/fromstusent.component';
import { InfonameComponent } from './infoname/infoname.component';
const routes: Routes = [
{ path: '', component: CardComponent },
{ path: 'uplode', component: UploadfileComponent },
{ path: 'qrcode/:id', component: QrcodeComponent },
{ path: 'update/:id', component: EditComponent },
{ path: 'info/:id', component: InfoComponent },
{ path: 'student/:id', component: FromstusentComponent },
{ path: 'infoname/:id', component: InfonameComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
<app-topbar>
<br>
<router-outlet></router-outlet>
</app-topbar>
<!-- *ngIf="url!='student' && url!='scanfail'" -->
<!-- <app-fromstusent *ngIf="url='student' && url='scanfail'"></app-fromstusent> -->
<!-- <router-outlet></router-outlet> -->
import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent
],
}).compileComponents();
}));
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});
it(`should have as title 'test-team'`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app.title).toEqual('test-team');
});
it('should render title', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.nativeElement;
expect(compiled.querySelector('.content span').textContent).toContain('test-team app is running!');
});
});
import { Component,OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'test-team';
url: any;
show : any;
constructor(private route: ActivatedRoute) {
}
ngOnInit(){
this.url = location.pathname.split("/")[1];
if (this.url!='student') {
this.show = false;
}else{
this.show = true;
}
}
}
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { TopbarComponent } from './topbar/topbar.component';
import { CardComponent } from './card/card.component';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
//import { QrCodeAllModule } from 'ngx-qrcode-all';
import { QRCodeModule } from 'angular2-qrcode';
import { CountdownModule } from 'ngx-countdown';
import { CardFilterPipe } from "./card/card-filter.pipe";
import { EditFilterPipe } from "./edit/edit-filter.pipe";
import { StudentFilterPipe } from "./info/student-filter.pipe";
import { NgxPaginationModule } from 'ngx-pagination';
import { LayoutModule } from '@angular/cdk/layout';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatButtonModule } from '@angular/material/button';
import { MatSidenavModule } from '@angular/material/sidenav';
import { MatIconModule } from '@angular/material/icon';
import { MatListModule } from '@angular/material/list';
import { MatGridListModule } from '@angular/material/grid-list';
import { MatCardModule } from '@angular/material/card';
import { MatMenuModule } from '@angular/material/menu';
import { UploadfileComponent } from './uploadfile/uploadfile.component';
import { EditComponent } from './edit/edit.component';
import { FromstusentComponent } from './fromstusent/fromstusent.component';
import { InfoComponent } from './info/info.component';
import { InfonameComponent } from './infoname/infoname.component';
import { QrcodeComponent } from './qrcode/qrcode.component';
@NgModule({
declarations: [
AppComponent,
TopbarComponent,
CardComponent,
UploadfileComponent,
EditComponent,
FromstusentComponent,
InfoComponent,
InfonameComponent,
QrcodeComponent,
CardFilterPipe,
EditFilterPipe,
StudentFilterPipe,
],
entryComponents: [],
imports: [
AppRoutingModule,
BrowserModule,
BrowserAnimationsModule,
LayoutModule,
MatToolbarModule,
MatButtonModule,
MatSidenavModule,
MatIconModule,
MatListModule,
MatGridListModule,
MatCardModule,
MatMenuModule,
NgbModule,
HttpClientModule,
FormsModule,
NgxPaginationModule,
QRCodeModule,
CountdownModule
],
providers: [],
bootstrap: [AppComponent],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class AppModule { }
import { PipeTransform, Pipe } from '@angular/core';
@Pipe({
name: 'cardFilter'
})
export class CardFilterPipe implements PipeTransform{
transform(card:any,idcard: any): any {
if(!card||!idcard){
return card
}
return card.filter(res => res.course_id.toLowerCase().indexOf(idcard.toLowerCase()) !==-1);
}
}
\ No newline at end of file
.grid-container {
margin: 20px;
}
.dashboard-card {
position: absolute;
top: 15px;
left: 15px;
right: 15px;
bottom: 15px;
}
.more-button {
position: absolute;
top: 5px;
right: 10px;
}
.dashboard-card-content {
text-align: center;
}
/* .style {
left: 0px;
width: calc((50% - 0.5px) * 1 + 0px);
top: 0px;
height: calc(350px);
} */
<div class="grid-container">
<h1 class="mat-h1">Classroom All</h1>
<div class="row" [hidden]="show">
<div class="col-md-3"></div>
<div class="col-6">
<div class="input-group mb-3">
<mat-form-field>
<mat-label>ชื่ออาจารย์</mat-label>
<input matInput required #name name="name">
</mat-form-field>
<!-- <input type="text" class="form-control" #name name="name" placeholder="ชื่ออาจารย์"> -->
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="submit" (click)="nameT(name.value)">บันทึก</button>
</div>
</div>
</div>
</div>
<div class="text-center" [hidden]="!show">
<h4>ผู้สอน : {{namet}}</h4>
</div>
<br>
<div [hidden]="!show">
<div class="row">
<div class="col-md-3" style="text-align: center;">
<label class="text-center">
<h5>ค้นหาวิชา</h5>
</label>
</div>
<div class="col-md-3">
<input type="text" class="form-control" placeholder="รหัสวิชา" [(ngModel)]="search" />
</div>
</div>
<br>
<div class="row">
<div *ngFor="let c of course | cardFilter :search" class="col-md-3">
<mat-grid-list cols="2" rowHeight="350px">
<mat-grid-tile *ngFor="let card of cards | async" [colspan]="card.cols" [rowspan]="card.rows" class="style">
<mat-card class="dashboard-card">
<mat-card-header>
<mat-card-title>
{{sfc(c.course_id)}}
<button mat-icon-button class="more-button" [matMenuTriggerFor]="menu" aria-label="Toggle menu">
<mat-icon>more_vert</mat-icon>
</button>
<mat-menu #menu="matMenu" xPosition="before">
<button mat-menu-item (click)="pageinfo(c.id)">จัดการคะแนน</button>
<button mat-menu-item (click)="pageup(c.id)">อัพเดทชื่อ</button>
<button mat-menu-item (click)="pageinfoname(c.id)">ประวัติ</button>
</mat-menu>
</mat-card-title>
</mat-card-header>
<mat-card-content class="dashboard-card-content">
<div>
<br>
<br>
<p class="card-text">{{sfn(c.course_name)}}</p>
<p class="card-text">เทอม : {{c.seson}}</p>
<p class="card-text"><small class="text-muted">เวลาเริ่มสอน : {{c.time}}</small></p>
</div>
</mat-card-content>
<mat-card-actions>
<button mat-button (click)="pageqr(c.id,c.course_id)">QRcode</button>
<button mat-button class="float-right" (click)="delete(c.id)">ลบ</button>
</mat-card-actions>
</mat-card>
</mat-grid-tile>
</mat-grid-list>
</div>
</div>
</div>
</div>
\ No newline at end of file
import { LayoutModule } from '@angular/cdk/layout';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatGridListModule } from '@angular/material/grid-list';
import { MatIconModule } from '@angular/material/icon';
import { MatMenuModule } from '@angular/material/menu';
import { CardComponent } from './card.component';
describe('CardComponent', () => {
let component: CardComponent;
let fixture: ComponentFixture<CardComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [CardComponent],
imports: [
NoopAnimationsModule,
LayoutModule,
MatButtonModule,
MatCardModule,
MatGridListModule,
MatIconModule,
MatMenuModule,
]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(CardComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should compile', () => {
expect(component).toBeTruthy();
});
});
import { Component, OnInit } from '@angular/core';
import { map } from 'rxjs/operators';
import { Breakpoints, BreakpointObserver } from '@angular/cdk/layout';
import { Router } from '@angular/router'
import { StudentService } from "../services/student.service"
@Component({
selector: 'app-card',
templateUrl: './card.component.html',
styleUrls: ['./card.component.css']
})
export class CardComponent {
course: any;
search: any;
p:number=1;
namet: any;
show: any = false;
/** Based on the screen size, switch from standard to one column per row */
cards = this.breakpointObserver.observe(Breakpoints.Handset).pipe(
map(({ matches }) => {
if (matches) {
return [
{ title: 'Card 2', cols: 2, rows: 1 },
];
}
return [
{ title: 'Card 2', cols: 2, rows: 1 },
];
})
);
constructor(private breakpointObserver: BreakpointObserver,private router: Router, private studentService: StudentService) {
}
ngOnInit() {
this.studentService.getStudent().subscribe(
(res) => {
this.course = res
});
if (localStorage.getItem('name') != null) {
this.namet= localStorage.getItem('name');
this.show = true;
}
}
nameT(names: any) {
this.namet = names;
localStorage.setItem('name', names)
location.reload();
this.show = true;
}
delete(id:any){
this.studentService.deleteCourse(id).subscribe(
()=>{
window.location.reload();
}
)
this.router.navigateByUrl('card.component.html', { skipLocationChange: true }).then(() => {
this.router.navigate(['']);
});
}
pageqr(id:any,key:any) {
this.router.navigate(['qrcode/'+id+","+key]);
}
pageup(id :any) {
this.router.navigate(['update/'+id]);
}
pageinfo(id:any) {
this.router.navigate(['info/'+id]);
}
pageinfoname(id:any){
this.router.navigate(['infoname/'+id]);
}
sfc(data) {
data = data.split('-').shift();
return data
}
sfn(data){
var va= data.split(' ').shift();
var va1 = data.split(' ').slice()[6];
var va2 = data.split(' ').slice()[8];
return va+" "+va1+" "+va2
}
}
import { PipeTransform, Pipe } from '@angular/core';
@Pipe({
name: 'editFilter'
})
export class EditFilterPipe implements PipeTransform{
transform(student:any,id: any): any {
if(!student||!id){
return student
}
console.log(student);
return student.filter(res => res.id_student.toLowerCase().indexOf(id.toLowerCase()) !==-1);
}
}
\ No newline at end of file
.btn-group-lg>.btn, .btn-lg {
padding: 0.5rem 1rem;
font-size: 1.25rem;
line-height: 0.5;
border-radius: 1.3rem;
}
.dark-modal .modal-content {
background-color: #292b2c;
color: white;
}
.dark-modal .close {
color: white;
}
.light-blue-backdrop {
background-color: #5cb3fd;
}
<div class="container">
<br>
<h1 class="mat-h1">Update Student</h1>
<br>
<div class="container">
<button [hidden]="showB" class="btn-lg btn-block btn-info" (click)="show()" style="line-height: 1.5;">เพิ่ม
นักศึกษา</button>
<br>
<div [hidden]="showlist">
<form>
<div class="form-row">
<div class="col-3">
<input type="text" class="form-control" #idstudent name="idstudent" placeholder="รหัสนักศึกษา">
</div>
<div class="col-4">
<input type="text" class="form-control" #namefirst name="namefirst" placeholder="ชื่อ">
</div>
<div class="col-4">
<input type="text" class="form-control" #namelast name="namelast" placeholder="สกุล">
</div>
</div>
<br>
</form>
<div class="text-right">
<button type="submit" class="btn-lg btn-success"
(click)="addup(idstudent.value,namefirst.value,namelast.value)">ok</button>
<button class="btn-lg btn-danger" id="close1" (click)="unshow()">ยกเลิก</button>
</div>
</div>
<br>
</div>
<br>
<div class="row">
<div class="col-md-3" style="text-align: center;"><label class="text-center">
<h5>ค้นหา</h5>
</label></div>
<div class="col-md-4"><input type="text" class="form-control" placeholder="รหัสนักศึกษา" [(ngModel)]="search" />
</div>
</div>
<br>
<table class="table">
<thead>
<tr>
<th scope="col">เลขที่</th>
<th scope="col">รหัสนักศึกษา</th>
<th scope="col">ชื่อ</th>
<th colspan="2" class="text-center">Update</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let s of course.students | editFilter:search ">
<td class="text-center">{{s.number_id}}</td>
<td>{{s.id_student}}</td>
<td>{{s.name}}</td>
<td><button class="btn-lg btn-block btn-success" (click)="showadd(content)">แก้ไข</button></td>
<td><button type="submit" class="btn-lg btn-block btn-danger" (click)="delete(s.id_student)">ลบ</button></td>
<ng-template #content let-modal>
<div class="modal-header">
<h4 class="modal-title">Edit</h4>
<button type="button" class="close" aria-label="Close" id="close2" (click)="modal.dismiss('Cross click')">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-3">
<label for="">รหัส นักศึกษา</label>
<input type="text" class="form-control" #idstudent name="idstudent" value={{s.id_student}}>
</div>
<div class="col-4">
<label for="">ชื่อ-นามสกุล</label>
<input type="text" class="form-control" #name name="name" value={{s.name}}>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light"
(click)="editstudent(idstudent.value,name.value,s.number_id)">save</button>
<button type="button" class="btn btn-light" (click)="modal.close('Close click')">Close</button>
</div>
</ng-template>
</tr>
</tbody>
</table>
<div class="text-right">
<button class="btn btn-primary" [routerLink]="['/']">กลับ</button>
</div>
<br>
</div>
\ No newline at end of file
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { EditComponent } from './edit.component';
describe('EditComponent', () => {
let component: EditComponent;
let fixture: ComponentFixture<EditComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ EditComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(EditComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router'
import { StudentService } from '../services/student.service';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
@Component({
selector: 'app-edit',
templateUrl: './edit.component.html',
styleUrls: ['./edit.component.css']
})
export class EditComponent implements OnInit {
course: any;
showlist: any = true;
showB: any = false;
idcoure: any;
number: any;
statuspopup: any = true;
numadd: any;
constructor(private router: Router, private studentService: StudentService, private route: ActivatedRoute, private modalService: NgbModal) { }
ngOnInit(): void {
this.route.paramMap.subscribe(params => {
this.idcoure = params.get('id')
this.studentService.reportCourse(this.idcoure).subscribe(
(data) => {
this.course = data[0];
this.number = this.course.students.length;
}
)
});
}
addup(idstudent: any, namef: any, namel: any) {
var name = namef + " " + namel
this.number += 1;
this.studentService.addstudent(this.idcoure, idstudent, name, this.number).subscribe(
() => {
alert("status OK")
this.studentService.reportCourse(this.idcoure).subscribe(
(data) => {
this.course = data[0];
}
)
document.getElementById('close1').click()
}
)
}
editstudent(idstudent: any, name: any, number: any) {
this.studentService.editstudent(this.idcoure, idstudent, name, number).subscribe(
() => {
alert("status OK")
this.studentService.reportCourse(this.idcoure).subscribe(
(data) => {
this.course = data[0];
}
)
document.getElementById('close2').click()
}
)
}
delete(id: any) {
this.studentService.deletestudent(this.idcoure, id).subscribe(
() => {
this.studentService.reportCourse(this.idcoure).subscribe(
(data) => {
this.course = data[0];
}
)
}
);
}
show() {
this.showlist = false;
this.showB = true;
}
showadd(content) {
this.modalService.open(content, { size: 'lg' });
}
unshow() {
this.showB = false;
this.showlist = true;
}
back() {
this.router.navigate([''])
}
}
.grid-container {
margin: 20px;
}
\ No newline at end of file
<div class="container">
<h5 class="text-center">กรอกรหัส นักศึกษา</h5>
<form>
<div class="container col-md-6">
<input type="text" class="form-control" #idstudent name="idstudent" placeholder="กรอกรหัสนักศึกษา" >
<br>
<button type="button" class="btn btn-primary" (click)="submid(idstudent.value)">ตกลง</button>
</div>
</form>
</div>
\ No newline at end of file
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { FromstusentComponent } from './fromstusent.component';
describe('FromstusentComponent', () => {
let component: FromstusentComponent;
let fixture: ComponentFixture<FromstusentComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ FromstusentComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(FromstusentComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router'
import { StudentService } from '../services/student.service';
@Component({
selector: 'app-fromstusent',
templateUrl: './fromstusent.component.html',
styleUrls: ['./fromstusent.component.css']
})
export class FromstusentComponent implements OnInit {
course: any;
idcoure: any;
weeks: any;
gps2: any = [];
constructor(private route: ActivatedRoute, private studentService: StudentService, private router: Router) { }
ngOnInit(): void {
this.route.paramMap.subscribe(params => {
this.idcoure = params.get('id').split(',').shift();
this.weeks = params.get('id').split(',').slice()[1];
});
var coure = localStorage.getItem('idcoure');
var weekc = localStorage.getItem('week');
if (coure == this.idcoure) {
if (weekc == this.weeks) {
window.location.href='https://testmypro-01.herokuapp.com/success'
}
}
this.studentService.reportCourse(this.idcoure).subscribe(
(data) => {
this.course = data[0];
});
}
submid(sutdent: any) {
var coure = localStorage.getItem('idcoure');
var weekc = localStorage.getItem('week');
var checkid = localStorage.getItem('id_active');
var between = this.getlocaltion();
if (between <= 150) {
this.checknamesad(sutdent, coure, weekc, checkid);
} else {
alert("can not")
}
}
checknamesad(sutdent: any, coure: any, weekc: any, checkid: any) {
if (sutdent != "") {
console.log(sutdent+"check");
if (coure == this.idcoure) {
if (weekc == this.weeks) {
for (let index = 0; index < this.course.students.length; index++) {
var check = this.course.students[index].weeks['week' + this.weeks].id_active;
if (checkid == check) {
window.location.href='https://testmypro-01.herokuapp.com/success'
}
}
} else {
this.saddata(sutdent)
}
}
else {
this.saddata(sutdent)
}
} else {
alert("กรอกรหัส นศ.")
}
}
saddata(sutdent: any) {
var check = false;
for (let index = 0; index < this.course['students'].length; index++) {
if (sutdent == this.course['students'][index].id_student) {
check = true;
}
}
console.log(check);
if (check) {
this.studentService.chakname(this.idcoure, sutdent, this.weeks).subscribe(
() => {
localStorage.setItem('idcoure', this.idcoure)
localStorage.setItem('week', this.weeks)
localStorage.setItem('id_active', sutdent)
alert('เช็คชื่อเรียบร้อย')
window.location.href='https://testmypro-01.herokuapp.com/success'
})
} else {
alert("รหัสไม่ถูก")
}
}
getlocaltion() {
var c = 0;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(resp => {
this.gps2.latitude2 = resp.coords.latitude;
this.gps2.longtitude2 = resp.coords.longitude;
c = this.bitween(this.gps2);
})
}
return c;
}
bitween(gps2: any) {
var gps1 = this.studentService.getlocal();
var dLat = this.degreesToRadians(gps2.latitude2 - gps1.latitude1);
var dLon = this.degreesToRadians(gps2.longtitude2 - gps1.longitude1);
var lat1 = this.degreesToRadians(gps1.latitude1);
var lat2 = this.degreesToRadians(gps2.latitude2);
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var c = 6371 * c;
return c;
}
degreesToRadians(degrees: any) {
return degrees * Math.PI / 180;
}
}
.btn-warning {
color: #212529;
background-color: #ffd45bf2;
border-color: #ffd45bf2;
}
.grid-container {
margin: 20px;
}
\ No newline at end of file
<div class="grid-container">
<h1 class="mat-h1">Classroom Info</h1>
</div>
<div class="container" *ngIf="course">
<p>รหัสวิชา : {{course.course_id}}</p>
<p>ชื่อวิชา : {{course.course_name}}</p>
<p>เวลา : {{course.time}}</p>
<div class="col-md-6">
<div [hidden]="showS" class="input-group mb-3 text-right">
<div class="input-group-prepend">
<span class="input-group-text">เลือกอาทิตย์</span>
</div>
<select class="form-control" #weeks name="weeks" style="width: 20%;">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
</select>
<div class="input-group-prepend">
<span class="input-group-text">ค้นหา</span>
</div>
<select class="form-control" #status name="status" style="width: 20%;">
<option selected>ทั้งหมด</option>
<option value="1">มา</option>
<option value="0.5">สาย</option>
<option value="0">ขาด</option>
</select>
<div class="input-group-append">
<button class="btn btn-secondary" (click)="student(weeks.value, status.value)">ok</button>
</div>
</div>
</div>
<br>
<table class="table table-bordered">
<thead>
<tr class="text-center">
<th scope="col">เลขที่</th>
<th scope="col">รหัสนักศึกษา</th>
<th scope="col">ชื่อ</th>
<th colspan="4">สัปดาห์ที่ {{twee}}</th>
<th scope="col">รวม</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let s of course.students | studentFilter:[{week:twee},{status:statusShow}] | paginate: { itemsPerPage: 15, currentPage: p }" >
<td class="text-center">{{s.number_id}}</td>
<td>{{s.id_student}}</td>
<td>{{s.name}}</td>
<td class="text-center" style="font-size: 1.2rem;">
<span >{{retest(s.weeks)}}</span>
</td>
<td class="text-center"><button class="btn-lg btn-block btn-info" id="click1" (click)="chackbyTcome(s.id_student,1)">มา</button></td>
<td class="text-center"><button class="btn-lg btn-block btn-warning" (click)="chackbyTlast(s.id_student,0.5)">สาย</button></td>
<td class="text-center"><button class="btn-lg btn-block btn-danger" id="click1" (click)="chackbyOut(s.id_student,1)">ขาด</button></td>
<td class="text-center" style="font-size: 1.2rem;">{{getTotal(s.weeks) }}</td>
</tr>
</tbody>
</table>
<pagination-controls (pageChange)="p = $event"></pagination-controls>
<div class="text-right">
<a class="btn btn-primary" [routerLink]="['/']" style="color: white;">กลับ</a>
</div>
<br>
</div>
\ No newline at end of file
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { InfoComponent } from './info.component';
describe('InfoComponent', () => {
let component: InfoComponent;
let fixture: ComponentFixture<InfoComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ InfoComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(InfoComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router'
import { StudentService } from '../services/student.service';
@Component({
selector: 'app-info',
templateUrl: './info.component.html',
styleUrls: ['./info.component.css']
})
export class InfoComponent implements OnInit {
course: any;
//courseShow: any;
idcoure: any;
//week: any;
twee: any;
showS: any = false;
statusShow: any="ทั้งหมด";
p:number=1;
constructor(private router: Router, private studentService: StudentService, private route: ActivatedRoute) { }
ngOnInit(): void {
this.route.paramMap.subscribe(params => {
this.idcoure = params.get('id').split(',').shift();
this.twee = params.get('id').split(',').slice()[1];
if (this.twee == null) {
this.twee = 1;
} else {
this.showS = true;
}
});
this.studentService.reportCourse(this.idcoure).subscribe(
(data) => {
this.course = data[0];
});
}
student(weeks: any,status:any) {
this.twee = weeks;
this.statusShow=status;
}
search(status: any) {
var count = 0;
for (let index = 0; index < this.course['students'].length; index++) {
var data = this.course['students'][index].weeks['week' + this.twee].week
if (data == 1&& status==1) {
count ++;
}else if (data == 0.5&& status==2) {
count ++;
}else if (data == 0&& status==3) {
count ++;
}else if (status=="ทั้งหมด") {
count ++;
}
}
console.log(count);
}
chackbyTcome(idstudent: any, count: number) {
this.studentService.chakname(this.idcoure, idstudent, this.twee).subscribe(
() => {
console.log("เข้ายุ");
this.studentService.reportCourse(this.idcoure).subscribe(
(data) => {
this.course = data[0];
});
}
)
}
chackbyTlast(idstudent: any, count: number) {
this.studentService.chacknameby_t(this.idcoure, idstudent, this.twee).subscribe(
() => {
console.log("สาย");
this.studentService.reportCourse(this.idcoure).subscribe(
(data) => {
this.course = data[0];
});
// window.location.reload();
}
)
}
chackbyOut(idstudent: any, count: number) {
this.studentService.checknameOut_t(this.idcoure, idstudent, this.twee).subscribe(
() => {
console.log("ขาด");
this.studentService.reportCourse(this.idcoure).subscribe(
(data) => {
this.course = data[0];
});
// window.location.reload();
}
)
}
back() {
this.router.navigate([''])
}
retest(data) {
return data["week" + this.twee].week
}
getTotal(data) {
let total = 0;
for (let i = 1; i <= 16; i++) {
total += data["week" + i].week;
}
return total;
}
}
import { PipeTransform, Pipe } from '@angular/core';
@Pipe({
name: 'studentFilter'
})
export class StudentFilterPipe implements PipeTransform {
transform(students: any, statusShow?: any): any {
var weekthis = "week" + statusShow[0].week;
var status = statusShow[1].status;
if (status == "ทั้งหมด") {
//console.log('test1');
return students;
}
return students.filter((val) => {
let rVal;
for (let index = 0; index < students.length; index++) {
if (val.weeks[weekthis].week == status) {
rVal = students[index]
}
}
return rVal;
})
}
}
\ No newline at end of file
.dark-modal .modal-content {
background-color: #292b2c;
color: white;
}
.dark-modal .close {
color: white;
}
.light-blue-backdrop {
background-color: #5cb3fd;
}
.grid-container {
margin: 20px;
}
\ No newline at end of file
<div class="grid-container">
<h1 class="mat-h1">Classroom record</h1>
</div>
<div class="container" *ngIf="course">
<div class="row">
<div class="col-md-6">
<p>รหัสวิชา : {{course.course_id}}</p>
<p>ชื่อวิชา : {{course.course_name}}</p>
<p>เวลา : {{course.time}}</p>
</div>
<div class="col-md-6 text-right">
<br>
<br>
<br>
<button class="btn btn-success" (click)="downloadfile()">Download File</button>
.
<button class="btn btn-secondary" (click)="showsumfile(content)">รวมคะแนน</button>
</div>
</div>
<div class="container mt-5">
<div class="table-responsive">
<table class="table table-bordered table-hover">
<thead>
<tr>
<th scope="col" class="text-center">เลขที่</th>
<th scope="col" class="text-center">รหัสนักศึกษา</th>
<th scope="col" class="text-center">ชื่อ</th>
<th colspan="16" class="text-center">สัปดาห์</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let s of course.students | paginate: { itemsPerPage: 20, currentPage: p } ">
<td class="text-center">{{s.number_id}}</td>
<td>{{s.id_student}}</td>
<td>{{s.name}}</td>
<!-- <td style="padding: 0.05rem;" class="text-center"> -->
<td>
<span>{{s.weeks.week1.week}}</span>
</td>
<td>
<span>{{s.weeks.week2.week}}</span>
</td>
<td>
<span>{{s.weeks.week3.week}}</span>
</td>
<td>
<span>{{s.weeks.week4.week}}</span>
</td>
<td>
<span>{{s.weeks.week5.week}}</span>
</td>
<td>
<span>{{s.weeks.week6.week}}</span>
</td>
<td>
<span>{{s.weeks.week7.week}}</span>
</td>
<td>
<span>{{s.weeks.week8.week}}</span>
</td>
<td>
<span>{{s.weeks.week9.week}}</span>
</td>
<td>
<span>{{s.weeks.week10.week}}</span>
</td>
<td>
<span>{{s.weeks.week11.week}}</span>
</td>
<td>
<span>{{s.weeks.week12.week}}</span>
</td>
<td>
<span>{{s.weeks.week13.week}}</span>
</td>
<td>
<span>{{s.weeks.week14.week}}</span>
</td>
<td>
<span>{{s.weeks.week15.week}}</span>
</td>
<td>
<span>{{s.weeks.week16.week}}</span>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<pagination-controls (pageChange)="p = $event"></pagination-controls>
<div class="text-right">
<a class="btn btn-primary" [routerLink]="['/']" style="color: white;">กลับ</a>
</div>
<br>
</div>
<ng-template #content let-modal>
<div class="modal-header">
<h4 class="modal-title">รวมคะแนน</h4>
<button type="button" class="close" aria-label="Close" (click)="modal.dismiss('Cross click')">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<input class="btn btn-info " type="file" (change)="readfile($event)" multiple="false" />
<p>รวมคะแนน&hellip;</p>
<div class="container mt-10">
<table class="table table-bordered">
<thead>
<tr>
<th scope="col" class="text-center">เลขที่</th>
<th scope="col" class="text-center">รหัสนักศึกษา</th>
<th scope="col" class="text-center">ชื่อ</th>
<th colspan="16" class="text-center">คะแนนรวม</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let s of dataStrings">
<td class="text-center">{{s.number_id}}</td>
<td>{{s.id_student}}</td>
<td>{{s.name}}</td>
<td>
<span>{{s.week1}}</span>
</td>
<td>
<span>{{s.week2}}</span>
</td>
<td>
<span>{{s.week3}}</span>
</td>
<td>
<span>{{s.week4}}</span>
</td>
<td>
<span>{{s.week5}}</span>
</td>
<td>
<span>{{s.week6}}</span>
</td>
<td>
<span>{{s.week7}}</span>
</td>
<td>
<span>{{s.week8}}</span>
</td>
<td>
<span>{{s.week9}}</span>
</td>
<td>
<span>{{s.week10}}</span>
</td>
<td>
<span>{{s.week11}}</span>
</td>
<td>
<span>{{s.week12}}</span>
</td>
<td>
<span>{{s.week13}}</span>
</td>
<td>
<span>{{s.week14}}</span>
</td>
<td>
<span>{{s.week15}}</span>
</td>
<td>
<span>{{s.week16}}</span>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light" (click)="totle_score()">save</button>
<button type="button" class="btn btn-light" (click)="modal.close('Close click')">Close</button>
</div>
</ng-template>
\ No newline at end of file
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { InfonameComponent } from './infoname.component';
describe('InfonameComponent', () => {
let component: InfonameComponent;
let fixture: ComponentFixture<InfonameComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ InfonameComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(InfonameComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
import { Component, OnInit } from '@angular/core';
import { StudentService } from '../services/student.service';
import { Router, ActivatedRoute } from '@angular/router'
import { ExcelService } from '../services/excel.service';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import * as XLSX from 'xlsx';
import { MenuService } from "../services/menu.service";
@Component({
selector: 'app-infoname',
templateUrl: './infoname.component.html',
styleUrls: ['./infoname.component.css']
})
export class InfonameComponent implements OnInit {
course: any;
show: any = false;
dataStrings: any;
datagetweek: any = 16;
id: any;
count: number = 5;
p: number = 1;
idmenu: any;
constructor(
private router: Router,
private studentService: StudentService,
private route: ActivatedRoute,
private excelService: ExcelService,
private modalService: NgbModal,
private menuService: MenuService
) {
}
ngOnInit(): void {
this.route.paramMap.subscribe(params => {
this.idmenu = params.get('id');
});
var url1 = "qrcode/"+this.idmenu;
var url2 = "info/"+this.idmenu
var url3 = "update/"+this.idmenu
this.menuService.serMenuItem(url1,"QRCODE",url2,"จัดการคะแนน",url3,"อัพเดทชื่อ")
this.qruey();
}
qruey() {
this.route.paramMap.subscribe(params => {
this.id = params.get('id');
this.studentService.reportCourse(params.get('id')).subscribe(
(data) => {
this.course = data[0];
//console.log(this.course);
}
)
});
}
//////////////////////////////////downloadfile//////////////////////////////////////////////////////////////////
downloadfile() {
this.show = true
var excelfile = [[]];
for (let index = 0; index < this.course['students'].length; index++) {
excelfile[index] = this.course['students'][index];
for (let j = 1; j <= 16; j++) {
excelfile[index]['week' + j] = this.course['students'][index].weeks['week' + j].week;
}
excelfile[index]['course_id'] = this.course['course_id'];
delete excelfile[index]['weeks']
}
var nameCoure = this.course['course_name'].split(' ').shift() + "-เทอม:" + this.course['seson'] + "-sec-" + this.course['course_name'].split(' ').pop() + "-" + localStorage.getItem('name');
this.excelService.exportAsExcelFile(excelfile, nameCoure);
this.qruey()
}
/////////////////////////////////////////////////////////////////////
showsumfile(content) {
this.modalService.open(content, { size: 'xl' });
}
///////////////////อ่านชื่อไฟล์////////////////
sumfile(ent: any) {
let file = ent.target.files[0];
let fileName = file.name;
fileName = fileName.split('.').shift();
//var nameT = fileName.split('-').pop();//อาจจะได้ใช้
//this.readfile(ent)
//console.log(this.dataStrings);
}
readfile(evt: any) {
let workBook = null;
let jsonData = null;
const reader = new FileReader();
const file = evt.target.files[0];
reader.onload = (event) => {
const data = reader.result;
workBook = XLSX.read(data, { type: 'binary' });
jsonData = workBook.SheetNames.reduce((initial, name) => {
const sheet = workBook.Sheets[name];
initial[name] = XLSX.utils.sheet_to_json(sheet);
return initial;
}, {});
this.dataStrings = jsonData.data;
this.getweeks(this.dataStrings);
this.sumfile(evt);
}
reader.readAsBinaryString(file);
}
//////////////////////////seve/////////////////////////////
totle_score() {
var a = this.sumscore();
if (a != null) {
this.studentService.updateStudent(this.id, a).subscribe();
} else {
alert('fire ไม่รงกัน ')
}
}
///////////////////////////////seve/////////////////////////
sumscore() {
if (this.dataStrings.length == this.course['students'].length && this.dataStrings[0].course_id == this.course['course_id']) {
for (let index = 0; index < this.course['students'].length; index++) {
for (let j = 1; j <= 16; j++) {
if (this.course['students'][index].weeks['week' + j].week == 1 || this.dataStrings[index]['week' + j] == 1) {
this.course['students'][index].weeks['week' + j].week = 1
//console.log(1);
}
else if (this.course['students'][index].weeks['week' + j].week == 0.5 || this.dataStrings[index]['week' + j] == 0.5) {
this.course['students'][index].weeks['week' + j].week = 0.5
//console.log(0.5);
}
else {
this.course['students'][index].weeks['week' + j].week = 0
//console.log(0);
}
}
}
return this.course['students'];
} else {
return null
}
}
/////////////////////////////////////////////////////
getscore(data: any) {
let score = 0;
for (let i = 1; i <= 16; i++) {
score = data["week" + i];
return score;
}
}
getweeks(data: any) {
console.log(data);
// for (let index = 0; index < data.length; index++) {
// this.datagetweek[index]=""
// for (let j = 0; j <=16; j++) {
// console.log(data[index]['week'+j]);
// this.datagetweek=data[index]['week'+j];
// //this.datagetweek[index][j]=data[index]['week'+j]
// }
// }
// console.log(this.datagetweek);
}
back() {
this.router.navigate([''])
}
retest(data) {
return data.week
}
}
.qr{
width: 100%;
}
::ng-deep .aclass img {
width: 100%;
}
.grid-container {
margin: 20px;
}
\ No newline at end of file
<div class="grid-container">
<h1 class="mat-h1">Start QRcode</h1>
</div>
<div class="container">
<br>
<br>
<div class="text-center" *ngIf="!draw2cards">
<div class="row">
<div class="col-md-2">
<div class="form-group">
<label for="selete">เลือกอาทิต</label>
<select class="form-control" #weeks name="weeks" id="selete" style="width: 100%;">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label for="selete">setting time</label>
<select class="form-control" #times name="times" id="selete" style="width: 100%;">
<option value="60">5</option>
<option value="600">10</option>
<option value="900">15</option>
<option value="1200">20</option>
<option value="1500">25</option>
<option value="1800">30</option>
</select>
</div>
</div>
<div class="col-md-4">
<br>
<button type="button" class="btn btn-info btn-lg text-center"
(click)="Start(weeks.value,times.value,content); timerSrarted$.next(true);">Start QR
code</button>
</div>
</div>
<ng-template #content let-modal>
<div class="modal-header">
<h4 class="modal-title text-center">สัปดาห์ที่{{weeks.value}}</h4>
<a type="button" class="close" aria-label="Close" id="close"
(click)="timerSrarted$.next(false); modal.dismiss('Cross click')">
<span aria-hidden="true">&times;</span>
</a>
</div>
<div class="modal-body">
<div class="text-center">
<!-- <p>week at {{weeks.value}}</p> -->
<h1>
<countdown #countdown [config]="{leftTime: time, demand: ti}">$!m!:$!s!</countdown>
</h1>
</div>
<div class="text-center">
<qr-code [value]="qrcode_url" [size]="500" [level]="L"></qr-code>
<!-- <ngx-qrcode
[qrc-value]="qrcode_url"
qrc-element-type="url"
qrc-class="aclass"
qrc-errorCorrectionLevel="L"
qrc-scanQrcode="timeqrcode"
>
</ngx-qrcode> -->
</div>
<br>
</div>
</ng-template>
</div>
<div [hidden]="show">
<p class="text-center"><button class="btn btn-outline-secondary" (click)="fixinfo()" type="button">จัดการ
นศ</button></p>
<br>
<!-- <button (click)="test()">test</button> -->
<br>
<button class="btn btn-secondary" (click)="reset()">รีเซ็ต</button>
<!-- <button (click)="getlocaltion()">getlocals</button> -->
<div class="text-center" id="reload_page">
<p>{{contcome}}/{{cont}}</p>
</div>
<table class="table table-bordered">
<thead>
<tr class="text-center">
<th scope="col">เลขที่</th>
<th scope="col">รหัสนักศึกษา</th>
<th scope="col">ชื่อ</th>
<th scope="col">คะแนน</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let s of showstudent ">
<td class="text-center">{{s.number_id}}</td>
<td class="text-center">{{s.id_student}}</td>
<td>{{s.name}}</td>
<td class="text-center">{{ getTotal(s.weeks) }}</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- <div></div> -->
<!-- <script>
$('#reload_page').DataTable({
ajax: "data.json"
});
setInterval(function () {
table.ajax.reload();
}, 3000)
console.log('hello');
</script> -->
\ No newline at end of file
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { QrcodeComponent } from './qrcode.component';
describe('QrcodeComponent', () => {
let component: QrcodeComponent;
let fixture: ComponentFixture<QrcodeComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ QrcodeComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(QrcodeComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router'
import { StudentService } from '../services/student.service';
import { HerokuService } from '../services/heroku.service'
import { interval, Subscription, Observable, BehaviorSubject } from 'rxjs';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { takeWhile, tap } from 'rxjs/operators';
@Component({
selector: 'app-qrcode',
templateUrl: './qrcode.component.html',
styleUrls: ['./qrcode.component.css']
})
export class QrcodeComponent implements OnInit {
////////////////localtion//////////////////////////////////////////
[x: string]: any;
qrcode_url = "";
course: any;
showstudent: any[] = [];
getKey: any
idcoure: any;
keycoure: any
weeks: any;
ip: any;
cont: any;
testt: any;
contcome: any;
subscription: Subscription;
show: any = true;
////////////////localtion//////////////////////////////////////////
show2: any = false;
localtion: any = []
////////////////time QR//////////////////////////////////////////
timerSrarted$ = new BehaviorSubject(false);
isAlive = true;
draw2cards = false;
timer;
time: any = 300;
ti = true;
timeqrcode = true;
constructor(private router: Router, private studentService: StudentService, private route: ActivatedRoute, private modalService: NgbModal, private herokuService: HerokuService) {
studentService.messages.subscribe(msg => {
if (msg.action == "[student][checkname]") {
this.studentService.reportCourse(this.idcoure).subscribe((data) => {
this.course = data[0];
this.cont = this.course.students.length;
this.studentcome()
})
//console.log(this.showstudent);
}
});
}
ngOnInit(): void {
this.studentService.getIP().subscribe(
(data) => {
this.ip = data;
});
this.route.paramMap.subscribe(params => {
this.idcoure = params.get('id').split(',').shift();
this.keycoure = params.get('id').split(',').slice()[1];
});
this.studentService.reportCourse(this.idcoure).subscribe(
(data) => {
this.course = data[0];
this.cont = this.course.students.length;
});
////////////////time out///////////////////////////////////////////////////
this.timerSrarted$.pipe(
takeWhile(() => this.isAlive),
tap((next) => {
if (next) {
this.ti = false;
clearTimeout(this.timer);
this.timer = setTimeout(() => {
this.draw2cards = true;
this.herokuService.updateQR(this.keycoure, this.idcoure,"https://testmypro-01.herokuapp.com/").subscribe()
document.getElementById('close').click()
//console.log(this.timerSrarted$);
this.qrcode_url = "timeout"
console.log(this.qrcode_url);
this.timerSrarted$.next(false);
}, this.time * 1000)
}
})
).subscribe();
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
Start(week: any, times: any, content) {
this.weeks = week;
this.time = times;
console.log(this.ip);
var herokuUrl = 'http://'+this.ip+':80/student/' + this.idcoure + ',' + this.weeks;
console.log(herokuUrl);
this.heroku(herokuUrl,content)
this.qruery()
this.show2 = true;
this.show = false;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(resp => {
this.localtion.latitude1 = resp.coords.latitude;
this.localtion.longitude1 = resp.coords.longitude;
})
} else {
alert('ไม่รองรับ gps')
}
}
//////////////////heroku/////////////////////////////////////////////
heroku(herokuUrl:any,content){
this.herokuService.getAll().subscribe(
(data) => {
var status;
for (let i = 0; i < data.length; i++) {
if (data[i]['course_id'] == this.keycoure||data==null) {
status = false;
} else {
status = true;
}
}
if (status) {
console.log('create');
this.herokuService.craeteQR(this.keycoure, this.idcoure, herokuUrl).subscribe(
(Key) => {
this.getKey = Key['key'];
this.qrcode(content,this.getKey)
});
} else {
console.log('update');
this.herokuService.updateQR(this.keycoure, this.idcoure,herokuUrl).subscribe(
(key) => {
this.getKey = key;
this.qrcode(content,this.getKey)
}
);
}
})
}
////////////////////////////////////////////////////////////////////////////
//////////////////////////qrcode/////////////////////////////////////////////////////
qrcode(content,getKey:any) {
this.modalService.open(content, { size: 'xl', backdropClass: 'light-blue-backdrop' });
this.qrcode_url = 'https://testmypro-01.herokuapp.com/getKey/' + getKey;
console.log(this.qrcode_url);
}
////////////////////////////////
qruery() {
this.studentService.reportCourse(this.idcoure).subscribe((data) => {
this.course = data[0];
this.cont = this.course.students.length;
})
this.studentcome()
}
studentcome() {
var w = 'week' + this.weeks;
this.contcome = 0;
var i = 0;
//console.log(this.course.students);
for (let index = 0; index < this.course.students.length; index++) {
var wk = this.course.students[index].weeks[w].week;
if (wk == 1) {
this.showstudent[i] = this.course.students[index];
i++;
this.contcome++;
}
}
}
///////////////////////////////////////////////////////////////////////////////
getTotal(data: any) {
var w = 'week' + this.weeks;
return data[w].week;
}
fixinfo() {
this.router.navigate(['info/' + this.idcoure + ',' + this.weeks])
}
back() {
this.router.navigate(['student/' + this.idcoure + ',' + this.weeks])
}
reset() {
window.location.reload()
}
ngOnDestroy() {
this.isAlive = false;
}
}
import { TestBed } from '@angular/core/testing';
import { ExcelService } from './excel.service';
describe('ExcelService', () => {
let service: ExcelService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(ExcelService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
import { Injectable } from '@angular/core';
import * as FileSaver from 'file-saver';
import * as XLSX from 'xlsx';
const EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
@Injectable({
providedIn: 'root'
})
export class ExcelService {
constructor() { }
exportAsExcelFile(json: any[], excelFileName: string): void {
const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json);
const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
this.saveAsExcelFile(excelBuffer, excelFileName);
}
saveAsExcelFile(buffer: any, fileName: string): void {
const data: Blob = new Blob([buffer], {type: EXCEL_TYPE});
FileSaver.saveAs(data, fileName);
}
}
import { TestBed } from '@angular/core/testing';
import { HerokuService } from './heroku.service';
describe('HerokuService', () => {
let service: HerokuService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(HerokuService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { getAllLifecycleHooks } from '@angular/compiler/src/lifecycle_reflector';
@Injectable({
providedIn: 'root'
})
export class HerokuService {
apiURL : string = "https://testmypro-01.herokuapp.com"
constructor(private httpClient: HttpClient) { }
getAll(){
return this.httpClient.get(`${this.apiURL}/getAll`);
}
getKey(key:any){
return this.httpClient.get(`${this.apiURL}/getKey/`+key)
}
craeteQR(idcours:any,keycours:any,herokuUrl:any){
return this.httpClient.post(`${this.apiURL}/createqr`,{
course_id:idcours,
course_key:keycours,
url:herokuUrl
});
}
updateQR(idcours:any,keycours:any,herokuUrl:any){
var Data:any = new FormData();
Data.append("courseid",idcours)
Data.append("coursekey",keycours)
Data.append("url",herokuUrl)
return this.httpClient.post(`${this.apiURL}/updateqr`,Data)
}
}
import { TestBed } from '@angular/core/testing';
import { MenuService } from './menu.service';
describe('MenuService', () => {
let service: MenuService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(MenuService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
import { Injectable } from '@angular/core';
import { MatMenuItem } from '@angular/material/menu';
@Injectable({
providedIn: 'root'
})
export class MenuService {
menuLists: MenuItem[];
constructor() { }
getMenuList() {
return this.menuLists;
}
serMenuItem(url1, name1, url2, name2, url3, name3) {
this.menuLists = [
{
group: { code: url1, name: name1 }
},
{
group: { code: url2, name: name2 }
},
{
group: { code: url3, name: name3 }
}
];
console.log(this.menuLists);
}
}
export interface MenuItem {
group: Menu;
}
export interface Menu {
code: string;
name: string;
}
import { Injectable } from "@angular/core";
import * as Rx from "rxjs";
@Injectable({
providedIn: 'root'
})
export class SocketService {
constructor() {}
private subject: Rx.Subject<MessageEvent>;
public connect(url): Rx.Subject<MessageEvent> {
if (!this.subject) {
this.subject = this.create(url);
console.log("Successfully connected: " + url);
}
return this.subject;
}
private create(url): Rx.Subject<MessageEvent> {
let ws = new WebSocket(url);
let observable = Rx.Observable.create((obs: Rx.Observer<MessageEvent>) => {
ws.onmessage = obs.next.bind(obs);
ws.onerror = obs.error.bind(obs);
ws.onclose = obs.complete.bind(obs);
return ws.close.bind(ws);
});
let observer = {
next: (data: Object) => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify(data));
}
}
};
return Rx.Subject.create(observer, observable);
}
}
\ No newline at end of file
import { TestBed } from '@angular/core/testing';
import { StudentService } from './student.service';
describe('StudentService', () => {
let service: StudentService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(StudentService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
import { Injectable, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Local } from 'protractor/built/driverProviders';
import { SocketService } from '../services/socket.service';
import { Subject } from 'rxjs';
import { delay, map } from 'rxjs/operators';
const SOCKET_URL = "ws://192.168.1.15:443/ws";
export interface Message {
action: string;
message: string;
}
@Injectable({
providedIn: 'root'
})
export class StudentService {
Localtion: any = []
apiURL: string
//api: any
public messages: Subject<Message>;
constructor(private httpClient: HttpClient, private socketService: SocketService) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(resp => {
this.Localtion.latitude1 = resp.coords.latitude;
this.Localtion.longitude1 = resp.coords.longitude;
})
}
///////////////////////////////////////////////
this.messages = <Subject<Message>>socketService.connect(SOCKET_URL).pipe(
map(
(response: MessageEvent): Message => {
let data = JSON.parse(response.data);
return {
action: data.action,
message: data.message
}
}
)
)
////////////////////////////////////////////////////////////
//this.apiURL = 'http://10.35.1.89:443';
this.apiURL = 'http://192.168.1.15:443'
}
getStudent() {
return this.httpClient.get(`${this.apiURL}/getCourse`);
}
getIP() {
return this.httpClient.get(`${this.apiURL}/getIP`)
}
chakname(id: any, stdids: any, weeks: any) {
var Data: any = new FormData();
Data.append("stdid", stdids);
Data.append("week", weeks);
return this.httpClient.post(`${this.apiURL}/chackname/${id}`, Data);
}
chacknameby_t(id: any, stdids: any, weeks: any) {
var Data: any = new FormData();
Data.append("stdid", stdids);
Data.append("week", weeks);
return this.httpClient.post(`${this.apiURL}/chacknameT/${id}`, Data);
}
checknameOut_t(id: any, stdids: any, weeks: any) {
var Data: any = new FormData();
Data.append("stdid", stdids);
Data.append("week", weeks);
return this.httpClient.post(`${this.apiURL}/checknameO/${id}`, Data);
}
uploadStudent(course_id: any, course_names: any, times: any, sesons: any, student: any) {
return this.httpClient.post(`${this.apiURL}/upload`, {
course_id: course_id+"-"+sesons,
course_name: course_names,
time: times,
seson: sesons,
students: student
});
}
updateStudent(id: any, dataupdate: any) {
return this.httpClient.post(`${this.apiURL}/updatescore/${id}`, {
students: dataupdate
});
}
getlocal() {
return this.Localtion
}
addstudent(idcoure: any, idstudent: any, names: any, number: any) {
return this.httpClient.post(`${this.apiURL}/addupstudent/${idcoure}`, {
number_id: number,
id_student: idstudent,
name: names
})
}
editstudent(idcoure: any, idstudent: any, names: any, number: any) {
return this.httpClient.post(`${this.apiURL}/editstudent/${idcoure}`, {
number_id: number,
id_student: idstudent,
name: names
})
}
deletestudent(idcoure: any, idstudent: any) {
return this.httpClient.post(`${this.apiURL}/deletestudent/${idcoure}`, {
id_student: idstudent
})
}
deleteCourse(id: any) {
return this.httpClient.delete(`${this.apiURL}/deleteCourse/${id}`);
}
reportCourse(id: any) {
return this.httpClient.get(`${this.apiURL}/report/${id}`);
}
ferseh() {
}
}
.sidenav-container {
height: 100%;
}
.sidenav {
width: 200px;
}
.sidenav .mat-toolbar {
background: inherit;
}
.mat-toolbar.mat-primary {
position: sticky;
top: 0;
z-index: 1;
}
<mat-sidenav-container class="sidenav-container" >
<mat-sidenav #drawer class="sidenav" fixedInViewport [hidden]="show"
[attr.role]="(isHandset$ | async) ? 'dialog' : 'navigation'"
[mode]="(isHandset$ | async) ? 'over' : 'side'"
[opened]="(isHandset$ | async) === false">
<mat-toolbar>Menu</mat-toolbar>
<mat-nav-list>
<a mat-list-item matLis [routerLink]="['/uplode']">เพิ่ม ชั่นเรียน</a>
<div *ngFor="let m of menuList">
<a mat-list-item matLis [routerLink]="[m.group.code]">{{m.group.name}}</a>
</div>
<!-- <a mat-list-item matLis [routerLink]="['/uplode']">เพิ่ม ชั่นเรียน</a> -->
</mat-nav-list>
</mat-sidenav>
<mat-sidenav-content>
<mat-toolbar color="primary">
<button
type="button"
aria-label="Toggle sidenav"
mat-icon-button
(click)="drawer.toggle()"
*ngIf="isHandset$ | async">
<mat-icon aria-label="Side nav toggle icon">menu</mat-icon>
</button>
<span [routerLink]="['/']" [hidden]="show">CHECK NAME</span>
</mat-toolbar>
<ng-content></ng-content>
<!-- Add Content Here -->
</mat-sidenav-content>
</mat-sidenav-container>
import { LayoutModule } from '@angular/cdk/layout';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatListModule } from '@angular/material/list';
import { MatSidenavModule } from '@angular/material/sidenav';
import { MatToolbarModule } from '@angular/material/toolbar';
import { TopbarComponent } from './topbar.component';
describe('TopbarComponent', () => {
let component: TopbarComponent;
let fixture: ComponentFixture<TopbarComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [TopbarComponent],
imports: [
NoopAnimationsModule,
LayoutModule,
MatButtonModule,
MatIconModule,
MatListModule,
MatSidenavModule,
MatToolbarModule,
]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TopbarComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should compile', () => {
expect(component).toBeTruthy();
});
});
import { Component, OnInit } from '@angular/core';
import { BreakpointObserver, Breakpoints } from '@angular/cdk/layout';
import { Observable } from 'rxjs';
import { map, shareReplay } from 'rxjs/operators';
import { Router } from '@angular/router'
import { MenuService } from "../services/menu.service";
@Component({
selector: 'app-topbar',
templateUrl: './topbar.component.html',
styleUrls: ['./topbar.component.css']
})
export class TopbarComponent {
isHandset$: Observable<boolean> = this.breakpointObserver.observe(Breakpoints.Handset)
.pipe(
map(result => result.matches),
shareReplay()
);
nameT: any;
url: any;
menuList: any;
show: any = false;
constructor(
private breakpointObserver: BreakpointObserver,
private router: Router,
private menuService: MenuService
) {
this.url = location.pathname.split("/")[1];
console.log(this.url);
if (this.url=="student") {
this.show = true;
console.log(this.show);
console.log('g-hk');
}
}
ngOnInit() {
if (this.url != '') {
this.menuList = this.menuService.getMenuList();
console.log(this.menuList);
}
if (localStorage.getItem('name') != null) {
this.nameT = localStorage.getItem('name')
}
}
}
.btn{
border: 5px solid transparent;
padding: 0.375rem 1.75rem;
font-size: 1rem;
line-height: 1.5;
border-radius: 0rem;
}
.h1, .h2, .h3, .h4, .h5, .h6, h1, h2, h3, h4, h5, h6 {
margin-bottom: 1.5rem;
font-weight: 500;
line-height: 1.7;
}
.grid-container {
margin: 20px;
}
\ No newline at end of file
<div class="grid-container">
<p></p>
<h1 class="mat-h1">New Classroom</h1>
</div>
<div class="container">
<hr>
<div class="form-group">
<input class="btn btn-info " type="file" (change)="onFileChange($event)" multiple="false" />
<br>
<br>
<div class="row">
<div class="col-md-6"></div>
<div class="input-group col-md-4">
</div>
<div class="col-md-2 container">
<select class="form-control" #seson name="seson" id="">
<option selected>เลือกเทอม</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
<hr>
</div>
<p>รหัสวิชา :{{course_id}}</p>
<p>ชื่อวิชา : {{course_name}}</p>
<p>วันเวลาเรียน : {{time}}</p>
<div class="text-right">
<button class="btn btn-success " (click)="upload(seson.value)">Upload!</button>
</div>
<hr>
<table class="table">
<thead>
<tr>
<th scope="col">เลขที่</th>
<th scope="col">รหัสนักศึกษา</th>
<th scope="col">ชื่อ-นานสกุล</th>
</tr>
</thead>
<tbody *ngFor="let s of student | paginate: { itemsPerPage: 20, currentPage: p }">
<tr>
<th>{{s.number}}</th>
<td>{{s.id_student}}</td>
<td>{{s.name}}</td>
</tr>
</tbody>
</table>
<pagination-controls (pageChange)="p = $event"></pagination-controls>
</div>
\ No newline at end of file
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { UploadfileComponent } from './uploadfile.component';
describe('UploadfileComponent', () => {
let component: UploadfileComponent;
let fixture: ComponentFixture<UploadfileComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ UploadfileComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(UploadfileComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
import { Component, OnInit } from '@angular/core';
import * as XLSX from 'xlsx';
import { Router } from "@angular/router";
import { StudentService } from "../services/student.service"
@Component({
selector: 'app-uploadfile',
templateUrl: './uploadfile.component.html',
styleUrls: ['./uploadfile.component.css']
})
export class UploadfileComponent implements OnInit {
data: any
//wopts: XLSX.WritingOptions = { bookType: 'xlsx', type: 'array' };
//fileName: string = 'SheetJS.xlsx';
wss: any
//check: any[]=[];
student: any[][] = [[]];
nameT: any;
course : any;
course_id: any;
course_name: any;
//classroom:any;
time: any;
p:number=1;
constructor(private router: Router, private studentService: StudentService) { }
ngOnInit(): void {
}
onFileChange(evt: any) {
try {
/* wire up file reader */
const target: DataTransfer = <DataTransfer>(evt.target);
if (target.files.length !== 1) throw new Error('Cannot use multiple files');
const reader: FileReader = new FileReader();
reader.onload = (e: any) => {
/* read workbook */
const bstr: string = e.target.result;
const wb: XLSX.WorkBook = XLSX.read(bstr, { type: 'binary' });
/* grab first sheet */
const wsname: string = wb.SheetNames[0];
const ws: XLSX.WorkSheet = wb.Sheets[wsname];
this.wss = [ws.B4.w, ws.B6.w, ws.M4.w]
/* save data */
this.data = <any>(XLSX.utils.sheet_to_json(ws, { header: 1 }));
this.course = ws.B4.w;
this.time = ws.B6.w;
for (let i = 9; i <= this.data.length - 3; i++) {
this.student[i - 9] = this.data[i];
for (let j = 1; j <= 3; j++) {
this.student[i - 9]['number'] = this.data[i][1];
this.student[i - 9]['id_student'] = this.data[i][2];
this.student[i - 9]['name'] = this.data[i][3];
}
this.student[i - 9].splice(0)
}
this.course_id = this.course.substr(10,7);
this.course_name=this.course.substr(19);
this.time=this.time.substr(13);
};
return reader.readAsBinaryString(target.files[0]);
} catch (error) {
alert('fire ไม่ถูกต้อง')
}
}
upload(seson:number) {
var data =[];
for (var key in this.student) {
data.push({
'number_id': this.student[key]['number'],
'id_student': this.student[key]['id_student'],
'name': this.student[key]['name']
});
}
if (this.student.length<=1) {
alert("ยังไม่ได้เลือก fire");
}else{
if (localStorage.getItem('name')!=null) {
this.nameT=localStorage.getItem('name');
if (seson==1||seson==2||seson==3) {
console.log("work seson");
this.studentService.uploadStudent(this.course_id,this.course_name,this.time,seson, data).subscribe(
() => {
this.router.navigate(['/'])
}
)
}else{
alert('เลือกเทอม')
}
}else{
alert('ยังไม่มีชื่ออาจารย์')
}
}
}
}
export const environment = {
production: true
};
// This file can be replaced during build by using the `fileReplacements` array.
// `ng build --prod` replaces `environment.ts` with `environment.prod.ts`.
// The list of file replacements can be found in `angular.json`.
export const environment = {
production: false
};
/*
* For easier debugging in development mode, you can import the following file
* to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`.
*
* This import should be commented out in production mode because it will have a negative impact
* on performance if an error is thrown.
*/
// import 'zone.js/dist/zone-error'; // Included with Angular CLI.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Check name by QRcode</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="logo.ico">
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body>
<app-root></app-root>
</body>
</html>
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
if (environment.production) {
enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.error(err));
/***************************************************************************************************
* Load `$localize` onto the global scope - used if i18n tags appear in Angular templates.
*/
import '@angular/localize/init';
/**
* This file includes polyfills needed by Angular and is loaded before the app.
* You can add your own extra polyfills to this file.
*
* This file is divided into 2 sections:
* 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.
* 2. Application imports. Files imported after ZoneJS that should be loaded before your main
* file.
*
* The current setup is for so-called "evergreen" browsers; the last versions of browsers that
* automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera),
* Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile.
*
* Learn more in https://angular.io/guide/browser-support
*/
/***************************************************************************************************
* BROWSER POLYFILLS
*/
/** IE10 and IE11 requires the following for NgClass support on SVG elements */
// import 'classlist.js'; // Run `npm install --save classlist.js`.
/**
* Web Animations `@angular/platform-browser/animations`
* Only required if AnimationBuilder is used within the application and using IE/Edge or Safari.
* Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0).
*/
// import 'web-animations-js'; // Run `npm install --save web-animations-js`.
/**
* By default, zone.js will patch all possible macroTask and DomEvents
* user can disable parts of macroTask/DomEvents patch by setting following flags
* because those flags need to be set before `zone.js` being loaded, and webpack
* will put import in the top of bundle, so user need to create a separate file
* in this directory (for example: zone-flags.ts), and put the following flags
* into that file, and then add the following code before importing zone.js.
* import './zone-flags';
*
* The flags allowed in zone-flags.ts are listed here.
*
* The following flags will work for all browsers.
*
* (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame
* (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick
* (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames
*
* in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js
* with the following flag, it will bypass `zone.js` patch for IE/Edge
*
* (window as any).__Zone_enable_cross_context_check = true;
*
*/
/***************************************************************************************************
* Zone JS is required by default for Angular itself.
*/
import 'zone.js/dist/zone'; // Included with Angular CLI.
/***************************************************************************************************
* APPLICATION IMPORTS
*/
/* You can add global styles to this file, and also import other style files */
html, body { height: 100%; }
body { margin: 0; font-family: Roboto, "Helvetica Neue", sans-serif; }
// This file is required by karma.conf.js and loads recursively all the .spec and framework files
import 'zone.js/dist/zone-testing';
import { getTestBed } from '@angular/core/testing';
import {
BrowserDynamicTestingModule,
platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';
declare const require: {
context(path: string, deep?: boolean, filter?: RegExp): {
keys(): string[];
<T>(id: string): T;
};
};
// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
BrowserDynamicTestingModule,
platformBrowserDynamicTesting()
);
// Then we find all the tests.
const context = require.context('./', true, /\.spec\.ts$/);
// And load the modules.
context.keys().map(context);
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": []
},
"files": [
"src/main.ts",
"src/polyfills.ts"
],
"include": [
"src/**/*.d.ts"
]
}
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"downlevelIteration": true,
"experimentalDecorators": true,
"module": "esnext",
"moduleResolution": "node",
"importHelpers": true,
"target": "es2015",
"typeRoots": [
"node_modules/@types"
],
"lib": [
"es2018",
"dom"
]
},
"angularCompilerOptions": {
"fullTemplateTypeCheck": true,
"strictInjectionParameters": true
}
}
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/spec",
"types": [
"jasmine",
"node"
]
},
"files": [
"src/test.ts",
"src/polyfills.ts"
],
"include": [
"src/**/*.spec.ts",
"src/**/*.d.ts"
]
}
{
"extends": "tslint:recommended",
"rules": {
"array-type": false,
"arrow-parens": false,
"deprecation": {
"severity": "warning"
},
"component-class-suffix": true,
"contextual-lifecycle": true,
"directive-class-suffix": true,
"directive-selector": [
true,
"attribute",
"app",
"camelCase"
],
"component-selector": [
true,
"element",
"app",
"kebab-case"
],
"import-blacklist": [
true,
"rxjs/Rx"
],
"interface-name": false,
"max-classes-per-file": false,
"max-line-length": [
true,
140
],
"member-access": false,
"member-ordering": [
true,
{
"order": [
"static-field",
"instance-field",
"static-method",
"instance-method"
]
}
],
"no-consecutive-blank-lines": false,
"no-console": [
true,
"debug",
"info",
"time",
"timeEnd",
"trace"
],
"no-empty": false,
"no-inferrable-types": [
true,
"ignore-params"
],
"no-non-null-assertion": true,
"no-redundant-jsdoc": true,
"no-switch-case-fall-through": true,
"no-var-requires": false,
"object-literal-key-quotes": [
true,
"as-needed"
],
"object-literal-sort-keys": false,
"ordered-imports": false,
"quotemark": [
true,
"single"
],
"trailing-comma": false,
"no-conflicting-lifecycle": true,
"no-host-metadata-property": true,
"no-input-rename": true,
"no-inputs-metadata-property": true,
"no-output-native": true,
"no-output-on-prefix": true,
"no-output-rename": true,
"no-outputs-metadata-property": true,
"template-banana-in-box": true,
"template-no-negated-async": true,
"use-lifecycle-interface": true,
"use-pipe-transform-interface": true
},
"rulesDirectory": [
"codelyzer"
]
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment