/// add comment func DoComment(w http.ResponseWriter, r *http.Request) { var err error vars := mux.Vars(r) args := bson.M{} if err = rpc.ReadJson(r, &args); err != nil { rpc.WriteJson(r, w, nil, errors.New("Invalid JSON!")) } c := db.C("Post") q := c.FindId(vars["postId"]) var post Post err = q.One(&post) if err == nil { aCmt := Comment{User: r.Header.Get("User"), Date: time.Now().String()[:19], Text: args["Text"].(string)} if len(post.Comments) == 0 { post.Comments = []Comment{aCmt} } else { post.Comments = append(post.Comments, aCmt) } err = c.UpdateId(post.Id, post) } rpc.WriteJson(r, w, "OK", err) }
func _approveOrReject(approve bool, w http.ResponseWriter, r *http.Request) { var err error vars := mux.Vars(r) // wf хүсэлтийг олох c := db.C(colWfAction) q := c.FindId(vars["id"]) var reqObj bson.M if err = q.One(&reqObj); err != nil { rpc.WriteJson(r, w, nil, errors.New("Буруу хүсэлт !")) return } if reqObj["Active"].(bool) == false { rpc.WriteJson(r, w, nil, errors.New("Өмнө нь ашиглагдсан холбоос байна !")) return } state := "зөвшөөрсөн" msg := "Чөлөө зөвшөөрөгдлөө" if !approve { state = "татгалзсан" msg = "Чөлөөг татгалзлаа" } c1 := db.C("Leave") if err = c1.UpdateId(reqObj["LeaveId"], bson.M{"$set": bson.M{"State": state}}); err == nil { err = c.UpdateId(vars["id"], bson.M{"$set": bson.M{"Active": false}}) } rpc.WriteJson(r, w, msg, err) }
func SaveFeedback(w http.ResponseWriter, r *http.Request) { var err error vars := mux.Vars(r) var obj SurveyFeedback if err = rpc.ReadJson(r, &obj); err != nil { rpc.WriteJson(r, w, nil, err) return } c := db.C("SurveyFeedback") // асуултын тоогоор мөр үүсгэж бичих for _, ans := range obj.Answers { a := bson.M{} a["_id"] = bson.NewObjectId().Hex() a["User"] = r.Header.Get("User") a["Survey"] = vars["surveyId"] a["Question"] = ans["Question"] a["Answer"] = ans["Answer"] c.Insert(a) } // OK - амжилттай // DUP - давхардсан // LIMIT - хариулах хязгаарт хүрсэн rpc.WriteJson(r, w, "OK", err) }
// ирц бүртгэх функц func RegAtt(w http.ResponseWriter, r *http.Request) { var err error obj := bson.M{} if err = rpc.ReadJson(r, &obj); err != nil { rpc.WriteJson(r, w, nil, err) return } obj["_id"] = bson.NewObjectId().Hex() obj["RemoteAddr"] = r.RemoteAddr // TODO: орсон, гарсан эсэхийг ялгаж таних // Map EnrollNumber into Employee ID, Name empC := db.C("Employee") q := empC.Find(bson.M{"CardNo": obj["EnrollNumber"]}) var emp bson.M if err = q.One(&emp); err == nil { obj["Employee"] = bson.M{"_id": emp["_id"], "Name": emp["Name"]} } // Баазад оруулах c := db.C("Attendance") err = c.Insert(obj) rpc.WriteJson(r, w, obj["_id"], err) }
func UnfollowGroup(w http.ResponseWriter, r *http.Request) { var err error vars := mux.Vars(r) c := db.C("PlusGroup") q := c.FindId(vars["groupId"]) var pg PlusGroup err = q.One(&pg) if err == nil { if len(pg.Followers) > 0 { for i := 0; i < len(pg.Followers); i++ { if pg.Followers[i] == r.Header.Get("User") { // remove all occurences pg.Followers = append(pg.Followers[:i], pg.Followers[i+1:]...) } } err = c.UpdateId(pg.Id, pg) } } rpc.WriteJson(r, w, "OK", nil) }
func MyManager(w http.ResponseWriter, r *http.Request) { var err error vars := mux.Vars(r) mgr := "" // ажилтныг хайж олох empCol := db.C("Employee") q := empCol.FindId(vars["empId"]) var emp bson.M err = q.One(&emp) if err == nil { // нэгжийг хайж олох deptCol := db.C("Dept") q1 := deptCol.FindId(emp["Dept"].(string)) var dept bson.M err = q1.One(&dept) if err == nil { mgr = dept["Manager"].(string) } } rpc.WriteJson(r, w, mgr, err) }
func UnSubscribe(w http.ResponseWriter, r *http.Request) { var err error vars := mux.Vars(r) c := db.C("Event") q := c.FindId(vars["eventId"]) var ev Event err = q.One(&ev) if err == nil { if len(ev.Participants) > 0 { for i := 0; i < len(ev.Participants); i++ { if ev.Participants[i].Id == r.Header.Get("User") { // remove all occurences ev.Participants = append(ev.Participants[:i], ev.Participants[i+1:]...) } } err = c.UpdateId(ev.Id, ev) } } rpc.WriteJson(r, w, "OK", nil) }
/// Тайлан боловсруулах func Report(w http.ResponseWriter, r *http.Request) { var err error args := JsArgs{} rpc.ReadJson(r, &args) // call stored js var runResult bson.M var resp []bson.M err = _db.Run(bson.D{ {"eval", args.Src}, {"args", []bson.M{args.Params}}, {"nolock", true}, }, &runResult) if err == nil { // боловсруулалтын дараах үр дүнг уншиж буцаах c := _db.C(runResult["retval"].(string)) q := c.Find(bson.M{}) if args.Params["Sort"] != nil { q.Sort([]string{args.Params["Sort"].(string)}...) } err = q.All(&resp) } rpc.WriteJson(r, w, resp, err) }
// Id-аар устгах func Delete(w http.ResponseWriter, r *http.Request) { var err error vars := mux.Vars(r) c := _db.C(vars["collection"]) err = c.Remove(bson.M{"_id": vars["id"]}) rpc.WriteJson(r, w, vars["id"], err) }
func ExecJS1(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) params := bson.M{} rpc.ReadJson(r, ¶ms) err, runResult := ExecJS(vars["js"], params) rpc.WriteJson(r, w, runResult, err) }
// мэдээ тоолох // TODO: replace with db.MapReduce func PostCount(w http.ResponseWriter, r *http.Request) { var err error args := bson.M{} if err = rpc.ReadJson(r, &args); err != nil { rpc.WriteJson(r, w, nil, errors.New("Invalid JSON!")) } c := db.C("Post") mr := &mgo.MapReduce{ Map: "function() { if (!this.Type) { emit('news', 1) } else { emit(this.Type, 1) } }", Reduce: "function(key, values) { return Array.sum(values); }", } var result []bson.M _, err = c.Find(nil).MapReduce(mr, &result) rpc.WriteJson(r, w, result, err) }
// Applicant бүртгэх func RegApp(w http.ResponseWriter, r *http.Request) { var err error //vars := mux.Vars(r) obj := bson.M{} if err = rpc.ReadJson(r, &obj); err != nil { rpc.WriteJson(r, w, nil, err) return } c := db.C("Applicant") if obj["_id"] == nil { obj["_id"] = bson.NewObjectId().Hex() } obj["RemoteAddr"] = r.RemoteAddr err = c.Insert(obj) rpc.WriteJson(r, w, "OK", err) }
// Id-аар хайх func FindId(w http.ResponseWriter, r *http.Request) { var err error vars := mux.Vars(r) c := _db.C(vars["collection"]) q := c.FindId(vars["id"]) var resp bson.M err = q.One(&resp) rpc.WriteJson(r, w, resp, err) }
/// Нэгийг хайх func FindOne(w http.ResponseWriter, r *http.Request) { var err error vars := mux.Vars(r) args := DbArgs{} if err = rpc.ReadJson(r, &args); err != nil { rpc.WriteJson(r, w, nil, err) return } c := _db.C(vars["collection"]) q := c.Find(args.Query) // select if args.Select != nil { q.Select(args.Select) } var resp bson.M err = q.One(&resp) rpc.WriteJson(r, w, resp, err) }
func _save(op string, w http.ResponseWriter, r *http.Request) { var err error vars := mux.Vars(r) obj := bson.M{} if err = rpc.ReadJson(r, &obj); err != nil { rpc.WriteJson(r, w, nil, err) return } obj["updated"] = time.Now().String()[:19] obj["updatedBy"] = r.Header.Get("User") onSave(vars["collection"], obj, w, r) // TODO: foreign key талбарууд шинэчилэх // tags шинэчилэх UpdateTags(obj) c := _db.C(vars["collection"]) if op == "save" { if obj["_id"] != nil { _, err = c.UpsertId(obj["_id"], obj) } else { obj["_id"] = bson.NewObjectId().Hex() err = c.Insert(obj) } } else if op == "insert" { obj["_id"] = bson.NewObjectId().Hex() err = c.Insert(obj) } else if op == "update" { //delete(obj, "_id") err = c.UpdateId(obj["_id"], obj) } rpc.WriteJson(r, w, obj["_id"], err) }
func ZipBanner(w http.ResponseWriter, r *http.Request) { var err error var rdr *zip.ReadCloser vars := mux.Vars(r) // extract zip rdr, err = zip.OpenReader(vars["file"]) if err != nil { log.Fatal(err) } defer rdr.Close() // Архив дахь файлуудаар давтаж агуулгыг хэвлэх for _, f := range rdr.File { fmt.Printf("'%s' файлын агуулга:\n", f.Name) /* folder := conf.Conf["FileHome"] + "/Banner" filePath := folder + "/" + vars["file"] if _, e := os.Stat(folder); os.IsNotExist(e) { err = os.MkdirAll(folder, 0700) } rc, err := f.Open() if err != nil { log.Fatal(err) } defer rc.Close() d, err := os.Create(filePath) if err != nil { return err } if _, err := io.Copy(d, s); err != nil { d.Close() return err } return d.Close() _, err = io.Copy(os.Stdout, rc) if err != nil { log.Fatal(err) }*/ } rpc.WriteJson(r, w, "OK", err) }
func Aggregate(w http.ResponseWriter, r *http.Request) { var err error var resp []bson.M args := AggregateArgs{} err = rpc.ReadJson(r, &args) if err == nil { c := _db.C(args.Collection) pipe := c.Pipe(args.Pipeline) err = pipe.All(&resp) } rpc.WriteJson(r, w, resp, err) }
/// Хайх func Find(w http.ResponseWriter, r *http.Request) { var err error // параметр vars := mux.Vars(r) args := DbArgs{} rpc.ReadJson(r, &args) c := _db.C(vars["collection"]) if args.Query == nil { args.Query = bson.M{} } onFind(args.Query, w, r) q := c.Find(args.Query) // select if args.Select != nil { q.Select(args.Select) } // skip if args.Skip > 0 { q.Skip(args.Skip) } // limit if args.Limit > 0 { q.Limit(args.Limit) } // sort if len(args.Sort) > 0 { q.Sort(args.Sort...) } var resp []bson.M err = q.All(&resp) //log.Printf("db.Find(%v) алдаа: %v", args, err) rpc.WriteJson(r, w, resp, err) }
// Map attendance func MapEnrollId(w http.ResponseWriter, r *http.Request) { var err error vars := mux.Vars(r) // ажилтныг олох empC := db.C("Employee") q := empC.FindId(vars["empId"]) var emp bson.M if err = q.One(&emp); err == nil { empRef := bson.M{"_id": emp["_id"], "Name": emp["Name"]} // ирцийн өгөгдлийг засах c := db.C("Attendance") c.UpdateAll(bson.M{"EnrollId": vars["enId"]}, bson.M{"$set": bson.M{"Employee": empRef}}) } rpc.WriteJson(r, w, "OK", err) }
func MapReduce(w http.ResponseWriter, r *http.Request) { var err error var resp []bson.M args := MapReduceArgs{} err = rpc.ReadJson(r, &args) if err == nil { job := &mgo.MapReduce{ Map: args.Map, Reduce: args.Reduce, } c := _db.C(args.Collection) _, err = c.Find(args.Query).MapReduce(job, &resp) } rpc.WriteJson(r, w, resp, err) }
/// +1 on the post func Plus1(w http.ResponseWriter, r *http.Request) { var err error vars := mux.Vars(r) c := db.C("Post") q := c.FindId(vars["postId"]) var post Post err = q.One(&post) aLike := Like{User: r.Header.Get("User"), Date: time.Now().String()[:19]} if err == nil { if len(post.Likes) == 0 { post.Likes = []Like{aLike} } else { // байхгүй бол нэмэх (like), байгаа бол хасах (dislike) var i int = 0 var exists bool for ; i < len(post.Likes); i++ { if post.Likes[i].User == r.Header.Get("User") { exists = true break } } if exists { post.Likes = append(post.Likes[:i], post.Likes[i+1:]...) aLike.User = "" // notify a dislike } else { post.Likes = append(post.Likes, aLike) } } err = c.UpdateId(post.Id, post) } rpc.WriteJson(r, w, aLike, err) }
func Subscribe(w http.ResponseWriter, r *http.Request) { var err error vars := mux.Vars(r) c := db.C("Event") q := c.FindId(vars["eventId"]) resp := "OK" var ev Event err = q.One(&ev) if err == nil { p := IdName{Id: r.Header.Get("User"), Name: r.Header.Get("Name")} if len(ev.Participants) == 0 { ev.Participants = []IdName{p} err = c.UpdateId(ev.Id, ev) } else { // өмнө бүртгүүлсэн эсэхийг шалгах i := 0 for i < len(ev.Participants) { if ev.Participants[i].Id == r.Header.Get("User") { break } i++ } if i >= len(ev.Participants) { ev.Participants = append(ev.Participants, p) err = c.UpdateId(ev.Id, ev) } else { // давхардсан resp = "Dup" } } } rpc.WriteJson(r, w, resp, nil) }
func FollowGroup(w http.ResponseWriter, r *http.Request) { var err error vars := mux.Vars(r) c := db.C("PlusGroup") q := c.FindId(vars["groupId"]) var pg PlusGroup err = q.One(&pg) if err == nil { if len(pg.Followers) == 0 { pg.Followers = []string{r.Header.Get("User")} } else { pg.Followers = append(pg.Followers, r.Header.Get("User")) } err = c.UpdateId(pg.Id, pg) } rpc.WriteJson(r, w, "OK", nil) }
// Бичлэгийн тоо func Count(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) var n int var err error c := _db.C(vars["collection"]) q := bson.M{} if r.Method == "GET" { // n, err = c.Find(q).Count() } else { args := DbArgs{} rpc.ReadJson(r, &args) q = args.Query } // тоолох үйлдэл дээр мөн дүрийн filter хамаатай onFind(q, w, r) n, err = c.Find(q).Count() rpc.WriteJson(r, w, n, err) }
func CollectionList(w http.ResponseWriter, r *http.Request) { rpc.WriteJson(r, w, Cols, nil) }
// wf/leave/start/{id} func LeaveStart(w http.ResponseWriter, r *http.Request) { var err error vars := mux.Vars(r) c := db.C("Leave") q := c.FindId(vars["id"]) var leaveObj bson.M if err = q.One(&leaveObj); err != nil { rpc.WriteJson(r, w, nil, errors.New("Чөлөөний мэдээлэл олдсонгүй!")) return } // хүсэлтэд санамсаргүй дугаар үүсгэх actionRequestId := bson.NewObjectId().Hex() approveUrl := "http://localhost:8000/wf/approve/" + actionRequestId rejectUrl := "http://localhost:8000/wf/reject/" + actionRequestId c1 := db.C(colWfAction) c1.Insert(bson.M{ "_id": actionRequestId, "LeaveId": vars["id"], "Date": time.Now().String()[:19], "Active": true}) // Э-мэйл загвар msg := fmt.Sprintf(`<p>Танд чөлөөний хүсэлт ирлээ.</p> <br/> -------------------------- <br/> <strong>Чөлөөний төрөл:</strong> %v <br/> <strong>Явах огноо:</strong> %v %v <br/> <strong>Хугацаа:</strong> %v цаг <br/> <strong>Шалтгаан:</strong> %v <br/> <br/> <p><a href=%s>Зөвшөөрөх</a> <a href=%s>Татгалзах</a></p> `, leaveObj["Name"], leaveObj["DateFrom"], leaveObj["TimeFrom"], leaveObj["Duration"], leaveObj["Notes"], approveUrl, rejectUrl) // менежерийн э-мэйл хаягийг олох var mgr bson.M if mgr, err = MyManager(r.Header.Get("User")); err != nil { rpc.WriteJson(r, w, nil, errors.New("Таны дээд удирдлага тодорхойгүй байна!")) return } if mgr["WorkEmail"] == nil || mgr["WorkEmail"] == "" { rpc.WriteJson(r, w, nil, errors.New("Таны дээд удирдлагын э-мэйл хаяг тодорхойгүй байна!")) return } // э-мэйлийг илгээх m := NewMessage("Чөлөөний хүсэлт", msg, mgr["WorkEmail"].(string)) m.BodyContentType = "text/html" m.From = r.Header.Get("Name") if err = _sendEmail(m); err == nil { // төлөв өөрчлөх c.UpdateId(vars["id"], bson.M{"$set": bson.M{"State": "хүсэлт"}}) } rpc.WriteJson(r, w, "OK", err) }
func Hello(w http.ResponseWriter, r *http.Request) { rpc.WriteJson(r, w, "Hello from HR", nil) }
func UpdateGroups(w http.ResponseWriter, r *http.Request) { // TODO: албан (нэгж) болон албан бус группүүд // TODO: employee tag юунд ашиглах вэ? Survey, Plus post ? rpc.WriteJson(r, w, "Done !", nil) }