forms.gno

2.46 Kb ยท 118 lines
  1package forms
  2
  3import (
  4	"std"
  5
  6	"gno.land/p/agherasie/forms"
  7	"gno.land/p/demo/json"
  8	"gno.land/p/demo/ufmt"
  9	"gno.land/r/leon/hof"
 10)
 11
 12var db *forms.FormDB
 13
 14func init() {
 15	hof.Register("Ahgerasle's forms", "")
 16	db = forms.NewDB()
 17}
 18
 19func CreateForm(title string, description string, openAt string, closeAt string, data string) string {
 20	id, err := db.CreateForm(title, description, openAt, closeAt, data)
 21	if err != nil {
 22		panic(err)
 23	}
 24	return id
 25}
 26
 27func GetForms() string {
 28	builder := forms.FormNodeBuilder{json.Builder()}
 29
 30	builder.WriteArray("forms", func(builder *forms.FormArrayBuilder) {
 31		for _, form := range db.Forms {
 32			builder.WriteObject(func(builder *forms.FormNodeBuilder) {
 33				builder.WriteForm("form", form)
 34			})
 35		}
 36	})
 37
 38	encoded, err := json.Marshal(builder.Node())
 39	if err != nil {
 40		panic(err)
 41	}
 42
 43	return string(encoded)
 44}
 45
 46func GetFormByID(id string) string {
 47	form, err := db.GetForm(id)
 48	if err != nil {
 49		panic(err)
 50	}
 51
 52	builder := forms.FormNodeBuilder{json.Builder()}
 53
 54	builder.WriteForm("form", form).
 55		WriteObject("submissions", func(builder *forms.FormNodeBuilder) {
 56			formSubmissions := db.GetSubmissionsByFormID(form.ID)
 57			for _, submission := range formSubmissions {
 58				builder.WriteFormSubmission(submission.Author.String(), submission)
 59			}
 60		})
 61
 62	openAt, err := form.OpenAt()
 63	if err == nil {
 64		builder.WriteString("openAt", openAt.Format("2006-01-02 15:04:05"))
 65	}
 66	closeAt, err := form.CloseAt()
 67	if err == nil {
 68		builder.WriteString("closeAt", closeAt.Format("2006-01-02 15:04:05"))
 69	}
 70
 71	encoded, err := json.Marshal(builder.Node())
 72	if err != nil {
 73		panic(err)
 74	}
 75
 76	return string(encoded)
 77}
 78
 79func GetAnswer(formID string, authorID string) string {
 80	_, err := db.GetForm(formID)
 81	if err != nil {
 82		panic(err)
 83	}
 84
 85	answer, err := db.GetAnswer(formID, std.Address(authorID))
 86	if answer != nil {
 87		panic(err)
 88	}
 89
 90	return answer.Answers
 91}
 92
 93func SubmitForm(formID string, answers string) {
 94	_, err := db.GetForm(formID)
 95	if err != nil {
 96		panic(err)
 97	}
 98
 99	db.SubmitForm(formID, answers)
100}
101
102func Render(path string) string {
103	if len(db.Forms) == 0 {
104		response := "No forms yet !"
105		return response
106	}
107
108	response := "Forms:\n\n"
109	for _, form := range db.Forms {
110		response += ufmt.Sprintf("- %s\n\n", GetFormByID(form.ID))
111	}
112	response += "Answers:\n\n"
113	for _, answer := range db.Answers {
114		response += ufmt.Sprintf("- Form ID: %s\nAuthor: %s\nSubmitted At: %s\n>Answers: %s\n\n", answer.FormID, answer.Author, answer.SubmittedAt, answer.Answers)
115	}
116
117	return response
118}