func PostApplyScoreData(teamName string, ApplyScore *PostApplyScore) (*Status, error) { l.PutInfo(l.I_M_PostPage, teamName, ApplyScore) //更新情報をGlobal変数に格納する defer SetPlayerCol(ApplyScore.UserIds) AUserIdInTheTeam := teams[teamName].UserIds[0] if players[AUserIdInTheTeam].Apply != 0 { l.Output( logrus.Fields{ "User Apply": l.Sprintf(players[AUserIdInTheTeam].Apply), }, "Apply score is already registered", l.Debug, ) return &Status{"already registered"}, nil } for playerIndex, userId := range ApplyScore.UserIds { findQuery := bson.M{"userid": userId} setQuery := bson.M{"$set": bson.M{"apply": ApplyScore.Apply[playerIndex]}} if err = UpdateMongoData("player", findQuery, setQuery); err != nil { l.PutErr(err, l.Trace(), l.E_M_Update, ApplyScore.Apply[playerIndex]) return &Status{"failed"}, err } } return &Status{"success"}, nil }
func RegisterThreadImg(r *RequestTakePictureStatus) (*RequestTakePictureStatus, error) { l.PutInfo(l.I_M_RegisterCol, r, nil) defer SetPlayerCol([]string{r.UserId}) if len(r.ThreadId) == 0 { return nil, errors.New("there is not thread id") } if len(r.PhotoUrl) == 0 { return nil, errors.New("there is not pthoto url ") } threadFindQuery := bson.M{"threadid": r.ThreadId} threadSetQuery := bson.M{"$set": bson.M{"imgurl": r.PhotoUrl}} if err = UpdateMongoData("thread", threadFindQuery, threadSetQuery); err != nil { l.PutErr(err, l.Trace(), l.E_M_Update, r.PhotoUrl) return &RequestTakePictureStatus{Status: "failed"}, err } var photoKey string if r.Positive { photoKey = "positivephotourl" } else { photoKey = "negativephotourl" } playerFindQuery := bson.M{"userid": r.UserId} playerSetQuery := bson.M{"$set": bson.M{photoKey: r.PhotoUrl}} if err = UpdateMongoData("player", playerFindQuery, playerSetQuery); err != nil { l.PutErr(err, l.Trace(), l.E_M_Update, r.PhotoUrl) return &RequestTakePictureStatus{Status: "failed"}, err } SetAllThreadCol() thread := &Thread{ ThreadId: r.ThreadId, UserId: threads[r.ThreadId].UserId, UserName: threads[r.ThreadId].UserName, Msg: threads[r.ThreadId].Msg, ImgUrl: threads[r.ThreadId].ImgUrl, ColorCode: threads[r.ThreadId].ColorCode, Positive: threads[r.ThreadId].Positive, CreatedAt: threads[r.ThreadId].CreatedAt, } ThreadChan <- thread requestTakePictureStatus, err := RequestTakePicture(r.TeamUserIds) if err != nil { return nil, err } if len(requestTakePictureStatus.ThreadId) != 0 { return requestTakePictureStatus, nil } return &RequestTakePictureStatus{Status: "success"}, nil }
func RegisterFieldColData(date string, fieldCols []FieldCol) (*Status, error) { l.PutInfo(l.I_M_RegisterCol, date, fieldCols) defer SetAllFieldCol() db, session := mongoConn() fieldC := db.C("field") defer session.Close() var createCnt, updateCnt int for _, fieldCol := range fieldCols { if fieldCol.Hole > 18 || fieldCol.Hole < 0 { l.PutErr(nil, l.Trace(), l.E_WrongData, fieldCol.Hole) return &Status{"this is not hole number"}, err } fieldCol.Ignore = false fieldCol.Date = date findQuery := bson.M{"hole": fieldCol.Hole} change, err := fieldC.Upsert(findQuery, fieldCol) if err != nil { l.PutErr(err, l.Trace(), l.E_M_Upsert, fieldCol.Hole) return &Status{"can not upsert"}, err } if change.Updated == 0 { createCnt += 1 } else { updateCnt += 1 } } return &Status{"success"}, nil }
func GetScoreEntrySheetPageData(teamName string, holeString string) (*ScoreEntrySheet, error) { l.PutInfo(l.I_M_GetPage, teamName, holeString) if len(holeString) == 0 { l.PutErr(nil, l.Trace(), l.E_Nil, teamName) return nil, errors.New("hole string is nil") } holeNum, _ := strconv.Atoi(holeString) holeIndex := holeNum - 1 field := fields[holeNum] userIds := teams[teamName].UserIds member := make([]string, len(userIds)) total := make([]int, len(userIds)) putt := make([]int, len(userIds)) for i, userId := range userIds { member[i] = users[userId].Name total[i] = players[userId].Score[holeIndex]["total"].(int) putt[i] = players[userId].Score[holeIndex]["putt"].(int) } scoreEntrySheet := ScoreEntrySheet{ Team: teamName, Hole: holeNum, Member: member, UserIds: userIds, Par: field.Par, Yard: field.Yard, Total: total, Putt: putt, Excnt: excnt[teamName][holeNum], } return &scoreEntrySheet, nil }
func GetLeadersBoardPageData() (*LeadersBoard, error) { l.PutInfo(l.I_M_GetPage, nil, nil) var leadersBoard LeadersBoard var userScore UserScore for _, player := range players { var totalPar, totalScore, passedHoleCnt int for holeIndex, playerScore := range player.Score { holeNum := holeIndex + 1 if playerScore["total"].(int) != 0 { totalPar += fields[holeNum].Par total, _ := playerScore["total"].(int) totalScore += total passedHoleCnt += 1 } } userScore = UserScore{ Score: totalScore - totalPar, Total: totalScore, Name: users[player.UserId].Name, Hole: passedHoleCnt, } leadersBoard.Ranking = append(leadersBoard.Ranking, userScore) } sort.Sort(sortByScore(leadersBoard.Ranking)) return &leadersBoard, nil }
func UpsertNewTimeLine(thread *Thread) error { l.PutInfo(l.I_M_PostPage, thread, nil) //更新情報をGlobal変数に格納する defer SetAllThreadCol() defaultColor := "#c0c0c0" if len(thread.ThreadId) != 0 { l.PutErr(nil, l.Trace(), l.E_WrongData, thread) return errors.New("thread id exists") } db, session := mongoConn() threadCol := db.C("thread") defer session.Close() thread.ThreadId = make20lengthHashString() thread.CreatedAt = time.Now().Format(c.DatetimeFormat) thread.ColorCode = defaultColor if err = threadCol.Insert(thread); err != nil { l.PutErr(err, l.Trace(), l.E_M_Insert, thread) return err } ThreadChan <- thread return nil }
func RegisterTeamColData(date string, teamCols []TeamCol) (*Status, error) { l.PutInfo(l.I_M_RegisterCol, date, teamCols) defer SetAllPlayerCol() defer SetAllTeamCol() db, session := mongoConn() playerC := db.C("player") teamC := db.C("team") defer session.Close() var OneBeforebyteOfA byte = 64 alphabet := make([]byte, 1) alphabet[0] = OneBeforebyteOfA totalHoleNum := 18 for _, teamCol := range teamCols { if len(teamCol.UserIds) == 0 { l.PutErr(nil, l.Trace(), l.E_Nil, teamCol) return &Status{"this team do not have user id"}, nil } alphabet[0] += 1 teamCol.Name = string(alphabet) teamCol.Defined = false teamCol.Date = date if err := teamC.Insert(teamCol); err != nil { l.PutErr(err, l.Trace(), l.E_M_Insert, teamCol) return &Status{"can not insert"}, err } for _, userId := range teamCol.UserIds { scores := []bson.M{} for holeNum := 1; holeNum <= totalHoleNum; holeNum++ { score := bson.M{ "hole": holeNum, "putt": 0, "total": 0, } scores = append(scores, score) } player := PlayerCol{ UserId: userId, Score: scores, Date: date, } if err := playerC.Insert(player); err != nil { l.PutErr(err, l.Trace(), l.E_M_Insert, player) return &Status{"can not insert"}, err } } } return &Status{"success"}, nil }
func PostScoreEntrySheetPageData(teamName string, holeString string, teamScore *PostTeamScore) (*RequestTakePictureStatus, error) { l.PutInfo(l.I_M_PostPage, teamName, teamScore) userIds := teams[teamName].UserIds //更新情報をGlobal変数に格納する defer SetPlayerCol(userIds) if len(holeString) == 0 { l.PutErr(nil, l.Trace(), l.E_Nil, teamName) return &RequestTakePictureStatus{Status: "failed"}, errors.New("hole is not string") } holeNum, _ := strconv.Atoi(holeString) holeIndex := holeNum - 1 holeIndexString := strconv.Itoa(holeIndex) if teamScore.Excnt != excnt[teamName][holeNum] { return &RequestTakePictureStatus{Status: "other updated"}, nil } else { excnt[teamName][holeNum]++ } for playerIndex, userId := range teamScore.UserIds { total, putt := teamScore.Total[playerIndex], teamScore.Putt[playerIndex] findQuery := bson.M{"userid": userId} setQuery := bson.M{ "$set": bson.M{ "score." + holeIndexString + ".total": total, "score." + holeIndexString + ".putt": putt, }, } if err = UpdateMongoData("player", findQuery, setQuery); err != nil { l.PutErr(err, l.Trace(), l.E_M_Update, userId) return &RequestTakePictureStatus{Status: "failed update score"}, err } } // Thread登録 if err := RegisterThreadOfScore(holeString, teamScore); err != nil { l.PutErr(err, l.Trace(), l.E_M_RegisterThread, teamScore) return nil, err } // チーム内に写真リクエストがあるか確認する requestTakePictureStatus, err := RequestTakePicture(userIds) if err != nil { l.PutErr(err, l.Trace(), l.E_M_SearchPhotoTask, userIds) return nil, err } return requestTakePictureStatus, nil }
func PostLoginPageData(loginInfo *PostLogin) (*LoginStatus, error) { l.PutInfo(l.I_M_PostPage, loginInfo, nil) var admin bool _, ok := users[loginInfo.UserId] if ok { var teamName string for _, team := range teams { for _, userid := range team.UserIds { if userid == loginInfo.UserId { teamName = team.Name } } } l.Output( logrus.Fields{ "User ID": loginInfo.UserId, "User Name": users[loginInfo.UserId].Name, }, "login success", l.Debug, ) if players[loginInfo.UserId].Admin == true { admin = true } else { admin = false } loginStatus := &LoginStatus{ Status: "success", UserId: loginInfo.UserId, UserName: users[loginInfo.UserId].Name, Team: teamName, Admin: admin, } return loginStatus, nil } else { l.Output( logrus.Fields{ "User ID": loginInfo.UserId, }, "login faild", l.Debug, ) return &LoginStatus{Status: "failed"}, nil } }
func GetIndexPageData() (*Index, error) { l.PutInfo(l.I_M_GetPage, nil, nil) var teamArray []string for name, _ := range teams { teamArray = append(teamArray, name) } sort.Strings(teamArray) index := &Index{ Team: teamArray, Length: len(teams), } return index, nil }
func PostScoreViewSheetPageData(teamName string, definedTeam *PostDefinedTeam) (*Status, error) { l.PutInfo(l.I_M_PostPage, teamName, definedTeam) //更新情報をGlobal変数に格納する defer SetTeamCol(teamName) findQuery := bson.M{"name": teamName} setQuery := bson.M{"$set": bson.M{"defined": true}} if err = UpdateMongoData("team", findQuery, setQuery); err != nil { l.PutErr(err, l.Trace(), l.E_M_Update, teamName) return &Status{"failed"}, err } return &Status{"success"}, nil }
func GetTimeLinePageData() (*TimeLine, error) { l.PutInfo(l.I_M_GetPage, nil, nil) var timeLine TimeLine var tmpThreads []Thread threadsKeys := sortByDate{} for k, v := range threads { t := ThreadDate{k, v.CreatedAt} threadsKeys = append(threadsKeys, t) } sort.Sort(threadsKeys) for _, threadKey := range threadsKeys { var tmpThread Thread var tmpReactions []Reaction threadId := threadKey.ThreadId if len(threads[threadId].ImgUrl) == 0 { continue } for _, reaction := range threads[threadId].Reactions { var tmpReaction Reaction tmpReaction.UserId = reaction["userid"].(string) tmpReaction.UserName = reaction["username"].(string) tmpReaction.ContentType = reaction["contenttype"].(int) tmpReaction.Content = reaction["content"].(string) tmpReaction.DateTime = reaction["datetime"].(string) tmpReactions = append(tmpReactions, tmpReaction) } tmpThread.ThreadId = threadId tmpThread.UserId = threads[threadId].UserId tmpThread.UserName = threads[threadId].UserName tmpThread.Msg = threads[threadId].Msg tmpThread.ImgUrl = threads[threadId].ImgUrl tmpThread.ColorCode = threads[threadId].ColorCode tmpThread.Positive = threads[threadId].Positive tmpThread.CreatedAt = threads[threadId].CreatedAt tmpThread.Reactions = tmpReactions tmpThreads = append(tmpThreads, tmpThread) } timeLine.Threads = tmpThreads return &timeLine, nil }
func RegisterUserColData(userCols []UserCol) (*Status, error) { l.PutInfo(l.I_M_RegisterCol, userCols, nil) defer SetAllUserCol() db, session := mongoConn() col := db.C("user") defer session.Close() var createCnt, updateCnt int for _, userCol := range userCols { if len(userCol.Name) == 0 { l.PutErr(nil, l.Trace(), l.E_Nil, userCol.Name) return &Status{"this user do not have name"}, nil } if len(userCol.UserId) == 0 { userCol.UserId = make20lengthHashString() } if len(userCol.CreatedAt) == 0 { userCol.CreatedAt = time.Now().Format(c.DatetimeFormat) } findQuery := bson.M{"userid": userCol.UserId} change, err := col.Upsert(findQuery, userCol) if err != nil { l.PutErr(err, l.Trace(), l.E_M_Upsert, userCol.UserId) return &Status{"can not upsert"}, err } if change.Updated == 0 { createCnt += 1 } else { updateCnt += 1 } } return &Status{"success"}, nil }
func GetScoreViewSheetPageData(teamName string) (*ScoreViewSheet, error) { l.PutInfo(l.I_M_GetPage, teamName, nil) userIds := teams[teamName].UserIds member := make([]string, len(userIds)) apply := make([]int, len(userIds)) totalScore := make([]int, len(userIds)) totalPutt := make([]int, len(userIds)) outTotalScore := make([]int, len(userIds)) outTotalPutt := make([]int, len(userIds)) inTotalScore := make([]int, len(userIds)) inTotalPutt := make([]int, len(userIds)) holes := make([]Hole, len(fields)) var totalPar int var outTotalPar int var inTotalPar int for holeNum, field := range fields { holeIndex := holeNum - 1 totalPar += field.Par if holeNum < 10 { outTotalPar += field.Par } else { inTotalPar += field.Par } score := make([]int, len(userIds)) for playerIndex, userId := range userIds { scoreAHole := players[userId].Score[holeIndex]["total"].(int) puttAHole := players[userId].Score[holeIndex]["putt"].(int) score[playerIndex] = scoreAHole if holeNum < 10 { outTotalScore[playerIndex] += scoreAHole outTotalPutt[playerIndex] += puttAHole } else { inTotalScore[playerIndex] += scoreAHole inTotalPutt[playerIndex] += puttAHole } totalScore[playerIndex] += scoreAHole totalPutt[playerIndex] += puttAHole if holeIndex == 0 { member[playerIndex] = users[userId].Name apply[playerIndex] = players[userId].Apply } } holes[holeIndex] = Hole{ Hole: holeNum, Par: field.Par, Yard: field.Yard, Score: score, } } outSum := Sum{ Par: outTotalPar, Score: outTotalScore, Putt: outTotalPutt, } inSum := Sum{ Par: inTotalPar, Score: inTotalScore, Putt: inTotalPutt, } sum := Sum{ Par: totalPar, Score: totalScore, Putt: totalPutt, } scoreViewSheet := ScoreViewSheet{ Team: teamName, Member: member, UserIds: userIds, Apply: apply, Hole: holes, OutSum: outSum, InSum: inSum, Sum: sum, Defined: teams[teamName].Defined, } return &scoreViewSheet, nil }
func GetEntireScorePageData() (*EntireScore, error) { l.PutInfo(l.I_M_GetPage, nil, nil) //rows[*][0] ホール rows[*][1] パー rows[*][2->n] PlayerName //rows[0] チーム名 //rows[1] プレーヤー名 //rows[2] IN //rows[3] ホール1 //rows[4] ホール2 //rows[5] ホール3 //rows[6] ホール4 //rows[7] ホール5 //rows[8] ホール6 //rows[9] ホール7 //rows[10] ホール8 //rows[11] ホール9 //rows[12] OUT //rows[13] ホール1 //rows[14] ホール2 //rows[15] ホール3 //rows[16] ホール4 //rows[17] ホール5 //rows[18] ホール6 //rows[19] ホール7 //rows[20] ホール8 //rows[21] ホール9 //rows[22] Gross //rows[23] Net //rows[24] 申請 //rows[25] スコア差 //rows[26] 順位 rowSize := 27 columnSize := len(players) + 2 rows := make([][]string, rowSize) for i := 0; i < rowSize; i++ { if i == 0 { rows[i] = make([]string, len(teams)*2) } else { rows[i] = make([]string, columnSize) } } rows[1][0], rows[1][1] = "ホール", "パー" rows[2][0], rows[2][1] = "OUT", "ー" rows[12][0], rows[12][1] = "IN", "ー" rows[22][0], rows[22][1] = "Gross", "ー" rows[23][0], rows[23][1] = "Net", "ー" rows[24][0], rows[24][1] = "申請", "ー" rows[25][0], rows[25][1] = "スコア差", "ー" rows[26][0], rows[26][1] = "順位", "ー" var passedPlayerNum int var teamIndex int var headingColumnNum = 2 var inColumNum = 1 var outColumNum = 1 var userIdArrayOrder []string var keys []string for k := range teams { keys = append(keys, k) } sort.Strings(keys) finalRankings := []FinalRanking{} for _, teamName := range keys { rows[0][teamIndex*2] = strconv.Itoa(len(teams[teamName].UserIds)) rows[0][teamIndex*2+1] = "TEAM " + teamName userIds := teams[teamName].UserIds for playerIndex, userId := range userIds { userIdArrayOrder = append(userIdArrayOrder, userId) var gross int var net int userDataIndex := playerIndex + passedPlayerNum + headingColumnNum rows[1][userDataIndex] = users[userId].Name for holeNum, field := range fields { holeIndex := holeNum - 1 halfHoleNum := len(fields) / 2 holeRowNum := holeIndex + headingColumnNum + inColumNum inOutBorderline := headingColumnNum + inColumNum + halfHoleNum if holeRowNum >= inOutBorderline { holeRowNum = holeRowNum + outColumNum } if playerIndex == 0 { if holeNum > halfHoleNum { holeNum = holeNum - halfHoleNum } if field.Ignore { rows[holeRowNum][0] = "-i" + strconv.Itoa(holeNum) } rows[holeRowNum][0] = strconv.Itoa(holeNum) rows[holeRowNum][1] = strconv.Itoa(field.Par) } playerTotal := players[userId].Score[holeIndex]["total"].(int) gross += playerTotal if field.Ignore { net += field.Par } else { net += playerTotal } rows[holeRowNum][userDataIndex] = strconv.Itoa(playerTotal) } rows[22][userDataIndex] = strconv.Itoa(gross) rows[23][userDataIndex] = strconv.Itoa(net) rows[24][userDataIndex] = strconv.Itoa(players[userId].Apply) scoreDiff := players[userId].Apply - net if scoreDiff < 0 { scoreDiff = scoreDiff * -1 } rows[25][userDataIndex] = strconv.Itoa(scoreDiff) finalRanking := FinalRanking{ UserId: userId, ScoreDiff: scoreDiff, Gross: gross, } finalRankings = append(finalRankings, finalRanking) } passedPlayerNum += len(userIds) teamIndex++ } sort.Sort(sortByRank(finalRankings)) for userIdIndex, userId := range userIdArrayOrder { userDataIndex := userIdIndex + 2 for rankingIndex, ranking := range finalRankings { if userId != ranking.UserId { continue } rows[26][userDataIndex] = strconv.Itoa(rankingIndex + 1) } } EntireScore := EntireScore{ Rows: rows, } return &EntireScore, nil }
func UpdateExistingTimeLine(thread *Thread) (*Thread, error) { l.PutInfo(l.I_M_PostPage, thread, nil) targetThreadId := thread.ThreadId //更新情報をGlobal変数に格納する defer SetAllThreadCol() colorFeeling := make(map[string]string) colorFeeling["default"] = "#c0c0c0" colorFeeling["angry"] = "#ff7f7f" colorFeeling["great"] = "#ffff7f" colorFeeling["sad"] = "#7fbfff" colorFeeling["vexing"] = "#7fff7f" if len(targetThreadId) == 0 { l.PutErr(nil, l.Trace(), l.E_Nil, thread) return nil, errors.New("thread id do not exist") } if len(thread.ColorCode) == 0 { l.PutErr(err, l.Trace(), l.E_Nil, thread.ColorCode) return nil, errors.New("current colorCode do not contain in posted thread") } if len(thread.Reactions) > 1 { l.PutErr(err, l.Trace(), l.E_TooManyData, thread.Reactions) return nil, errors.New("reactions is not 1") } currentFeeling := "" currentColor := threads[targetThreadId].ColorCode postedFeeling := getFeelingFromAWSUrl(thread.Reactions[0].Content) postedColor := colorFeeling[postedFeeling] for feeling, code := range colorFeeling { if currentColor == code { currentFeeling = feeling } } thread.Reactions[0].DateTime = time.Now().Format(c.DatetimeFormat) findQuery := bson.M{"threadid": targetThreadId} pushQuery := bson.M{"$push": bson.M{"reactions": thread.Reactions[0]}} if err = UpdateMongoData("thread", findQuery, pushQuery); err != nil { l.PutErr(err, l.Trace(), l.E_M_Update, thread.Reactions[0]) return nil, err } //投稿された感情と、現在の感情に相違がある場合 if currentFeeling != postedFeeling { var setColor string var currentFeelingCount, postedFeelingCount int if currentColor == colorFeeling["default"] { setColor = postedColor } else { //直前の更新を反映させる SetAllThreadCol() for _, r := range threads[targetThreadId].Reactions { switch getFeelingFromAWSUrl(r["content"].(string)) { case currentFeeling: currentFeelingCount++ case postedFeeling: postedFeelingCount++ } } if currentFeelingCount >= postedFeelingCount { setColor = currentColor } else { setColor = postedColor } } setQuery := bson.M{"$set": bson.M{"colorcode": setColor}} if err = UpdateMongoData("thread", findQuery, setQuery); err != nil { l.PutErr(err, l.Trace(), l.E_M_Update, setColor) return nil, err } thread.ColorCode = setColor } return thread, nil }