From e6d94567b11fa74fce23e616604b2172b42a2890 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Thu, 15 Aug 2024 11:07:27 +0300 Subject: [PATCH 001/201] init: go work file --- go.work | 7 +++++++ go.work.sum | 3 +++ 2 files changed, 10 insertions(+) create mode 100644 go.work create mode 100644 go.work.sum diff --git a/go.work b/go.work new file mode 100644 index 0000000..9006f9f --- /dev/null +++ b/go.work @@ -0,0 +1,7 @@ +go 1.22.6 + + +use ( + ./go-vise + . +) \ No newline at end of file diff --git a/go.work.sum b/go.work.sum new file mode 100644 index 0000000..35e0f01 --- /dev/null +++ b/go.work.sum @@ -0,0 +1,3 @@ +github.com/alecthomas/assert/v2 v2.2.2/go.mod h1:pXcQ2Asjp247dahGEmsZ6ru0UVwnkhktn7S0bBDLxvQ= +github.com/alecthomas/repr v0.2.0/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4= +github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg= From c3166813c60a4243131a67487f6154e363f6230f Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Thu, 15 Aug 2024 11:08:47 +0300 Subject: [PATCH 002/201] update makefile to match new dir sctructure --- services/registration/Makefile | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 services/registration/Makefile diff --git a/services/registration/Makefile b/services/registration/Makefile new file mode 100644 index 0000000..578ebc6 --- /dev/null +++ b/services/registration/Makefile @@ -0,0 +1,17 @@ +# Variables to match files in the current directory +INPUTS = $(wildcard ./*.vis) +TXTS = $(wildcard ./*.txt.orig) + +# Rule to build .bin files from .vis files +%.vis: + go run ../../go-vise/dev/asm $(basename $@).vis > $(basename $@).bin + @echo "Built $(basename $@).bin from $(basename $@).vis" + +# Rule to copy .orig files to .txt +%.txt.orig: + cp -v $(basename $@).orig $(basename $@) + @echo "Copied $(basename $@).orig to $(basename $@)" + +# 'all' target depends on all .vis and .txt.orig files +all: $(INPUTS) $(TXTS) + @echo "Running all: $(INPUTS) $(TXTS)" From 84da39628191a7cbe6bef91238cedd423af9ca15 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Thu, 15 Aug 2024 11:11:17 +0300 Subject: [PATCH 003/201] initialize templates and menu handling scripts --- services/registration/registration | 1 + services/registration/registration.vis | 7 +++++++ services/registration/registration_swa | 1 + services/registration/terms | 1 + services/registration/terms.vis | 2 ++ services/registration/terms_swa | 1 + 6 files changed, 13 insertions(+) create mode 100644 services/registration/registration create mode 100644 services/registration/registration.vis create mode 100644 services/registration/registration_swa create mode 100644 services/registration/terms create mode 100644 services/registration/terms.vis create mode 100644 services/registration/terms_swa diff --git a/services/registration/registration b/services/registration/registration new file mode 100644 index 0000000..3928a82 --- /dev/null +++ b/services/registration/registration @@ -0,0 +1 @@ +Welcome to Sarafu Network \ No newline at end of file diff --git a/services/registration/registration.vis b/services/registration/registration.vis new file mode 100644 index 0000000..65dc910 --- /dev/null +++ b/services/registration/registration.vis @@ -0,0 +1,7 @@ +LOAD select_language 0 +MOUT english 0 +MOUT kiswahili 1 +HALT +INCMP terms 0 +INCMP terms 1 +RELOAD select_language diff --git a/services/registration/registration_swa b/services/registration/registration_swa new file mode 100644 index 0000000..7edd566 --- /dev/null +++ b/services/registration/registration_swa @@ -0,0 +1 @@ +Karibu Sarafu Network \ No newline at end of file diff --git a/services/registration/terms b/services/registration/terms new file mode 100644 index 0000000..05b8c11 --- /dev/null +++ b/services/registration/terms @@ -0,0 +1 @@ +Do you agree to terms and conditions? \ No newline at end of file diff --git a/services/registration/terms.vis b/services/registration/terms.vis new file mode 100644 index 0000000..59b1e06 --- /dev/null +++ b/services/registration/terms.vis @@ -0,0 +1,2 @@ +MOUT yes 0 +MOUT no 1 diff --git a/services/registration/terms_swa b/services/registration/terms_swa new file mode 100644 index 0000000..7113cd7 --- /dev/null +++ b/services/registration/terms_swa @@ -0,0 +1 @@ +Kwa kutumia hii huduma umekubali sheria na masharti? \ No newline at end of file From 1e82d18604f3b68fb0854434a1e9f009254b3796 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Thu, 15 Aug 2024 11:12:58 +0300 Subject: [PATCH 004/201] initialize main entry point --- cmd/main.go | 87 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 cmd/main.go diff --git a/cmd/main.go b/cmd/main.go new file mode 100644 index 0000000..3ba7865 --- /dev/null +++ b/cmd/main.go @@ -0,0 +1,87 @@ +package main + +import ( + "context" + "flag" + "fmt" + "os" + "path" + "git.defalsify.org/vise.git/engine" + + "git.defalsify.org/vise.git/resource" + "git.defalsify.org/vise.git/state" +) + +const ( + USERFLAG_LANGUAGE_SET = iota + state.FLAG_USERSTART +) + +type fsData struct { + path string +} + +func (fsd *fsData) SetLanguageSelected(ctx context.Context, sym string, input []byte) (resource.Result, error) { + inputStr := string(input) + res := resource.Result{} + + switch inputStr { + case "0": + res.FlagSet = []uint32{state.FLAG_LANG} + res.Content = "eng" + case "1": + res.FlagSet = []uint32{state.FLAG_LANG} + res.Content = "swa" + default: + } + return res, nil +} + +func main() { + var dir string + var root string + var size uint + var sessionId string + var persist bool + flag.StringVar(&dir, "d", ".", "resource dir to read from") + flag.UintVar(&size, "s", 0, "max size of output") + flag.StringVar(&root, "root", "root", "entry point symbol") + flag.StringVar(&sessionId, "session-id", "default", "session id") + flag.BoolVar(&persist, "persist", false, "use state persistence") + flag.Parse() + fmt.Fprintf(os.Stderr, "starting session at symbol '%s' using resource dir: %s\n", root, dir) + + fp := path.Join(dir, sessionId) + fs := &fsData{ + path: fp, + } + + ctx := context.Background() + en, rs, err := engine.NewSizedEnginee(dir, uint32(size), persist, &sessionId) + rs.AddLocalFunc("select_language", fs.SetLanguageSelected) + + if err != nil { + fmt.Fprintf(os.Stderr, "engine create error: %v", err) + os.Exit(1) + } + cont, err := en.Init(ctx) + if err != nil { + fmt.Fprintf(os.Stderr, "engine init exited with error: %v\n", err) + os.Exit(1) + } + if !cont { + _, err = en.WriteResult(ctx, os.Stdout) + if err != nil { + fmt.Fprintf(os.Stderr, "dead init write error: %v\n", err) + os.Exit(1) + } + os.Stdout.Write([]byte{0x0a}) + os.Exit(0) + } + + err = engine.Loop(ctx, en, os.Stdin, os.Stdout) + if err != nil { + fmt.Fprintf(os.Stderr, "loop exited with error: %v\n", err) + os.Exit(1) + } + +} From b9baccb1e82c284c8a460754a1877714a101104a Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Thu, 15 Aug 2024 12:09:15 +0300 Subject: [PATCH 005/201] remove development files --- go.work | 7 ------- go.work.sum | 3 --- 2 files changed, 10 deletions(-) delete mode 100644 go.work delete mode 100644 go.work.sum diff --git a/go.work b/go.work deleted file mode 100644 index 9006f9f..0000000 --- a/go.work +++ /dev/null @@ -1,7 +0,0 @@ -go 1.22.6 - - -use ( - ./go-vise - . -) \ No newline at end of file diff --git a/go.work.sum b/go.work.sum deleted file mode 100644 index 35e0f01..0000000 --- a/go.work.sum +++ /dev/null @@ -1,3 +0,0 @@ -github.com/alecthomas/assert/v2 v2.2.2/go.mod h1:pXcQ2Asjp247dahGEmsZ6ru0UVwnkhktn7S0bBDLxvQ= -github.com/alecthomas/repr v0.2.0/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4= -github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg= From 87c8e83f596cc3b39a2d3223919c15aebe75f548 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Thu, 15 Aug 2024 12:10:51 +0300 Subject: [PATCH 006/201] ignore development files --- .gitignore | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 562e720..ddd3da6 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ **/*.env -covprofile \ No newline at end of file +covprofile +go.work* +services/registration/*.bin \ No newline at end of file From fb7b35af7461faaaaca997eaafda0890c8f96ed7 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Thu, 15 Aug 2024 13:49:36 +0300 Subject: [PATCH 007/201] directly use the persistedEngine --- .gitignore | 4 ++- cmd/main.go | 58 ++++++++++++++++++++++++--------- go-vise | 1 + services/registration/root | 1 + services/registration/root.vis | 5 +++ services/registration/root_swa | 1 + services/registration/terms.vis | 2 ++ 7 files changed, 55 insertions(+), 17 deletions(-) create mode 160000 go-vise create mode 100644 services/registration/root create mode 100644 services/registration/root.vis create mode 100644 services/registration/root_swa diff --git a/.gitignore b/.gitignore index ddd3da6..54ad3ff 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,6 @@ **/*.env covprofile go.work* -services/registration/*.bin \ No newline at end of file +**/*/*.bin +**/*/.state/ +cmd/.state/ diff --git a/cmd/main.go b/cmd/main.go index 3ba7865..d9b0692 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -6,8 +6,10 @@ import ( "fmt" "os" "path" - "git.defalsify.org/vise.git/engine" + "git.defalsify.org/vise.git/cache" + "git.defalsify.org/vise.git/engine" + "git.defalsify.org/vise.git/persist" "git.defalsify.org/vise.git/resource" "git.defalsify.org/vise.git/state" ) @@ -17,7 +19,7 @@ const ( ) type fsData struct { - path string + path string } func (fsd *fsData) SetLanguageSelected(ctx context.Context, sym string, input []byte) (resource.Result, error) { @@ -36,33 +38,54 @@ func (fsd *fsData) SetLanguageSelected(ctx context.Context, sym string, input [] return res, nil } +var ( + scriptDir = path.Join("services", "registration") +) + func main() { var dir string var root string var size uint var sessionId string - var persist bool flag.StringVar(&dir, "d", ".", "resource dir to read from") flag.UintVar(&size, "s", 0, "max size of output") flag.StringVar(&root, "root", "root", "entry point symbol") flag.StringVar(&sessionId, "session-id", "default", "session id") - flag.BoolVar(&persist, "persist", false, "use state persistence") flag.Parse() fmt.Fprintf(os.Stderr, "starting session at symbol '%s' using resource dir: %s\n", root, dir) - fp := path.Join(dir, sessionId) + ctx := context.Background() + st := state.NewState(3) + rfs := resource.NewFsResource(scriptDir) + ca := cache.NewCache() + cfg := engine.Config{ + Root: "root", + SessionId: sessionId, + } + + dp := path.Join(scriptDir, ".state") + err := os.MkdirAll(dp, 0700) + if err != nil { + fmt.Fprintf(os.Stderr, "state dir create exited with error: %v\n", err) + os.Exit(1) + } + pr := persist.NewFsPersister(dp) + en, err := engine.NewPersistedEngine(ctx, cfg, pr, rfs) + if err != nil { + pr = pr.WithContent(&st, ca) + err = pr.Save(cfg.SessionId) + en, err = engine.NewPersistedEngine(ctx, cfg, pr, rfs) + if err != nil { + fmt.Fprintf(os.Stderr, "engine create exited with error: %v\n", err) + os.Exit(1) + } + } + + fp := path.Join(dp, sessionId) fs := &fsData{ path: fp, } - - ctx := context.Background() - en, rs, err := engine.NewSizedEnginee(dir, uint32(size), persist, &sessionId) - rs.AddLocalFunc("select_language", fs.SetLanguageSelected) - - if err != nil { - fmt.Fprintf(os.Stderr, "engine create error: %v", err) - os.Exit(1) - } + rfs.AddLocalFunc("select_language", fs.SetLanguageSelected) cont, err := en.Init(ctx) if err != nil { fmt.Fprintf(os.Stderr, "engine init exited with error: %v\n", err) @@ -74,14 +97,17 @@ func main() { fmt.Fprintf(os.Stderr, "dead init write error: %v\n", err) os.Exit(1) } + err = en.Finish() + if err != nil { + fmt.Fprintf(os.Stderr, "engine finish error: %v\n", err) + os.Exit(1) + } os.Stdout.Write([]byte{0x0a}) os.Exit(0) } - err = engine.Loop(ctx, en, os.Stdin, os.Stdout) if err != nil { fmt.Fprintf(os.Stderr, "loop exited with error: %v\n", err) os.Exit(1) } - } diff --git a/go-vise b/go-vise new file mode 160000 index 0000000..ef9a4c3 --- /dev/null +++ b/go-vise @@ -0,0 +1 @@ +Subproject commit ef9a4c3073e7e878846693d4aa7fd0cf1cc977a7 diff --git a/services/registration/root b/services/registration/root new file mode 100644 index 0000000..c6dabe8 --- /dev/null +++ b/services/registration/root @@ -0,0 +1 @@ +Welcome to Sarafu Network! diff --git a/services/registration/root.vis b/services/registration/root.vis new file mode 100644 index 0000000..1017a0f --- /dev/null +++ b/services/registration/root.vis @@ -0,0 +1,5 @@ +MOUT english 0 +MOUT kiswahili 1 +HALT +INCMP terms 0 +INCMP terms 1 diff --git a/services/registration/root_swa b/services/registration/root_swa new file mode 100644 index 0000000..e5ab103 --- /dev/null +++ b/services/registration/root_swa @@ -0,0 +1 @@ +Karibu Sarafu Network! \ No newline at end of file diff --git a/services/registration/terms.vis b/services/registration/terms.vis index 59b1e06..572e7e8 100644 --- a/services/registration/terms.vis +++ b/services/registration/terms.vis @@ -1,2 +1,4 @@ +LOAD select_language 0 +RELOAD select_language MOUT yes 0 MOUT no 1 From a096d3f5b529a2fb2f1e6d7b3fa687ebbd8e556f Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Thu, 15 Aug 2024 14:58:44 +0300 Subject: [PATCH 008/201] change to use registration as the entry point --- cmd/main.go | 4 ++-- services/registration/registration | 2 +- services/registration/registration.vis | 2 -- 3 files changed, 3 insertions(+), 5 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index d9b0692..ebbfc75 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -49,7 +49,7 @@ func main() { var sessionId string flag.StringVar(&dir, "d", ".", "resource dir to read from") flag.UintVar(&size, "s", 0, "max size of output") - flag.StringVar(&root, "root", "root", "entry point symbol") + flag.StringVar(&root, "root", "registration", "entry point symbol") flag.StringVar(&sessionId, "session-id", "default", "session id") flag.Parse() fmt.Fprintf(os.Stderr, "starting session at symbol '%s' using resource dir: %s\n", root, dir) @@ -59,7 +59,7 @@ func main() { rfs := resource.NewFsResource(scriptDir) ca := cache.NewCache() cfg := engine.Config{ - Root: "root", + Root: "registration", SessionId: sessionId, } diff --git a/services/registration/registration b/services/registration/registration index 3928a82..01db78c 100644 --- a/services/registration/registration +++ b/services/registration/registration @@ -1 +1 @@ -Welcome to Sarafu Network \ No newline at end of file +Welcome to Sarafu Network registration \ No newline at end of file diff --git a/services/registration/registration.vis b/services/registration/registration.vis index 65dc910..1017a0f 100644 --- a/services/registration/registration.vis +++ b/services/registration/registration.vis @@ -1,7 +1,5 @@ -LOAD select_language 0 MOUT english 0 MOUT kiswahili 1 HALT INCMP terms 0 INCMP terms 1 -RELOAD select_language From 46b9e2eba91b8fea3e95e6a93947a75421b30885 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Thu, 15 Aug 2024 15:01:06 +0300 Subject: [PATCH 009/201] deleted the root files --- services/registration/root | 1 - services/registration/root.vis | 5 ----- services/registration/root_swa | 1 - 3 files changed, 7 deletions(-) delete mode 100644 services/registration/root delete mode 100644 services/registration/root.vis delete mode 100644 services/registration/root_swa diff --git a/services/registration/root b/services/registration/root deleted file mode 100644 index c6dabe8..0000000 --- a/services/registration/root +++ /dev/null @@ -1 +0,0 @@ -Welcome to Sarafu Network! diff --git a/services/registration/root.vis b/services/registration/root.vis deleted file mode 100644 index 1017a0f..0000000 --- a/services/registration/root.vis +++ /dev/null @@ -1,5 +0,0 @@ -MOUT english 0 -MOUT kiswahili 1 -HALT -INCMP terms 0 -INCMP terms 1 diff --git a/services/registration/root_swa b/services/registration/root_swa deleted file mode 100644 index e5ab103..0000000 --- a/services/registration/root_swa +++ /dev/null @@ -1 +0,0 @@ -Karibu Sarafu Network! \ No newline at end of file From 88731124df6219eac16c4b45e63adc7150d3c7be Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Fri, 16 Aug 2024 13:38:58 +0300 Subject: [PATCH 010/201] generate account using english and swahili --- cmd/main.go | 189 ++++++++++++++++++++- services/registration/account_creation | 1 + services/registration/account_creation.vis | 2 + services/registration/account_pending | 1 + services/registration/account_pending.vis | 3 + services/registration/account_pending_swa | 1 + services/registration/no_menu | 1 + services/registration/no_menu_swa | 1 + services/registration/profile | 2 + services/registration/profile.vis | 4 + services/registration/profile_swa | 2 + services/registration/registration | 2 +- services/registration/registration.vis | 9 +- services/registration/registration_swa | 2 +- services/registration/select_language | 2 + services/registration/select_language.vis | 5 + services/registration/terms.vis | 3 + services/registration/yes_menu | 1 + services/registration/yes_menu_swa | 1 + 19 files changed, 225 insertions(+), 7 deletions(-) create mode 100644 services/registration/account_creation create mode 100644 services/registration/account_creation.vis create mode 100644 services/registration/account_pending create mode 100644 services/registration/account_pending.vis create mode 100644 services/registration/account_pending_swa create mode 100644 services/registration/no_menu create mode 100644 services/registration/no_menu_swa create mode 100644 services/registration/profile create mode 100644 services/registration/profile.vis create mode 100644 services/registration/profile_swa create mode 100644 services/registration/select_language create mode 100644 services/registration/select_language.vis create mode 100644 services/registration/yes_menu create mode 100644 services/registration/yes_menu_swa diff --git a/cmd/main.go b/cmd/main.go index ebbfc75..6e75eec 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -2,10 +2,14 @@ package main import ( "context" + "encoding/json" "flag" "fmt" + "io" + "net/http" "os" "path" + "time" "git.defalsify.org/vise.git/cache" "git.defalsify.org/vise.git/engine" @@ -16,8 +20,38 @@ import ( const ( USERFLAG_LANGUAGE_SET = iota + state.FLAG_USERSTART + USERFLAG_ACCOUNT_CREATED + USERFLAG_ACCOUNT_PENDING + USERFLAG_ACCOUNT_SUCCESS ) +const ( + createAccountURL = "https://custodial.sarafu.africa/api/account/create" + trackStatusURL = "https://custodial.sarafu.africa/api/track/" +) + +type accountResponse struct { + Ok bool `json:"ok"` + Result struct { + CustodialId json.Number `json:"custodialId"` + PublicKey string `json:"publicKey"` + TrackingId string `json:"trackingId"` + } `json:"result"` +} + +type trackStatusResponse struct { + Ok bool `json:"ok"` + Result struct { + Transaction struct { + CreatedAt time.Time `json:"createdAt"` + Status string `json:"status"` + TransferValue json.Number `json:"transferValue"` + TxHash string `json:"txHash"` + TxType string `json:"txType"` + } + } `json:"result"` +} + type fsData struct { path string } @@ -35,9 +69,158 @@ func (fsd *fsData) SetLanguageSelected(ctx context.Context, sym string, input [] res.Content = "swa" default: } + + res.FlagSet = append(res.FlagSet, USERFLAG_LANGUAGE_SET) + return res, nil } +func (fsd *fsData) create_account(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + fp := fsd.path + "_data" + f, err := os.OpenFile(fp, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) + if err != nil { + return res, err + } + f.Close() + + accountResp, err := createAccount() + + if err != nil { + fmt.Println("Failed to create account:", err) + return res, err + } + + accountData := map[string]string{ + "TrackingId": accountResp.Result.TrackingId, + "PublicKey": accountResp.Result.PublicKey, + "CustodialId": accountResp.Result.CustodialId.String(), + "Status": "PENDING", + } + + jsonData, err := json.Marshal(accountData) + if err != nil { + return res, err + } + + err = os.WriteFile(fp, jsonData, 0644) + if err != nil { + return res, err + } + + res.FlagSet = []uint32{USERFLAG_ACCOUNT_CREATED} + return res, err +} + +func (fsd *fsData) checkIdentifier(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + fp := fsd.path + "_data" + + jsonData, err := os.ReadFile(fp) + if err != nil { + return res, err + } + + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return res, err + } + + res.Content = accountData["PublicKey"] + + return res, nil +} + +func (fsd *fsData) check_account_status(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + fp := fsd.path + "_data" + + jsonData, err := os.ReadFile(fp) + if err != nil { + return res, err + } + + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return res, err + } + + status, err := checkAccountStatus(accountData["TrackingId"]) + + if err != nil { + fmt.Println("Error checking account status:", err) + return res, nil + } + + accountData["Status"] = status + + if status == "SUCCESS" { + res.FlagSet = []uint32{USERFLAG_ACCOUNT_SUCCESS} + res.FlagReset = []uint32{USERFLAG_ACCOUNT_PENDING} + } else { + res.FlagSet = []uint32{USERFLAG_ACCOUNT_PENDING} + res.FlagReset = []uint32{USERFLAG_ACCOUNT_SUCCESS} + } + + updatedJsonData, err := json.Marshal(accountData) + if err != nil { + return res, err + } + + err = os.WriteFile(fp, updatedJsonData, 0644) + if err != nil { + return res, err + } + + return res, nil +} + +func createAccount() (*accountResponse, error) { + resp, err := http.Post(createAccountURL, "application/json", nil) + if err != nil { + return nil, err + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, err + } + + var accountResp accountResponse + err = json.Unmarshal(body, &accountResp) + if err != nil { + return nil, err + } + + return &accountResp, nil +} + +func checkAccountStatus(trackingId string) (string, error) { + resp, err := http.Get(trackStatusURL + trackingId) + if err != nil { + return "", err + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return "", err + } + + var trackResp trackStatusResponse + err = json.Unmarshal(body, &trackResp) + if err != nil { + return "", err + } + + status := trackResp.Result.Transaction.Status + + return status, nil +} + var ( scriptDir = path.Join("services", "registration") ) @@ -55,7 +238,7 @@ func main() { fmt.Fprintf(os.Stderr, "starting session at symbol '%s' using resource dir: %s\n", root, dir) ctx := context.Background() - st := state.NewState(3) + st := state.NewState(7) rfs := resource.NewFsResource(scriptDir) ca := cache.NewCache() cfg := engine.Config{ @@ -86,6 +269,10 @@ func main() { path: fp, } rfs.AddLocalFunc("select_language", fs.SetLanguageSelected) + rfs.AddLocalFunc("create_account", fs.create_account) + rfs.AddLocalFunc("check_identifier", fs.checkIdentifier) + rfs.AddLocalFunc("check_account_status", fs.check_account_status) + cont, err := en.Init(ctx) if err != nil { fmt.Fprintf(os.Stderr, "engine init exited with error: %v\n", err) diff --git a/services/registration/account_creation b/services/registration/account_creation new file mode 100644 index 0000000..e9463a6 --- /dev/null +++ b/services/registration/account_creation @@ -0,0 +1 @@ +Your account is being created... \ No newline at end of file diff --git a/services/registration/account_creation.vis b/services/registration/account_creation.vis new file mode 100644 index 0000000..3476cfc --- /dev/null +++ b/services/registration/account_creation.vis @@ -0,0 +1,2 @@ +LOAD create_account 0 +HALT diff --git a/services/registration/account_pending b/services/registration/account_pending new file mode 100644 index 0000000..4eadf25 --- /dev/null +++ b/services/registration/account_pending @@ -0,0 +1 @@ +Your account is still being created. \ No newline at end of file diff --git a/services/registration/account_pending.vis b/services/registration/account_pending.vis new file mode 100644 index 0000000..43b2dd4 --- /dev/null +++ b/services/registration/account_pending.vis @@ -0,0 +1,3 @@ +RELOAD check_account_status +CATCH profile 11 1 +HALT diff --git a/services/registration/account_pending_swa b/services/registration/account_pending_swa new file mode 100644 index 0000000..2e514b5 --- /dev/null +++ b/services/registration/account_pending_swa @@ -0,0 +1 @@ +Akaunti yako bado inatengenezwa \ No newline at end of file diff --git a/services/registration/no_menu b/services/registration/no_menu new file mode 100644 index 0000000..7ecb56e --- /dev/null +++ b/services/registration/no_menu @@ -0,0 +1 @@ +no diff --git a/services/registration/no_menu_swa b/services/registration/no_menu_swa new file mode 100644 index 0000000..2ece186 --- /dev/null +++ b/services/registration/no_menu_swa @@ -0,0 +1 @@ +la diff --git a/services/registration/profile b/services/registration/profile new file mode 100644 index 0000000..89144dd --- /dev/null +++ b/services/registration/profile @@ -0,0 +1,2 @@ +Welcome. Your account is +{{.check_identifier}} diff --git a/services/registration/profile.vis b/services/registration/profile.vis new file mode 100644 index 0000000..56dc044 --- /dev/null +++ b/services/registration/profile.vis @@ -0,0 +1,4 @@ +LOAD check_identifier 64 +RELOAD check_identifier +MAP check_identifier +HALT diff --git a/services/registration/profile_swa b/services/registration/profile_swa new file mode 100644 index 0000000..2738ff1 --- /dev/null +++ b/services/registration/profile_swa @@ -0,0 +1,2 @@ +Karibu. Akaunti yako ni +{{.check_identifier}} diff --git a/services/registration/registration b/services/registration/registration index 01db78c..3928a82 100644 --- a/services/registration/registration +++ b/services/registration/registration @@ -1 +1 @@ -Welcome to Sarafu Network registration \ No newline at end of file +Welcome to Sarafu Network \ No newline at end of file diff --git a/services/registration/registration.vis b/services/registration/registration.vis index 1017a0f..76fa921 100644 --- a/services/registration/registration.vis +++ b/services/registration/registration.vis @@ -1,5 +1,6 @@ -MOUT english 0 -MOUT kiswahili 1 +CATCH select_language 8 0 +CATCH terms 9 0 +CATCH account_pending 10 1 +CATCH profile 11 1 +LOAD check_account_status 0 HALT -INCMP terms 0 -INCMP terms 1 diff --git a/services/registration/registration_swa b/services/registration/registration_swa index 7edd566..75bb624 100644 --- a/services/registration/registration_swa +++ b/services/registration/registration_swa @@ -1 +1 @@ -Karibu Sarafu Network \ No newline at end of file +Karibu Sarafu Network \ No newline at end of file diff --git a/services/registration/select_language b/services/registration/select_language new file mode 100644 index 0000000..b3d4304 --- /dev/null +++ b/services/registration/select_language @@ -0,0 +1,2 @@ +Welcome to Sarafu Network +Please select a language \ No newline at end of file diff --git a/services/registration/select_language.vis b/services/registration/select_language.vis new file mode 100644 index 0000000..1017a0f --- /dev/null +++ b/services/registration/select_language.vis @@ -0,0 +1,5 @@ +MOUT english 0 +MOUT kiswahili 1 +HALT +INCMP terms 0 +INCMP terms 1 diff --git a/services/registration/terms.vis b/services/registration/terms.vis index 572e7e8..5375925 100644 --- a/services/registration/terms.vis +++ b/services/registration/terms.vis @@ -2,3 +2,6 @@ LOAD select_language 0 RELOAD select_language MOUT yes 0 MOUT no 1 +HALT +INCMP account_creation 0 +INCMP _ * diff --git a/services/registration/yes_menu b/services/registration/yes_menu new file mode 100644 index 0000000..7cfab5b --- /dev/null +++ b/services/registration/yes_menu @@ -0,0 +1 @@ +yes diff --git a/services/registration/yes_menu_swa b/services/registration/yes_menu_swa new file mode 100644 index 0000000..6908a6c --- /dev/null +++ b/services/registration/yes_menu_swa @@ -0,0 +1 @@ +ndio From 659e1c95a231df64b93dc783f5e8783181fa9f38 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Fri, 16 Aug 2024 17:57:36 +0300 Subject: [PATCH 011/201] change entry node to root --- cmd/main.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index 6e75eec..7d0dc58 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -232,7 +232,7 @@ func main() { var sessionId string flag.StringVar(&dir, "d", ".", "resource dir to read from") flag.UintVar(&size, "s", 0, "max size of output") - flag.StringVar(&root, "root", "registration", "entry point symbol") + flag.StringVar(&root, "root", "root", "entry point symbol") flag.StringVar(&sessionId, "session-id", "default", "session id") flag.Parse() fmt.Fprintf(os.Stderr, "starting session at symbol '%s' using resource dir: %s\n", root, dir) @@ -242,7 +242,7 @@ func main() { rfs := resource.NewFsResource(scriptDir) ca := cache.NewCache() cfg := engine.Config{ - Root: "registration", + Root: "root", SessionId: sessionId, } From 21bf571eedafbd2857217e241133e4e2229637c5 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Fri, 16 Aug 2024 18:17:55 +0300 Subject: [PATCH 012/201] chore: rename registration files to root --- services/registration/root | 1 + services/registration/root.vis | 6 ++++++ services/registration/root_swa | 1 + 3 files changed, 8 insertions(+) create mode 100644 services/registration/root create mode 100644 services/registration/root.vis create mode 100644 services/registration/root_swa diff --git a/services/registration/root b/services/registration/root new file mode 100644 index 0000000..3928a82 --- /dev/null +++ b/services/registration/root @@ -0,0 +1 @@ +Welcome to Sarafu Network \ No newline at end of file diff --git a/services/registration/root.vis b/services/registration/root.vis new file mode 100644 index 0000000..76fa921 --- /dev/null +++ b/services/registration/root.vis @@ -0,0 +1,6 @@ +CATCH select_language 8 0 +CATCH terms 9 0 +CATCH account_pending 10 1 +CATCH profile 11 1 +LOAD check_account_status 0 +HALT diff --git a/services/registration/root_swa b/services/registration/root_swa new file mode 100644 index 0000000..75bb624 --- /dev/null +++ b/services/registration/root_swa @@ -0,0 +1 @@ +Karibu Sarafu Network \ No newline at end of file From 951413cc03f74afcea73598f062b3816a504dcdc Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Fri, 16 Aug 2024 18:21:02 +0300 Subject: [PATCH 013/201] chore: remove registration files --- services/registration/registration | 1 - services/registration/registration.vis | 6 ------ services/registration/registration_swa | 1 - 3 files changed, 8 deletions(-) delete mode 100644 services/registration/registration delete mode 100644 services/registration/registration.vis delete mode 100644 services/registration/registration_swa diff --git a/services/registration/registration b/services/registration/registration deleted file mode 100644 index 3928a82..0000000 --- a/services/registration/registration +++ /dev/null @@ -1 +0,0 @@ -Welcome to Sarafu Network \ No newline at end of file diff --git a/services/registration/registration.vis b/services/registration/registration.vis deleted file mode 100644 index 76fa921..0000000 --- a/services/registration/registration.vis +++ /dev/null @@ -1,6 +0,0 @@ -CATCH select_language 8 0 -CATCH terms 9 0 -CATCH account_pending 10 1 -CATCH profile 11 1 -LOAD check_account_status 0 -HALT diff --git a/services/registration/registration_swa b/services/registration/registration_swa deleted file mode 100644 index 75bb624..0000000 --- a/services/registration/registration_swa +++ /dev/null @@ -1 +0,0 @@ -Karibu Sarafu Network \ No newline at end of file From 7afca54c54911cea4e7684522d6b658b0e3f27eb Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Sat, 17 Aug 2024 17:51:37 +0300 Subject: [PATCH 014/201] feat: add swahili and english send menu options --- services/registration/send_menu | 1 + services/registration/send_menu_swa | 1 + 2 files changed, 2 insertions(+) create mode 100644 services/registration/send_menu create mode 100644 services/registration/send_menu_swa diff --git a/services/registration/send_menu b/services/registration/send_menu new file mode 100644 index 0000000..5f5a837 --- /dev/null +++ b/services/registration/send_menu @@ -0,0 +1 @@ +Send \ No newline at end of file diff --git a/services/registration/send_menu_swa b/services/registration/send_menu_swa new file mode 100644 index 0000000..605c8e8 --- /dev/null +++ b/services/registration/send_menu_swa @@ -0,0 +1 @@ +Tuma \ No newline at end of file From e44c36cadbc7b3fe92296add1ae60f79aad5669a Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Sat, 17 Aug 2024 17:52:09 +0300 Subject: [PATCH 015/201] feat: add swahili and english help menu options --- services/registration/help_menu | 1 + services/registration/help_menu_swa | 1 + 2 files changed, 2 insertions(+) create mode 100644 services/registration/help_menu create mode 100644 services/registration/help_menu_swa diff --git a/services/registration/help_menu b/services/registration/help_menu new file mode 100644 index 0000000..0c64ced --- /dev/null +++ b/services/registration/help_menu @@ -0,0 +1 @@ +Help \ No newline at end of file diff --git a/services/registration/help_menu_swa b/services/registration/help_menu_swa new file mode 100644 index 0000000..393e0c8 --- /dev/null +++ b/services/registration/help_menu_swa @@ -0,0 +1 @@ +Usaidizi \ No newline at end of file From 2989b236b1569edd9bb16fc15d35b57240b2ddc1 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Sat, 17 Aug 2024 17:52:54 +0300 Subject: [PATCH 016/201] feat: add swahili and english voucher menu options --- services/registration/vouchers_menu | 1 + services/registration/vouchers_menu_swa | 1 + 2 files changed, 2 insertions(+) create mode 100644 services/registration/vouchers_menu create mode 100644 services/registration/vouchers_menu_swa diff --git a/services/registration/vouchers_menu b/services/registration/vouchers_menu new file mode 100644 index 0000000..5084c32 --- /dev/null +++ b/services/registration/vouchers_menu @@ -0,0 +1 @@ +My Vouchers \ No newline at end of file diff --git a/services/registration/vouchers_menu_swa b/services/registration/vouchers_menu_swa new file mode 100644 index 0000000..64ba54e --- /dev/null +++ b/services/registration/vouchers_menu_swa @@ -0,0 +1 @@ +Sarafu yangu \ No newline at end of file From 00926e66da4752ee6f4a14ff53ecf448b122fb83 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Sat, 17 Aug 2024 17:53:50 +0300 Subject: [PATCH 017/201] feat: add swahili and english account menu options --- services/registration/account_menu | 1 + services/registration/account_menu_swa | 1 + 2 files changed, 2 insertions(+) create mode 100644 services/registration/account_menu create mode 100644 services/registration/account_menu_swa diff --git a/services/registration/account_menu b/services/registration/account_menu new file mode 100644 index 0000000..7aa9fe9 --- /dev/null +++ b/services/registration/account_menu @@ -0,0 +1 @@ +My Account \ No newline at end of file diff --git a/services/registration/account_menu_swa b/services/registration/account_menu_swa new file mode 100644 index 0000000..c77102f --- /dev/null +++ b/services/registration/account_menu_swa @@ -0,0 +1 @@ +Akaunti yangu \ No newline at end of file From 9e3dfd2428aac4d9d7d953ce04379a8b93284710 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Sat, 17 Aug 2024 17:55:59 +0300 Subject: [PATCH 018/201] feat: register the profile menu options,show balances on profile page --- services/registration/profile | 4 ++-- services/registration/profile.vis | 5 +++++ services/registration/profile_swa | 3 +-- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/services/registration/profile b/services/registration/profile index 89144dd..5c1d929 100644 --- a/services/registration/profile +++ b/services/registration/profile @@ -1,2 +1,2 @@ -Welcome. Your account is -{{.check_identifier}} +Balance: 0.00 SRF + diff --git a/services/registration/profile.vis b/services/registration/profile.vis index 56dc044..5ed3357 100644 --- a/services/registration/profile.vis +++ b/services/registration/profile.vis @@ -1,4 +1,9 @@ LOAD check_identifier 64 RELOAD check_identifier MAP check_identifier +MOUT send 1 +MOUT vouchers 2 +MOUT account 3 +MOUT help 4 HALT + diff --git a/services/registration/profile_swa b/services/registration/profile_swa index 2738ff1..19eb750 100644 --- a/services/registration/profile_swa +++ b/services/registration/profile_swa @@ -1,2 +1 @@ -Karibu. Akaunti yako ni -{{.check_identifier}} +Salio: 0.00 SRF From 289fc2b69a16a38c422a94b9c49ddb07c6e601b0 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Sat, 17 Aug 2024 17:57:39 +0300 Subject: [PATCH 019/201] chore: log error when saving state fails --- cmd/main.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/cmd/main.go b/cmd/main.go index 7d0dc58..6219580 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -59,7 +59,6 @@ type fsData struct { func (fsd *fsData) SetLanguageSelected(ctx context.Context, sym string, input []byte) (resource.Result, error) { inputStr := string(input) res := resource.Result{} - switch inputStr { case "0": res.FlagSet = []uint32{state.FLAG_LANG} @@ -257,6 +256,9 @@ func main() { if err != nil { pr = pr.WithContent(&st, ca) err = pr.Save(cfg.SessionId) + if err != nil { + fmt.Fprintf(os.Stderr, "Failed to save state with error: %v\n", err) + } en, err = engine.NewPersistedEngine(ctx, cfg, pr, rfs) if err != nil { fmt.Fprintf(os.Stderr, "engine create exited with error: %v\n", err) From 3e764e79d803d52a3123380775f8e8d3e212f3a1 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Mon, 19 Aug 2024 09:55:56 +0300 Subject: [PATCH 020/201] Added swahili template for account_creation --- services/registration/account_creation_swa | 1 + 1 file changed, 1 insertion(+) create mode 100644 services/registration/account_creation_swa diff --git a/services/registration/account_creation_swa b/services/registration/account_creation_swa new file mode 100644 index 0000000..6e5b1e1 --- /dev/null +++ b/services/registration/account_creation_swa @@ -0,0 +1 @@ +Akaunti yako inatengenezwa... \ No newline at end of file From 4f41ff341dc7f2597dbc6f11c04d4ce91bf895fe Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Mon, 19 Aug 2024 10:11:10 +0300 Subject: [PATCH 021/201] add quit script for handling graceful quiting --- services/registration/quit.vis | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 services/registration/quit.vis diff --git a/services/registration/quit.vis b/services/registration/quit.vis new file mode 100644 index 0000000..0c8bb46 --- /dev/null +++ b/services/registration/quit.vis @@ -0,0 +1,2 @@ +LOAD quit 0 +HALT From f2f978196730448d829da53b79ae9615cd3f2aa3 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Mon, 19 Aug 2024 10:12:31 +0300 Subject: [PATCH 022/201] perform check account status before catching --- services/registration/root.vis | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/registration/root.vis b/services/registration/root.vis index 76fa921..ff42fca 100644 --- a/services/registration/root.vis +++ b/services/registration/root.vis @@ -1,6 +1,6 @@ CATCH select_language 8 0 CATCH terms 9 0 +LOAD check_account_status 0 CATCH account_pending 10 1 CATCH profile 11 1 -LOAD check_account_status 0 HALT From 0a37073c8da2b49015aa6f4fe5adbbc4b5e3e4a1 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Mon, 19 Aug 2024 10:13:51 +0300 Subject: [PATCH 023/201] add instruction to move to quit node --- services/registration/account_creation.vis | 1 + 1 file changed, 1 insertion(+) diff --git a/services/registration/account_creation.vis b/services/registration/account_creation.vis index 3476cfc..72f46dd 100644 --- a/services/registration/account_creation.vis +++ b/services/registration/account_creation.vis @@ -1,2 +1,3 @@ LOAD create_account 0 HALT +MOVE quit From 16ea648014b6be1746d0215ef8d777f711145030 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Mon, 19 Aug 2024 10:15:26 +0300 Subject: [PATCH 024/201] add handler for quiting and use debug on states --- cmd/main.go | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/cmd/main.go b/cmd/main.go index 6219580..6919975 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -220,6 +220,13 @@ func checkAccountStatus(trackingId string) (string, error) { return status, nil } +func (fsd *fsData) quit(ctx context.Context, sym string, input []byte) (resource.Result, error) { + return resource.Result{ + Content: "", + }, nil +} + + var ( scriptDir = path.Join("services", "registration") ) @@ -238,6 +245,7 @@ func main() { ctx := context.Background() st := state.NewState(7) + st.UseDebug() rfs := resource.NewFsResource(scriptDir) ca := cache.NewCache() cfg := engine.Config{ @@ -274,6 +282,7 @@ func main() { rfs.AddLocalFunc("create_account", fs.create_account) rfs.AddLocalFunc("check_identifier", fs.checkIdentifier) rfs.AddLocalFunc("check_account_status", fs.check_account_status) + rfs.AddLocalFunc("quit",fs.quit) cont, err := en.Init(ctx) if err != nil { From afe238003a9d5b6678925aae3c981fcea505ef17 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Mon, 19 Aug 2024 10:59:20 +0300 Subject: [PATCH 025/201] use strings for state flags --- cmd/main.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/cmd/main.go b/cmd/main.go index 6919975..af21dae 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -246,6 +246,12 @@ func main() { ctx := context.Background() st := state.NewState(7) st.UseDebug() + state.FlagDebugger.Register(USERFLAG_LANGUAGE_SET, "LANGUAGE_CHANGE") + state.FlagDebugger.Register(USERFLAG_ACCOUNT_CREATED,"ACCOUNT_CREATED") + state.FlagDebugger.Register(USERFLAG_ACCOUNT_SUCCESS,"ACCOUNT_SUCCESS") + state.FlagDebugger.Register(USERFLAG_ACCOUNT_PENDING,"ACCOUNT_PENDING") + + rfs := resource.NewFsResource(scriptDir) ca := cache.NewCache() cfg := engine.Config{ From 82bca5bd29cf2943279d35aad60834359c51f7c3 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Tue, 20 Aug 2024 16:51:15 +0300 Subject: [PATCH 026/201] add navigation node --- services/registration/account_pending.vis | 2 +- services/registration/address | 1 + services/registration/address.vis | 6 ++++++ services/registration/back_menu | 1 + services/registration/back_menu_swa | 1 + services/registration/balances | 1 + services/registration/balances.vis | 8 ++++++++ services/registration/balances_swa | 1 + services/registration/change_language_menu | 1 + services/registration/change_language_menu_swa | 1 + services/registration/change_pin_menu | 1 + services/registration/change_pin_menu_swa | 1 + services/registration/check_balance_menu | 1 + services/registration/check_balance_menu_swa | 1 + services/registration/check_statement_menu | 1 + services/registration/check_statement_menu_swa | 1 + services/registration/community_balance_menu | 1 + .../registration/community_balance_menu_swa | 1 + services/registration/default | Bin 0 -> 341 bytes services/registration/display_profile_info | 5 +++++ services/registration/display_profile_info.vis | 3 +++ services/registration/display_profile_info_swa | 0 services/registration/edit_gender_menu | 1 + services/registration/edit_gender_menu_swa | 1 + services/registration/edit_location_menu | 1 + services/registration/edit_location_menu_swa | 1 + services/registration/edit_name_menu | 1 + services/registration/edit_name_menu_swa | 1 + services/registration/edit_offerings_menu | 1 + services/registration/edit_offerings_menu_swa | 1 + services/registration/edit_profile | 1 + services/registration/edit_profile.vis | 17 +++++++++++++++++ services/registration/edit_profile_swa | 1 + services/registration/edit_yob_menu | 1 + services/registration/edit_yob_menu_swa | 1 + services/registration/enter_location | 1 + services/registration/enter_location.vis | 3 +++ services/registration/enter_location_swa | 1 + services/registration/enter_name | 1 + services/registration/enter_name.vis | 3 +++ services/registration/enter_name_swa | 1 + services/registration/enter_offerings | 1 + services/registration/enter_offerings.vis | 3 +++ services/registration/enter_offerings_swa | 1 + services/registration/enter_pin | 1 + services/registration/enter_pin.vis | 4 ++++ services/registration/enter_pin_swa | 1 + services/registration/enter_yob | 1 + services/registration/enter_yob.vis | 3 +++ services/registration/enter_yob_swa | 1 + services/registration/female_menu | 1 + services/registration/female_menu_swa | 1 + services/registration/guard_pin_menu | 1 + services/registration/guard_pin_menu_swa | 1 + services/registration/main | 2 ++ services/registration/main.vis | 9 +++++++++ services/registration/main_swa | 1 + services/registration/male_menu | 1 + services/registration/male_menu_swa | 1 + services/registration/my_account | 1 + services/registration/my_account.vis | 14 ++++++++++++++ services/registration/my_account_swa | 1 + services/registration/my_address_menu | 1 + services/registration/my_address_menu_swa | 1 + services/registration/my_balance | 1 + services/registration/my_balance.vis | 3 +++ services/registration/my_balance_menu | 1 + services/registration/my_balance_menu_swa | 1 + services/registration/my_balance_swa | 1 + services/registration/my_comminity_balance_swa | 1 + services/registration/my_community_balance | 2 ++ services/registration/my_community_balance.vis | 3 +++ services/registration/other_gender_menu | 1 + services/registration/other_gender_menu_swa | 1 + services/registration/pin_entry | 1 + services/registration/pin_entry.vis | 4 ++++ services/registration/pin_entry_swa | 1 + services/registration/pin_management | 1 + services/registration/pin_management.vis | 6 ++++++ services/registration/pin_management_swa | 0 services/registration/pin_options_menu | 1 + services/registration/pin_options_menu_swa | 1 + services/registration/profile_menu_swa | 1 + services/registration/reset_pin_menu | 1 + services/registration/reset_pin_menu_swa | 1 + services/registration/root.vis | 2 +- services/registration/select_gender | 1 + services/registration/select_gender.vis | 6 ++++++ services/registration/select_gender_swa | 1 + services/registration/view_menu | 1 + services/registration/view_profile.vis | 1 + services/registration/view_swa | 1 + 92 files changed, 174 insertions(+), 2 deletions(-) create mode 100644 services/registration/address create mode 100644 services/registration/address.vis create mode 100644 services/registration/back_menu create mode 100644 services/registration/back_menu_swa create mode 100644 services/registration/balances create mode 100644 services/registration/balances.vis create mode 100644 services/registration/balances_swa create mode 100644 services/registration/change_language_menu create mode 100644 services/registration/change_language_menu_swa create mode 100644 services/registration/change_pin_menu create mode 100644 services/registration/change_pin_menu_swa create mode 100644 services/registration/check_balance_menu create mode 100644 services/registration/check_balance_menu_swa create mode 100644 services/registration/check_statement_menu create mode 100644 services/registration/check_statement_menu_swa create mode 100644 services/registration/community_balance_menu create mode 100644 services/registration/community_balance_menu_swa create mode 100644 services/registration/default create mode 100644 services/registration/display_profile_info create mode 100644 services/registration/display_profile_info.vis create mode 100644 services/registration/display_profile_info_swa create mode 100644 services/registration/edit_gender_menu create mode 100644 services/registration/edit_gender_menu_swa create mode 100644 services/registration/edit_location_menu create mode 100644 services/registration/edit_location_menu_swa create mode 100644 services/registration/edit_name_menu create mode 100644 services/registration/edit_name_menu_swa create mode 100644 services/registration/edit_offerings_menu create mode 100644 services/registration/edit_offerings_menu_swa create mode 100644 services/registration/edit_profile create mode 100644 services/registration/edit_profile.vis create mode 100644 services/registration/edit_profile_swa create mode 100644 services/registration/edit_yob_menu create mode 100644 services/registration/edit_yob_menu_swa create mode 100644 services/registration/enter_location create mode 100644 services/registration/enter_location.vis create mode 100644 services/registration/enter_location_swa create mode 100644 services/registration/enter_name create mode 100644 services/registration/enter_name.vis create mode 100644 services/registration/enter_name_swa create mode 100644 services/registration/enter_offerings create mode 100644 services/registration/enter_offerings.vis create mode 100644 services/registration/enter_offerings_swa create mode 100644 services/registration/enter_pin create mode 100644 services/registration/enter_pin.vis create mode 100644 services/registration/enter_pin_swa create mode 100644 services/registration/enter_yob create mode 100644 services/registration/enter_yob.vis create mode 100644 services/registration/enter_yob_swa create mode 100644 services/registration/female_menu create mode 100644 services/registration/female_menu_swa create mode 100644 services/registration/guard_pin_menu create mode 100644 services/registration/guard_pin_menu_swa create mode 100644 services/registration/main create mode 100644 services/registration/main.vis create mode 100644 services/registration/main_swa create mode 100644 services/registration/male_menu create mode 100644 services/registration/male_menu_swa create mode 100644 services/registration/my_account create mode 100644 services/registration/my_account.vis create mode 100644 services/registration/my_account_swa create mode 100644 services/registration/my_address_menu create mode 100644 services/registration/my_address_menu_swa create mode 100644 services/registration/my_balance create mode 100644 services/registration/my_balance.vis create mode 100644 services/registration/my_balance_menu create mode 100644 services/registration/my_balance_menu_swa create mode 100644 services/registration/my_balance_swa create mode 100644 services/registration/my_comminity_balance_swa create mode 100644 services/registration/my_community_balance create mode 100644 services/registration/my_community_balance.vis create mode 100644 services/registration/other_gender_menu create mode 100644 services/registration/other_gender_menu_swa create mode 100644 services/registration/pin_entry create mode 100644 services/registration/pin_entry.vis create mode 100644 services/registration/pin_entry_swa create mode 100644 services/registration/pin_management create mode 100644 services/registration/pin_management.vis create mode 100644 services/registration/pin_management_swa create mode 100644 services/registration/pin_options_menu create mode 100644 services/registration/pin_options_menu_swa create mode 100644 services/registration/profile_menu_swa create mode 100644 services/registration/reset_pin_menu create mode 100644 services/registration/reset_pin_menu_swa create mode 100644 services/registration/select_gender create mode 100644 services/registration/select_gender.vis create mode 100644 services/registration/select_gender_swa create mode 100644 services/registration/view_menu create mode 100644 services/registration/view_profile.vis create mode 100644 services/registration/view_swa diff --git a/services/registration/account_pending.vis b/services/registration/account_pending.vis index 43b2dd4..19e308c 100644 --- a/services/registration/account_pending.vis +++ b/services/registration/account_pending.vis @@ -1,3 +1,3 @@ RELOAD check_account_status -CATCH profile 11 1 +CATCH main 11 1 HALT diff --git a/services/registration/address b/services/registration/address new file mode 100644 index 0000000..6353876 --- /dev/null +++ b/services/registration/address @@ -0,0 +1 @@ +Address: {{.check_identifier}} \ No newline at end of file diff --git a/services/registration/address.vis b/services/registration/address.vis new file mode 100644 index 0000000..d716499 --- /dev/null +++ b/services/registration/address.vis @@ -0,0 +1,6 @@ +LOAD check_identifier 0 +RELOAD check_identifier +MAP check_identifier +HALT +MOVE quit + diff --git a/services/registration/back_menu b/services/registration/back_menu new file mode 100644 index 0000000..2278c97 --- /dev/null +++ b/services/registration/back_menu @@ -0,0 +1 @@ +Back \ No newline at end of file diff --git a/services/registration/back_menu_swa b/services/registration/back_menu_swa new file mode 100644 index 0000000..751fb22 --- /dev/null +++ b/services/registration/back_menu_swa @@ -0,0 +1 @@ +Rudi diff --git a/services/registration/balances b/services/registration/balances new file mode 100644 index 0000000..697be51 --- /dev/null +++ b/services/registration/balances @@ -0,0 +1 @@ +Balances: diff --git a/services/registration/balances.vis b/services/registration/balances.vis new file mode 100644 index 0000000..e968325 --- /dev/null +++ b/services/registration/balances.vis @@ -0,0 +1,8 @@ +MOUT my_balance 1 +MOUT community_balance 2 +MOUT back 0 +HALT +INCMP ^ 0 +INCMP my_balance 1 +INCMP my_community_balance 2 + diff --git a/services/registration/balances_swa b/services/registration/balances_swa new file mode 100644 index 0000000..61a05a6 --- /dev/null +++ b/services/registration/balances_swa @@ -0,0 +1 @@ +Salio \ No newline at end of file diff --git a/services/registration/change_language_menu b/services/registration/change_language_menu new file mode 100644 index 0000000..7175fce --- /dev/null +++ b/services/registration/change_language_menu @@ -0,0 +1 @@ +Change language \ No newline at end of file diff --git a/services/registration/change_language_menu_swa b/services/registration/change_language_menu_swa new file mode 100644 index 0000000..02c46e1 --- /dev/null +++ b/services/registration/change_language_menu_swa @@ -0,0 +1 @@ +Badili lugha diff --git a/services/registration/change_pin_menu b/services/registration/change_pin_menu new file mode 100644 index 0000000..3ef432e --- /dev/null +++ b/services/registration/change_pin_menu @@ -0,0 +1 @@ +Change PIN diff --git a/services/registration/change_pin_menu_swa b/services/registration/change_pin_menu_swa new file mode 100644 index 0000000..cd48f9d --- /dev/null +++ b/services/registration/change_pin_menu_swa @@ -0,0 +1 @@ +Badili PIN diff --git a/services/registration/check_balance_menu b/services/registration/check_balance_menu new file mode 100644 index 0000000..253f368 --- /dev/null +++ b/services/registration/check_balance_menu @@ -0,0 +1 @@ +Check balances \ No newline at end of file diff --git a/services/registration/check_balance_menu_swa b/services/registration/check_balance_menu_swa new file mode 100644 index 0000000..4fe14f2 --- /dev/null +++ b/services/registration/check_balance_menu_swa @@ -0,0 +1 @@ +Angalia salio \ No newline at end of file diff --git a/services/registration/check_statement_menu b/services/registration/check_statement_menu new file mode 100644 index 0000000..f29634b --- /dev/null +++ b/services/registration/check_statement_menu @@ -0,0 +1 @@ +Check statement diff --git a/services/registration/check_statement_menu_swa b/services/registration/check_statement_menu_swa new file mode 100644 index 0000000..b8a338d --- /dev/null +++ b/services/registration/check_statement_menu_swa @@ -0,0 +1 @@ +Taarifa ya matumizi \ No newline at end of file diff --git a/services/registration/community_balance_menu b/services/registration/community_balance_menu new file mode 100644 index 0000000..3833589 --- /dev/null +++ b/services/registration/community_balance_menu @@ -0,0 +1 @@ +Community balance \ No newline at end of file diff --git a/services/registration/community_balance_menu_swa b/services/registration/community_balance_menu_swa new file mode 100644 index 0000000..726fc99 --- /dev/null +++ b/services/registration/community_balance_menu_swa @@ -0,0 +1 @@ +Salio la kikundi \ No newline at end of file diff --git a/services/registration/default b/services/registration/default new file mode 100644 index 0000000000000000000000000000000000000000..a2c29ede131370fcc852b5812b522b8fd8795697 GIT binary patch literal 341 zcmc(aK?=e!5JdxSJ%C$pA}tjJD?)KCL-L&j(gd0))umex;IYw(1#kW@6JzClGI2VVe`5RnI_0|A09ryLdL!Q2$O2~HMtkQ?!_BR CSdQNS literal 0 HcmV?d00001 diff --git a/services/registration/display_profile_info b/services/registration/display_profile_info new file mode 100644 index 0000000..669c6c6 --- /dev/null +++ b/services/registration/display_profile_info @@ -0,0 +1,5 @@ +Wasifu wangu +Name: Not provided +Gender: Not provided +Age: Not provided +Location: Not provided \ No newline at end of file diff --git a/services/registration/display_profile_info.vis b/services/registration/display_profile_info.vis new file mode 100644 index 0000000..07fcf94 --- /dev/null +++ b/services/registration/display_profile_info.vis @@ -0,0 +1,3 @@ +MOUT back 0 +HALT +INCMP ^ 0 diff --git a/services/registration/display_profile_info_swa b/services/registration/display_profile_info_swa new file mode 100644 index 0000000..e69de29 diff --git a/services/registration/edit_gender_menu b/services/registration/edit_gender_menu new file mode 100644 index 0000000..8946918 --- /dev/null +++ b/services/registration/edit_gender_menu @@ -0,0 +1 @@ +Edit gender \ No newline at end of file diff --git a/services/registration/edit_gender_menu_swa b/services/registration/edit_gender_menu_swa new file mode 100644 index 0000000..6d31ea8 --- /dev/null +++ b/services/registration/edit_gender_menu_swa @@ -0,0 +1 @@ +Weka jinsia \ No newline at end of file diff --git a/services/registration/edit_location_menu b/services/registration/edit_location_menu new file mode 100644 index 0000000..39ff1b7 --- /dev/null +++ b/services/registration/edit_location_menu @@ -0,0 +1 @@ +Edit location \ No newline at end of file diff --git a/services/registration/edit_location_menu_swa b/services/registration/edit_location_menu_swa new file mode 100644 index 0000000..a2a0e59 --- /dev/null +++ b/services/registration/edit_location_menu_swa @@ -0,0 +1 @@ +Weka eneo \ No newline at end of file diff --git a/services/registration/edit_name_menu b/services/registration/edit_name_menu new file mode 100644 index 0000000..63d97b9 --- /dev/null +++ b/services/registration/edit_name_menu @@ -0,0 +1 @@ +Edit name diff --git a/services/registration/edit_name_menu_swa b/services/registration/edit_name_menu_swa new file mode 100644 index 0000000..c50424f --- /dev/null +++ b/services/registration/edit_name_menu_swa @@ -0,0 +1 @@ +Weka jina diff --git a/services/registration/edit_offerings_menu b/services/registration/edit_offerings_menu new file mode 100644 index 0000000..74563b2 --- /dev/null +++ b/services/registration/edit_offerings_menu @@ -0,0 +1 @@ +Edit offerings diff --git a/services/registration/edit_offerings_menu_swa b/services/registration/edit_offerings_menu_swa new file mode 100644 index 0000000..f37e125 --- /dev/null +++ b/services/registration/edit_offerings_menu_swa @@ -0,0 +1 @@ +Weka unachouza \ No newline at end of file diff --git a/services/registration/edit_profile b/services/registration/edit_profile new file mode 100644 index 0000000..2c808e6 --- /dev/null +++ b/services/registration/edit_profile @@ -0,0 +1 @@ +My profile \ No newline at end of file diff --git a/services/registration/edit_profile.vis b/services/registration/edit_profile.vis new file mode 100644 index 0000000..b454820 --- /dev/null +++ b/services/registration/edit_profile.vis @@ -0,0 +1,17 @@ +MOUT edit_name 1 +MOUT edit_gender 2 +MOUT edit_yob 3 +MOUT edit_location 4 +MOUT edit_offerings 5 +MOUT view 6 +MOUT back 0 +HALT +INCMP ^ 0 +INCMP enter_name 1 +INCMP select_gender 2 +INCMP enter_yob 3 +INCMP enter_location 4 +INCMP enter_offerings 5 +INCMP view_profile 6 + + diff --git a/services/registration/edit_profile_swa b/services/registration/edit_profile_swa new file mode 100644 index 0000000..8a12b7d --- /dev/null +++ b/services/registration/edit_profile_swa @@ -0,0 +1 @@ +Wasifu wangu \ No newline at end of file diff --git a/services/registration/edit_yob_menu b/services/registration/edit_yob_menu new file mode 100644 index 0000000..3451781 --- /dev/null +++ b/services/registration/edit_yob_menu @@ -0,0 +1 @@ +Edit year of birth \ No newline at end of file diff --git a/services/registration/edit_yob_menu_swa b/services/registration/edit_yob_menu_swa new file mode 100644 index 0000000..9bb272a --- /dev/null +++ b/services/registration/edit_yob_menu_swa @@ -0,0 +1 @@ +Weka mwaka wa kuzaliwa \ No newline at end of file diff --git a/services/registration/enter_location b/services/registration/enter_location new file mode 100644 index 0000000..da0e148 --- /dev/null +++ b/services/registration/enter_location @@ -0,0 +1 @@ +Enter your location: diff --git a/services/registration/enter_location.vis b/services/registration/enter_location.vis new file mode 100644 index 0000000..07fcf94 --- /dev/null +++ b/services/registration/enter_location.vis @@ -0,0 +1,3 @@ +MOUT back 0 +HALT +INCMP ^ 0 diff --git a/services/registration/enter_location_swa b/services/registration/enter_location_swa new file mode 100644 index 0000000..41682a2 --- /dev/null +++ b/services/registration/enter_location_swa @@ -0,0 +1 @@ +Weka eneo: \ No newline at end of file diff --git a/services/registration/enter_name b/services/registration/enter_name new file mode 100644 index 0000000..c6851cf --- /dev/null +++ b/services/registration/enter_name @@ -0,0 +1 @@ +Enter your first names: \ No newline at end of file diff --git a/services/registration/enter_name.vis b/services/registration/enter_name.vis new file mode 100644 index 0000000..07fcf94 --- /dev/null +++ b/services/registration/enter_name.vis @@ -0,0 +1,3 @@ +MOUT back 0 +HALT +INCMP ^ 0 diff --git a/services/registration/enter_name_swa b/services/registration/enter_name_swa new file mode 100644 index 0000000..db04d35 --- /dev/null +++ b/services/registration/enter_name_swa @@ -0,0 +1 @@ +Weka majina yako ya kwanza: diff --git a/services/registration/enter_offerings b/services/registration/enter_offerings new file mode 100644 index 0000000..a9333ba --- /dev/null +++ b/services/registration/enter_offerings @@ -0,0 +1 @@ +Enter the services or goods you offer: \ No newline at end of file diff --git a/services/registration/enter_offerings.vis b/services/registration/enter_offerings.vis new file mode 100644 index 0000000..07fcf94 --- /dev/null +++ b/services/registration/enter_offerings.vis @@ -0,0 +1,3 @@ +MOUT back 0 +HALT +INCMP ^ 0 diff --git a/services/registration/enter_offerings_swa b/services/registration/enter_offerings_swa new file mode 100644 index 0000000..f37e125 --- /dev/null +++ b/services/registration/enter_offerings_swa @@ -0,0 +1 @@ +Weka unachouza \ No newline at end of file diff --git a/services/registration/enter_pin b/services/registration/enter_pin new file mode 100644 index 0000000..cbb44ca --- /dev/null +++ b/services/registration/enter_pin @@ -0,0 +1 @@ +Please enter your PIN: \ No newline at end of file diff --git a/services/registration/enter_pin.vis b/services/registration/enter_pin.vis new file mode 100644 index 0000000..f9f06b9 --- /dev/null +++ b/services/registration/enter_pin.vis @@ -0,0 +1,4 @@ +MOUT back 0 +HALT +INCMP ^ 0 +INCMP display_profile_info * diff --git a/services/registration/enter_pin_swa b/services/registration/enter_pin_swa new file mode 100644 index 0000000..bb30cfd --- /dev/null +++ b/services/registration/enter_pin_swa @@ -0,0 +1 @@ +Weka PIN yako \ No newline at end of file diff --git a/services/registration/enter_yob b/services/registration/enter_yob new file mode 100644 index 0000000..54e039e --- /dev/null +++ b/services/registration/enter_yob @@ -0,0 +1 @@ +Enter your year of birth \ No newline at end of file diff --git a/services/registration/enter_yob.vis b/services/registration/enter_yob.vis new file mode 100644 index 0000000..07fcf94 --- /dev/null +++ b/services/registration/enter_yob.vis @@ -0,0 +1,3 @@ +MOUT back 0 +HALT +INCMP ^ 0 diff --git a/services/registration/enter_yob_swa b/services/registration/enter_yob_swa new file mode 100644 index 0000000..9bb272a --- /dev/null +++ b/services/registration/enter_yob_swa @@ -0,0 +1 @@ +Weka mwaka wa kuzaliwa \ No newline at end of file diff --git a/services/registration/female_menu b/services/registration/female_menu new file mode 100644 index 0000000..b26600f --- /dev/null +++ b/services/registration/female_menu @@ -0,0 +1 @@ +Female diff --git a/services/registration/female_menu_swa b/services/registration/female_menu_swa new file mode 100644 index 0000000..0506300 --- /dev/null +++ b/services/registration/female_menu_swa @@ -0,0 +1 @@ +Mwanamke \ No newline at end of file diff --git a/services/registration/guard_pin_menu b/services/registration/guard_pin_menu new file mode 100644 index 0000000..63ff8dd --- /dev/null +++ b/services/registration/guard_pin_menu @@ -0,0 +1 @@ +Guard my PIN diff --git a/services/registration/guard_pin_menu_swa b/services/registration/guard_pin_menu_swa new file mode 100644 index 0000000..e6f30d4 --- /dev/null +++ b/services/registration/guard_pin_menu_swa @@ -0,0 +1 @@ +Linda PIN yangu diff --git a/services/registration/main b/services/registration/main new file mode 100644 index 0000000..5c1d929 --- /dev/null +++ b/services/registration/main @@ -0,0 +1,2 @@ +Balance: 0.00 SRF + diff --git a/services/registration/main.vis b/services/registration/main.vis new file mode 100644 index 0000000..477e80a --- /dev/null +++ b/services/registration/main.vis @@ -0,0 +1,9 @@ +LOAD check_identifier 64 +RELOAD check_identifier +MAP check_identifier +MOUT send 1 +MOUT vouchers 2 +MOUT account 3 +MOUT help 4 +HALT +INCMP my_account 3 diff --git a/services/registration/main_swa b/services/registration/main_swa new file mode 100644 index 0000000..19eb750 --- /dev/null +++ b/services/registration/main_swa @@ -0,0 +1 @@ +Salio: 0.00 SRF diff --git a/services/registration/male_menu b/services/registration/male_menu new file mode 100644 index 0000000..183883f --- /dev/null +++ b/services/registration/male_menu @@ -0,0 +1 @@ +Male \ No newline at end of file diff --git a/services/registration/male_menu_swa b/services/registration/male_menu_swa new file mode 100644 index 0000000..7afdee9 --- /dev/null +++ b/services/registration/male_menu_swa @@ -0,0 +1 @@ +Mwanaume \ No newline at end of file diff --git a/services/registration/my_account b/services/registration/my_account new file mode 100644 index 0000000..7aa9fe9 --- /dev/null +++ b/services/registration/my_account @@ -0,0 +1 @@ +My Account \ No newline at end of file diff --git a/services/registration/my_account.vis b/services/registration/my_account.vis new file mode 100644 index 0000000..0232e06 --- /dev/null +++ b/services/registration/my_account.vis @@ -0,0 +1,14 @@ +MOUT profile 1 +MOUT change_language 2 +MOUT check_balance 3 +MOUT check_statement 4 +MOUT pin_options 5 +MOUT my_address 6 +MOUT back 0 +HALT +INCMP ^ 0 +INCMP edit_profile 1 +INCMP balances 3 +INCMP pin_management 5 +INCMP address 6 + diff --git a/services/registration/my_account_swa b/services/registration/my_account_swa new file mode 100644 index 0000000..c77102f --- /dev/null +++ b/services/registration/my_account_swa @@ -0,0 +1 @@ +Akaunti yangu \ No newline at end of file diff --git a/services/registration/my_address_menu b/services/registration/my_address_menu new file mode 100644 index 0000000..5c13a7d --- /dev/null +++ b/services/registration/my_address_menu @@ -0,0 +1 @@ +My Address \ No newline at end of file diff --git a/services/registration/my_address_menu_swa b/services/registration/my_address_menu_swa new file mode 100644 index 0000000..8ec744e --- /dev/null +++ b/services/registration/my_address_menu_swa @@ -0,0 +1 @@ +Anwani yangu diff --git a/services/registration/my_balance b/services/registration/my_balance new file mode 100644 index 0000000..15c5901 --- /dev/null +++ b/services/registration/my_balance @@ -0,0 +1 @@ +Your balance is: 0.00 SRF \ No newline at end of file diff --git a/services/registration/my_balance.vis b/services/registration/my_balance.vis new file mode 100644 index 0000000..90c3937 --- /dev/null +++ b/services/registration/my_balance.vis @@ -0,0 +1,3 @@ +CATCH pin_entry 12 0 +HALT +MOVE quit diff --git a/services/registration/my_balance_menu b/services/registration/my_balance_menu new file mode 100644 index 0000000..fdd930b --- /dev/null +++ b/services/registration/my_balance_menu @@ -0,0 +1 @@ +My balance \ No newline at end of file diff --git a/services/registration/my_balance_menu_swa b/services/registration/my_balance_menu_swa new file mode 100644 index 0000000..810c386 --- /dev/null +++ b/services/registration/my_balance_menu_swa @@ -0,0 +1 @@ +Salio langu \ No newline at end of file diff --git a/services/registration/my_balance_swa b/services/registration/my_balance_swa new file mode 100644 index 0000000..3f6741f --- /dev/null +++ b/services/registration/my_balance_swa @@ -0,0 +1 @@ +Salio lako ni: 0.00 SRF diff --git a/services/registration/my_comminity_balance_swa b/services/registration/my_comminity_balance_swa new file mode 100644 index 0000000..726fc99 --- /dev/null +++ b/services/registration/my_comminity_balance_swa @@ -0,0 +1 @@ +Salio la kikundi \ No newline at end of file diff --git a/services/registration/my_community_balance b/services/registration/my_community_balance new file mode 100644 index 0000000..e79d40a --- /dev/null +++ b/services/registration/my_community_balance @@ -0,0 +1,2 @@ +Your community balance is: 0.00SRF + diff --git a/services/registration/my_community_balance.vis b/services/registration/my_community_balance.vis new file mode 100644 index 0000000..90c3937 --- /dev/null +++ b/services/registration/my_community_balance.vis @@ -0,0 +1,3 @@ +CATCH pin_entry 12 0 +HALT +MOVE quit diff --git a/services/registration/other_gender_menu b/services/registration/other_gender_menu new file mode 100644 index 0000000..2212621 --- /dev/null +++ b/services/registration/other_gender_menu @@ -0,0 +1 @@ +Other \ No newline at end of file diff --git a/services/registration/other_gender_menu_swa b/services/registration/other_gender_menu_swa new file mode 100644 index 0000000..28ac5ec --- /dev/null +++ b/services/registration/other_gender_menu_swa @@ -0,0 +1 @@ +Nyingineo \ No newline at end of file diff --git a/services/registration/pin_entry b/services/registration/pin_entry new file mode 100644 index 0000000..cbb44ca --- /dev/null +++ b/services/registration/pin_entry @@ -0,0 +1 @@ +Please enter your PIN: \ No newline at end of file diff --git a/services/registration/pin_entry.vis b/services/registration/pin_entry.vis new file mode 100644 index 0000000..b991017 --- /dev/null +++ b/services/registration/pin_entry.vis @@ -0,0 +1,4 @@ +LOAD unlock_account 0 +HALT +RELOAD unlock_account +INCMP _ * diff --git a/services/registration/pin_entry_swa b/services/registration/pin_entry_swa new file mode 100644 index 0000000..bffbf0f --- /dev/null +++ b/services/registration/pin_entry_swa @@ -0,0 +1 @@ +Tafadhali weka PIN yako diff --git a/services/registration/pin_management b/services/registration/pin_management new file mode 100644 index 0000000..876d1f7 --- /dev/null +++ b/services/registration/pin_management @@ -0,0 +1 @@ +PIN Management diff --git a/services/registration/pin_management.vis b/services/registration/pin_management.vis new file mode 100644 index 0000000..0e40b9f --- /dev/null +++ b/services/registration/pin_management.vis @@ -0,0 +1,6 @@ +MOUT change_pin 1 +MOUT reset_pin 2 +MOUT guard_pin 3 +MOUT back 0 +HALT +INCMP ^ 0 diff --git a/services/registration/pin_management_swa b/services/registration/pin_management_swa new file mode 100644 index 0000000..e69de29 diff --git a/services/registration/pin_options_menu b/services/registration/pin_options_menu new file mode 100644 index 0000000..778d28d --- /dev/null +++ b/services/registration/pin_options_menu @@ -0,0 +1 @@ +PIN options \ No newline at end of file diff --git a/services/registration/pin_options_menu_swa b/services/registration/pin_options_menu_swa new file mode 100644 index 0000000..e47ca0f --- /dev/null +++ b/services/registration/pin_options_menu_swa @@ -0,0 +1 @@ +Mipangilio ya PIN \ No newline at end of file diff --git a/services/registration/profile_menu_swa b/services/registration/profile_menu_swa new file mode 100644 index 0000000..b34a86b --- /dev/null +++ b/services/registration/profile_menu_swa @@ -0,0 +1 @@ +Wasifu wangu diff --git a/services/registration/reset_pin_menu b/services/registration/reset_pin_menu new file mode 100644 index 0000000..1f5d676 --- /dev/null +++ b/services/registration/reset_pin_menu @@ -0,0 +1 @@ +Reset other's PIN \ No newline at end of file diff --git a/services/registration/reset_pin_menu_swa b/services/registration/reset_pin_menu_swa new file mode 100644 index 0000000..d17e316 --- /dev/null +++ b/services/registration/reset_pin_menu_swa @@ -0,0 +1 @@ +Badili PIN ya mwenzio diff --git a/services/registration/root.vis b/services/registration/root.vis index ff42fca..f3e6216 100644 --- a/services/registration/root.vis +++ b/services/registration/root.vis @@ -2,5 +2,5 @@ CATCH select_language 8 0 CATCH terms 9 0 LOAD check_account_status 0 CATCH account_pending 10 1 -CATCH profile 11 1 +CATCH main 11 1 HALT diff --git a/services/registration/select_gender b/services/registration/select_gender new file mode 100644 index 0000000..f8a6f47 --- /dev/null +++ b/services/registration/select_gender @@ -0,0 +1 @@ +Select gender: \ No newline at end of file diff --git a/services/registration/select_gender.vis b/services/registration/select_gender.vis new file mode 100644 index 0000000..e30f71e --- /dev/null +++ b/services/registration/select_gender.vis @@ -0,0 +1,6 @@ +MOUT male 1 +MOUT female 2 +MOUT other_gender 3 +MOUT back 0 +HALT +INCMP ^ 0 diff --git a/services/registration/select_gender_swa b/services/registration/select_gender_swa new file mode 100644 index 0000000..2b3a748 --- /dev/null +++ b/services/registration/select_gender_swa @@ -0,0 +1 @@ +Chagua jinsia \ No newline at end of file diff --git a/services/registration/view_menu b/services/registration/view_menu new file mode 100644 index 0000000..03add31 --- /dev/null +++ b/services/registration/view_menu @@ -0,0 +1 @@ +View profile \ No newline at end of file diff --git a/services/registration/view_profile.vis b/services/registration/view_profile.vis new file mode 100644 index 0000000..72e55ad --- /dev/null +++ b/services/registration/view_profile.vis @@ -0,0 +1 @@ +HALT diff --git a/services/registration/view_swa b/services/registration/view_swa new file mode 100644 index 0000000..7483b4b --- /dev/null +++ b/services/registration/view_swa @@ -0,0 +1 @@ +Angalia Wasifu From 7ba5815375a3e54b19bf16e03f9a3b90f5671a6a Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Tue, 20 Aug 2024 16:52:09 +0300 Subject: [PATCH 027/201] add menu option --- services/registration/profile_menu | 1 + 1 file changed, 1 insertion(+) create mode 100644 services/registration/profile_menu diff --git a/services/registration/profile_menu b/services/registration/profile_menu new file mode 100644 index 0000000..99455ed --- /dev/null +++ b/services/registration/profile_menu @@ -0,0 +1 @@ +Profile From 277e85ef74a5d64fa0319f8a68c65f8637567df9 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Tue, 20 Aug 2024 16:53:09 +0300 Subject: [PATCH 028/201] remove unused nodes --- services/registration/profile | 2 -- services/registration/profile.vis | 9 --------- services/registration/profile_swa | 1 - 3 files changed, 12 deletions(-) delete mode 100644 services/registration/profile delete mode 100644 services/registration/profile.vis delete mode 100644 services/registration/profile_swa diff --git a/services/registration/profile b/services/registration/profile deleted file mode 100644 index 5c1d929..0000000 --- a/services/registration/profile +++ /dev/null @@ -1,2 +0,0 @@ -Balance: 0.00 SRF - diff --git a/services/registration/profile.vis b/services/registration/profile.vis deleted file mode 100644 index 5ed3357..0000000 --- a/services/registration/profile.vis +++ /dev/null @@ -1,9 +0,0 @@ -LOAD check_identifier 64 -RELOAD check_identifier -MAP check_identifier -MOUT send 1 -MOUT vouchers 2 -MOUT account 3 -MOUT help 4 -HALT - diff --git a/services/registration/profile_swa b/services/registration/profile_swa deleted file mode 100644 index 19eb750..0000000 --- a/services/registration/profile_swa +++ /dev/null @@ -1 +0,0 @@ -Salio: 0.00 SRF From be6c0d6afbe764a42ab07679c2746ef071fc09b3 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Tue, 20 Aug 2024 16:55:43 +0300 Subject: [PATCH 029/201] add pin unlock flag --- cmd/main.go | 60 +++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 49 insertions(+), 11 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index af21dae..5ae7928 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -23,6 +23,7 @@ const ( USERFLAG_ACCOUNT_CREATED USERFLAG_ACCOUNT_PENDING USERFLAG_ACCOUNT_SUCCESS + USERFLAG_ACCOUNT_UNLOCKED ) const ( @@ -54,6 +55,7 @@ type trackStatusResponse struct { type fsData struct { path string + st *state.State } func (fsd *fsData) SetLanguageSelected(ctx context.Context, sym string, input []byte) (resource.Result, error) { @@ -83,12 +85,24 @@ func (fsd *fsData) create_account(ctx context.Context, sym string, input []byte) } f.Close() - accountResp, err := createAccount() + // accountResp, err := createAccount() - if err != nil { - fmt.Println("Failed to create account:", err) - return res, err - } + // if err != nil { + // fmt.Println("Failed to create account:", err) + // return res, err + // } + + accountResp := accountResponse{ + Ok: true, + Result: struct { + CustodialId json.Number `json:"custodialId"` + PublicKey string `json:"publicKey"` + TrackingId string `json:"trackingId"` + }{ + CustodialId: "636", + PublicKey: "0x8d86F9D4A4eae41Dc3B68034895EA97BcA90e8c1", + TrackingId: "45c67314-7995-4890-89d6-e5af987754ac", + }} accountData := map[string]string{ "TrackingId": accountResp.Result.TrackingId, @@ -131,6 +145,18 @@ func (fsd *fsData) checkIdentifier(ctx context.Context, sym string, input []byte return res, nil } + +func (fsd *fsData) unlock(ctx context.Context,sym string,input []byte) (resource.Result,error){ + res := resource.Result{} + //res.FlagSet = []uint32{USERFLAG_ACCOUNT_UNLOCKED} + if fsd.st.MatchFlag(USERFLAG_ACCOUNT_UNLOCKED, false) { + res.FlagSet = append(res.FlagSet, USERFLAG_ACCOUNT_UNLOCKED) + } else { + res.FlagReset = append(res.FlagReset, USERFLAG_ACCOUNT_UNLOCKED) + } + return res,nil +} + func (fsd *fsData) check_account_status(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} fp := fsd.path + "_data" @@ -156,13 +182,15 @@ func (fsd *fsData) check_account_status(ctx context.Context, sym string, input [ accountData["Status"] = status if status == "SUCCESS" { - res.FlagSet = []uint32{USERFLAG_ACCOUNT_SUCCESS} - res.FlagReset = []uint32{USERFLAG_ACCOUNT_PENDING} + res.FlagSet = append(res.FlagSet, USERFLAG_ACCOUNT_SUCCESS) + res.FlagReset = append(res.FlagReset,USERFLAG_ACCOUNT_PENDING) } else { - res.FlagSet = []uint32{USERFLAG_ACCOUNT_PENDING} - res.FlagReset = []uint32{USERFLAG_ACCOUNT_SUCCESS} + res.FlagReset = append(res.FlagSet, USERFLAG_ACCOUNT_SUCCESS) + res.FlagSet = append(res.FlagReset,USERFLAG_ACCOUNT_PENDING) } + + updatedJsonData, err := json.Marshal(accountData) if err != nil { return res, err @@ -221,9 +249,17 @@ func checkAccountStatus(trackingId string) (string, error) { } func (fsd *fsData) quit(ctx context.Context, sym string, input []byte) (resource.Result, error) { - return resource.Result{ + res := resource.Result{ Content: "", - }, nil + } + st := fsd.st + if(st.MatchFlag(USERFLAG_ACCOUNT_UNLOCKED,true)){ + //res.FlagReset = []uint32{USERFLAG_ACCOUNT_UNLOCKED} + // res.FlagReset = append(res.FlagReset, USERFLAG_ACCOUNT_UNLOCKED) + }else { + res.FlagReset = append(res.FlagReset, USERFLAG_ACCOUNT_UNLOCKED) + } + return res, nil } @@ -283,11 +319,13 @@ func main() { fp := path.Join(dp, sessionId) fs := &fsData{ path: fp, + st: &st, } rfs.AddLocalFunc("select_language", fs.SetLanguageSelected) rfs.AddLocalFunc("create_account", fs.create_account) rfs.AddLocalFunc("check_identifier", fs.checkIdentifier) rfs.AddLocalFunc("check_account_status", fs.check_account_status) + rfs.AddLocalFunc("unlock_account", fs.unlock) rfs.AddLocalFunc("quit",fs.quit) cont, err := en.Init(ctx) From d76063261a0258db475b0360acd001067e673f44 Mon Sep 17 00:00:00 2001 From: carlos Date: Tue, 20 Aug 2024 15:58:13 +0200 Subject: [PATCH 030/201] Delete services/registration/default --- services/registration/default | Bin 341 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 services/registration/default diff --git a/services/registration/default b/services/registration/default deleted file mode 100644 index a2c29ede131370fcc852b5812b522b8fd8795697..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 341 zcmc(aK?=e!5JdxSJ%C$pA}tjJD?)KCL-L&j(gd0))umex;IYw(1#kW@6JzClGI2VVe`5RnI_0|A09ryLdL!Q2$O2~HMtkQ?!_BR CSdQNS From e4ebb02b77190a1499168cd040f5bdd43c913927 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Mon, 19 Aug 2024 13:36:17 +0300 Subject: [PATCH 031/201] Added main template and check balance --- cmd/main.go | 49 ++++++++++++++++++++++++++++++++++ go-vise | 2 +- services/registration/main | 3 +-- services/registration/main.vis | 12 ++++++--- services/registration/main_swa | 2 +- 5 files changed, 61 insertions(+), 7 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index 5ae7928..d408f9f 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -29,6 +29,7 @@ const ( const ( createAccountURL = "https://custodial.sarafu.africa/api/account/create" trackStatusURL = "https://custodial.sarafu.africa/api/track/" + checkBalanceURL = "https://custodial.sarafu.africa/api/account/status/" ) type accountResponse struct { @@ -53,6 +54,14 @@ type trackStatusResponse struct { } `json:"result"` } +type balanceResponse struct { + Ok bool `json:"ok"` + Result struct { + Balance string `json:"balance"` + Nonce json.Number `json:"nonce"` + } `json:"result"` +} + type fsData struct { path string st *state.State @@ -262,6 +271,45 @@ func (fsd *fsData) quit(ctx context.Context, sym string, input []byte) (resourc return res, nil } +func (fsd *fsData) checkBalance(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + + fp := fsd.path + "_data" + + jsonData, err := os.ReadFile(fp) + if err != nil { + return res, err + } + + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return res, err + } + + resp, err := http.Get(checkBalanceURL + accountData["PublicKey"]) + if err != nil { + return res, nil + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return res, nil + } + + var balanceResp balanceResponse + err = json.Unmarshal(body, &balanceResp) + if err != nil { + return res, nil + } + + balance := balanceResp.Result.Balance + + res.Content = balance + + return res, nil +} var ( scriptDir = path.Join("services", "registration") @@ -327,6 +375,7 @@ func main() { rfs.AddLocalFunc("check_account_status", fs.check_account_status) rfs.AddLocalFunc("unlock_account", fs.unlock) rfs.AddLocalFunc("quit",fs.quit) + rfs.AddLocalFunc("check_balance", fs.checkBalance) cont, err := en.Init(ctx) if err != nil { diff --git a/go-vise b/go-vise index ef9a4c3..1f47a67 160000 --- a/go-vise +++ b/go-vise @@ -1 +1 @@ -Subproject commit ef9a4c3073e7e878846693d4aa7fd0cf1cc977a7 +Subproject commit 1f47a674d95380be8c387f410f0342eb72357df5 diff --git a/services/registration/main b/services/registration/main index 5c1d929..bf15ea5 100644 --- a/services/registration/main +++ b/services/registration/main @@ -1,2 +1 @@ -Balance: 0.00 SRF - +Balance: {{.check_balance}} diff --git a/services/registration/main.vis b/services/registration/main.vis index 477e80a..ae46d5e 100644 --- a/services/registration/main.vis +++ b/services/registration/main.vis @@ -1,9 +1,15 @@ -LOAD check_identifier 64 -RELOAD check_identifier -MAP check_identifier +LOAD check_balance 64 +RELOAD check_balance +MAP check_balance MOUT send 1 MOUT vouchers 2 MOUT account 3 MOUT help 4 +MOUT quit 9 HALT +INCMP send 1 +INCMP vouchers 2 INCMP my_account 3 +INCMP help 4 +INCMP quit 9 +INCMP . * diff --git a/services/registration/main_swa b/services/registration/main_swa index 19eb750..b72abf0 100644 --- a/services/registration/main_swa +++ b/services/registration/main_swa @@ -1 +1 @@ -Salio: 0.00 SRF +Salio: {{.check_balance}} From fc1b9e5bfa43a615620a7c41380d042997876f6b Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Tue, 20 Aug 2024 10:14:36 +0300 Subject: [PATCH 032/201] Added send menu with srecipient input --- services/registration/invalid_recipient | 1 + services/registration/invalid_recipient.vis | 7 +++++++ services/registration/invalid_recipient_swa | 1 + services/registration/send | 1 + services/registration/send.vis | 7 +++++++ services/registration/send_swa | 1 + 6 files changed, 18 insertions(+) create mode 100644 services/registration/invalid_recipient create mode 100644 services/registration/invalid_recipient.vis create mode 100644 services/registration/invalid_recipient_swa create mode 100644 services/registration/send create mode 100644 services/registration/send.vis create mode 100644 services/registration/send_swa diff --git a/services/registration/invalid_recipient b/services/registration/invalid_recipient new file mode 100644 index 0000000..6231e76 --- /dev/null +++ b/services/registration/invalid_recipient @@ -0,0 +1 @@ +{{.send_transaction}} is not registered or invalid, please try again: \ No newline at end of file diff --git a/services/registration/invalid_recipient.vis b/services/registration/invalid_recipient.vis new file mode 100644 index 0000000..87454cf --- /dev/null +++ b/services/registration/invalid_recipient.vis @@ -0,0 +1,7 @@ +MAP send_transaction +LOAD transaction_reset 0 +MOUT retry 1 +MOUT quit 9 +HALT +INCMP send 1 +INCMP quit 9 diff --git a/services/registration/invalid_recipient_swa b/services/registration/invalid_recipient_swa new file mode 100644 index 0000000..b19e53f --- /dev/null +++ b/services/registration/invalid_recipient_swa @@ -0,0 +1 @@ +{{.send_transaction}} haijasajiliwa au sio sahihi, tafadhali weka tena: \ No newline at end of file diff --git a/services/registration/send b/services/registration/send new file mode 100644 index 0000000..2d5ad69 --- /dev/null +++ b/services/registration/send @@ -0,0 +1 @@ +Enter recipient's phone number: diff --git a/services/registration/send.vis b/services/registration/send.vis new file mode 100644 index 0000000..2e1479b --- /dev/null +++ b/services/registration/send.vis @@ -0,0 +1,7 @@ +LOAD transaction_reset 0 +MOUT back 0 +HALT +INCMP ^ 0 +LOAD send_transaction 0 +MAP send_transaction +MOVE invalid_recipient diff --git a/services/registration/send_swa b/services/registration/send_swa new file mode 100644 index 0000000..016760e --- /dev/null +++ b/services/registration/send_swa @@ -0,0 +1 @@ +Weka nambari ya simu: \ No newline at end of file From 231967b120c42e03d4dfc54b474a02d0b4aa4fba Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Tue, 20 Aug 2024 10:15:33 +0300 Subject: [PATCH 033/201] added recipient flags and functions --- cmd/main.go | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/cmd/main.go b/cmd/main.go index d408f9f..22ba037 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -24,6 +24,8 @@ const ( USERFLAG_ACCOUNT_PENDING USERFLAG_ACCOUNT_SUCCESS USERFLAG_ACCOUNT_UNLOCKED + invalidRecipient + invalidRecipientWithInvite ) const ( @@ -311,6 +313,22 @@ func (fsd *fsData) checkBalance(ctx context.Context, sym string, input []byte) ( return res, nil } +func(fsd *fsData) send_transaction(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + recipient := string(input) + + res.FlagSet = []uint32{invalidRecipient} + res.Content = recipient + + return res, nil +} + +func(fsd *fsData) transaction_reset(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + res.FlagReset = []uint32{invalidRecipient} + return res, nil +} + var ( scriptDir = path.Join("services", "registration") ) @@ -376,6 +394,8 @@ func main() { rfs.AddLocalFunc("unlock_account", fs.unlock) rfs.AddLocalFunc("quit",fs.quit) rfs.AddLocalFunc("check_balance", fs.checkBalance) + rfs.AddLocalFunc("send_transaction", fs.send_transaction) + rfs.AddLocalFunc("transaction_reset", fs.transaction_reset) cont, err := en.Init(ctx) if err != nil { From 59ff44214d8da4920cbfa8d48497953a9acf62a7 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Tue, 20 Aug 2024 15:09:02 +0300 Subject: [PATCH 034/201] save the recipient to the user data --- cmd/main.go | 78 +++++++++++++++++++-- services/registration/amount | 2 + services/registration/amount.vis | 6 ++ services/registration/amount_swa | 0 services/registration/invalid_recipient | 2 +- services/registration/invalid_recipient.vis | 2 +- services/registration/invalid_recipient_swa | 2 +- services/registration/send.vis | 6 +- 8 files changed, 88 insertions(+), 10 deletions(-) create mode 100644 services/registration/amount create mode 100644 services/registration/amount.vis create mode 100644 services/registration/amount_swa diff --git a/cmd/main.go b/cmd/main.go index 22ba037..7824218 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -313,19 +313,88 @@ func (fsd *fsData) checkBalance(ctx context.Context, sym string, input []byte) ( return res, nil } -func(fsd *fsData) send_transaction(ctx context.Context, sym string, input []byte) (resource.Result, error) { +func(fsd *fsData) validate_recipient(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} recipient := string(input) - res.FlagSet = []uint32{invalidRecipient} - res.Content = recipient + res.FlagReset = []uint32{invalidRecipient} + res.FlagReset = []uint32{invalidRecipientWithInvite} + + fp := fsd.path + "_data" + + jsonData, err := os.ReadFile(fp) + if err != nil { + return res, err + } + + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return res, err + } + + // mimic invalid number check + if recipient == "000" { + res.FlagSet = []uint32{invalidRecipient} + res.Content = recipient + + return res, nil + } + + accountData["Recipient"] = recipient + + updatedJsonData, err := json.Marshal(accountData) + if err != nil { + return res, err + } + + err = os.WriteFile(fp, updatedJsonData, 0644) + if err != nil { + return res, err + } return res, nil } func(fsd *fsData) transaction_reset(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} + fp := fsd.path + "_data" + + jsonData, err := os.ReadFile(fp) + if err != nil { + return res, err + } + + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return res, err + } + + // reset the recipient + accountData["Recipient"] = "" + + updatedJsonData, err := json.Marshal(accountData) + if err != nil { + return res, err + } + + err = os.WriteFile(fp, updatedJsonData, 0644) + if err != nil { + return res, err + } + res.FlagReset = []uint32{invalidRecipient} + res.FlagReset = []uint32{invalidRecipientWithInvite} + return res, nil +} + +func(fsd *fsData) max_amount(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + + // mimic a max amount + res.Content = "10.00" + return res, nil } @@ -394,8 +463,9 @@ func main() { rfs.AddLocalFunc("unlock_account", fs.unlock) rfs.AddLocalFunc("quit",fs.quit) rfs.AddLocalFunc("check_balance", fs.checkBalance) - rfs.AddLocalFunc("send_transaction", fs.send_transaction) + rfs.AddLocalFunc("validate_recipient", fs.validate_recipient) rfs.AddLocalFunc("transaction_reset", fs.transaction_reset) + rfs.AddLocalFunc("max_amount", fs.max_amount) cont, err := en.Init(ctx) if err != nil { diff --git a/services/registration/amount b/services/registration/amount new file mode 100644 index 0000000..9142aba --- /dev/null +++ b/services/registration/amount @@ -0,0 +1,2 @@ +Maximum amount: {{.max_amount}} +Enter amount: \ No newline at end of file diff --git a/services/registration/amount.vis b/services/registration/amount.vis new file mode 100644 index 0000000..4923a89 --- /dev/null +++ b/services/registration/amount.vis @@ -0,0 +1,6 @@ +LOAD max_amount 0 +MAP max_amount +MOUT back 0 +HALT +INCMP ^ 0 +INCMP quit * diff --git a/services/registration/amount_swa b/services/registration/amount_swa new file mode 100644 index 0000000..e69de29 diff --git a/services/registration/invalid_recipient b/services/registration/invalid_recipient index 6231e76..0be78bd 100644 --- a/services/registration/invalid_recipient +++ b/services/registration/invalid_recipient @@ -1 +1 @@ -{{.send_transaction}} is not registered or invalid, please try again: \ No newline at end of file +{{.validate_recipient}} is not registered or invalid, please try again: \ No newline at end of file diff --git a/services/registration/invalid_recipient.vis b/services/registration/invalid_recipient.vis index 87454cf..6f4e6b5 100644 --- a/services/registration/invalid_recipient.vis +++ b/services/registration/invalid_recipient.vis @@ -1,4 +1,4 @@ -MAP send_transaction +MAP validate_recipient LOAD transaction_reset 0 MOUT retry 1 MOUT quit 9 diff --git a/services/registration/invalid_recipient_swa b/services/registration/invalid_recipient_swa index b19e53f..39e7804 100644 --- a/services/registration/invalid_recipient_swa +++ b/services/registration/invalid_recipient_swa @@ -1 +1 @@ -{{.send_transaction}} haijasajiliwa au sio sahihi, tafadhali weka tena: \ No newline at end of file +{{.validate_recipient}} haijasajiliwa au sio sahihi, tafadhali weka tena: \ No newline at end of file diff --git a/services/registration/send.vis b/services/registration/send.vis index 2e1479b..a3b79d9 100644 --- a/services/registration/send.vis +++ b/services/registration/send.vis @@ -2,6 +2,6 @@ LOAD transaction_reset 0 MOUT back 0 HALT INCMP ^ 0 -LOAD send_transaction 0 -MAP send_transaction -MOVE invalid_recipient +LOAD validate_recipient 0 +MAP validate_recipient +MOVE amount From 1964623daa0d83005c54911d48ea4d068a7260d9 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Tue, 20 Aug 2024 16:25:57 +0300 Subject: [PATCH 035/201] retrieve transaction data and display the PIN page --- cmd/main.go | 106 +++++++++++++++++++--- services/registration/amount.vis | 5 +- services/registration/select_language.vis | 1 + services/registration/transaction_pin | 2 + services/registration/transaction_pin.vis | 11 +++ services/registration/transaction_pin_swa | 2 + 6 files changed, 115 insertions(+), 12 deletions(-) create mode 100644 services/registration/transaction_pin create mode 100644 services/registration/transaction_pin.vis create mode 100644 services/registration/transaction_pin_swa diff --git a/cmd/main.go b/cmd/main.go index 7824218..3a06b81 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -59,8 +59,8 @@ type trackStatusResponse struct { type balanceResponse struct { Ok bool `json:"ok"` Result struct { - Balance string `json:"balance"` - Nonce json.Number `json:"nonce"` + Balance string `json:"balance"` + Nonce json.Number `json:"nonce"` } `json:"result"` } @@ -313,7 +313,7 @@ func (fsd *fsData) checkBalance(ctx context.Context, sym string, input []byte) ( return res, nil } -func(fsd *fsData) validate_recipient(ctx context.Context, sym string, input []byte) (resource.Result, error) { +func (fsd *fsData) validate_recipient(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} recipient := string(input) @@ -356,7 +356,7 @@ func(fsd *fsData) validate_recipient(ctx context.Context, sym string, input []by return res, nil } -func(fsd *fsData) transaction_reset(ctx context.Context, sym string, input []byte) (resource.Result, error) { +func (fsd *fsData) transaction_reset(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} fp := fsd.path + "_data" @@ -389,12 +389,94 @@ func(fsd *fsData) transaction_reset(ctx context.Context, sym string, input []byt return res, nil } -func(fsd *fsData) max_amount(ctx context.Context, sym string, input []byte) (resource.Result, error) { +func (fsd *fsData) max_amount(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} // mimic a max amount res.Content = "10.00" - + + return res, nil +} + +func (fsd *fsData) validate_amount(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + amount := string(input) + + fp := fsd.path + "_data" + + jsonData, err := os.ReadFile(fp) + if err != nil { + return res, err + } + + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return res, err + } + + // mimic invalid amount check + if amount == "0" { + // res.FlagSet = []uint32{invalidAmount} + res.Content = amount + + return res, nil + } + + res.Content = amount + + accountData["Amount"] = amount + + updatedJsonData, err := json.Marshal(accountData) + if err != nil { + return res, err + } + + err = os.WriteFile(fp, updatedJsonData, 0644) + if err != nil { + return res, err + } + + return res, nil +} + +func (fsd *fsData) get_recipient(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + fp := fsd.path + "_data" + + jsonData, err := os.ReadFile(fp) + if err != nil { + return res, err + } + + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return res, err + } + + res.Content = accountData["Recipient"] + + return res, nil +} + +func (fsd *fsData) get_sender(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + fp := fsd.path + "_data" + + jsonData, err := os.ReadFile(fp) + if err != nil { + return res, err + } + + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return res, err + } + + res.Content = accountData["PublicKey"] + return res, nil } @@ -418,10 +500,9 @@ func main() { st := state.NewState(7) st.UseDebug() state.FlagDebugger.Register(USERFLAG_LANGUAGE_SET, "LANGUAGE_CHANGE") - state.FlagDebugger.Register(USERFLAG_ACCOUNT_CREATED,"ACCOUNT_CREATED") - state.FlagDebugger.Register(USERFLAG_ACCOUNT_SUCCESS,"ACCOUNT_SUCCESS") - state.FlagDebugger.Register(USERFLAG_ACCOUNT_PENDING,"ACCOUNT_PENDING") - + state.FlagDebugger.Register(USERFLAG_ACCOUNT_CREATED, "ACCOUNT_CREATED") + state.FlagDebugger.Register(USERFLAG_ACCOUNT_SUCCESS, "ACCOUNT_SUCCESS") + state.FlagDebugger.Register(USERFLAG_ACCOUNT_PENDING, "ACCOUNT_PENDING") rfs := resource.NewFsResource(scriptDir) ca := cache.NewCache() @@ -461,11 +542,14 @@ func main() { rfs.AddLocalFunc("check_identifier", fs.checkIdentifier) rfs.AddLocalFunc("check_account_status", fs.check_account_status) rfs.AddLocalFunc("unlock_account", fs.unlock) - rfs.AddLocalFunc("quit",fs.quit) + rfs.AddLocalFunc("quit", fs.quit) rfs.AddLocalFunc("check_balance", fs.checkBalance) rfs.AddLocalFunc("validate_recipient", fs.validate_recipient) rfs.AddLocalFunc("transaction_reset", fs.transaction_reset) rfs.AddLocalFunc("max_amount", fs.max_amount) + rfs.AddLocalFunc("validate_amount", fs.validate_amount) + rfs.AddLocalFunc("get_recipient", fs.get_recipient) + rfs.AddLocalFunc("get_sender", fs.get_sender) cont, err := en.Init(ctx) if err != nil { diff --git a/services/registration/amount.vis b/services/registration/amount.vis index 4923a89..a4cffe6 100644 --- a/services/registration/amount.vis +++ b/services/registration/amount.vis @@ -3,4 +3,7 @@ MAP max_amount MOUT back 0 HALT INCMP ^ 0 -INCMP quit * +LOAD validate_amount 0 +LOAD get_recipient 12 +LOAD get_sender 64 +MOVE transaction_pin diff --git a/services/registration/select_language.vis b/services/registration/select_language.vis index 1017a0f..1dd92ae 100644 --- a/services/registration/select_language.vis +++ b/services/registration/select_language.vis @@ -3,3 +3,4 @@ MOUT kiswahili 1 HALT INCMP terms 0 INCMP terms 1 +INCMP . * diff --git a/services/registration/transaction_pin b/services/registration/transaction_pin new file mode 100644 index 0000000..39a1206 --- /dev/null +++ b/services/registration/transaction_pin @@ -0,0 +1,2 @@ +{{.get_recipient}} will receive {{.validate_amount}} from {{.get_sender}} +Please enter your PIN to confirm: diff --git a/services/registration/transaction_pin.vis b/services/registration/transaction_pin.vis new file mode 100644 index 0000000..9020e90 --- /dev/null +++ b/services/registration/transaction_pin.vis @@ -0,0 +1,11 @@ +RELOAD validate_amount +MAP validate_amount +RELOAD get_recipient +MAP get_recipient +RELOAD get_sender +MAP get_sender +MOUT back 0 +MOUT quit 9 +HALT +INCMP ^ 0 +INCMP quit 9 diff --git a/services/registration/transaction_pin_swa b/services/registration/transaction_pin_swa new file mode 100644 index 0000000..8529f0e --- /dev/null +++ b/services/registration/transaction_pin_swa @@ -0,0 +1,2 @@ +{{.get_recipient}} atapokea {{.validate_amount}} kutoka kwa {{.get_sender}} +Tafadhali weka PIN yako kudhibitisha: \ No newline at end of file From cc6cfc864607bc762c79eaf7b089b4241f84fee7 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Wed, 21 Aug 2024 20:30:59 +0300 Subject: [PATCH 036/201] validate a recipient --- cmd/main.go | 41 ++++++++++----------- services/registration/amount.vis | 10 +++-- services/registration/invalid_recipient.vis | 2 +- services/registration/send.vis | 7 ++-- services/registration/transaction_pin.vis | 2 +- 5 files changed, 31 insertions(+), 31 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index 3a06b81..07e966f 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -24,8 +24,8 @@ const ( USERFLAG_ACCOUNT_PENDING USERFLAG_ACCOUNT_SUCCESS USERFLAG_ACCOUNT_UNLOCKED - invalidRecipient - invalidRecipientWithInvite + USERFLAG_INVALID_RECIPIENT + USERFLAG_INVALID_RECIPIENT_WITH_INVITE ) const ( @@ -317,9 +317,6 @@ func (fsd *fsData) validate_recipient(ctx context.Context, sym string, input []b res := resource.Result{} recipient := string(input) - res.FlagReset = []uint32{invalidRecipient} - res.FlagReset = []uint32{invalidRecipientWithInvite} - fp := fsd.path + "_data" jsonData, err := os.ReadFile(fp) @@ -333,24 +330,26 @@ func (fsd *fsData) validate_recipient(ctx context.Context, sym string, input []b return res, err } - // mimic invalid number check - if recipient == "000" { - res.FlagSet = []uint32{invalidRecipient} - res.Content = recipient + if recipient != "0" { + // mimic invalid number check + if recipient == "000" { + res.FlagSet = append(res.FlagSet, USERFLAG_INVALID_RECIPIENT) + res.Content = recipient - return res, nil - } + return res, nil + } - accountData["Recipient"] = recipient + accountData["Recipient"] = recipient - updatedJsonData, err := json.Marshal(accountData) - if err != nil { - return res, err - } + updatedJsonData, err := json.Marshal(accountData) + if err != nil { + return res, err + } - err = os.WriteFile(fp, updatedJsonData, 0644) - if err != nil { - return res, err + err = os.WriteFile(fp, updatedJsonData, 0644) + if err != nil { + return res, err + } } return res, nil @@ -384,8 +383,8 @@ func (fsd *fsData) transaction_reset(ctx context.Context, sym string, input []by return res, err } - res.FlagReset = []uint32{invalidRecipient} - res.FlagReset = []uint32{invalidRecipientWithInvite} + res.FlagReset = append(res.FlagReset, USERFLAG_INVALID_RECIPIENT, USERFLAG_INVALID_RECIPIENT_WITH_INVITE) + return res, nil } diff --git a/services/registration/amount.vis b/services/registration/amount.vis index a4cffe6..ef1dd76 100644 --- a/services/registration/amount.vis +++ b/services/registration/amount.vis @@ -1,9 +1,11 @@ -LOAD max_amount 0 +RELOAD validate_recipient +CATCH invalid_recipient 13 1 +LOAD max_amount 10 MAP max_amount MOUT back 0 HALT -INCMP ^ 0 -LOAD validate_amount 0 +INCMP _ 0 +LOAD validate_amount 64 LOAD get_recipient 12 LOAD get_sender 64 -MOVE transaction_pin +INCMP transaction_pin * diff --git a/services/registration/invalid_recipient.vis b/services/registration/invalid_recipient.vis index 6f4e6b5..905ad2a 100644 --- a/services/registration/invalid_recipient.vis +++ b/services/registration/invalid_recipient.vis @@ -1,5 +1,5 @@ MAP validate_recipient -LOAD transaction_reset 0 +RELOAD transaction_reset MOUT retry 1 MOUT quit 9 HALT diff --git a/services/registration/send.vis b/services/registration/send.vis index a3b79d9..25d6304 100644 --- a/services/registration/send.vis +++ b/services/registration/send.vis @@ -1,7 +1,6 @@ LOAD transaction_reset 0 MOUT back 0 HALT -INCMP ^ 0 -LOAD validate_recipient 0 -MAP validate_recipient -MOVE amount +LOAD validate_recipient 20 +INCMP _ 0 +INCMP amount * diff --git a/services/registration/transaction_pin.vis b/services/registration/transaction_pin.vis index 9020e90..c63c2d8 100644 --- a/services/registration/transaction_pin.vis +++ b/services/registration/transaction_pin.vis @@ -7,5 +7,5 @@ MAP get_sender MOUT back 0 MOUT quit 9 HALT -INCMP ^ 0 +INCMP _ 0 INCMP quit 9 From 80ff5c477faa1c5131c39b457571cec93daa2156 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Wed, 21 Aug 2024 21:37:29 +0300 Subject: [PATCH 037/201] implement pin check --- cmd/main.go | 128 ++++++++++++------ services/registration/account_creation.vis | 3 +- services/registration/balances.vis | 2 +- ...nity_balance_swa => comminity_balance_swa} | 0 ...my_community_balance => community_balance} | 0 services/registration/community_balance.vis | 6 + services/registration/enter_pin.vis | 2 +- services/registration/incorrect_pin | 1 + services/registration/incorrect_pin.vis | 7 + services/registration/incorrect_pin_swa | 1 + services/registration/my_balance.vis | 5 +- .../registration/my_community_balance.vis | 3 - 12 files changed, 113 insertions(+), 45 deletions(-) rename services/registration/{my_comminity_balance_swa => comminity_balance_swa} (100%) rename services/registration/{my_community_balance => community_balance} (100%) create mode 100644 services/registration/community_balance.vis create mode 100644 services/registration/incorrect_pin create mode 100644 services/registration/incorrect_pin.vis create mode 100644 services/registration/incorrect_pin_swa delete mode 100644 services/registration/my_community_balance.vis diff --git a/cmd/main.go b/cmd/main.go index 3a06b81..d7bf738 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -26,6 +26,7 @@ const ( USERFLAG_ACCOUNT_UNLOCKED invalidRecipient invalidRecipientWithInvite + USERFLAG_INCORRECTPIN ) const ( @@ -66,7 +67,7 @@ type balanceResponse struct { type fsData struct { path string - st *state.State + st *state.State } func (fsd *fsData) SetLanguageSelected(ctx context.Context, sym string, input []byte) (resource.Result, error) { @@ -104,16 +105,16 @@ func (fsd *fsData) create_account(ctx context.Context, sym string, input []byte) // } accountResp := accountResponse{ - Ok: true, - Result: struct { - CustodialId json.Number `json:"custodialId"` - PublicKey string `json:"publicKey"` - TrackingId string `json:"trackingId"` - }{ - CustodialId: "636", - PublicKey: "0x8d86F9D4A4eae41Dc3B68034895EA97BcA90e8c1", - TrackingId: "45c67314-7995-4890-89d6-e5af987754ac", - }} + Ok: true, + Result: struct { + CustodialId json.Number `json:"custodialId"` + PublicKey string `json:"publicKey"` + TrackingId string `json:"trackingId"` + }{ + CustodialId: "636", + PublicKey: "0x8d86F9D4A4eae41Dc3B68034895EA97BcA90e8c1", + TrackingId: "45c67314-7995-4890-89d6-e5af987754ac", + }} accountData := map[string]string{ "TrackingId": accountResp.Result.TrackingId, @@ -131,8 +132,7 @@ func (fsd *fsData) create_account(ctx context.Context, sym string, input []byte) if err != nil { return res, err } - - res.FlagSet = []uint32{USERFLAG_ACCOUNT_CREATED} + res.FlagSet = append(res.FlagSet, USERFLAG_ACCOUNT_CREATED) return res, err } @@ -156,16 +156,33 @@ func (fsd *fsData) checkIdentifier(ctx context.Context, sym string, input []byte return res, nil } - -func (fsd *fsData) unlock(ctx context.Context,sym string,input []byte) (resource.Result,error){ +func (fsd *fsData) unLock(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - //res.FlagSet = []uint32{USERFLAG_ACCOUNT_UNLOCKED} - if fsd.st.MatchFlag(USERFLAG_ACCOUNT_UNLOCKED, false) { - res.FlagSet = append(res.FlagSet, USERFLAG_ACCOUNT_UNLOCKED) - } else { - res.FlagReset = append(res.FlagReset, USERFLAG_ACCOUNT_UNLOCKED) + pin := string(input) + if len(input) > 0 { + if pin == "0000" { + res.FlagSet = append(res.FlagSet, USERFLAG_INCORRECTPIN) + res.FlagReset = append(res.FlagReset, USERFLAG_ACCOUNT_UNLOCKED) + return res, nil + } + if fsd.st.MatchFlag(USERFLAG_ACCOUNT_UNLOCKED, false) { + res.FlagSet = append(res.FlagSet, USERFLAG_ACCOUNT_UNLOCKED) + } else { + res.FlagReset = append(res.FlagReset, USERFLAG_ACCOUNT_UNLOCKED) + } } - return res,nil + return res, nil +} + +func (fsd *fsData) ResetIncorrectPin(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + isIncorrectPinSet := fsd.st.MatchFlag(USERFLAG_INCORRECTPIN, true) + if isIncorrectPinSet { + res.FlagReset = append(res.FlagReset, USERFLAG_INCORRECTPIN) + } else { + res.FlagReset = append(res.FlagReset, USERFLAG_INCORRECTPIN) + } + return res, nil } func (fsd *fsData) check_account_status(ctx context.Context, sym string, input []byte) (resource.Result, error) { @@ -192,16 +209,14 @@ func (fsd *fsData) check_account_status(ctx context.Context, sym string, input [ accountData["Status"] = status - if status == "SUCCESS" { + if status == "REVERTED" { res.FlagSet = append(res.FlagSet, USERFLAG_ACCOUNT_SUCCESS) - res.FlagReset = append(res.FlagReset,USERFLAG_ACCOUNT_PENDING) + res.FlagReset = append(res.FlagReset, USERFLAG_ACCOUNT_PENDING) } else { res.FlagReset = append(res.FlagSet, USERFLAG_ACCOUNT_SUCCESS) - res.FlagSet = append(res.FlagReset,USERFLAG_ACCOUNT_PENDING) + res.FlagSet = append(res.FlagReset, USERFLAG_ACCOUNT_PENDING) } - - updatedJsonData, err := json.Marshal(accountData) if err != nil { return res, err @@ -259,17 +274,11 @@ func checkAccountStatus(trackingId string) (string, error) { return status, nil } -func (fsd *fsData) quit(ctx context.Context, sym string, input []byte) (resource.Result, error) { +func (fsd *fsData) quit(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{ - Content: "", - } - st := fsd.st - if(st.MatchFlag(USERFLAG_ACCOUNT_UNLOCKED,true)){ - //res.FlagReset = []uint32{USERFLAG_ACCOUNT_UNLOCKED} - // res.FlagReset = append(res.FlagReset, USERFLAG_ACCOUNT_UNLOCKED) - }else { - res.FlagReset = append(res.FlagReset, USERFLAG_ACCOUNT_UNLOCKED) + Content: "Your account is being created", } + res.FlagReset = append(res.FlagReset, USERFLAG_ACCOUNT_UNLOCKED) return res, nil } @@ -480,6 +489,44 @@ func (fsd *fsData) get_sender(ctx context.Context, sym string, input []byte) (re return res, nil } + +func (fsd *fsData) quitWithBalance(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{ + } + fp := fsd.path + "_data" + + jsonData, err := os.ReadFile(fp) + if err != nil { + return res, err + } + + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return res, err + } + resp, err := http.Get(checkBalanceURL + accountData["PublicKey"]) + if err != nil { + return res, nil + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return res, nil + } + + var balanceResp balanceResponse + err = json.Unmarshal(body, &balanceResp) + if err != nil { + return res, nil + } + balance := balanceResp.Result.Balance + res.Content = fmt.Sprintf("Your account balance is: %s", balance) + res.FlagReset = append(res.FlagReset, USERFLAG_ACCOUNT_UNLOCKED) + return res, nil +} + var ( scriptDir = path.Join("services", "registration") ) @@ -497,12 +544,13 @@ func main() { fmt.Fprintf(os.Stderr, "starting session at symbol '%s' using resource dir: %s\n", root, dir) ctx := context.Background() - st := state.NewState(7) + st := state.NewState(9) st.UseDebug() state.FlagDebugger.Register(USERFLAG_LANGUAGE_SET, "LANGUAGE_CHANGE") state.FlagDebugger.Register(USERFLAG_ACCOUNT_CREATED, "ACCOUNT_CREATED") state.FlagDebugger.Register(USERFLAG_ACCOUNT_SUCCESS, "ACCOUNT_SUCCESS") state.FlagDebugger.Register(USERFLAG_ACCOUNT_PENDING, "ACCOUNT_PENDING") + state.FlagDebugger.Register(USERFLAG_INCORRECTPIN, "INCORRECTPIN") rfs := resource.NewFsResource(scriptDir) ca := cache.NewCache() @@ -519,6 +567,7 @@ func main() { } pr := persist.NewFsPersister(dp) en, err := engine.NewPersistedEngine(ctx, cfg, pr, rfs) + if err != nil { pr = pr.WithContent(&st, ca) err = pr.Save(cfg.SessionId) @@ -535,13 +584,13 @@ func main() { fp := path.Join(dp, sessionId) fs := &fsData{ path: fp, - st: &st, + st: &st, } rfs.AddLocalFunc("select_language", fs.SetLanguageSelected) rfs.AddLocalFunc("create_account", fs.create_account) rfs.AddLocalFunc("check_identifier", fs.checkIdentifier) rfs.AddLocalFunc("check_account_status", fs.check_account_status) - rfs.AddLocalFunc("unlock_account", fs.unlock) + rfs.AddLocalFunc("unlock_account", fs.unLock) rfs.AddLocalFunc("quit", fs.quit) rfs.AddLocalFunc("check_balance", fs.checkBalance) rfs.AddLocalFunc("validate_recipient", fs.validate_recipient) @@ -550,8 +599,11 @@ func main() { rfs.AddLocalFunc("validate_amount", fs.validate_amount) rfs.AddLocalFunc("get_recipient", fs.get_recipient) rfs.AddLocalFunc("get_sender", fs.get_sender) + rfs.AddLocalFunc("reset_incorrect", fs.ResetIncorrectPin) + rfs.AddLocalFunc("quit_with_balance",fs.quitWithBalance) cont, err := en.Init(ctx) + en.SetDebugger(engine.NewSimpleDebug(nil)) if err != nil { fmt.Fprintf(os.Stderr, "engine init exited with error: %v\n", err) os.Exit(1) diff --git a/services/registration/account_creation.vis b/services/registration/account_creation.vis index 72f46dd..b810e1a 100644 --- a/services/registration/account_creation.vis +++ b/services/registration/account_creation.vis @@ -1,3 +1,4 @@ LOAD create_account 0 +LOAD quit 0 HALT -MOVE quit + diff --git a/services/registration/balances.vis b/services/registration/balances.vis index e968325..c936c15 100644 --- a/services/registration/balances.vis +++ b/services/registration/balances.vis @@ -4,5 +4,5 @@ MOUT back 0 HALT INCMP ^ 0 INCMP my_balance 1 -INCMP my_community_balance 2 +INCMP community_balance 2 diff --git a/services/registration/my_comminity_balance_swa b/services/registration/comminity_balance_swa similarity index 100% rename from services/registration/my_comminity_balance_swa rename to services/registration/comminity_balance_swa diff --git a/services/registration/my_community_balance b/services/registration/community_balance similarity index 100% rename from services/registration/my_community_balance rename to services/registration/community_balance diff --git a/services/registration/community_balance.vis b/services/registration/community_balance.vis new file mode 100644 index 0000000..e6d5805 --- /dev/null +++ b/services/registration/community_balance.vis @@ -0,0 +1,6 @@ +LOAD reset_incorrect 0 +CATCH incorrect_pin 15 1 +CATCH pin_entry 12 0 +LOAD quit_with_balance 0 +HALT + diff --git a/services/registration/enter_pin.vis b/services/registration/enter_pin.vis index f9f06b9..1217074 100644 --- a/services/registration/enter_pin.vis +++ b/services/registration/enter_pin.vis @@ -1,4 +1,4 @@ MOUT back 0 HALT -INCMP ^ 0 +INCMP _ 0 INCMP display_profile_info * diff --git a/services/registration/incorrect_pin b/services/registration/incorrect_pin new file mode 100644 index 0000000..2bb04e6 --- /dev/null +++ b/services/registration/incorrect_pin @@ -0,0 +1 @@ +Incorrect pin \ No newline at end of file diff --git a/services/registration/incorrect_pin.vis b/services/registration/incorrect_pin.vis new file mode 100644 index 0000000..844f3d6 --- /dev/null +++ b/services/registration/incorrect_pin.vis @@ -0,0 +1,7 @@ +LOAD reset_incorrect 0 +RELOAD reset_incorrect +MOUT retry 1 +MOUT quit 9 +HALT +INCMP _ 1 +INCMP quit 9 diff --git a/services/registration/incorrect_pin_swa b/services/registration/incorrect_pin_swa new file mode 100644 index 0000000..34a0b28 --- /dev/null +++ b/services/registration/incorrect_pin_swa @@ -0,0 +1 @@ +PIN ulioeka sio sahihi \ No newline at end of file diff --git a/services/registration/my_balance.vis b/services/registration/my_balance.vis index 90c3937..e6d5805 100644 --- a/services/registration/my_balance.vis +++ b/services/registration/my_balance.vis @@ -1,3 +1,6 @@ +LOAD reset_incorrect 0 +CATCH incorrect_pin 15 1 CATCH pin_entry 12 0 +LOAD quit_with_balance 0 HALT -MOVE quit + diff --git a/services/registration/my_community_balance.vis b/services/registration/my_community_balance.vis deleted file mode 100644 index 90c3937..0000000 --- a/services/registration/my_community_balance.vis +++ /dev/null @@ -1,3 +0,0 @@ -CATCH pin_entry 12 0 -HALT -MOVE quit From 47c38bf5077008542d57b6ed763a152e4c875b5d Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Wed, 21 Aug 2024 21:49:27 +0300 Subject: [PATCH 038/201] call api on creating an account --- cmd/main.go | 32 +++++++++----------------------- 1 file changed, 9 insertions(+), 23 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index c806752..5944e71 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -97,24 +97,12 @@ func (fsd *fsData) create_account(ctx context.Context, sym string, input []byte) } f.Close() - // accountResp, err := createAccount() + accountResp, err := createAccount() - // if err != nil { - // fmt.Println("Failed to create account:", err) - // return res, err - // } - - accountResp := accountResponse{ - Ok: true, - Result: struct { - CustodialId json.Number `json:"custodialId"` - PublicKey string `json:"publicKey"` - TrackingId string `json:"trackingId"` - }{ - CustodialId: "636", - PublicKey: "0x8d86F9D4A4eae41Dc3B68034895EA97BcA90e8c1", - TrackingId: "45c67314-7995-4890-89d6-e5af987754ac", - }} + if err != nil { + fmt.Println("Failed to create account:", err) + return res, err + } accountData := map[string]string{ "TrackingId": accountResp.Result.TrackingId, @@ -209,7 +197,7 @@ func (fsd *fsData) check_account_status(ctx context.Context, sym string, input [ accountData["Status"] = status - if status == "REVERTED" { + if status == "SUCCESS" { res.FlagSet = append(res.FlagSet, USERFLAG_ACCOUNT_SUCCESS) res.FlagReset = append(res.FlagReset, USERFLAG_ACCOUNT_PENDING) } else { @@ -488,10 +476,8 @@ func (fsd *fsData) get_sender(ctx context.Context, sym string, input []byte) (re return res, nil } - func (fsd *fsData) quitWithBalance(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{ - } + res := resource.Result{} fp := fsd.path + "_data" jsonData, err := os.ReadFile(fp) @@ -521,7 +507,7 @@ func (fsd *fsData) quitWithBalance(ctx context.Context, sym string, input []byte return res, nil } balance := balanceResp.Result.Balance - res.Content = fmt.Sprintf("Your account balance is: %s", balance) + res.Content = fmt.Sprintf("Your account balance is: %s", balance) res.FlagReset = append(res.FlagReset, USERFLAG_ACCOUNT_UNLOCKED) return res, nil } @@ -599,7 +585,7 @@ func main() { rfs.AddLocalFunc("get_recipient", fs.get_recipient) rfs.AddLocalFunc("get_sender", fs.get_sender) rfs.AddLocalFunc("reset_incorrect", fs.ResetIncorrectPin) - rfs.AddLocalFunc("quit_with_balance",fs.quitWithBalance) + rfs.AddLocalFunc("quit_with_balance", fs.quitWithBalance) cont, err := en.Init(ctx) en.SetDebugger(engine.NewSimpleDebug(nil)) From 075355980a8619e97a1ec0e02795e9785337a5a7 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Wed, 21 Aug 2024 22:03:37 +0300 Subject: [PATCH 039/201] replace ^ with _ (for 'back') --- services/registration/balances.vis | 2 +- services/registration/display_profile_info.vis | 2 +- services/registration/edit_profile.vis | 2 +- services/registration/enter_location.vis | 2 +- services/registration/enter_name.vis | 2 +- services/registration/enter_offerings.vis | 2 +- services/registration/enter_yob.vis | 2 +- services/registration/my_account.vis | 2 +- services/registration/pin_management.vis | 2 +- services/registration/select_gender.vis | 2 +- 10 files changed, 10 insertions(+), 10 deletions(-) diff --git a/services/registration/balances.vis b/services/registration/balances.vis index c936c15..50c3943 100644 --- a/services/registration/balances.vis +++ b/services/registration/balances.vis @@ -2,7 +2,7 @@ MOUT my_balance 1 MOUT community_balance 2 MOUT back 0 HALT -INCMP ^ 0 +INCMP _ 0 INCMP my_balance 1 INCMP community_balance 2 diff --git a/services/registration/display_profile_info.vis b/services/registration/display_profile_info.vis index 07fcf94..3790a08 100644 --- a/services/registration/display_profile_info.vis +++ b/services/registration/display_profile_info.vis @@ -1,3 +1,3 @@ MOUT back 0 HALT -INCMP ^ 0 +INCMP _ 0 diff --git a/services/registration/edit_profile.vis b/services/registration/edit_profile.vis index b454820..8afb933 100644 --- a/services/registration/edit_profile.vis +++ b/services/registration/edit_profile.vis @@ -6,7 +6,7 @@ MOUT edit_offerings 5 MOUT view 6 MOUT back 0 HALT -INCMP ^ 0 +INCMP _ 0 INCMP enter_name 1 INCMP select_gender 2 INCMP enter_yob 3 diff --git a/services/registration/enter_location.vis b/services/registration/enter_location.vis index 07fcf94..3790a08 100644 --- a/services/registration/enter_location.vis +++ b/services/registration/enter_location.vis @@ -1,3 +1,3 @@ MOUT back 0 HALT -INCMP ^ 0 +INCMP _ 0 diff --git a/services/registration/enter_name.vis b/services/registration/enter_name.vis index 07fcf94..3790a08 100644 --- a/services/registration/enter_name.vis +++ b/services/registration/enter_name.vis @@ -1,3 +1,3 @@ MOUT back 0 HALT -INCMP ^ 0 +INCMP _ 0 diff --git a/services/registration/enter_offerings.vis b/services/registration/enter_offerings.vis index 07fcf94..3790a08 100644 --- a/services/registration/enter_offerings.vis +++ b/services/registration/enter_offerings.vis @@ -1,3 +1,3 @@ MOUT back 0 HALT -INCMP ^ 0 +INCMP _ 0 diff --git a/services/registration/enter_yob.vis b/services/registration/enter_yob.vis index 07fcf94..3790a08 100644 --- a/services/registration/enter_yob.vis +++ b/services/registration/enter_yob.vis @@ -1,3 +1,3 @@ MOUT back 0 HALT -INCMP ^ 0 +INCMP _ 0 diff --git a/services/registration/my_account.vis b/services/registration/my_account.vis index 0232e06..5cbe722 100644 --- a/services/registration/my_account.vis +++ b/services/registration/my_account.vis @@ -6,7 +6,7 @@ MOUT pin_options 5 MOUT my_address 6 MOUT back 0 HALT -INCMP ^ 0 +INCMP _ 0 INCMP edit_profile 1 INCMP balances 3 INCMP pin_management 5 diff --git a/services/registration/pin_management.vis b/services/registration/pin_management.vis index 0e40b9f..ecd5a8c 100644 --- a/services/registration/pin_management.vis +++ b/services/registration/pin_management.vis @@ -3,4 +3,4 @@ MOUT reset_pin 2 MOUT guard_pin 3 MOUT back 0 HALT -INCMP ^ 0 +INCMP _ 0 diff --git a/services/registration/select_gender.vis b/services/registration/select_gender.vis index e30f71e..8a2ef60 100644 --- a/services/registration/select_gender.vis +++ b/services/registration/select_gender.vis @@ -3,4 +3,4 @@ MOUT female 2 MOUT other_gender 3 MOUT back 0 HALT -INCMP ^ 0 +INCMP _ 0 From 32ba22c0439f3be6a65ced29e48999ffd316b5b1 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Thu, 22 Aug 2024 15:01:30 +0300 Subject: [PATCH 040/201] added validation for amount --- services/registration/amount.vis | 1 + services/registration/amount_swa | 2 ++ services/registration/invalid_amount | 1 + services/registration/invalid_amount.vis | 7 +++++++ services/registration/invalid_amount_swa | 1 + services/registration/transaction_pin.vis | 1 + 6 files changed, 13 insertions(+) create mode 100644 services/registration/invalid_amount create mode 100644 services/registration/invalid_amount.vis create mode 100644 services/registration/invalid_amount_swa diff --git a/services/registration/amount.vis b/services/registration/amount.vis index ef1dd76..07bbbd9 100644 --- a/services/registration/amount.vis +++ b/services/registration/amount.vis @@ -1,3 +1,4 @@ +LOAD reset_transaction_amount 0 RELOAD validate_recipient CATCH invalid_recipient 13 1 LOAD max_amount 10 diff --git a/services/registration/amount_swa b/services/registration/amount_swa index e69de29..0c8cf01 100644 --- a/services/registration/amount_swa +++ b/services/registration/amount_swa @@ -0,0 +1,2 @@ +Kiwango cha juu: {{.max_amount}} +Weka kiwango: \ No newline at end of file diff --git a/services/registration/invalid_amount b/services/registration/invalid_amount new file mode 100644 index 0000000..c4bbe3f --- /dev/null +++ b/services/registration/invalid_amount @@ -0,0 +1 @@ +Amount {{.validate_amount}} is invalid, please try again: \ No newline at end of file diff --git a/services/registration/invalid_amount.vis b/services/registration/invalid_amount.vis new file mode 100644 index 0000000..833e81c --- /dev/null +++ b/services/registration/invalid_amount.vis @@ -0,0 +1,7 @@ +MAP validate_amount +RELOAD reset_transaction_amount +MOUT retry 1 +MOUT quit 9 +HALT +INCMP amount 1 +INCMP quit 9 diff --git a/services/registration/invalid_amount_swa b/services/registration/invalid_amount_swa new file mode 100644 index 0000000..836d7b2 --- /dev/null +++ b/services/registration/invalid_amount_swa @@ -0,0 +1 @@ +Kiwango {{.validate_amount}} sio sahihi, tafadhali weka tena: \ No newline at end of file diff --git a/services/registration/transaction_pin.vis b/services/registration/transaction_pin.vis index c63c2d8..983e4c6 100644 --- a/services/registration/transaction_pin.vis +++ b/services/registration/transaction_pin.vis @@ -1,5 +1,6 @@ RELOAD validate_amount MAP validate_amount +CATCH invalid_amount 17 1 RELOAD get_recipient MAP get_recipient RELOAD get_sender From 9aedc5d48f930e9ed388dbc95e63571524eb710f Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Thu, 22 Aug 2024 15:44:28 +0300 Subject: [PATCH 041/201] added amount validation flag and logic --- cmd/main.go | 76 ++++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 58 insertions(+), 18 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index 5944e71..186c0e4 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -27,6 +27,8 @@ const ( USERFLAG_INVALID_RECIPIENT USERFLAG_INVALID_RECIPIENT_WITH_INVITE USERFLAG_INCORRECTPIN + USERFLAG_UNLOCKFORUPDATE + USERFLAG_INVALID_AMOUNT ) const ( @@ -385,6 +387,39 @@ func (fsd *fsData) transaction_reset(ctx context.Context, sym string, input []by return res, nil } +func (fsd *fsData) reset_transaction_amount(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + fp := fsd.path + "_data" + + jsonData, err := os.ReadFile(fp) + if err != nil { + return res, err + } + + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return res, err + } + + // reset the amount + accountData["Amount"] = "" + + updatedJsonData, err := json.Marshal(accountData) + if err != nil { + return res, err + } + + err = os.WriteFile(fp, updatedJsonData, 0644) + if err != nil { + return res, err + } + + res.FlagReset = append(res.FlagReset, USERFLAG_INVALID_AMOUNT) + + return res, nil +} + func (fsd *fsData) max_amount(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} @@ -411,28 +446,32 @@ func (fsd *fsData) validate_amount(ctx context.Context, sym string, input []byte return res, err } - // mimic invalid amount check - if amount == "0" { - // res.FlagSet = []uint32{invalidAmount} + if amount != "0" { + // mimic invalid amount + if amount == "00" { + res.FlagSet = append(res.FlagSet, USERFLAG_INVALID_AMOUNT) + res.Content = amount + + return res, nil + } + res.Content = amount + accountData["Amount"] = amount + + updatedJsonData, err := json.Marshal(accountData) + if err != nil { + return res, err + } + + err = os.WriteFile(fp, updatedJsonData, 0644) + if err != nil { + return res, err + } + return res, nil } - res.Content = amount - - accountData["Amount"] = amount - - updatedJsonData, err := json.Marshal(accountData) - if err != nil { - return res, err - } - - err = os.WriteFile(fp, updatedJsonData, 0644) - if err != nil { - return res, err - } - return res, nil } @@ -529,7 +568,7 @@ func main() { fmt.Fprintf(os.Stderr, "starting session at symbol '%s' using resource dir: %s\n", root, dir) ctx := context.Background() - st := state.NewState(9) + st := state.NewState(15) st.UseDebug() state.FlagDebugger.Register(USERFLAG_LANGUAGE_SET, "LANGUAGE_CHANGE") state.FlagDebugger.Register(USERFLAG_ACCOUNT_CREATED, "ACCOUNT_CREATED") @@ -582,6 +621,7 @@ func main() { rfs.AddLocalFunc("transaction_reset", fs.transaction_reset) rfs.AddLocalFunc("max_amount", fs.max_amount) rfs.AddLocalFunc("validate_amount", fs.validate_amount) + rfs.AddLocalFunc("reset_transaction_amount", fs.reset_transaction_amount) rfs.AddLocalFunc("get_recipient", fs.get_recipient) rfs.AddLocalFunc("get_sender", fs.get_sender) rfs.AddLocalFunc("reset_incorrect", fs.ResetIncorrectPin) From f50be01b8949b4a0814c75f868b74115bbe59fc4 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Thu, 22 Aug 2024 19:48:34 +0300 Subject: [PATCH 042/201] create a PIN during registration --- cmd/main.go | 62 +++++++++++++++++++ services/registration/account_creation.vis | 4 +- services/registration/confirm_create_pin | 1 + services/registration/confirm_create_pin.vis | 4 ++ services/registration/confirm_create_pin_swa | 1 + services/registration/create_pin | 1 + services/registration/create_pin.vis | 5 ++ services/registration/create_pin_mismatch | 1 + services/registration/create_pin_mismatch.vis | 5 ++ services/registration/create_pin_mismatch_swa | 1 + services/registration/create_pin_swa | 1 + services/registration/exit_menu | 1 + services/registration/exit_menu_swa | 1 + services/registration/terms.vis | 2 +- 14 files changed, 87 insertions(+), 3 deletions(-) create mode 100644 services/registration/confirm_create_pin create mode 100644 services/registration/confirm_create_pin.vis create mode 100644 services/registration/confirm_create_pin_swa create mode 100644 services/registration/create_pin create mode 100644 services/registration/create_pin.vis create mode 100644 services/registration/create_pin_mismatch create mode 100644 services/registration/create_pin_mismatch.vis create mode 100644 services/registration/create_pin_mismatch_swa create mode 100644 services/registration/create_pin_swa create mode 100644 services/registration/exit_menu create mode 100644 services/registration/exit_menu_swa diff --git a/cmd/main.go b/cmd/main.go index 186c0e4..694eebb 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -1,6 +1,7 @@ package main import ( + "bytes" "context" "encoding/json" "flag" @@ -29,6 +30,9 @@ const ( USERFLAG_INCORRECTPIN USERFLAG_UNLOCKFORUPDATE USERFLAG_INVALID_AMOUNT + USERFLAG_QUERYPIN + USERFLAG_VALIDPIN + USERFLAG_INVALIDPIN ) const ( @@ -551,6 +555,62 @@ func (fsd *fsData) quitWithBalance(ctx context.Context, sym string, input []byte return res, nil } +func (fsd *fsData) save_pin(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + accountPIN := string(input) + fp := fsd.path + "_data" + + jsonData, err := os.ReadFile(fp) + if err != nil { + return res, err + } + + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return res, err + } + + accountData["AccountPIN"] = accountPIN + + updatedJsonData, err := json.Marshal(accountData) + if err != nil { + return res, err + } + + err = os.WriteFile(fp, updatedJsonData, 0644) + if err != nil { + return res, err + } + + return res, nil +} + +func (fsd *fsData) verify_pin(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + fp := fsd.path + "_data" + + jsonData, err := os.ReadFile(fp) + if err != nil { + return res, err + } + + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return res, err + } + + if bytes.Equal(input, []byte(accountData["AccountPIN"])) { + res.FlagSet = []uint32{USERFLAG_VALIDPIN} + res.FlagReset = []uint32{USERFLAG_INVALIDPIN} + } else { + res.FlagSet = []uint32{USERFLAG_INVALIDPIN} + } + + return res, nil +} + var ( scriptDir = path.Join("services", "registration") ) @@ -612,6 +672,8 @@ func main() { } rfs.AddLocalFunc("select_language", fs.SetLanguageSelected) rfs.AddLocalFunc("create_account", fs.create_account) + rfs.AddLocalFunc("save_pin", fs.save_pin) + rfs.AddLocalFunc("verify_pin", fs.verify_pin) rfs.AddLocalFunc("check_identifier", fs.checkIdentifier) rfs.AddLocalFunc("check_account_status", fs.check_account_status) rfs.AddLocalFunc("unlock_account", fs.unLock) diff --git a/services/registration/account_creation.vis b/services/registration/account_creation.vis index b810e1a..e3ecebb 100644 --- a/services/registration/account_creation.vis +++ b/services/registration/account_creation.vis @@ -1,4 +1,4 @@ -LOAD create_account 0 +RELOAD verify_pin +CATCH create_pin_mismatch 20 1 LOAD quit 0 HALT - diff --git a/services/registration/confirm_create_pin b/services/registration/confirm_create_pin new file mode 100644 index 0000000..e4632ad --- /dev/null +++ b/services/registration/confirm_create_pin @@ -0,0 +1 @@ +Enter your four number PIN again: \ No newline at end of file diff --git a/services/registration/confirm_create_pin.vis b/services/registration/confirm_create_pin.vis new file mode 100644 index 0000000..1235916 --- /dev/null +++ b/services/registration/confirm_create_pin.vis @@ -0,0 +1,4 @@ +LOAD save_pin 0 +HALT +LOAD verify_pin 8 +INCMP account_creation * diff --git a/services/registration/confirm_create_pin_swa b/services/registration/confirm_create_pin_swa new file mode 100644 index 0000000..f697854 --- /dev/null +++ b/services/registration/confirm_create_pin_swa @@ -0,0 +1 @@ +Weka PIN yako tena: \ No newline at end of file diff --git a/services/registration/create_pin b/services/registration/create_pin new file mode 100644 index 0000000..f8836f5 --- /dev/null +++ b/services/registration/create_pin @@ -0,0 +1 @@ +Please enter a new four number PIN for your account: \ No newline at end of file diff --git a/services/registration/create_pin.vis b/services/registration/create_pin.vis new file mode 100644 index 0000000..852bf47 --- /dev/null +++ b/services/registration/create_pin.vis @@ -0,0 +1,5 @@ +LOAD create_account 0 +MOUT exit 0 +HALT +LOAD save_pin 0 +INCMP confirm_create_pin * diff --git a/services/registration/create_pin_mismatch b/services/registration/create_pin_mismatch new file mode 100644 index 0000000..e75068c --- /dev/null +++ b/services/registration/create_pin_mismatch @@ -0,0 +1 @@ +The PIN is not a match. Try again \ No newline at end of file diff --git a/services/registration/create_pin_mismatch.vis b/services/registration/create_pin_mismatch.vis new file mode 100644 index 0000000..91793b5 --- /dev/null +++ b/services/registration/create_pin_mismatch.vis @@ -0,0 +1,5 @@ +MOUT retry 1 +MOUT quit 9 +HALT +INCMP confirm_create_pin 1 +INCMP quit 9 diff --git a/services/registration/create_pin_mismatch_swa b/services/registration/create_pin_mismatch_swa new file mode 100644 index 0000000..a1d7b6d --- /dev/null +++ b/services/registration/create_pin_mismatch_swa @@ -0,0 +1 @@ +PIN uliyoweka haifanani. Jaribu tena \ No newline at end of file diff --git a/services/registration/create_pin_swa b/services/registration/create_pin_swa new file mode 100644 index 0000000..1fdd972 --- /dev/null +++ b/services/registration/create_pin_swa @@ -0,0 +1 @@ +Tafadhali weka PIN mpya yenye nambari nne kwa akaunti yako: \ No newline at end of file diff --git a/services/registration/exit_menu b/services/registration/exit_menu new file mode 100644 index 0000000..1105a55 --- /dev/null +++ b/services/registration/exit_menu @@ -0,0 +1 @@ +Exit \ No newline at end of file diff --git a/services/registration/exit_menu_swa b/services/registration/exit_menu_swa new file mode 100644 index 0000000..474f1ff --- /dev/null +++ b/services/registration/exit_menu_swa @@ -0,0 +1 @@ +Ondoka \ No newline at end of file diff --git a/services/registration/terms.vis b/services/registration/terms.vis index 5375925..768efa3 100644 --- a/services/registration/terms.vis +++ b/services/registration/terms.vis @@ -3,5 +3,5 @@ RELOAD select_language MOUT yes 0 MOUT no 1 HALT -INCMP account_creation 0 +INCMP create_pin 0 INCMP _ * From 9cc75185b3fcdf99f626d7d1f79dff0a4e076e69 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Fri, 23 Aug 2024 01:05:14 +0300 Subject: [PATCH 043/201] creuse a universal quit message --- cmd/main.go | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index 694eebb..17eb906 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -14,6 +14,7 @@ import ( "git.defalsify.org/vise.git/cache" "git.defalsify.org/vise.git/engine" + "git.defalsify.org/vise.git/lang" "git.defalsify.org/vise.git/persist" "git.defalsify.org/vise.git/resource" "git.defalsify.org/vise.git/state" @@ -76,6 +77,16 @@ type fsData struct { st *state.State } +func codeFromCtx(ctx context.Context) string { + var code string + engine.Logg.DebugCtxf(ctx, "in msg", "ctx", ctx, "val", code) + if ctx.Value("Language") != nil { + lang := ctx.Value("Language").(lang.Language) + code = lang.Code + } + return code +} + func (fsd *fsData) SetLanguageSelected(ctx context.Context, sym string, input []byte) (resource.Result, error) { inputStr := string(input) res := resource.Result{} @@ -269,8 +280,12 @@ func checkAccountStatus(trackingId string) (string, error) { } func (fsd *fsData) quit(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{ - Content: "Your account is being created", + res := resource.Result{} + switch codeFromCtx(ctx) { + case "swa": + res.Content = "Asante kwa kutumia huduma ya Sarafu. Kwaheri!" + default: + res.Content = "Thank you for using Sarafu. Goodbye!" } res.FlagReset = append(res.FlagReset, USERFLAG_ACCOUNT_UNLOCKED) return res, nil From 722bb10441dc58746c3c82d9c1ce042b4dc0e1e7 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Fri, 23 Aug 2024 06:35:49 +0300 Subject: [PATCH 044/201] implement profile data persistence --- cmd/main.go | 267 ++++++++++++++++++++- services/registration/balances.vis | 1 + services/registration/edit_profile.vis | 2 + services/registration/enter_familyname | 1 + services/registration/enter_familyname.vis | 6 + services/registration/enter_familyname_swa | 0 services/registration/enter_location.vis | 2 + services/registration/enter_name.vis | 1 + services/registration/enter_offerings.vis | 7 + services/registration/enter_yob.vis | 2 + services/registration/my_account.vis | 1 + services/registration/select_gender.vis | 4 + services/registration/update_success | 1 + services/registration/update_success.vis | 3 + services/registration/update_success_swa | 1 + services/registration/view_profile | 2 + services/registration/view_profile.vis | 7 + services/registration/view_profile_swa | 1 + 18 files changed, 307 insertions(+), 2 deletions(-) create mode 100644 services/registration/enter_familyname create mode 100644 services/registration/enter_familyname.vis create mode 100644 services/registration/enter_familyname_swa create mode 100644 services/registration/update_success create mode 100644 services/registration/update_success.vis create mode 100644 services/registration/update_success_swa create mode 100644 services/registration/view_profile create mode 100644 services/registration/view_profile_swa diff --git a/cmd/main.go b/cmd/main.go index 5944e71..996b7be 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -27,6 +27,7 @@ const ( USERFLAG_INVALID_RECIPIENT USERFLAG_INVALID_RECIPIENT_WITH_INVITE USERFLAG_INCORRECTPIN + USERFLAG_UNLOCKFORUPDATE ) const ( @@ -70,6 +71,193 @@ type fsData struct { st *state.State } +func (fsd *fsData) saveFirstName(cxt context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + fp := fsd.path + "_data" + + jsonData, err := os.ReadFile(fp) + if err != nil { + return res, err + } + + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return res, err + } + if len(input) > 0 { + name := string(input) + accountData["FirstName"] = name + updatedJsonData, err := json.Marshal(accountData) + if err != nil { + return res, err + } + + err = os.WriteFile(fp, updatedJsonData, 0644) + if err != nil { + return res, err + } + } + + return res, nil +} + +func (fsd *fsData) saveFamilyName(cxt context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + fp := fsd.path + "_data" + + jsonData, err := os.ReadFile(fp) + if err != nil { + return res, err + } + + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return res, err + } + if len(input) > 0 { + //Save name + secondname := string(input) + fmt.Println("FamilyName:", secondname) + accountData["FamilyName"] = secondname + updatedJsonData, err := json.Marshal(accountData) + if err != nil { + return res, err + } + + err = os.WriteFile(fp, updatedJsonData, 0644) + if err != nil { + return res, err + } + } + + return res, nil +} +func (fsd *fsData) saveYOB(cxt context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + fp := fsd.path + "_data" + jsonData, err := os.ReadFile(fp) + if err != nil { + return res, err + } + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return res, err + } + if len(input) > 0 { + yob := string(input) + fmt.Println("YOB", yob) + accountData["YOB"] = yob + updatedJsonData, err := json.Marshal(accountData) + if err != nil { + return res, err + } + + err = os.WriteFile(fp, updatedJsonData, 0644) + if err != nil { + return res, err + } + } + + return res, nil +} + +func (fsd *fsData) saveLocation(cxt context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + fp := fsd.path + "_data" + jsonData, err := os.ReadFile(fp) + if err != nil { + return res, err + } + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return res, err + } + if len(input) > 0 { + location := string(input) + fmt.Println("Location:", location) + accountData["Location"] = location + updatedJsonData, err := json.Marshal(accountData) + if err != nil { + return res, err + } + + err = os.WriteFile(fp, updatedJsonData, 0644) + if err != nil { + return res, err + } + + } + + return res, nil +} + +func (fsd *fsData) saveGender(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + fp := fsd.path + "_data" + jsonData, err := os.ReadFile(fp) + if err != nil { + return res, err + } + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return res, err + } + if len(input) > 0 { + gender := string(input) + + switch gender { + case "1" : gender = "Male" + case "2" : gender = "Female" + case "3" : gender = "Other" + } + fmt.Println("gender", gender) + accountData["Gender"] = gender + updatedJsonData, err := json.Marshal(accountData) + if err != nil { + return res, err + } + + err = os.WriteFile(fp, updatedJsonData, 0644) + if err != nil { + return res, err + } + } + return res, nil +} + +func (fsd *fsData) saveOfferings(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + fp := fsd.path + "_data" + jsonData, err := os.ReadFile(fp) + if err != nil { + return res, err + } + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return res, err + } + if len(input) > 0 { + offerings := string(input) + fmt.Println("Offerings:", offerings) + accountData["Offerings"] = offerings + updatedJsonData, err := json.Marshal(accountData) + if err != nil { + return res, err + } + err = os.WriteFile(fp, updatedJsonData, 0644) + if err != nil { + return res, err + } + } + return res, nil +} + func (fsd *fsData) SetLanguageSelected(ctx context.Context, sym string, input []byte) (resource.Result, error) { inputStr := string(input) res := resource.Result{} @@ -97,7 +285,18 @@ func (fsd *fsData) create_account(ctx context.Context, sym string, input []byte) } f.Close() - accountResp, err := createAccount() + //accountResp, err := createAccount() + accountResp := accountResponse{ + Ok: true, + Result: struct { + CustodialId json.Number `json:"custodialId"` + PublicKey string `json:"publicKey"` + TrackingId string `json:"trackingId"` + }{ + CustodialId: "636", + PublicKey: "0x8d86F9D4A4eae41Dc3B68034895EA97BcA90e8c1", + TrackingId: "45c67314-7995-4890-89d6-e5af987754ac", + }} if err != nil { fmt.Println("Failed to create account:", err) @@ -124,6 +323,21 @@ func (fsd *fsData) create_account(ctx context.Context, sym string, input []byte) return res, err } +func (fsd *fsData) resetUnlockForUpdate(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + res.FlagReset = append(res.FlagReset, USERFLAG_UNLOCKFORUPDATE) + return res, nil +} + +func (fsd *fsData) resetAccountUnlocked(ctx context.Context,sym string,input []byte) (resource.Result,error){ + res := resource.Result{} + st := fsd.st + isSet := st.MatchFlag(USERFLAG_ACCOUNT_UNLOCKED,true) + res.FlagReset = append(res.FlagReset, USERFLAG_ACCOUNT_UNLOCKED) + fmt.Println("ISSET:",isSet) + return res,nil +} + func (fsd *fsData) checkIdentifier(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} fp := fsd.path + "_data" @@ -154,9 +368,11 @@ func (fsd *fsData) unLock(ctx context.Context, sym string, input []byte) (resour return res, nil } if fsd.st.MatchFlag(USERFLAG_ACCOUNT_UNLOCKED, false) { + //res.FlagSet = append(res.FlagSet, USERFLAG_UNLOCKFORUPDATE) res.FlagSet = append(res.FlagSet, USERFLAG_ACCOUNT_UNLOCKED) } else { res.FlagReset = append(res.FlagReset, USERFLAG_ACCOUNT_UNLOCKED) + //res.FlagReset = append(res.FlagReset, USERFLAG_UNLOCKFORUPDATE) } } return res, nil @@ -173,6 +389,11 @@ func (fsd *fsData) ResetIncorrectPin(ctx context.Context, sym string, input []by return res, nil } +func (fsd *fsData) ShowUpdateSuccess(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + return res, nil +} + func (fsd *fsData) check_account_status(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} fp := fsd.path + "_data" @@ -197,7 +418,7 @@ func (fsd *fsData) check_account_status(ctx context.Context, sym string, input [ accountData["Status"] = status - if status == "SUCCESS" { + if status == "REVERTED" { res.FlagSet = append(res.FlagSet, USERFLAG_ACCOUNT_SUCCESS) res.FlagReset = append(res.FlagReset, USERFLAG_ACCOUNT_PENDING) } else { @@ -456,6 +677,35 @@ func (fsd *fsData) get_recipient(ctx context.Context, sym string, input []byte) return res, nil } + +func (fsd *fsData) getProfileInfo(ctx context.Context,sym string,input []byte) (resource.Result,error){ + res := resource.Result{} + fp := fsd.path + "_data" + + jsonData, err := os.ReadFile(fp) + if err != nil { + return res, err + } + + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return res, err + } + name := accountData["FirstName"] + gender := accountData["Gender"] + age := accountData["YOB"] + location := accountData["Location"] + + // Format the data into a string + formattedData := fmt.Sprintf("Name: %s\nGender: %s\nAge: %s\nLocation: %s\n", name, gender, age, location) + + + res.Content = formattedData + + return res,nil +} + func (fsd *fsData) get_sender(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} fp := fsd.path + "_data" @@ -585,7 +835,20 @@ func main() { rfs.AddLocalFunc("get_recipient", fs.get_recipient) rfs.AddLocalFunc("get_sender", fs.get_sender) rfs.AddLocalFunc("reset_incorrect", fs.ResetIncorrectPin) + rfs.AddLocalFunc("save_firstname", fs.saveFirstName) + rfs.AddLocalFunc("save_familyname", fs.saveFamilyName) + rfs.AddLocalFunc("save_gender", fs.saveGender) + rfs.AddLocalFunc("save_location", fs.saveLocation) + rfs.AddLocalFunc("save_yob", fs.saveYOB) + rfs.AddLocalFunc("save_offerings", fs.saveOfferings) rfs.AddLocalFunc("quit_with_balance", fs.quitWithBalance) + rfs.AddLocalFunc("show_update_success", fs.ShowUpdateSuccess) + rfs.AddLocalFunc("reset_unlocked",fs.resetAccountUnlocked) + rfs.AddLocalFunc("reset_unlock_for_update", fs.resetUnlockForUpdate) + rfs.AddLocalFunc("get_profile_info",fs.getProfileInfo) + + + cont, err := en.Init(ctx) en.SetDebugger(engine.NewSimpleDebug(nil)) diff --git a/services/registration/balances.vis b/services/registration/balances.vis index 50c3943..7873dd2 100644 --- a/services/registration/balances.vis +++ b/services/registration/balances.vis @@ -1,3 +1,4 @@ +LOAD reset_unlocked 0 MOUT my_balance 1 MOUT community_balance 2 MOUT back 0 diff --git a/services/registration/edit_profile.vis b/services/registration/edit_profile.vis index 8afb933..a8b0e49 100644 --- a/services/registration/edit_profile.vis +++ b/services/registration/edit_profile.vis @@ -1,3 +1,5 @@ +LOAD reset_unlocked 0 +LOAD get_profile_info 0 MOUT edit_name 1 MOUT edit_gender 2 MOUT edit_yob 3 diff --git a/services/registration/enter_familyname b/services/registration/enter_familyname new file mode 100644 index 0000000..15ffb07 --- /dev/null +++ b/services/registration/enter_familyname @@ -0,0 +1 @@ +Enter family name: diff --git a/services/registration/enter_familyname.vis b/services/registration/enter_familyname.vis new file mode 100644 index 0000000..2085c38 --- /dev/null +++ b/services/registration/enter_familyname.vis @@ -0,0 +1,6 @@ +LOAD save_firstname 0 +MOUT back 0 +HALT +INCMP _ 0 +INCMP select_gender * + diff --git a/services/registration/enter_familyname_swa b/services/registration/enter_familyname_swa new file mode 100644 index 0000000..e69de29 diff --git a/services/registration/enter_location.vis b/services/registration/enter_location.vis index 3790a08..7ef9348 100644 --- a/services/registration/enter_location.vis +++ b/services/registration/enter_location.vis @@ -1,3 +1,5 @@ +LOAD save_yob 0 MOUT back 0 HALT INCMP _ 0 +INCMP enter_offerings * diff --git a/services/registration/enter_name.vis b/services/registration/enter_name.vis index 3790a08..4126f07 100644 --- a/services/registration/enter_name.vis +++ b/services/registration/enter_name.vis @@ -1,3 +1,4 @@ MOUT back 0 HALT INCMP _ 0 +INCMP enter_familyname * diff --git a/services/registration/enter_offerings.vis b/services/registration/enter_offerings.vis index 3790a08..eb7dad2 100644 --- a/services/registration/enter_offerings.vis +++ b/services/registration/enter_offerings.vis @@ -1,3 +1,10 @@ +LOAD save_location 0 +CATCH incorrect_pin 15 1 +CATCH update_success 16 1 MOUT back 0 HALT +LOAD save_offerings 0 INCMP _ 0 +INCMP pin_entry * + + diff --git a/services/registration/enter_yob.vis b/services/registration/enter_yob.vis index 3790a08..d169e05 100644 --- a/services/registration/enter_yob.vis +++ b/services/registration/enter_yob.vis @@ -1,3 +1,5 @@ +LOAD save_gender 0 MOUT back 0 HALT INCMP _ 0 +INCMP enter_location * diff --git a/services/registration/my_account.vis b/services/registration/my_account.vis index 5cbe722..48f12ee 100644 --- a/services/registration/my_account.vis +++ b/services/registration/my_account.vis @@ -1,3 +1,4 @@ +LOAD reset_unlock_for_update 0 MOUT profile 1 MOUT change_language 2 MOUT check_balance 3 diff --git a/services/registration/select_gender.vis b/services/registration/select_gender.vis index 8a2ef60..e9868a5 100644 --- a/services/registration/select_gender.vis +++ b/services/registration/select_gender.vis @@ -1,6 +1,10 @@ +LOAD save_familyname 0 MOUT male 1 MOUT female 2 MOUT other_gender 3 MOUT back 0 HALT INCMP _ 0 +INCMP enter_yob 1 +INCMP enter_yob 2 +INCMP enter_yob 3 diff --git a/services/registration/update_success b/services/registration/update_success new file mode 100644 index 0000000..652942a --- /dev/null +++ b/services/registration/update_success @@ -0,0 +1 @@ +Profile updated successfully diff --git a/services/registration/update_success.vis b/services/registration/update_success.vis new file mode 100644 index 0000000..07fcf94 --- /dev/null +++ b/services/registration/update_success.vis @@ -0,0 +1,3 @@ +MOUT back 0 +HALT +INCMP ^ 0 diff --git a/services/registration/update_success_swa b/services/registration/update_success_swa new file mode 100644 index 0000000..19949ad --- /dev/null +++ b/services/registration/update_success_swa @@ -0,0 +1 @@ +Akaunti imeupdatiwa diff --git a/services/registration/view_profile b/services/registration/view_profile new file mode 100644 index 0000000..7708bd5 --- /dev/null +++ b/services/registration/view_profile @@ -0,0 +1,2 @@ +My profile: +{{.get_profile_info}} diff --git a/services/registration/view_profile.vis b/services/registration/view_profile.vis index 72e55ad..8bf2b76 100644 --- a/services/registration/view_profile.vis +++ b/services/registration/view_profile.vis @@ -1 +1,8 @@ +LOAD get_profile_info 0 +MAP get_profile_info +LOAD reset_incorrect 0 +CATCH incorrect_pin 15 1 +CATCH pin_entry 12 0 +MOUT back 0 HALT +INCMP _ 0 diff --git a/services/registration/view_profile_swa b/services/registration/view_profile_swa new file mode 100644 index 0000000..8a12b7d --- /dev/null +++ b/services/registration/view_profile_swa @@ -0,0 +1 @@ +Wasifu wangu \ No newline at end of file From b440881441128658399232671a2f321a9661bc64 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Fri, 23 Aug 2024 07:06:54 +0300 Subject: [PATCH 045/201] remove unused code --- cmd/main.go | 54 ++++++++++++++++++++--------------------------------- 1 file changed, 20 insertions(+), 34 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index 4dbcbd6..8295bc0 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -34,7 +34,6 @@ const ( USERFLAG_QUERYPIN USERFLAG_VALIDPIN USERFLAG_INVALIDPIN - USERFLAG_UNLOCKFORUPDATE ) const ( @@ -136,7 +135,6 @@ func (fsd *fsData) saveFamilyName(cxt context.Context, sym string, input []byte) if len(input) > 0 { //Save name secondname := string(input) - fmt.Println("FamilyName:", secondname) accountData["FamilyName"] = secondname updatedJsonData, err := json.Marshal(accountData) if err != nil { @@ -165,7 +163,6 @@ func (fsd *fsData) saveYOB(cxt context.Context, sym string, input []byte) (resou } if len(input) > 0 { yob := string(input) - fmt.Println("YOB", yob) accountData["YOB"] = yob updatedJsonData, err := json.Marshal(accountData) if err != nil { @@ -195,7 +192,6 @@ func (fsd *fsData) saveLocation(cxt context.Context, sym string, input []byte) ( } if len(input) > 0 { location := string(input) - fmt.Println("Location:", location) accountData["Location"] = location updatedJsonData, err := json.Marshal(accountData) if err != nil { @@ -228,9 +224,12 @@ func (fsd *fsData) saveGender(ctx context.Context, sym string, input []byte) (re gender := string(input) switch gender { - case "1" : gender = "Male" - case "2" : gender = "Female" - case "3" : gender = "Other" + case "1": + gender = "Male" + case "2": + gender = "Female" + case "3": + gender = "Other" } fmt.Println("gender", gender) accountData["Gender"] = gender @@ -261,7 +260,6 @@ func (fsd *fsData) saveOfferings(ctx context.Context, sym string, input []byte) } if len(input) > 0 { offerings := string(input) - fmt.Println("Offerings:", offerings) accountData["Offerings"] = offerings updatedJsonData, err := json.Marshal(accountData) if err != nil { @@ -346,13 +344,10 @@ func (fsd *fsData) resetUnlockForUpdate(ctx context.Context, sym string, input [ return res, nil } -func (fsd *fsData) resetAccountUnlocked(ctx context.Context,sym string,input []byte) (resource.Result,error){ - res := resource.Result{} - st := fsd.st - isSet := st.MatchFlag(USERFLAG_ACCOUNT_UNLOCKED,true) - res.FlagReset = append(res.FlagReset, USERFLAG_ACCOUNT_UNLOCKED) - fmt.Println("ISSET:",isSet) - return res,nil +func (fsd *fsData) resetAccountUnlocked(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + res.FlagReset = append(res.FlagReset, USERFLAG_ACCOUNT_UNLOCKED) + return res, nil } func (fsd *fsData) checkIdentifier(ctx context.Context, sym string, input []byte) (resource.Result, error) { @@ -385,11 +380,9 @@ func (fsd *fsData) unLock(ctx context.Context, sym string, input []byte) (resour return res, nil } if fsd.st.MatchFlag(USERFLAG_ACCOUNT_UNLOCKED, false) { - //res.FlagSet = append(res.FlagSet, USERFLAG_UNLOCKFORUPDATE) res.FlagSet = append(res.FlagSet, USERFLAG_ACCOUNT_UNLOCKED) } else { res.FlagReset = append(res.FlagReset, USERFLAG_ACCOUNT_UNLOCKED) - //res.FlagReset = append(res.FlagReset, USERFLAG_UNLOCKFORUPDATE) } } return res, nil @@ -735,9 +728,8 @@ func (fsd *fsData) get_recipient(ctx context.Context, sym string, input []byte) return res, nil } - -func (fsd *fsData) getProfileInfo(ctx context.Context,sym string,input []byte) (resource.Result,error){ - res := resource.Result{} +func (fsd *fsData) getProfileInfo(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} fp := fsd.path + "_data" jsonData, err := os.ReadFile(fp) @@ -750,18 +742,15 @@ func (fsd *fsData) getProfileInfo(ctx context.Context,sym string,input []byte) ( if err != nil { return res, err } - name := accountData["FirstName"] - gender := accountData["Gender"] - age := accountData["YOB"] - location := accountData["Location"] - - // Format the data into a string - formattedData := fmt.Sprintf("Name: %s\nGender: %s\nAge: %s\nLocation: %s\n", name, gender, age, location) - + name := accountData["FirstName"] + gender := accountData["Gender"] + age := accountData["YOB"] + location := accountData["Location"] + formattedData := fmt.Sprintf("Name: %s\nGender: %s\nAge: %s\nLocation: %s\n", name, gender, age, location) res.Content = formattedData - return res,nil + return res, nil } func (fsd *fsData) get_sender(ctx context.Context, sym string, input []byte) (resource.Result, error) { @@ -960,12 +949,9 @@ func main() { rfs.AddLocalFunc("save_offerings", fs.saveOfferings) rfs.AddLocalFunc("quit_with_balance", fs.quitWithBalance) rfs.AddLocalFunc("show_update_success", fs.ShowUpdateSuccess) - rfs.AddLocalFunc("reset_unlocked",fs.resetAccountUnlocked) + rfs.AddLocalFunc("reset_unlocked", fs.resetAccountUnlocked) rfs.AddLocalFunc("reset_unlock_for_update", fs.resetUnlockForUpdate) - rfs.AddLocalFunc("get_profile_info",fs.getProfileInfo) - - - + rfs.AddLocalFunc("get_profile_info", fs.getProfileInfo) cont, err := en.Init(ctx) en.SetDebugger(engine.NewSimpleDebug(nil)) From a508f06583cc0efe096f6fa518a496856e8d69f4 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Fri, 23 Aug 2024 14:34:55 +0300 Subject: [PATCH 046/201] create an account using the API --- cmd/main.go | 15 ++------------- 1 file changed, 2 insertions(+), 13 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index 8295bc0..dbe702b 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -300,18 +300,7 @@ func (fsd *fsData) create_account(ctx context.Context, sym string, input []byte) } f.Close() - //accountResp, err := createAccount() - accountResp := accountResponse{ - Ok: true, - Result: struct { - CustodialId json.Number `json:"custodialId"` - PublicKey string `json:"publicKey"` - TrackingId string `json:"trackingId"` - }{ - CustodialId: "636", - PublicKey: "0x8d86F9D4A4eae41Dc3B68034895EA97BcA90e8c1", - TrackingId: "45c67314-7995-4890-89d6-e5af987754ac", - }} + accountResp, err := createAccount() if err != nil { fmt.Println("Failed to create account:", err) @@ -428,7 +417,7 @@ func (fsd *fsData) check_account_status(ctx context.Context, sym string, input [ accountData["Status"] = status - if status == "REVERTED" { + if status == "SUCCESS" { res.FlagSet = append(res.FlagSet, USERFLAG_ACCOUNT_SUCCESS) res.FlagReset = append(res.FlagReset, USERFLAG_ACCOUNT_PENDING) } else { From 460e9515849b8b0a2d305101babf40d0e82112ce Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Fri, 23 Aug 2024 16:01:13 +0300 Subject: [PATCH 047/201] validate PIN using the set AccountPIN --- cmd/main.go | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index dbe702b..8b8043a 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -362,8 +362,21 @@ func (fsd *fsData) checkIdentifier(ctx context.Context, sym string, input []byte func (fsd *fsData) unLock(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} pin := string(input) - if len(input) > 0 { - if pin == "0000" { + fp := fsd.path + "_data" + + jsonData, err := os.ReadFile(fp) + if err != nil { + return res, err + } + + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return res, err + } + + if len(input) > 1 { + if pin != accountData["AccountPIN"] { res.FlagSet = append(res.FlagSet, USERFLAG_INCORRECTPIN) res.FlagReset = append(res.FlagReset, USERFLAG_ACCOUNT_UNLOCKED) return res, nil From 538a06887a49b4cd9412b79a125a79cf83f7de8e Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Fri, 23 Aug 2024 18:53:24 +0300 Subject: [PATCH 048/201] change position of CATCH to correct node and route to previous node --- services/registration/amount.vis | 6 +++--- services/registration/invalid_amount.vis | 2 +- services/registration/invalid_recipient.vis | 2 +- services/registration/send.vis | 2 ++ services/registration/transaction_pin.vis | 2 -- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/services/registration/amount.vis b/services/registration/amount.vis index 07bbbd9..884c8a5 100644 --- a/services/registration/amount.vis +++ b/services/registration/amount.vis @@ -1,12 +1,12 @@ LOAD reset_transaction_amount 0 -RELOAD validate_recipient -CATCH invalid_recipient 13 1 LOAD max_amount 10 MAP max_amount MOUT back 0 HALT -INCMP _ 0 LOAD validate_amount 64 +RELOAD validate_amount +CATCH invalid_amount 17 1 +INCMP _ 0 LOAD get_recipient 12 LOAD get_sender 64 INCMP transaction_pin * diff --git a/services/registration/invalid_amount.vis b/services/registration/invalid_amount.vis index 833e81c..d5b5f03 100644 --- a/services/registration/invalid_amount.vis +++ b/services/registration/invalid_amount.vis @@ -3,5 +3,5 @@ RELOAD reset_transaction_amount MOUT retry 1 MOUT quit 9 HALT -INCMP amount 1 +INCMP _ 1 INCMP quit 9 diff --git a/services/registration/invalid_recipient.vis b/services/registration/invalid_recipient.vis index 905ad2a..09efdde 100644 --- a/services/registration/invalid_recipient.vis +++ b/services/registration/invalid_recipient.vis @@ -3,5 +3,5 @@ RELOAD transaction_reset MOUT retry 1 MOUT quit 9 HALT -INCMP send 1 +INCMP _ 1 INCMP quit 9 diff --git a/services/registration/send.vis b/services/registration/send.vis index 25d6304..d0fe211 100644 --- a/services/registration/send.vis +++ b/services/registration/send.vis @@ -2,5 +2,7 @@ LOAD transaction_reset 0 MOUT back 0 HALT LOAD validate_recipient 20 +RELOAD validate_recipient +CATCH invalid_recipient 13 1 INCMP _ 0 INCMP amount * diff --git a/services/registration/transaction_pin.vis b/services/registration/transaction_pin.vis index 983e4c6..38347ba 100644 --- a/services/registration/transaction_pin.vis +++ b/services/registration/transaction_pin.vis @@ -1,6 +1,4 @@ -RELOAD validate_amount MAP validate_amount -CATCH invalid_amount 17 1 RELOAD get_recipient MAP get_recipient RELOAD get_sender From 617a6101aac610335ef819e7eb03c701bc195636 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Fri, 23 Aug 2024 19:07:09 +0300 Subject: [PATCH 049/201] remove extra new lines --- services/registration/address.vis | 1 - services/registration/balances.vis | 1 - services/registration/community_balance.vis | 1 - services/registration/edit_profile.vis | 2 -- services/registration/enter_familyname.vis | 1 - services/registration/enter_offerings.vis | 2 -- services/registration/my_account.vis | 1 - services/registration/my_balance.vis | 1 - 8 files changed, 10 deletions(-) diff --git a/services/registration/address.vis b/services/registration/address.vis index d716499..ac7b631 100644 --- a/services/registration/address.vis +++ b/services/registration/address.vis @@ -3,4 +3,3 @@ RELOAD check_identifier MAP check_identifier HALT MOVE quit - diff --git a/services/registration/balances.vis b/services/registration/balances.vis index 7873dd2..552acdb 100644 --- a/services/registration/balances.vis +++ b/services/registration/balances.vis @@ -6,4 +6,3 @@ HALT INCMP _ 0 INCMP my_balance 1 INCMP community_balance 2 - diff --git a/services/registration/community_balance.vis b/services/registration/community_balance.vis index e6d5805..4894944 100644 --- a/services/registration/community_balance.vis +++ b/services/registration/community_balance.vis @@ -3,4 +3,3 @@ CATCH incorrect_pin 15 1 CATCH pin_entry 12 0 LOAD quit_with_balance 0 HALT - diff --git a/services/registration/edit_profile.vis b/services/registration/edit_profile.vis index a8b0e49..5c92ac2 100644 --- a/services/registration/edit_profile.vis +++ b/services/registration/edit_profile.vis @@ -15,5 +15,3 @@ INCMP enter_yob 3 INCMP enter_location 4 INCMP enter_offerings 5 INCMP view_profile 6 - - diff --git a/services/registration/enter_familyname.vis b/services/registration/enter_familyname.vis index 2085c38..93def9b 100644 --- a/services/registration/enter_familyname.vis +++ b/services/registration/enter_familyname.vis @@ -3,4 +3,3 @@ MOUT back 0 HALT INCMP _ 0 INCMP select_gender * - diff --git a/services/registration/enter_offerings.vis b/services/registration/enter_offerings.vis index eb7dad2..f48f1ea 100644 --- a/services/registration/enter_offerings.vis +++ b/services/registration/enter_offerings.vis @@ -6,5 +6,3 @@ HALT LOAD save_offerings 0 INCMP _ 0 INCMP pin_entry * - - diff --git a/services/registration/my_account.vis b/services/registration/my_account.vis index 48f12ee..20eb6d5 100644 --- a/services/registration/my_account.vis +++ b/services/registration/my_account.vis @@ -12,4 +12,3 @@ INCMP edit_profile 1 INCMP balances 3 INCMP pin_management 5 INCMP address 6 - diff --git a/services/registration/my_balance.vis b/services/registration/my_balance.vis index e6d5805..4894944 100644 --- a/services/registration/my_balance.vis +++ b/services/registration/my_balance.vis @@ -3,4 +3,3 @@ CATCH incorrect_pin 15 1 CATCH pin_entry 12 0 LOAD quit_with_balance 0 HALT - From 3007989b8e187ce9a566e161faaf96ded74350fd Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Sat, 24 Aug 2024 06:11:15 +0300 Subject: [PATCH 050/201] updates --- services/registration/edit_profile.vis | 4 ++-- services/registration/{enter_location => enter_loca} | 0 .../{enter_location.vis => enter_loca.vis} | 3 +++ .../{enter_location_swa => enter_loca_swa} | 0 services/registration/{enter_offerings => enter_off} | 0 services/registration/enter_off.vis | 6 ++++++ .../{enter_offerings_swa => enter_off_swa} | 0 services/registration/enter_offerings.vis | 10 ---------- services/registration/list_offering | 0 services/registration/list_offering.vis | 0 10 files changed, 11 insertions(+), 12 deletions(-) rename services/registration/{enter_location => enter_loca} (100%) rename services/registration/{enter_location.vis => enter_loca.vis} (95%) rename services/registration/{enter_location_swa => enter_loca_swa} (100%) rename services/registration/{enter_offerings => enter_off} (100%) create mode 100644 services/registration/enter_off.vis rename services/registration/{enter_offerings_swa => enter_off_swa} (100%) delete mode 100644 services/registration/enter_offerings.vis create mode 100644 services/registration/list_offering create mode 100644 services/registration/list_offering.vis diff --git a/services/registration/edit_profile.vis b/services/registration/edit_profile.vis index a8b0e49..ca7c425 100644 --- a/services/registration/edit_profile.vis +++ b/services/registration/edit_profile.vis @@ -12,8 +12,8 @@ INCMP _ 0 INCMP enter_name 1 INCMP select_gender 2 INCMP enter_yob 3 -INCMP enter_location 4 -INCMP enter_offerings 5 +INCMP enter_loca 4 INCMP view_profile 6 + diff --git a/services/registration/enter_location b/services/registration/enter_loca similarity index 100% rename from services/registration/enter_location rename to services/registration/enter_loca diff --git a/services/registration/enter_location.vis b/services/registration/enter_loca.vis similarity index 95% rename from services/registration/enter_location.vis rename to services/registration/enter_loca.vis index 7ef9348..effecb0 100644 --- a/services/registration/enter_location.vis +++ b/services/registration/enter_loca.vis @@ -3,3 +3,6 @@ MOUT back 0 HALT INCMP _ 0 INCMP enter_offerings * + + + diff --git a/services/registration/enter_location_swa b/services/registration/enter_loca_swa similarity index 100% rename from services/registration/enter_location_swa rename to services/registration/enter_loca_swa diff --git a/services/registration/enter_offerings b/services/registration/enter_off similarity index 100% rename from services/registration/enter_offerings rename to services/registration/enter_off diff --git a/services/registration/enter_off.vis b/services/registration/enter_off.vis new file mode 100644 index 0000000..90e44da --- /dev/null +++ b/services/registration/enter_off.vis @@ -0,0 +1,6 @@ +MOUT back 0 +HALT +INCMP _ 0 + + + diff --git a/services/registration/enter_offerings_swa b/services/registration/enter_off_swa similarity index 100% rename from services/registration/enter_offerings_swa rename to services/registration/enter_off_swa diff --git a/services/registration/enter_offerings.vis b/services/registration/enter_offerings.vis deleted file mode 100644 index eb7dad2..0000000 --- a/services/registration/enter_offerings.vis +++ /dev/null @@ -1,10 +0,0 @@ -LOAD save_location 0 -CATCH incorrect_pin 15 1 -CATCH update_success 16 1 -MOUT back 0 -HALT -LOAD save_offerings 0 -INCMP _ 0 -INCMP pin_entry * - - diff --git a/services/registration/list_offering b/services/registration/list_offering new file mode 100644 index 0000000..e69de29 diff --git a/services/registration/list_offering.vis b/services/registration/list_offering.vis new file mode 100644 index 0000000..e69de29 From 730c92c28417b8833fd4560baaec24b07c8ee56f Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Sat, 24 Aug 2024 17:08:38 +0300 Subject: [PATCH 051/201] rename symbols,add check for invalid date inputs --- cmd/main.go | 94 +++++++++++++++++++++++++++++++++-------------------- 1 file changed, 58 insertions(+), 36 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index 8b8043a..4169c58 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -10,6 +10,7 @@ import ( "net/http" "os" "path" + "regexp" "time" "git.defalsify.org/vise.git/cache" @@ -34,6 +35,7 @@ const ( USERFLAG_QUERYPIN USERFLAG_VALIDPIN USERFLAG_INVALIDPIN + USERFLAG_INCORRECTDATEFORMAT ) const ( @@ -87,7 +89,7 @@ func codeFromCtx(ctx context.Context) string { return code } -func (fsd *fsData) saveFirstName(cxt context.Context, sym string, input []byte) (resource.Result, error) { +func (fsd *fsData) save_firstname(cxt context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} fp := fsd.path + "_data" @@ -118,7 +120,7 @@ func (fsd *fsData) saveFirstName(cxt context.Context, sym string, input []byte) return res, nil } -func (fsd *fsData) saveFamilyName(cxt context.Context, sym string, input []byte) (resource.Result, error) { +func (fsd *fsData) save_familyname(cxt context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} fp := fsd.path + "_data" @@ -149,7 +151,7 @@ func (fsd *fsData) saveFamilyName(cxt context.Context, sym string, input []byte) return res, nil } -func (fsd *fsData) saveYOB(cxt context.Context, sym string, input []byte) (resource.Result, error) { +func (fsd *fsData) save_yob(cxt context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} fp := fsd.path + "_data" jsonData, err := os.ReadFile(fp) @@ -178,7 +180,7 @@ func (fsd *fsData) saveYOB(cxt context.Context, sym string, input []byte) (resou return res, nil } -func (fsd *fsData) saveLocation(cxt context.Context, sym string, input []byte) (resource.Result, error) { +func (fsd *fsData) save_location(cxt context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} fp := fsd.path + "_data" jsonData, err := os.ReadFile(fp) @@ -208,7 +210,7 @@ func (fsd *fsData) saveLocation(cxt context.Context, sym string, input []byte) ( return res, nil } -func (fsd *fsData) saveGender(ctx context.Context, sym string, input []byte) (resource.Result, error) { +func (fsd *fsData) save_gender(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} fp := fsd.path + "_data" jsonData, err := os.ReadFile(fp) @@ -231,7 +233,6 @@ func (fsd *fsData) saveGender(ctx context.Context, sym string, input []byte) (re case "3": gender = "Other" } - fmt.Println("gender", gender) accountData["Gender"] = gender updatedJsonData, err := json.Marshal(accountData) if err != nil { @@ -246,7 +247,7 @@ func (fsd *fsData) saveGender(ctx context.Context, sym string, input []byte) (re return res, nil } -func (fsd *fsData) saveOfferings(ctx context.Context, sym string, input []byte) (resource.Result, error) { +func (fsd *fsData) save_offerings(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} fp := fsd.path + "_data" jsonData, err := os.ReadFile(fp) @@ -273,7 +274,7 @@ func (fsd *fsData) saveOfferings(ctx context.Context, sym string, input []byte) return res, nil } -func (fsd *fsData) SetLanguageSelected(ctx context.Context, sym string, input []byte) (resource.Result, error) { +func (fsd *fsData) set_language(ctx context.Context, sym string, input []byte) (resource.Result, error) { inputStr := string(input) res := resource.Result{} switch inputStr { @@ -327,19 +328,19 @@ func (fsd *fsData) create_account(ctx context.Context, sym string, input []byte) return res, err } -func (fsd *fsData) resetUnlockForUpdate(ctx context.Context, sym string, input []byte) (resource.Result, error) { +func (fsd *fsData) reset_unlock_for_update(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} res.FlagReset = append(res.FlagReset, USERFLAG_UNLOCKFORUPDATE) return res, nil } -func (fsd *fsData) resetAccountUnlocked(ctx context.Context, sym string, input []byte) (resource.Result, error) { +func (fsd *fsData) reset_account_unlocked(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} res.FlagReset = append(res.FlagReset, USERFLAG_ACCOUNT_UNLOCKED) return res, nil } -func (fsd *fsData) checkIdentifier(ctx context.Context, sym string, input []byte) (resource.Result, error) { +func (fsd *fsData) check_identifier(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} fp := fsd.path + "_data" @@ -359,7 +360,7 @@ func (fsd *fsData) checkIdentifier(ctx context.Context, sym string, input []byte return res, nil } -func (fsd *fsData) unLock(ctx context.Context, sym string, input []byte) (resource.Result, error) { +func (fsd *fsData) unlock(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} pin := string(input) fp := fsd.path + "_data" @@ -382,6 +383,8 @@ func (fsd *fsData) unLock(ctx context.Context, sym string, input []byte) (resour return res, nil } if fsd.st.MatchFlag(USERFLAG_ACCOUNT_UNLOCKED, false) { + res.FlagReset = append(res.FlagReset, USERFLAG_INCORRECTPIN) + res.FlagSet = append(res.FlagSet, USERFLAG_UNLOCKFORUPDATE) res.FlagSet = append(res.FlagSet, USERFLAG_ACCOUNT_UNLOCKED) } else { res.FlagReset = append(res.FlagReset, USERFLAG_ACCOUNT_UNLOCKED) @@ -390,7 +393,7 @@ func (fsd *fsData) unLock(ctx context.Context, sym string, input []byte) (resour return res, nil } -func (fsd *fsData) ResetIncorrectPin(ctx context.Context, sym string, input []byte) (resource.Result, error) { +func (fsd *fsData) reset_incorrect_pin(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} isIncorrectPinSet := fsd.st.MatchFlag(USERFLAG_INCORRECTPIN, true) if isIncorrectPinSet { @@ -401,10 +404,7 @@ func (fsd *fsData) ResetIncorrectPin(ctx context.Context, sym string, input []by return res, nil } -func (fsd *fsData) ShowUpdateSuccess(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} - return res, nil -} + func (fsd *fsData) check_account_status(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} @@ -507,7 +507,28 @@ func (fsd *fsData) quit(ctx context.Context, sym string, input []byte) (resource return res, nil } -func (fsd *fsData) checkBalance(ctx context.Context, sym string, input []byte) (resource.Result, error) { +func (fsd *fsData) verify_yob(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + date := string(input) + + dateRegex := regexp.MustCompile(`^\d{2}/\d{2}/\d{4}$`) + isCorrectFormat := dateRegex.MatchString(date) + if !isCorrectFormat { + res.FlagSet = append(res.FlagSet, USERFLAG_INCORRECTDATEFORMAT) + } else { + res.FlagReset = append(res.FlagReset, USERFLAG_INCORRECTDATEFORMAT) + } + + return res, nil +} + +func (fsd *fsData) reser_incorrect_yob(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + res.FlagReset = append(res.FlagReset, USERFLAG_INCORRECTDATEFORMAT) + return res, nil +} + +func (fsd *fsData) check_balance(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} fp := fsd.path + "_data" @@ -730,7 +751,7 @@ func (fsd *fsData) get_recipient(ctx context.Context, sym string, input []byte) return res, nil } -func (fsd *fsData) getProfileInfo(ctx context.Context, sym string, input []byte) (resource.Result, error) { +func (fsd *fsData) get_profile_info(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} fp := fsd.path + "_data" @@ -775,7 +796,7 @@ func (fsd *fsData) get_sender(ctx context.Context, sym string, input []byte) (re return res, nil } -func (fsd *fsData) quitWithBalance(ctx context.Context, sym string, input []byte) (resource.Result, error) { +func (fsd *fsData) quit_with_balance(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} fp := fsd.path + "_data" @@ -926,15 +947,15 @@ func main() { path: fp, st: &st, } - rfs.AddLocalFunc("select_language", fs.SetLanguageSelected) + rfs.AddLocalFunc("select_language", fs.set_language) rfs.AddLocalFunc("create_account", fs.create_account) rfs.AddLocalFunc("save_pin", fs.save_pin) rfs.AddLocalFunc("verify_pin", fs.verify_pin) - rfs.AddLocalFunc("check_identifier", fs.checkIdentifier) + rfs.AddLocalFunc("check_identifier", fs.check_identifier) rfs.AddLocalFunc("check_account_status", fs.check_account_status) - rfs.AddLocalFunc("unlock_account", fs.unLock) + rfs.AddLocalFunc("unlock_account", fs.unlock) rfs.AddLocalFunc("quit", fs.quit) - rfs.AddLocalFunc("check_balance", fs.checkBalance) + rfs.AddLocalFunc("check_balance", fs.check_balance) rfs.AddLocalFunc("validate_recipient", fs.validate_recipient) rfs.AddLocalFunc("transaction_reset", fs.transaction_reset) rfs.AddLocalFunc("max_amount", fs.max_amount) @@ -942,18 +963,19 @@ func main() { rfs.AddLocalFunc("reset_transaction_amount", fs.reset_transaction_amount) rfs.AddLocalFunc("get_recipient", fs.get_recipient) rfs.AddLocalFunc("get_sender", fs.get_sender) - rfs.AddLocalFunc("reset_incorrect", fs.ResetIncorrectPin) - rfs.AddLocalFunc("save_firstname", fs.saveFirstName) - rfs.AddLocalFunc("save_familyname", fs.saveFamilyName) - rfs.AddLocalFunc("save_gender", fs.saveGender) - rfs.AddLocalFunc("save_location", fs.saveLocation) - rfs.AddLocalFunc("save_yob", fs.saveYOB) - rfs.AddLocalFunc("save_offerings", fs.saveOfferings) - rfs.AddLocalFunc("quit_with_balance", fs.quitWithBalance) - rfs.AddLocalFunc("show_update_success", fs.ShowUpdateSuccess) - rfs.AddLocalFunc("reset_unlocked", fs.resetAccountUnlocked) - rfs.AddLocalFunc("reset_unlock_for_update", fs.resetUnlockForUpdate) - rfs.AddLocalFunc("get_profile_info", fs.getProfileInfo) + rfs.AddLocalFunc("reset_incorrect", fs.reset_incorrect_pin) + rfs.AddLocalFunc("save_firstname", fs.save_firstname) + rfs.AddLocalFunc("save_familyname", fs.save_familyname) + rfs.AddLocalFunc("save_gender", fs.save_gender) + rfs.AddLocalFunc("save_location", fs.save_location) + rfs.AddLocalFunc("save_yob", fs.save_yob) + rfs.AddLocalFunc("save_offerings", fs.save_offerings) + rfs.AddLocalFunc("quit_with_balance", fs.quit_with_balance) + rfs.AddLocalFunc("reset_unlocked", fs.reset_account_unlocked) + rfs.AddLocalFunc("reset_unlock_for_update", fs.reset_unlock_for_update) + rfs.AddLocalFunc("get_profile_info", fs.get_profile_info) + rfs.AddLocalFunc("verify_yob", fs.verify_yob) + rfs.AddLocalFunc("reset_incorrect_date_format", fs.reser_incorrect_yob) cont, err := en.Init(ctx) en.SetDebugger(engine.NewSimpleDebug(nil)) From a7d27f142e791f41eea4ca69287907983c71b1c0 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Sat, 24 Aug 2024 17:09:07 +0300 Subject: [PATCH 052/201] show quit menu option after showing address --- services/registration/address.vis | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/registration/address.vis b/services/registration/address.vis index ac7b631..f3ba04a 100644 --- a/services/registration/address.vis +++ b/services/registration/address.vis @@ -1,5 +1,6 @@ LOAD check_identifier 0 RELOAD check_identifier MAP check_identifier +MOUT quit 9 HALT -MOVE quit +INCMP quit 9 From 6a35101d69c97939a3b440502c4d72fffbb2a7f0 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Sat, 24 Aug 2024 17:11:05 +0300 Subject: [PATCH 053/201] show quit option after performing an update --- services/registration/update_success.vis | 2 ++ 1 file changed, 2 insertions(+) diff --git a/services/registration/update_success.vis b/services/registration/update_success.vis index 07fcf94..832ef22 100644 --- a/services/registration/update_success.vis +++ b/services/registration/update_success.vis @@ -1,3 +1,5 @@ MOUT back 0 +MOUT quit 9 HALT INCMP ^ 0 +INCMP quit 9 From 37809a05b4bdf4f22a2f03c7286816df51b239a9 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Sat, 24 Aug 2024 17:12:46 +0300 Subject: [PATCH 054/201] cleanup code,define node for showing invalid date formats --- services/registration/{enter_loca => enter_location} | 0 .../registration/{enter_loca.vis => enter_location.vis} | 1 + .../registration/{enter_loca_swa => enter_location_swa} | 0 services/registration/{enter_off => enter_offerings} | 0 .../registration/{enter_off_swa => enter_offerings_swa} | 0 services/registration/enter_yob.vis | 1 + services/registration/incorrect_date_format | 2 ++ services/registration/incorrect_date_format.vis | 6 ++++++ services/registration/incorrect_date_format_swa | 0 9 files changed, 10 insertions(+) rename services/registration/{enter_loca => enter_location} (100%) rename services/registration/{enter_loca.vis => enter_location.vis} (67%) rename services/registration/{enter_loca_swa => enter_location_swa} (100%) rename services/registration/{enter_off => enter_offerings} (100%) rename services/registration/{enter_off_swa => enter_offerings_swa} (100%) create mode 100644 services/registration/incorrect_date_format create mode 100644 services/registration/incorrect_date_format.vis create mode 100644 services/registration/incorrect_date_format_swa diff --git a/services/registration/enter_loca b/services/registration/enter_location similarity index 100% rename from services/registration/enter_loca rename to services/registration/enter_location diff --git a/services/registration/enter_loca.vis b/services/registration/enter_location.vis similarity index 67% rename from services/registration/enter_loca.vis rename to services/registration/enter_location.vis index effecb0..9245bb1 100644 --- a/services/registration/enter_loca.vis +++ b/services/registration/enter_location.vis @@ -1,3 +1,4 @@ +CATCH incorrect_date_format 21 1 LOAD save_yob 0 MOUT back 0 HALT diff --git a/services/registration/enter_loca_swa b/services/registration/enter_location_swa similarity index 100% rename from services/registration/enter_loca_swa rename to services/registration/enter_location_swa diff --git a/services/registration/enter_off b/services/registration/enter_offerings similarity index 100% rename from services/registration/enter_off rename to services/registration/enter_offerings diff --git a/services/registration/enter_off_swa b/services/registration/enter_offerings_swa similarity index 100% rename from services/registration/enter_off_swa rename to services/registration/enter_offerings_swa diff --git a/services/registration/enter_yob.vis b/services/registration/enter_yob.vis index d169e05..0a5b778 100644 --- a/services/registration/enter_yob.vis +++ b/services/registration/enter_yob.vis @@ -2,4 +2,5 @@ LOAD save_gender 0 MOUT back 0 HALT INCMP _ 0 +LOAD verify_yob 8 INCMP enter_location * diff --git a/services/registration/incorrect_date_format b/services/registration/incorrect_date_format new file mode 100644 index 0000000..517ea52 --- /dev/null +++ b/services/registration/incorrect_date_format @@ -0,0 +1,2 @@ +Unsuported date format +Please provide date format as 12/01/1972 diff --git a/services/registration/incorrect_date_format.vis b/services/registration/incorrect_date_format.vis new file mode 100644 index 0000000..e94db5d --- /dev/null +++ b/services/registration/incorrect_date_format.vis @@ -0,0 +1,6 @@ +LOAD reset_incorrect_date_format 8 +MOUT retry 1 +MOUT quit 9 +HALT +INCMP enter_yob 1 +INCMP quit 9 diff --git a/services/registration/incorrect_date_format_swa b/services/registration/incorrect_date_format_swa new file mode 100644 index 0000000..e69de29 From a1fde55d8d0e07536a333abe47fbff208088d46f Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Sun, 25 Aug 2024 22:13:41 +0300 Subject: [PATCH 055/201] remove unneccesary if-else --- cmd/main.go | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index 4169c58..63126f0 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -395,12 +395,7 @@ func (fsd *fsData) unlock(ctx context.Context, sym string, input []byte) (resour func (fsd *fsData) reset_incorrect_pin(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - isIncorrectPinSet := fsd.st.MatchFlag(USERFLAG_INCORRECTPIN, true) - if isIncorrectPinSet { - res.FlagReset = append(res.FlagReset, USERFLAG_INCORRECTPIN) - } else { - res.FlagReset = append(res.FlagReset, USERFLAG_INCORRECTPIN) - } + res.FlagReset = append(res.FlagReset, USERFLAG_INCORRECTPIN) return res, nil } From cd28fd0b5eaddf7e79f1006c5522179bea104b1b Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Sun, 25 Aug 2024 22:18:55 +0300 Subject: [PATCH 056/201] fix typo on rese_ incorrect_yob --- cmd/main.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index 63126f0..4246ae2 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -517,7 +517,7 @@ func (fsd *fsData) verify_yob(ctx context.Context, sym string, input []byte) (re return res, nil } -func (fsd *fsData) reser_incorrect_yob(ctx context.Context, sym string, input []byte) (resource.Result, error) { +func (fsd *fsData) reset_incorrect_yob(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} res.FlagReset = append(res.FlagReset, USERFLAG_INCORRECTDATEFORMAT) return res, nil @@ -970,7 +970,7 @@ func main() { rfs.AddLocalFunc("reset_unlock_for_update", fs.reset_unlock_for_update) rfs.AddLocalFunc("get_profile_info", fs.get_profile_info) rfs.AddLocalFunc("verify_yob", fs.verify_yob) - rfs.AddLocalFunc("reset_incorrect_date_format", fs.reser_incorrect_yob) + rfs.AddLocalFunc("reset_incorrect_date_format", fs.reset_incorrect_yob) cont, err := en.Init(ctx) en.SetDebugger(engine.NewSimpleDebug(nil)) From ef1034885283f429ad2ebc15d8735fd38edef146 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Mon, 26 Aug 2024 12:09:48 +0300 Subject: [PATCH 057/201] setup file for handling configurations --- config/config.go | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 config/config.go diff --git a/config/config.go b/config/config.go new file mode 100644 index 0000000..0fa5225 --- /dev/null +++ b/config/config.go @@ -0,0 +1,6 @@ +package config + + + + +//We define our endpoints here? From 30504b81e2953a43c188d1761e16054fc41be7a3 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Mon, 26 Aug 2024 12:10:16 +0300 Subject: [PATCH 058/201] setup structure for handling api calls --- internal/server/handlers/balancecheck.go | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 internal/server/handlers/balancecheck.go diff --git a/internal/server/handlers/balancecheck.go b/internal/server/handlers/balancecheck.go new file mode 100644 index 0000000..38fb232 --- /dev/null +++ b/internal/server/handlers/balancecheck.go @@ -0,0 +1,4 @@ +package handlers + + + From ee649dc79e7af6a7c2d2e01ce25ac44f07ec4269 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Mon, 26 Aug 2024 12:10:39 +0300 Subject: [PATCH 059/201] setup models for handling api responses --- internal/models/accountresponse.go | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 internal/models/accountresponse.go diff --git a/internal/models/accountresponse.go b/internal/models/accountresponse.go new file mode 100644 index 0000000..342de0a --- /dev/null +++ b/internal/models/accountresponse.go @@ -0,0 +1,20 @@ +package models + +import ( + "encoding/json" + "time" +) + + +type trackStatusResponse struct { + Ok bool `json:"ok"` + Result struct { + Transaction struct { + CreatedAt time.Time `json:"createdAt"` + Status string `json:"status"` + TransferValue json.Number `json:"transferValue"` + TxHash string `json:"txHash"` + TxType string `json:"txType"` + } + } `json:"result"` +} \ No newline at end of file From 430c5d32c8d85bb184b7153dd71e08375d9979e1 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Mon, 26 Aug 2024 13:31:20 +0300 Subject: [PATCH 060/201] define api calls response --- internal/models/accountresponse.go | 15 +++++---------- internal/models/balanceresponse.go | 12 ++++++++++++ internal/models/trackstatusresponse.go | 20 ++++++++++++++++++++ 3 files changed, 37 insertions(+), 10 deletions(-) create mode 100644 internal/models/balanceresponse.go create mode 100644 internal/models/trackstatusresponse.go diff --git a/internal/models/accountresponse.go b/internal/models/accountresponse.go index 342de0a..1422a20 100644 --- a/internal/models/accountresponse.go +++ b/internal/models/accountresponse.go @@ -2,19 +2,14 @@ package models import ( "encoding/json" - "time" + ) - -type trackStatusResponse struct { +type AccountResponse struct { Ok bool `json:"ok"` Result struct { - Transaction struct { - CreatedAt time.Time `json:"createdAt"` - Status string `json:"status"` - TransferValue json.Number `json:"transferValue"` - TxHash string `json:"txHash"` - TxType string `json:"txType"` - } + CustodialId json.Number `json:"custodialId"` + PublicKey string `json:"publicKey"` + TrackingId string `json:"trackingId"` } `json:"result"` } \ No newline at end of file diff --git a/internal/models/balanceresponse.go b/internal/models/balanceresponse.go new file mode 100644 index 0000000..57c8e5a --- /dev/null +++ b/internal/models/balanceresponse.go @@ -0,0 +1,12 @@ +package models + +import "encoding/json" + + +type BalanceResponse struct { + Ok bool `json:"ok"` + Result struct { + Balance string `json:"balance"` + Nonce json.Number `json:"nonce"` + } `json:"result"` +} diff --git a/internal/models/trackstatusresponse.go b/internal/models/trackstatusresponse.go new file mode 100644 index 0000000..6054281 --- /dev/null +++ b/internal/models/trackstatusresponse.go @@ -0,0 +1,20 @@ +package models + +import ( + "encoding/json" + "time" +) + + +type TrackStatusResponse struct { + Ok bool `json:"ok"` + Result struct { + Transaction struct { + CreatedAt time.Time `json:"createdAt"` + Status string `json:"status"` + TransferValue json.Number `json:"transferValue"` + TxHash string `json:"txHash"` + TxType string `json:"txType"` + } + } `json:"result"` +} \ No newline at end of file From 36d3f05a31376db3cc457b54b16195fdd15f4988 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Mon, 26 Aug 2024 13:32:12 +0300 Subject: [PATCH 061/201] move api calls in main to handlers package --- internal/server/handlers/accountstatus.go | 34 +++++++++++++++++++++++ internal/server/handlers/balancecheck.go | 29 +++++++++++++++++++ internal/server/handlers/createaccount.go | 32 +++++++++++++++++++++ 3 files changed, 95 insertions(+) create mode 100644 internal/server/handlers/accountstatus.go create mode 100644 internal/server/handlers/createaccount.go diff --git a/internal/server/handlers/accountstatus.go b/internal/server/handlers/accountstatus.go new file mode 100644 index 0000000..1992acc --- /dev/null +++ b/internal/server/handlers/accountstatus.go @@ -0,0 +1,34 @@ +package handlers + +import ( + "encoding/json" + "io" + "net/http" + + "git.grassecon.net/urdt/ussd/config" + "git.grassecon.net/urdt/ussd/internal/models" +) + + +func CheckAccountStatus(trackingId string) (string, error) { + resp, err := http.Get(config.TrackStatusURL + trackingId) + if err != nil { + return "", err + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return "", err + } + + var trackResp models.TrackStatusResponse + err = json.Unmarshal(body, &trackResp) + if err != nil { + return "", err + } + + status := trackResp.Result.Transaction.Status + + return status, nil +} \ No newline at end of file diff --git a/internal/server/handlers/balancecheck.go b/internal/server/handlers/balancecheck.go index 38fb232..137050d 100644 --- a/internal/server/handlers/balancecheck.go +++ b/internal/server/handlers/balancecheck.go @@ -1,4 +1,33 @@ package handlers +import ( + "encoding/json" + "io" + "net/http" + "git.grassecon.net/urdt/ussd/config" + "git.grassecon.net/urdt/ussd/internal/models" +) +func CheckBalance(publicKey string) (string, error) { + + resp, err := http.Get(config.BalanceURL + publicKey) + if err != nil { + return "0.0", err + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return "0.0", err + } + + var balanceResp models.BalanceResponse + err = json.Unmarshal(body, &balanceResp) + if err != nil { + return "0.0", err + } + + balance := balanceResp.Result.Balance + return balance, nil +} diff --git a/internal/server/handlers/createaccount.go b/internal/server/handlers/createaccount.go new file mode 100644 index 0000000..5175a3b --- /dev/null +++ b/internal/server/handlers/createaccount.go @@ -0,0 +1,32 @@ +package handlers + +import ( + "encoding/json" + "io" + "net/http" + + "git.grassecon.net/urdt/ussd/config" + "git.grassecon.net/urdt/ussd/internal/models" +) + + +func CreateAccount() (*models.AccountResponse, error) { + resp, err := http.Post(config.CreateAccountURL, "application/json", nil) + if err != nil { + return nil, err + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, err + } + + var accountResp models.AccountResponse + err = json.Unmarshal(body, &accountResp) + if err != nil { + return nil, err + } + + return &accountResp, nil +} \ No newline at end of file From 90f6d26f6d8c3f650c8c70cbb789a3b50980b7c2 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Mon, 26 Aug 2024 13:37:54 +0300 Subject: [PATCH 062/201] add function to calculate age --- internal/utils/age.go | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 internal/utils/age.go diff --git a/internal/utils/age.go b/internal/utils/age.go new file mode 100644 index 0000000..56c3e2b --- /dev/null +++ b/internal/utils/age.go @@ -0,0 +1,21 @@ +package utils + +import "time" + + +func CalculateAge(birthdate, today time.Time) int { + today = today.In(birthdate.Location()) + ty, tm, td := today.Date() + today = time.Date(ty, tm, td, 0, 0, 0, 0, time.UTC) + by, bm, bd := birthdate.Date() + birthdate = time.Date(by, bm, bd, 0, 0, 0, 0, time.UTC) + if today.Before(birthdate) { + return 0 + } + age := ty - by + anniversary := birthdate.AddDate(age, 0, 0) + if anniversary.After(today) { + age-- + } + return age +} \ No newline at end of file From d86de39b390b4148c535467d49124de159f1f91f Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Mon, 26 Aug 2024 13:38:14 +0300 Subject: [PATCH 063/201] define the api endpoints --- config/config.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/config/config.go b/config/config.go index 0fa5225..0571503 100644 --- a/config/config.go +++ b/config/config.go @@ -2,5 +2,9 @@ package config +const ( + CreateAccountURL = "https://custodial.sarafu.africa/api/account/create" + TrackStatusURL = "https://custodial.sarafu.africa/api/track/" + BalanceURL = "https://custodial.sarafu.africa/api/account/status/" +) -//We define our endpoints here? From 3c66a2ded2440fda52fd64db8e00ffae36012ac6 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Mon, 26 Aug 2024 13:40:20 +0300 Subject: [PATCH 064/201] handle age calculation,call apis from handlers --- cmd/main.go | 150 +++++++++------------------------------------------- 1 file changed, 26 insertions(+), 124 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index 4246ae2..407fcf1 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -6,8 +6,6 @@ import ( "encoding/json" "flag" "fmt" - "io" - "net/http" "os" "path" "regexp" @@ -19,6 +17,8 @@ import ( "git.defalsify.org/vise.git/persist" "git.defalsify.org/vise.git/resource" "git.defalsify.org/vise.git/state" + "git.grassecon.net/urdt/ussd/internal/server/handlers" + "git.grassecon.net/urdt/ussd/internal/utils" ) const ( @@ -38,42 +38,6 @@ const ( USERFLAG_INCORRECTDATEFORMAT ) -const ( - createAccountURL = "https://custodial.sarafu.africa/api/account/create" - trackStatusURL = "https://custodial.sarafu.africa/api/track/" - checkBalanceURL = "https://custodial.sarafu.africa/api/account/status/" -) - -type accountResponse struct { - Ok bool `json:"ok"` - Result struct { - CustodialId json.Number `json:"custodialId"` - PublicKey string `json:"publicKey"` - TrackingId string `json:"trackingId"` - } `json:"result"` -} - -type trackStatusResponse struct { - Ok bool `json:"ok"` - Result struct { - Transaction struct { - CreatedAt time.Time `json:"createdAt"` - Status string `json:"status"` - TransferValue json.Number `json:"transferValue"` - TxHash string `json:"txHash"` - TxType string `json:"txType"` - } - } `json:"result"` -} - -type balanceResponse struct { - Ok bool `json:"ok"` - Result struct { - Balance string `json:"balance"` - Nonce json.Number `json:"nonce"` - } `json:"result"` -} - type fsData struct { path string st *state.State @@ -300,9 +264,7 @@ func (fsd *fsData) create_account(ctx context.Context, sym string, input []byte) return res, err } f.Close() - - accountResp, err := createAccount() - + accountResp, err := handlers.CreateAccount() if err != nil { fmt.Println("Failed to create account:", err) return res, err @@ -399,8 +361,6 @@ func (fsd *fsData) reset_incorrect_pin(ctx context.Context, sym string, input [] return res, nil } - - func (fsd *fsData) check_account_status(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} fp := fsd.path + "_data" @@ -416,7 +376,8 @@ func (fsd *fsData) check_account_status(ctx context.Context, sym string, input [ return res, err } - status, err := checkAccountStatus(accountData["TrackingId"]) + //status, err := checkAccountStatus(accountData["TrackingId"]) + status, err := handlers.CheckAccountStatus(accountData["TrackingId"]) if err != nil { fmt.Println("Error checking account status:", err) @@ -446,50 +407,6 @@ func (fsd *fsData) check_account_status(ctx context.Context, sym string, input [ return res, nil } -func createAccount() (*accountResponse, error) { - resp, err := http.Post(createAccountURL, "application/json", nil) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := io.ReadAll(resp.Body) - if err != nil { - return nil, err - } - - var accountResp accountResponse - err = json.Unmarshal(body, &accountResp) - if err != nil { - return nil, err - } - - return &accountResp, nil -} - -func checkAccountStatus(trackingId string) (string, error) { - resp, err := http.Get(trackStatusURL + trackingId) - if err != nil { - return "", err - } - defer resp.Body.Close() - - body, err := io.ReadAll(resp.Body) - if err != nil { - return "", err - } - - var trackResp trackStatusResponse - err = json.Unmarshal(body, &trackResp) - if err != nil { - return "", err - } - - status := trackResp.Result.Transaction.Status - - return status, nil -} - func (fsd *fsData) quit(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} switch codeFromCtx(ctx) { @@ -527,37 +444,19 @@ func (fsd *fsData) check_balance(ctx context.Context, sym string, input []byte) res := resource.Result{} fp := fsd.path + "_data" - jsonData, err := os.ReadFile(fp) if err != nil { return res, err } - var accountData map[string]string err = json.Unmarshal(jsonData, &accountData) if err != nil { return res, err } - - resp, err := http.Get(checkBalanceURL + accountData["PublicKey"]) + balance, err := handlers.CheckBalance(accountData["PublicKey"]) if err != nil { return res, nil } - defer resp.Body.Close() - - body, err := io.ReadAll(resp.Body) - if err != nil { - return res, nil - } - - var balanceResp balanceResponse - err = json.Unmarshal(body, &balanceResp) - if err != nil { - return res, nil - } - - balance := balanceResp.Result.Balance - res.Content = balance return res, nil @@ -760,12 +659,28 @@ func (fsd *fsData) get_profile_info(ctx context.Context, sym string, input []byt if err != nil { return res, err } - name := accountData["FirstName"] + name := accountData["FirstName"] + " " + accountData["FamilyName"] gender := accountData["Gender"] - age := accountData["YOB"] + yob := accountData["YOB"] location := accountData["Location"] + offerings := accountData["Offerings"] - formattedData := fmt.Sprintf("Name: %s\nGender: %s\nAge: %s\nLocation: %s\n", name, gender, age, location) + layout := "02/01/2006" + + birthdate, err := time.Parse(layout, yob) + if err != nil { + return res, err + } + + currentDate := time.Now() + formattedDate := currentDate.Format(layout) + today, err := time.Parse(layout, formattedDate) + if err != nil { + return res, nil + } + age := utils.CalculateAge(birthdate, today) + + formattedData := fmt.Sprintf("Name: %s\nGender: %s\nAge: %d\nLocation: %s\nYou provide: %s\n", name, gender, age, location, offerings) res.Content = formattedData return res, nil @@ -805,23 +720,10 @@ func (fsd *fsData) quit_with_balance(ctx context.Context, sym string, input []by if err != nil { return res, err } - resp, err := http.Get(checkBalanceURL + accountData["PublicKey"]) + balance, err := handlers.CheckBalance(accountData["PublicKey"]) if err != nil { return res, nil } - defer resp.Body.Close() - - body, err := io.ReadAll(resp.Body) - if err != nil { - return res, nil - } - - var balanceResp balanceResponse - err = json.Unmarshal(body, &balanceResp) - if err != nil { - return res, nil - } - balance := balanceResp.Result.Balance res.Content = fmt.Sprintf("Your account balance is: %s", balance) res.FlagReset = append(res.FlagReset, USERFLAG_ACCOUNT_UNLOCKED) return res, nil From 68dc77d5eb62cddddb4d1d39caca30080dc3dfd5 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Mon, 26 Aug 2024 14:34:38 +0300 Subject: [PATCH 065/201] added flags model --- cmd/main.go | 84 ++++++++++++++++------------------------ internal/models/flags.go | 20 ++++++++++ 2 files changed, 54 insertions(+), 50 deletions(-) create mode 100644 internal/models/flags.go diff --git a/cmd/main.go b/cmd/main.go index 407fcf1..61f015f 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -17,27 +17,11 @@ import ( "git.defalsify.org/vise.git/persist" "git.defalsify.org/vise.git/resource" "git.defalsify.org/vise.git/state" + "git.grassecon.net/urdt/ussd/internal/models" "git.grassecon.net/urdt/ussd/internal/server/handlers" "git.grassecon.net/urdt/ussd/internal/utils" ) -const ( - USERFLAG_LANGUAGE_SET = iota + state.FLAG_USERSTART - USERFLAG_ACCOUNT_CREATED - USERFLAG_ACCOUNT_PENDING - USERFLAG_ACCOUNT_SUCCESS - USERFLAG_ACCOUNT_UNLOCKED - USERFLAG_INVALID_RECIPIENT - USERFLAG_INVALID_RECIPIENT_WITH_INVITE - USERFLAG_INCORRECTPIN - USERFLAG_UNLOCKFORUPDATE - USERFLAG_INVALID_AMOUNT - USERFLAG_QUERYPIN - USERFLAG_VALIDPIN - USERFLAG_INVALIDPIN - USERFLAG_INCORRECTDATEFORMAT -) - type fsData struct { path string st *state.State @@ -251,7 +235,7 @@ func (fsd *fsData) set_language(ctx context.Context, sym string, input []byte) ( default: } - res.FlagSet = append(res.FlagSet, USERFLAG_LANGUAGE_SET) + res.FlagSet = append(res.FlagSet, models.USERFLAG_LANGUAGE_SET) return res, nil } @@ -286,19 +270,19 @@ func (fsd *fsData) create_account(ctx context.Context, sym string, input []byte) if err != nil { return res, err } - res.FlagSet = append(res.FlagSet, USERFLAG_ACCOUNT_CREATED) + res.FlagSet = append(res.FlagSet, models.USERFLAG_ACCOUNT_CREATED) return res, err } func (fsd *fsData) reset_unlock_for_update(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - res.FlagReset = append(res.FlagReset, USERFLAG_UNLOCKFORUPDATE) + res.FlagReset = append(res.FlagReset, models.USERFLAG_UNLOCKFORUPDATE) return res, nil } func (fsd *fsData) reset_account_unlocked(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - res.FlagReset = append(res.FlagReset, USERFLAG_ACCOUNT_UNLOCKED) + res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_UNLOCKED) return res, nil } @@ -340,16 +324,16 @@ func (fsd *fsData) unlock(ctx context.Context, sym string, input []byte) (resour if len(input) > 1 { if pin != accountData["AccountPIN"] { - res.FlagSet = append(res.FlagSet, USERFLAG_INCORRECTPIN) - res.FlagReset = append(res.FlagReset, USERFLAG_ACCOUNT_UNLOCKED) + res.FlagSet = append(res.FlagSet, models.USERFLAG_INCORRECTPIN) + res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_UNLOCKED) return res, nil } - if fsd.st.MatchFlag(USERFLAG_ACCOUNT_UNLOCKED, false) { - res.FlagReset = append(res.FlagReset, USERFLAG_INCORRECTPIN) - res.FlagSet = append(res.FlagSet, USERFLAG_UNLOCKFORUPDATE) - res.FlagSet = append(res.FlagSet, USERFLAG_ACCOUNT_UNLOCKED) + if fsd.st.MatchFlag(models.USERFLAG_ACCOUNT_UNLOCKED, false) { + res.FlagReset = append(res.FlagReset, models.USERFLAG_INCORRECTPIN) + res.FlagSet = append(res.FlagSet, models.USERFLAG_UNLOCKFORUPDATE) + res.FlagSet = append(res.FlagSet, models.USERFLAG_ACCOUNT_UNLOCKED) } else { - res.FlagReset = append(res.FlagReset, USERFLAG_ACCOUNT_UNLOCKED) + res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_UNLOCKED) } } return res, nil @@ -357,7 +341,7 @@ func (fsd *fsData) unlock(ctx context.Context, sym string, input []byte) (resour func (fsd *fsData) reset_incorrect_pin(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - res.FlagReset = append(res.FlagReset, USERFLAG_INCORRECTPIN) + res.FlagReset = append(res.FlagReset, models.USERFLAG_INCORRECTPIN) return res, nil } @@ -387,11 +371,11 @@ func (fsd *fsData) check_account_status(ctx context.Context, sym string, input [ accountData["Status"] = status if status == "SUCCESS" { - res.FlagSet = append(res.FlagSet, USERFLAG_ACCOUNT_SUCCESS) - res.FlagReset = append(res.FlagReset, USERFLAG_ACCOUNT_PENDING) + res.FlagSet = append(res.FlagSet, models.USERFLAG_ACCOUNT_SUCCESS) + res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_PENDING) } else { - res.FlagReset = append(res.FlagSet, USERFLAG_ACCOUNT_SUCCESS) - res.FlagSet = append(res.FlagReset, USERFLAG_ACCOUNT_PENDING) + res.FlagReset = append(res.FlagSet, models.USERFLAG_ACCOUNT_SUCCESS) + res.FlagSet = append(res.FlagReset, models.USERFLAG_ACCOUNT_PENDING) } updatedJsonData, err := json.Marshal(accountData) @@ -415,7 +399,7 @@ func (fsd *fsData) quit(ctx context.Context, sym string, input []byte) (resource default: res.Content = "Thank you for using Sarafu. Goodbye!" } - res.FlagReset = append(res.FlagReset, USERFLAG_ACCOUNT_UNLOCKED) + res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_UNLOCKED) return res, nil } @@ -426,9 +410,9 @@ func (fsd *fsData) verify_yob(ctx context.Context, sym string, input []byte) (re dateRegex := regexp.MustCompile(`^\d{2}/\d{2}/\d{4}$`) isCorrectFormat := dateRegex.MatchString(date) if !isCorrectFormat { - res.FlagSet = append(res.FlagSet, USERFLAG_INCORRECTDATEFORMAT) + res.FlagSet = append(res.FlagSet, models.USERFLAG_INCORRECTDATEFORMAT) } else { - res.FlagReset = append(res.FlagReset, USERFLAG_INCORRECTDATEFORMAT) + res.FlagReset = append(res.FlagReset, models.USERFLAG_INCORRECTDATEFORMAT) } return res, nil @@ -436,7 +420,7 @@ func (fsd *fsData) verify_yob(ctx context.Context, sym string, input []byte) (re func (fsd *fsData) reset_incorrect_yob(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - res.FlagReset = append(res.FlagReset, USERFLAG_INCORRECTDATEFORMAT) + res.FlagReset = append(res.FlagReset, models.USERFLAG_INCORRECTDATEFORMAT) return res, nil } @@ -482,7 +466,7 @@ func (fsd *fsData) validate_recipient(ctx context.Context, sym string, input []b if recipient != "0" { // mimic invalid number check if recipient == "000" { - res.FlagSet = append(res.FlagSet, USERFLAG_INVALID_RECIPIENT) + res.FlagSet = append(res.FlagSet, models.USERFLAG_INVALID_RECIPIENT) res.Content = recipient return res, nil @@ -532,7 +516,7 @@ func (fsd *fsData) transaction_reset(ctx context.Context, sym string, input []by return res, err } - res.FlagReset = append(res.FlagReset, USERFLAG_INVALID_RECIPIENT, USERFLAG_INVALID_RECIPIENT_WITH_INVITE) + res.FlagReset = append(res.FlagReset, models.USERFLAG_INVALID_RECIPIENT, models.USERFLAG_INVALID_RECIPIENT_WITH_INVITE) return res, nil } @@ -565,7 +549,7 @@ func (fsd *fsData) reset_transaction_amount(ctx context.Context, sym string, inp return res, err } - res.FlagReset = append(res.FlagReset, USERFLAG_INVALID_AMOUNT) + res.FlagReset = append(res.FlagReset, models.USERFLAG_INVALID_AMOUNT) return res, nil } @@ -599,7 +583,7 @@ func (fsd *fsData) validate_amount(ctx context.Context, sym string, input []byte if amount != "0" { // mimic invalid amount if amount == "00" { - res.FlagSet = append(res.FlagSet, USERFLAG_INVALID_AMOUNT) + res.FlagSet = append(res.FlagSet, models.USERFLAG_INVALID_AMOUNT) res.Content = amount return res, nil @@ -725,7 +709,7 @@ func (fsd *fsData) quit_with_balance(ctx context.Context, sym string, input []by return res, nil } res.Content = fmt.Sprintf("Your account balance is: %s", balance) - res.FlagReset = append(res.FlagReset, USERFLAG_ACCOUNT_UNLOCKED) + res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_UNLOCKED) return res, nil } @@ -776,10 +760,10 @@ func (fsd *fsData) verify_pin(ctx context.Context, sym string, input []byte) (re } if bytes.Equal(input, []byte(accountData["AccountPIN"])) { - res.FlagSet = []uint32{USERFLAG_VALIDPIN} - res.FlagReset = []uint32{USERFLAG_INVALIDPIN} + res.FlagSet = []uint32{models.USERFLAG_VALIDPIN} + res.FlagReset = []uint32{models.USERFLAG_PINMISMATCH} } else { - res.FlagSet = []uint32{USERFLAG_INVALIDPIN} + res.FlagSet = []uint32{models.USERFLAG_PINMISMATCH} } return res, nil @@ -804,11 +788,11 @@ func main() { ctx := context.Background() st := state.NewState(15) st.UseDebug() - state.FlagDebugger.Register(USERFLAG_LANGUAGE_SET, "LANGUAGE_CHANGE") - state.FlagDebugger.Register(USERFLAG_ACCOUNT_CREATED, "ACCOUNT_CREATED") - state.FlagDebugger.Register(USERFLAG_ACCOUNT_SUCCESS, "ACCOUNT_SUCCESS") - state.FlagDebugger.Register(USERFLAG_ACCOUNT_PENDING, "ACCOUNT_PENDING") - state.FlagDebugger.Register(USERFLAG_INCORRECTPIN, "INCORRECTPIN") + state.FlagDebugger.Register(models.USERFLAG_LANGUAGE_SET, "LANGUAGE_CHANGE") + state.FlagDebugger.Register(models.USERFLAG_ACCOUNT_CREATED, "ACCOUNT_CREATED") + state.FlagDebugger.Register(models.USERFLAG_ACCOUNT_SUCCESS, "ACCOUNT_SUCCESS") + state.FlagDebugger.Register(models.USERFLAG_ACCOUNT_PENDING, "ACCOUNT_PENDING") + state.FlagDebugger.Register(models.USERFLAG_INCORRECTPIN, "INCORRECTPIN") rfs := resource.NewFsResource(scriptDir) ca := cache.NewCache() diff --git a/internal/models/flags.go b/internal/models/flags.go new file mode 100644 index 0000000..42805a0 --- /dev/null +++ b/internal/models/flags.go @@ -0,0 +1,20 @@ +package models + +import "git.defalsify.org/vise.git/state" + +const ( + USERFLAG_LANGUAGE_SET = iota + state.FLAG_USERSTART + USERFLAG_ACCOUNT_CREATED + USERFLAG_ACCOUNT_PENDING + USERFLAG_ACCOUNT_SUCCESS + USERFLAG_ACCOUNT_UNLOCKED + USERFLAG_INVALID_RECIPIENT + USERFLAG_INVALID_RECIPIENT_WITH_INVITE + USERFLAG_INCORRECTPIN + USERFLAG_UNLOCKFORUPDATE + USERFLAG_INVALID_AMOUNT + USERFLAG_QUERYPIN + USERFLAG_VALIDPIN + USERFLAG_PINMISMATCH + USERFLAG_INCORRECTDATEFORMAT +) From bf014055ea1f0846774890120cbd37a27b6b5ebe Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Mon, 26 Aug 2024 14:35:08 +0300 Subject: [PATCH 066/201] use MOVE_ instead of INCMP * --- services/registration/pin_entry.vis | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/registration/pin_entry.vis b/services/registration/pin_entry.vis index b991017..cb99035 100644 --- a/services/registration/pin_entry.vis +++ b/services/registration/pin_entry.vis @@ -1,4 +1,4 @@ LOAD unlock_account 0 HALT RELOAD unlock_account -INCMP _ * +MOVE _ From 1a997e8b261594fbaca8ab1ced450d610fb3c451 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Mon, 26 Aug 2024 15:53:07 +0300 Subject: [PATCH 067/201] updated the file structure to have external functions on a different package --- cmd/main.go | 820 +----------------- .../server}/accountstatus.go | 5 +- .../server}/balancecheck.go | 2 +- .../server}/createaccount.go | 2 +- internal/handlers/ussd/menuhandler.go | 780 +++++++++++++++++ 5 files changed, 817 insertions(+), 792 deletions(-) rename internal/{server/handlers => handlers/server}/accountstatus.go (96%) rename internal/{server/handlers => handlers/server}/balancecheck.go (97%) rename internal/{server/handlers => handlers/server}/createaccount.go (97%) create mode 100644 internal/handlers/ussd/menuhandler.go diff --git a/cmd/main.go b/cmd/main.go index 61f015f..75a7a8c 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -1,774 +1,21 @@ package main import ( - "bytes" "context" - "encoding/json" "flag" "fmt" "os" "path" - "regexp" - "time" "git.defalsify.org/vise.git/cache" "git.defalsify.org/vise.git/engine" - "git.defalsify.org/vise.git/lang" "git.defalsify.org/vise.git/persist" "git.defalsify.org/vise.git/resource" "git.defalsify.org/vise.git/state" "git.grassecon.net/urdt/ussd/internal/models" - "git.grassecon.net/urdt/ussd/internal/server/handlers" - "git.grassecon.net/urdt/ussd/internal/utils" + "git.grassecon.net/urdt/ussd/internal/handlers/ussd" ) -type fsData struct { - path string - st *state.State -} - -func codeFromCtx(ctx context.Context) string { - var code string - engine.Logg.DebugCtxf(ctx, "in msg", "ctx", ctx, "val", code) - if ctx.Value("Language") != nil { - lang := ctx.Value("Language").(lang.Language) - code = lang.Code - } - return code -} - -func (fsd *fsData) save_firstname(cxt context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} - fp := fsd.path + "_data" - - jsonData, err := os.ReadFile(fp) - if err != nil { - return res, err - } - - var accountData map[string]string - err = json.Unmarshal(jsonData, &accountData) - if err != nil { - return res, err - } - if len(input) > 0 { - name := string(input) - accountData["FirstName"] = name - updatedJsonData, err := json.Marshal(accountData) - if err != nil { - return res, err - } - - err = os.WriteFile(fp, updatedJsonData, 0644) - if err != nil { - return res, err - } - } - - return res, nil -} - -func (fsd *fsData) save_familyname(cxt context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} - fp := fsd.path + "_data" - - jsonData, err := os.ReadFile(fp) - if err != nil { - return res, err - } - - var accountData map[string]string - err = json.Unmarshal(jsonData, &accountData) - if err != nil { - return res, err - } - if len(input) > 0 { - //Save name - secondname := string(input) - accountData["FamilyName"] = secondname - updatedJsonData, err := json.Marshal(accountData) - if err != nil { - return res, err - } - - err = os.WriteFile(fp, updatedJsonData, 0644) - if err != nil { - return res, err - } - } - - return res, nil -} -func (fsd *fsData) save_yob(cxt context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} - fp := fsd.path + "_data" - jsonData, err := os.ReadFile(fp) - if err != nil { - return res, err - } - var accountData map[string]string - err = json.Unmarshal(jsonData, &accountData) - if err != nil { - return res, err - } - if len(input) > 0 { - yob := string(input) - accountData["YOB"] = yob - updatedJsonData, err := json.Marshal(accountData) - if err != nil { - return res, err - } - - err = os.WriteFile(fp, updatedJsonData, 0644) - if err != nil { - return res, err - } - } - - return res, nil -} - -func (fsd *fsData) save_location(cxt context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} - fp := fsd.path + "_data" - jsonData, err := os.ReadFile(fp) - if err != nil { - return res, err - } - var accountData map[string]string - err = json.Unmarshal(jsonData, &accountData) - if err != nil { - return res, err - } - if len(input) > 0 { - location := string(input) - accountData["Location"] = location - updatedJsonData, err := json.Marshal(accountData) - if err != nil { - return res, err - } - - err = os.WriteFile(fp, updatedJsonData, 0644) - if err != nil { - return res, err - } - - } - - return res, nil -} - -func (fsd *fsData) save_gender(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} - fp := fsd.path + "_data" - jsonData, err := os.ReadFile(fp) - if err != nil { - return res, err - } - var accountData map[string]string - err = json.Unmarshal(jsonData, &accountData) - if err != nil { - return res, err - } - if len(input) > 0 { - gender := string(input) - - switch gender { - case "1": - gender = "Male" - case "2": - gender = "Female" - case "3": - gender = "Other" - } - accountData["Gender"] = gender - updatedJsonData, err := json.Marshal(accountData) - if err != nil { - return res, err - } - - err = os.WriteFile(fp, updatedJsonData, 0644) - if err != nil { - return res, err - } - } - return res, nil -} - -func (fsd *fsData) save_offerings(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} - fp := fsd.path + "_data" - jsonData, err := os.ReadFile(fp) - if err != nil { - return res, err - } - var accountData map[string]string - err = json.Unmarshal(jsonData, &accountData) - if err != nil { - return res, err - } - if len(input) > 0 { - offerings := string(input) - accountData["Offerings"] = offerings - updatedJsonData, err := json.Marshal(accountData) - if err != nil { - return res, err - } - err = os.WriteFile(fp, updatedJsonData, 0644) - if err != nil { - return res, err - } - } - return res, nil -} - -func (fsd *fsData) set_language(ctx context.Context, sym string, input []byte) (resource.Result, error) { - inputStr := string(input) - res := resource.Result{} - switch inputStr { - case "0": - res.FlagSet = []uint32{state.FLAG_LANG} - res.Content = "eng" - case "1": - res.FlagSet = []uint32{state.FLAG_LANG} - res.Content = "swa" - default: - } - - res.FlagSet = append(res.FlagSet, models.USERFLAG_LANGUAGE_SET) - - return res, nil -} - -func (fsd *fsData) create_account(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} - fp := fsd.path + "_data" - f, err := os.OpenFile(fp, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) - if err != nil { - return res, err - } - f.Close() - accountResp, err := handlers.CreateAccount() - if err != nil { - fmt.Println("Failed to create account:", err) - return res, err - } - - accountData := map[string]string{ - "TrackingId": accountResp.Result.TrackingId, - "PublicKey": accountResp.Result.PublicKey, - "CustodialId": accountResp.Result.CustodialId.String(), - "Status": "PENDING", - } - - jsonData, err := json.Marshal(accountData) - if err != nil { - return res, err - } - - err = os.WriteFile(fp, jsonData, 0644) - if err != nil { - return res, err - } - res.FlagSet = append(res.FlagSet, models.USERFLAG_ACCOUNT_CREATED) - return res, err -} - -func (fsd *fsData) reset_unlock_for_update(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} - res.FlagReset = append(res.FlagReset, models.USERFLAG_UNLOCKFORUPDATE) - return res, nil -} - -func (fsd *fsData) reset_account_unlocked(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} - res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_UNLOCKED) - return res, nil -} - -func (fsd *fsData) check_identifier(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} - fp := fsd.path + "_data" - - jsonData, err := os.ReadFile(fp) - if err != nil { - return res, err - } - - var accountData map[string]string - err = json.Unmarshal(jsonData, &accountData) - if err != nil { - return res, err - } - - res.Content = accountData["PublicKey"] - - return res, nil -} - -func (fsd *fsData) unlock(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} - pin := string(input) - fp := fsd.path + "_data" - - jsonData, err := os.ReadFile(fp) - if err != nil { - return res, err - } - - var accountData map[string]string - err = json.Unmarshal(jsonData, &accountData) - if err != nil { - return res, err - } - - if len(input) > 1 { - if pin != accountData["AccountPIN"] { - res.FlagSet = append(res.FlagSet, models.USERFLAG_INCORRECTPIN) - res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_UNLOCKED) - return res, nil - } - if fsd.st.MatchFlag(models.USERFLAG_ACCOUNT_UNLOCKED, false) { - res.FlagReset = append(res.FlagReset, models.USERFLAG_INCORRECTPIN) - res.FlagSet = append(res.FlagSet, models.USERFLAG_UNLOCKFORUPDATE) - res.FlagSet = append(res.FlagSet, models.USERFLAG_ACCOUNT_UNLOCKED) - } else { - res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_UNLOCKED) - } - } - return res, nil -} - -func (fsd *fsData) reset_incorrect_pin(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} - res.FlagReset = append(res.FlagReset, models.USERFLAG_INCORRECTPIN) - return res, nil -} - -func (fsd *fsData) check_account_status(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} - fp := fsd.path + "_data" - - jsonData, err := os.ReadFile(fp) - if err != nil { - return res, err - } - - var accountData map[string]string - err = json.Unmarshal(jsonData, &accountData) - if err != nil { - return res, err - } - - //status, err := checkAccountStatus(accountData["TrackingId"]) - status, err := handlers.CheckAccountStatus(accountData["TrackingId"]) - - if err != nil { - fmt.Println("Error checking account status:", err) - return res, nil - } - - accountData["Status"] = status - - if status == "SUCCESS" { - res.FlagSet = append(res.FlagSet, models.USERFLAG_ACCOUNT_SUCCESS) - res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_PENDING) - } else { - res.FlagReset = append(res.FlagSet, models.USERFLAG_ACCOUNT_SUCCESS) - res.FlagSet = append(res.FlagReset, models.USERFLAG_ACCOUNT_PENDING) - } - - updatedJsonData, err := json.Marshal(accountData) - if err != nil { - return res, err - } - - err = os.WriteFile(fp, updatedJsonData, 0644) - if err != nil { - return res, err - } - - return res, nil -} - -func (fsd *fsData) quit(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} - switch codeFromCtx(ctx) { - case "swa": - res.Content = "Asante kwa kutumia huduma ya Sarafu. Kwaheri!" - default: - res.Content = "Thank you for using Sarafu. Goodbye!" - } - res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_UNLOCKED) - return res, nil -} - -func (fsd *fsData) verify_yob(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} - date := string(input) - - dateRegex := regexp.MustCompile(`^\d{2}/\d{2}/\d{4}$`) - isCorrectFormat := dateRegex.MatchString(date) - if !isCorrectFormat { - res.FlagSet = append(res.FlagSet, models.USERFLAG_INCORRECTDATEFORMAT) - } else { - res.FlagReset = append(res.FlagReset, models.USERFLAG_INCORRECTDATEFORMAT) - } - - return res, nil -} - -func (fsd *fsData) reset_incorrect_yob(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} - res.FlagReset = append(res.FlagReset, models.USERFLAG_INCORRECTDATEFORMAT) - return res, nil -} - -func (fsd *fsData) check_balance(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} - - fp := fsd.path + "_data" - jsonData, err := os.ReadFile(fp) - if err != nil { - return res, err - } - var accountData map[string]string - err = json.Unmarshal(jsonData, &accountData) - if err != nil { - return res, err - } - balance, err := handlers.CheckBalance(accountData["PublicKey"]) - if err != nil { - return res, nil - } - res.Content = balance - - return res, nil -} - -func (fsd *fsData) validate_recipient(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} - recipient := string(input) - - fp := fsd.path + "_data" - - jsonData, err := os.ReadFile(fp) - if err != nil { - return res, err - } - - var accountData map[string]string - err = json.Unmarshal(jsonData, &accountData) - if err != nil { - return res, err - } - - if recipient != "0" { - // mimic invalid number check - if recipient == "000" { - res.FlagSet = append(res.FlagSet, models.USERFLAG_INVALID_RECIPIENT) - res.Content = recipient - - return res, nil - } - - accountData["Recipient"] = recipient - - updatedJsonData, err := json.Marshal(accountData) - if err != nil { - return res, err - } - - err = os.WriteFile(fp, updatedJsonData, 0644) - if err != nil { - return res, err - } - } - - return res, nil -} - -func (fsd *fsData) transaction_reset(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} - fp := fsd.path + "_data" - - jsonData, err := os.ReadFile(fp) - if err != nil { - return res, err - } - - var accountData map[string]string - err = json.Unmarshal(jsonData, &accountData) - if err != nil { - return res, err - } - - // reset the recipient - accountData["Recipient"] = "" - - updatedJsonData, err := json.Marshal(accountData) - if err != nil { - return res, err - } - - err = os.WriteFile(fp, updatedJsonData, 0644) - if err != nil { - return res, err - } - - res.FlagReset = append(res.FlagReset, models.USERFLAG_INVALID_RECIPIENT, models.USERFLAG_INVALID_RECIPIENT_WITH_INVITE) - - return res, nil -} - -func (fsd *fsData) reset_transaction_amount(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} - fp := fsd.path + "_data" - - jsonData, err := os.ReadFile(fp) - if err != nil { - return res, err - } - - var accountData map[string]string - err = json.Unmarshal(jsonData, &accountData) - if err != nil { - return res, err - } - - // reset the amount - accountData["Amount"] = "" - - updatedJsonData, err := json.Marshal(accountData) - if err != nil { - return res, err - } - - err = os.WriteFile(fp, updatedJsonData, 0644) - if err != nil { - return res, err - } - - res.FlagReset = append(res.FlagReset, models.USERFLAG_INVALID_AMOUNT) - - return res, nil -} - -func (fsd *fsData) max_amount(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} - - // mimic a max amount - res.Content = "10.00" - - return res, nil -} - -func (fsd *fsData) validate_amount(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} - amount := string(input) - - fp := fsd.path + "_data" - - jsonData, err := os.ReadFile(fp) - if err != nil { - return res, err - } - - var accountData map[string]string - err = json.Unmarshal(jsonData, &accountData) - if err != nil { - return res, err - } - - if amount != "0" { - // mimic invalid amount - if amount == "00" { - res.FlagSet = append(res.FlagSet, models.USERFLAG_INVALID_AMOUNT) - res.Content = amount - - return res, nil - } - - res.Content = amount - - accountData["Amount"] = amount - - updatedJsonData, err := json.Marshal(accountData) - if err != nil { - return res, err - } - - err = os.WriteFile(fp, updatedJsonData, 0644) - if err != nil { - return res, err - } - - return res, nil - } - - return res, nil -} - -func (fsd *fsData) get_recipient(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} - fp := fsd.path + "_data" - - jsonData, err := os.ReadFile(fp) - if err != nil { - return res, err - } - - var accountData map[string]string - err = json.Unmarshal(jsonData, &accountData) - if err != nil { - return res, err - } - - res.Content = accountData["Recipient"] - - return res, nil -} - -func (fsd *fsData) get_profile_info(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} - fp := fsd.path + "_data" - - jsonData, err := os.ReadFile(fp) - if err != nil { - return res, err - } - - var accountData map[string]string - err = json.Unmarshal(jsonData, &accountData) - if err != nil { - return res, err - } - name := accountData["FirstName"] + " " + accountData["FamilyName"] - gender := accountData["Gender"] - yob := accountData["YOB"] - location := accountData["Location"] - offerings := accountData["Offerings"] - - layout := "02/01/2006" - - birthdate, err := time.Parse(layout, yob) - if err != nil { - return res, err - } - - currentDate := time.Now() - formattedDate := currentDate.Format(layout) - today, err := time.Parse(layout, formattedDate) - if err != nil { - return res, nil - } - age := utils.CalculateAge(birthdate, today) - - formattedData := fmt.Sprintf("Name: %s\nGender: %s\nAge: %d\nLocation: %s\nYou provide: %s\n", name, gender, age, location, offerings) - res.Content = formattedData - - return res, nil -} - -func (fsd *fsData) get_sender(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} - fp := fsd.path + "_data" - - jsonData, err := os.ReadFile(fp) - if err != nil { - return res, err - } - - var accountData map[string]string - err = json.Unmarshal(jsonData, &accountData) - if err != nil { - return res, err - } - - res.Content = accountData["PublicKey"] - - return res, nil -} - -func (fsd *fsData) quit_with_balance(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} - fp := fsd.path + "_data" - - jsonData, err := os.ReadFile(fp) - if err != nil { - return res, err - } - - var accountData map[string]string - err = json.Unmarshal(jsonData, &accountData) - if err != nil { - return res, err - } - balance, err := handlers.CheckBalance(accountData["PublicKey"]) - if err != nil { - return res, nil - } - res.Content = fmt.Sprintf("Your account balance is: %s", balance) - res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_UNLOCKED) - return res, nil -} - -func (fsd *fsData) save_pin(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} - accountPIN := string(input) - fp := fsd.path + "_data" - - jsonData, err := os.ReadFile(fp) - if err != nil { - return res, err - } - - var accountData map[string]string - err = json.Unmarshal(jsonData, &accountData) - if err != nil { - return res, err - } - - accountData["AccountPIN"] = accountPIN - - updatedJsonData, err := json.Marshal(accountData) - if err != nil { - return res, err - } - - err = os.WriteFile(fp, updatedJsonData, 0644) - if err != nil { - return res, err - } - - return res, nil -} - -func (fsd *fsData) verify_pin(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} - fp := fsd.path + "_data" - - jsonData, err := os.ReadFile(fp) - if err != nil { - return res, err - } - - var accountData map[string]string - err = json.Unmarshal(jsonData, &accountData) - if err != nil { - return res, err - } - - if bytes.Equal(input, []byte(accountData["AccountPIN"])) { - res.FlagSet = []uint32{models.USERFLAG_VALIDPIN} - res.FlagReset = []uint32{models.USERFLAG_PINMISMATCH} - } else { - res.FlagSet = []uint32{models.USERFLAG_PINMISMATCH} - } - - return res, nil -} - var ( scriptDir = path.Join("services", "registration") ) @@ -824,39 +71,38 @@ func main() { } fp := path.Join(dp, sessionId) - fs := &fsData{ - path: fp, - st: &st, - } - rfs.AddLocalFunc("select_language", fs.set_language) - rfs.AddLocalFunc("create_account", fs.create_account) - rfs.AddLocalFunc("save_pin", fs.save_pin) - rfs.AddLocalFunc("verify_pin", fs.verify_pin) - rfs.AddLocalFunc("check_identifier", fs.check_identifier) - rfs.AddLocalFunc("check_account_status", fs.check_account_status) - rfs.AddLocalFunc("unlock_account", fs.unlock) - rfs.AddLocalFunc("quit", fs.quit) - rfs.AddLocalFunc("check_balance", fs.check_balance) - rfs.AddLocalFunc("validate_recipient", fs.validate_recipient) - rfs.AddLocalFunc("transaction_reset", fs.transaction_reset) - rfs.AddLocalFunc("max_amount", fs.max_amount) - rfs.AddLocalFunc("validate_amount", fs.validate_amount) - rfs.AddLocalFunc("reset_transaction_amount", fs.reset_transaction_amount) - rfs.AddLocalFunc("get_recipient", fs.get_recipient) - rfs.AddLocalFunc("get_sender", fs.get_sender) - rfs.AddLocalFunc("reset_incorrect", fs.reset_incorrect_pin) - rfs.AddLocalFunc("save_firstname", fs.save_firstname) - rfs.AddLocalFunc("save_familyname", fs.save_familyname) - rfs.AddLocalFunc("save_gender", fs.save_gender) - rfs.AddLocalFunc("save_location", fs.save_location) - rfs.AddLocalFunc("save_yob", fs.save_yob) - rfs.AddLocalFunc("save_offerings", fs.save_offerings) - rfs.AddLocalFunc("quit_with_balance", fs.quit_with_balance) - rfs.AddLocalFunc("reset_unlocked", fs.reset_account_unlocked) - rfs.AddLocalFunc("reset_unlock_for_update", fs.reset_unlock_for_update) - rfs.AddLocalFunc("get_profile_info", fs.get_profile_info) - rfs.AddLocalFunc("verify_yob", fs.verify_yob) - rfs.AddLocalFunc("reset_incorrect_date_format", fs.reset_incorrect_yob) + + ussdHandlers := ussd.NewHandlers(fp, &st) + + rfs.AddLocalFunc("select_language", ussdHandlers.SetLanguage) + rfs.AddLocalFunc("create_account", ussdHandlers.CreateAccount) + rfs.AddLocalFunc("save_pin", ussdHandlers.SavePin) + rfs.AddLocalFunc("verify_pin", ussdHandlers.VerifyPin) + rfs.AddLocalFunc("check_identifier", ussdHandlers.CheckIdentifier) + rfs.AddLocalFunc("check_account_status", ussdHandlers.CheckAccountStatus) + rfs.AddLocalFunc("unlock_account", ussdHandlers.Unlock) + rfs.AddLocalFunc("quit", ussdHandlers.Quit) + rfs.AddLocalFunc("check_balance", ussdHandlers.CheckBalance) + rfs.AddLocalFunc("validate_recipient", ussdHandlers.ValidateRecipient) + rfs.AddLocalFunc("transaction_reset", ussdHandlers.TransactionReset) + rfs.AddLocalFunc("max_amount", ussdHandlers.MaxAmount) + rfs.AddLocalFunc("validate_amount", ussdHandlers.ValidateAmount) + rfs.AddLocalFunc("reset_transaction_amount", ussdHandlers.ResetTransactionAmount) + rfs.AddLocalFunc("get_recipient", ussdHandlers.GetRecipient) + rfs.AddLocalFunc("get_sender", ussdHandlers.GetSender) + rfs.AddLocalFunc("reset_incorrect", ussdHandlers.ResetIncorrectPin) + rfs.AddLocalFunc("save_firstname", ussdHandlers.SaveFirstname) + rfs.AddLocalFunc("save_familyname", ussdHandlers.SaveFamilyname) + rfs.AddLocalFunc("save_gender", ussdHandlers.SaveGender) + rfs.AddLocalFunc("save_location", ussdHandlers.SaveLocation) + rfs.AddLocalFunc("save_yob", ussdHandlers.SaveYob) + rfs.AddLocalFunc("save_offerings", ussdHandlers.SaveOfferings) + rfs.AddLocalFunc("quit_with_balance", ussdHandlers.QuitWithBalance) + rfs.AddLocalFunc("reset_unlocked", ussdHandlers.ResetAccountUnlocked) + rfs.AddLocalFunc("reset_unlock_for_update", ussdHandlers.ResetUnlockForUpdate) + rfs.AddLocalFunc("get_profile_info", ussdHandlers.GetProfileInfo) + rfs.AddLocalFunc("verify_yob", ussdHandlers.VerifyYob) + rfs.AddLocalFunc("reset_incorrect_date_format", ussdHandlers.ResetIncorrectYob) cont, err := en.Init(ctx) en.SetDebugger(engine.NewSimpleDebug(nil)) diff --git a/internal/server/handlers/accountstatus.go b/internal/handlers/server/accountstatus.go similarity index 96% rename from internal/server/handlers/accountstatus.go rename to internal/handlers/server/accountstatus.go index 1992acc..d93b25d 100644 --- a/internal/server/handlers/accountstatus.go +++ b/internal/handlers/server/accountstatus.go @@ -1,4 +1,4 @@ -package handlers +package server import ( "encoding/json" @@ -9,7 +9,6 @@ import ( "git.grassecon.net/urdt/ussd/internal/models" ) - func CheckAccountStatus(trackingId string) (string, error) { resp, err := http.Get(config.TrackStatusURL + trackingId) if err != nil { @@ -31,4 +30,4 @@ func CheckAccountStatus(trackingId string) (string, error) { status := trackResp.Result.Transaction.Status return status, nil -} \ No newline at end of file +} diff --git a/internal/server/handlers/balancecheck.go b/internal/handlers/server/balancecheck.go similarity index 97% rename from internal/server/handlers/balancecheck.go rename to internal/handlers/server/balancecheck.go index 137050d..059ced0 100644 --- a/internal/server/handlers/balancecheck.go +++ b/internal/handlers/server/balancecheck.go @@ -1,4 +1,4 @@ -package handlers +package server import ( "encoding/json" diff --git a/internal/server/handlers/createaccount.go b/internal/handlers/server/createaccount.go similarity index 97% rename from internal/server/handlers/createaccount.go rename to internal/handlers/server/createaccount.go index 5175a3b..bdab01c 100644 --- a/internal/server/handlers/createaccount.go +++ b/internal/handlers/server/createaccount.go @@ -1,4 +1,4 @@ -package handlers +package server import ( "encoding/json" diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go new file mode 100644 index 0000000..a53cb54 --- /dev/null +++ b/internal/handlers/ussd/menuhandler.go @@ -0,0 +1,780 @@ +package ussd + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "os" + "regexp" + "time" + + "git.defalsify.org/vise.git/engine" + "git.defalsify.org/vise.git/lang" + "git.defalsify.org/vise.git/resource" + "git.defalsify.org/vise.git/state" + "git.grassecon.net/urdt/ussd/internal/models" + "git.grassecon.net/urdt/ussd/internal/handlers/server" + "git.grassecon.net/urdt/ussd/internal/utils" +) + +type FSData struct { + Path string + St *state.State +} + +type Handlers struct { + fs *FSData +} + +func NewHandlers(path string, st *state.State) *Handlers { + return &Handlers{ + fs: &FSData{ + Path: path, + St: st, + }, + } +} + +func (h *Handlers) SetLanguage(ctx context.Context, sym string, input []byte) (resource.Result, error) { + inputStr := string(input) + res := resource.Result{} + switch inputStr { + case "0": + res.FlagSet = []uint32{state.FLAG_LANG} + res.Content = "eng" + case "1": + res.FlagSet = []uint32{state.FLAG_LANG} + res.Content = "swa" + default: + } + + res.FlagSet = append(res.FlagSet, models.USERFLAG_LANGUAGE_SET) + + return res, nil +} + +func (h *Handlers) CreateAccount(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + fp := h.fs.Path + "_data" + f, err := os.OpenFile(fp, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) + if err != nil { + return res, err + } + f.Close() + accountResp, err := server.CreateAccount() + if err != nil { + fmt.Println("Failed to create account:", err) + return res, err + } + + accountData := map[string]string{ + "TrackingId": accountResp.Result.TrackingId, + "PublicKey": accountResp.Result.PublicKey, + "CustodialId": accountResp.Result.CustodialId.String(), + "Status": "PENDING", + } + + jsonData, err := json.Marshal(accountData) + if err != nil { + return res, err + } + + err = os.WriteFile(fp, jsonData, 0644) + if err != nil { + return res, err + } + res.FlagSet = append(res.FlagSet, models.USERFLAG_ACCOUNT_CREATED) + return res, err +} + +func (h *Handlers) SavePin(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + accountPIN := string(input) + fp := h.fs.Path + "_data" + + jsonData, err := os.ReadFile(fp) + if err != nil { + return res, err + } + + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return res, err + } + + accountData["AccountPIN"] = accountPIN + + updatedJsonData, err := json.Marshal(accountData) + if err != nil { + return res, err + } + + err = os.WriteFile(fp, updatedJsonData, 0644) + if err != nil { + return res, err + } + + return res, nil +} + +func (h *Handlers) VerifyPin(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + fp := h.fs.Path + "_data" + + jsonData, err := os.ReadFile(fp) + if err != nil { + return res, err + } + + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return res, err + } + + if bytes.Equal(input, []byte(accountData["AccountPIN"])) { + res.FlagSet = []uint32{models.USERFLAG_VALIDPIN} + res.FlagReset = []uint32{models.USERFLAG_PINMISMATCH} + } else { + res.FlagSet = []uint32{models.USERFLAG_PINMISMATCH} + } + + return res, nil +} + +func codeFromCtx(ctx context.Context) string { + var code string + engine.Logg.DebugCtxf(ctx, "in msg", "ctx", ctx, "val", code) + if ctx.Value("Language") != nil { + lang := ctx.Value("Language").(lang.Language) + code = lang.Code + } + return code +} + +func (h *Handlers) SaveFirstname(cxt context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + fp := h.fs.Path + "_data" + + jsonData, err := os.ReadFile(fp) + if err != nil { + return res, err + } + + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return res, err + } + if len(input) > 0 { + name := string(input) + accountData["FirstName"] = name + updatedJsonData, err := json.Marshal(accountData) + if err != nil { + return res, err + } + + err = os.WriteFile(fp, updatedJsonData, 0644) + if err != nil { + return res, err + } + } + + return res, nil +} + +func (h *Handlers) SaveFamilyname(cxt context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + fp := h.fs.Path + "_data" + + jsonData, err := os.ReadFile(fp) + if err != nil { + return res, err + } + + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return res, err + } + if len(input) > 0 { + //Save name + secondname := string(input) + accountData["FamilyName"] = secondname + updatedJsonData, err := json.Marshal(accountData) + if err != nil { + return res, err + } + + err = os.WriteFile(fp, updatedJsonData, 0644) + if err != nil { + return res, err + } + } + + return res, nil +} + +func (h *Handlers) SaveYob(cxt context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + fp := h.fs.Path + "_data" + jsonData, err := os.ReadFile(fp) + if err != nil { + return res, err + } + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return res, err + } + if len(input) > 0 { + yob := string(input) + accountData["YOB"] = yob + updatedJsonData, err := json.Marshal(accountData) + if err != nil { + return res, err + } + + err = os.WriteFile(fp, updatedJsonData, 0644) + if err != nil { + return res, err + } + } + + return res, nil +} + +func (h *Handlers) SaveLocation(cxt context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + fp := h.fs.Path + "_data" + jsonData, err := os.ReadFile(fp) + if err != nil { + return res, err + } + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return res, err + } + if len(input) > 0 { + location := string(input) + accountData["Location"] = location + updatedJsonData, err := json.Marshal(accountData) + if err != nil { + return res, err + } + + err = os.WriteFile(fp, updatedJsonData, 0644) + if err != nil { + return res, err + } + + } + + return res, nil +} + +func (h *Handlers) SaveGender(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + fp := h.fs.Path + "_data" + jsonData, err := os.ReadFile(fp) + if err != nil { + return res, err + } + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return res, err + } + if len(input) > 0 { + gender := string(input) + + switch gender { + case "1": + gender = "Male" + case "2": + gender = "Female" + case "3": + gender = "Other" + } + accountData["Gender"] = gender + updatedJsonData, err := json.Marshal(accountData) + if err != nil { + return res, err + } + + err = os.WriteFile(fp, updatedJsonData, 0644) + if err != nil { + return res, err + } + } + return res, nil +} + +func (h *Handlers) SaveOfferings(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + fp := h.fs.Path + "_data" + jsonData, err := os.ReadFile(fp) + if err != nil { + return res, err + } + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return res, err + } + if len(input) > 0 { + offerings := string(input) + accountData["Offerings"] = offerings + updatedJsonData, err := json.Marshal(accountData) + if err != nil { + return res, err + } + err = os.WriteFile(fp, updatedJsonData, 0644) + if err != nil { + return res, err + } + } + return res, nil +} + +func (h *Handlers) ResetUnlockForUpdate(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + res.FlagReset = append(res.FlagReset, models.USERFLAG_UNLOCKFORUPDATE) + return res, nil +} + +func (h *Handlers) ResetAccountUnlocked(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_UNLOCKED) + return res, nil +} + +func (h *Handlers) CheckIdentifier(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + fp := h.fs.Path + "_data" + + jsonData, err := os.ReadFile(fp) + if err != nil { + return res, err + } + + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return res, err + } + + res.Content = accountData["PublicKey"] + + return res, nil +} + +func (h *Handlers) Unlock(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + pin := string(input) + fp := h.fs.Path + "_data" + + jsonData, err := os.ReadFile(fp) + if err != nil { + return res, err + } + + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return res, err + } + + if len(input) > 1 { + if pin != accountData["AccountPIN"] { + res.FlagSet = append(res.FlagSet, models.USERFLAG_INCORRECTPIN) + res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_UNLOCKED) + return res, nil + } + if h.fs.St.MatchFlag(models.USERFLAG_ACCOUNT_UNLOCKED, false) { + res.FlagReset = append(res.FlagReset, models.USERFLAG_INCORRECTPIN) + res.FlagSet = append(res.FlagSet, models.USERFLAG_UNLOCKFORUPDATE) + res.FlagSet = append(res.FlagSet, models.USERFLAG_ACCOUNT_UNLOCKED) + } else { + res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_UNLOCKED) + } + } + return res, nil +} + +func (h *Handlers) ResetIncorrectPin(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + res.FlagReset = append(res.FlagReset, models.USERFLAG_INCORRECTPIN) + return res, nil +} + +func (h *Handlers) CheckAccountStatus(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + fp := h.fs.Path + "_data" + + jsonData, err := os.ReadFile(fp) + if err != nil { + return res, err + } + + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return res, err + } + + //status, err := checkAccountStatus(accountData["TrackingId"]) + status, err := server.CheckAccountStatus(accountData["TrackingId"]) + + if err != nil { + fmt.Println("Error checking account status:", err) + return res, nil + } + + accountData["Status"] = status + + if status == "SUCCESS" { + res.FlagSet = append(res.FlagSet, models.USERFLAG_ACCOUNT_SUCCESS) + res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_PENDING) + } else { + res.FlagReset = append(res.FlagSet, models.USERFLAG_ACCOUNT_SUCCESS) + res.FlagSet = append(res.FlagReset, models.USERFLAG_ACCOUNT_PENDING) + } + + updatedJsonData, err := json.Marshal(accountData) + if err != nil { + return res, err + } + + err = os.WriteFile(fp, updatedJsonData, 0644) + if err != nil { + return res, err + } + + return res, nil +} + +func (h *Handlers) Quit(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + switch codeFromCtx(ctx) { + case "swa": + res.Content = "Asante kwa kutumia huduma ya Sarafu. Kwaheri!" + default: + res.Content = "Thank you for using Sarafu. Goodbye!" + } + res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_UNLOCKED) + return res, nil +} + +func (h *Handlers) VerifyYob(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + date := string(input) + + dateRegex := regexp.MustCompile(`^\d{2}/\d{2}/\d{4}$`) + isCorrectFormat := dateRegex.MatchString(date) + if !isCorrectFormat { + res.FlagSet = append(res.FlagSet, models.USERFLAG_INCORRECTDATEFORMAT) + } else { + res.FlagReset = append(res.FlagReset, models.USERFLAG_INCORRECTDATEFORMAT) + } + + return res, nil +} + +func (h *Handlers) ResetIncorrectYob(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + res.FlagReset = append(res.FlagReset, models.USERFLAG_INCORRECTDATEFORMAT) + return res, nil +} + +func (h *Handlers) CheckBalance(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + + fp := h.fs.Path + "_data" + jsonData, err := os.ReadFile(fp) + if err != nil { + return res, err + } + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return res, err + } + balance, err := server.CheckBalance(accountData["PublicKey"]) + if err != nil { + return res, nil + } + res.Content = balance + + return res, nil +} + +func (h *Handlers) ValidateRecipient(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + recipient := string(input) + + fp := h.fs.Path + "_data" + + jsonData, err := os.ReadFile(fp) + if err != nil { + return res, err + } + + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return res, err + } + + if recipient != "0" { + // mimic invalid number check + if recipient == "000" { + res.FlagSet = append(res.FlagSet, models.USERFLAG_INVALID_RECIPIENT) + res.Content = recipient + + return res, nil + } + + accountData["Recipient"] = recipient + + updatedJsonData, err := json.Marshal(accountData) + if err != nil { + return res, err + } + + err = os.WriteFile(fp, updatedJsonData, 0644) + if err != nil { + return res, err + } + } + + return res, nil +} + +func (h *Handlers) TransactionReset(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + fp := h.fs.Path + "_data" + + jsonData, err := os.ReadFile(fp) + if err != nil { + return res, err + } + + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return res, err + } + + // reset the recipient + accountData["Recipient"] = "" + + updatedJsonData, err := json.Marshal(accountData) + if err != nil { + return res, err + } + + err = os.WriteFile(fp, updatedJsonData, 0644) + if err != nil { + return res, err + } + + res.FlagReset = append(res.FlagReset, models.USERFLAG_INVALID_RECIPIENT, models.USERFLAG_INVALID_RECIPIENT_WITH_INVITE) + + return res, nil +} + +func (h *Handlers) ResetTransactionAmount(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + fp := h.fs.Path + "_data" + + jsonData, err := os.ReadFile(fp) + if err != nil { + return res, err + } + + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return res, err + } + + // reset the amount + accountData["Amount"] = "" + + updatedJsonData, err := json.Marshal(accountData) + if err != nil { + return res, err + } + + err = os.WriteFile(fp, updatedJsonData, 0644) + if err != nil { + return res, err + } + + res.FlagReset = append(res.FlagReset, models.USERFLAG_INVALID_AMOUNT) + + return res, nil +} + +func (h *Handlers) MaxAmount(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + + // mimic a max amount + res.Content = "10.00" + + return res, nil +} + +func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + amount := string(input) + + fp := h.fs.Path + "_data" + + jsonData, err := os.ReadFile(fp) + if err != nil { + return res, err + } + + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return res, err + } + + if amount != "0" { + // mimic invalid amount + if amount == "00" { + res.FlagSet = append(res.FlagSet, models.USERFLAG_INVALID_AMOUNT) + res.Content = amount + + return res, nil + } + + res.Content = amount + + accountData["Amount"] = amount + + updatedJsonData, err := json.Marshal(accountData) + if err != nil { + return res, err + } + + err = os.WriteFile(fp, updatedJsonData, 0644) + if err != nil { + return res, err + } + + return res, nil + } + + return res, nil +} + +func (h *Handlers) GetRecipient(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + fp := h.fs.Path + "_data" + + jsonData, err := os.ReadFile(fp) + if err != nil { + return res, err + } + + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return res, err + } + + res.Content = accountData["Recipient"] + + return res, nil +} + +func (h *Handlers) GetProfileInfo(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + fp := h.fs.Path + "_data" + + jsonData, err := os.ReadFile(fp) + if err != nil { + return res, err + } + + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return res, err + } + name := accountData["FirstName"] + " " + accountData["FamilyName"] + gender := accountData["Gender"] + yob := accountData["YOB"] + location := accountData["Location"] + offerings := accountData["Offerings"] + + layout := "02/01/2006" + + birthdate, err := time.Parse(layout, yob) + if err != nil { + return res, err + } + + currentDate := time.Now() + formattedDate := currentDate.Format(layout) + today, err := time.Parse(layout, formattedDate) + if err != nil { + return res, nil + } + age := utils.CalculateAge(birthdate, today) + + formattedData := fmt.Sprintf("Name: %s\nGender: %s\nAge: %d\nLocation: %s\nYou provide: %s\n", name, gender, age, location, offerings) + res.Content = formattedData + + return res, nil +} + +func (h *Handlers) GetSender(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + fp := h.fs.Path + "_data" + + jsonData, err := os.ReadFile(fp) + if err != nil { + return res, err + } + + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return res, err + } + + res.Content = accountData["PublicKey"] + + return res, nil +} + +func (h *Handlers) QuitWithBalance(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + fp := h.fs.Path + "_data" + + jsonData, err := os.ReadFile(fp) + if err != nil { + return res, err + } + + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return res, err + } + balance, err := server.CheckBalance(accountData["PublicKey"]) + if err != nil { + return res, nil + } + res.Content = fmt.Sprintf("Your account balance is: %s", balance) + res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_UNLOCKED) + return res, nil +} From 1634854231e16f9a61613c116099e101b1d1d1ce Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Mon, 26 Aug 2024 15:54:29 +0300 Subject: [PATCH 068/201] set the flags to 14 --- cmd/main.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/main.go b/cmd/main.go index 75a7a8c..fcd91ce 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -33,7 +33,7 @@ func main() { fmt.Fprintf(os.Stderr, "starting session at symbol '%s' using resource dir: %s\n", root, dir) ctx := context.Background() - st := state.NewState(15) + st := state.NewState(14) st.UseDebug() state.FlagDebugger.Register(models.USERFLAG_LANGUAGE_SET, "LANGUAGE_CHANGE") state.FlagDebugger.Register(models.USERFLAG_ACCOUNT_CREATED, "ACCOUNT_CREATED") From 460a3d19f731831db673057720810c619fcb78aa Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Mon, 26 Aug 2024 17:00:04 +0300 Subject: [PATCH 069/201] register all flags --- cmd/main.go | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/cmd/main.go b/cmd/main.go index fcd91ce..beddaf0 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -40,6 +40,17 @@ func main() { state.FlagDebugger.Register(models.USERFLAG_ACCOUNT_SUCCESS, "ACCOUNT_SUCCESS") state.FlagDebugger.Register(models.USERFLAG_ACCOUNT_PENDING, "ACCOUNT_PENDING") state.FlagDebugger.Register(models.USERFLAG_INCORRECTPIN, "INCORRECTPIN") + state.FlagDebugger.Register(models.USERFLAG_INCORRECTDATEFORMAT,"INVALIDDATEFORMAT") + state.FlagDebugger.Register(models.USERFLAG_INVALID_RECIPIENT,"INVALIDRECIPIENT") + state.FlagDebugger.Register(models.USERFLAG_PINMISMATCH,"PINMISMATCH") + state.FlagDebugger.Register(models.USERFLAG_QUERYPIN,"QUERYPIN") + state.FlagDebugger.Register(models.USERFLAG_INVALID_RECIPIENT_WITH_INVITE,"INVALIDRECIPIENT_WITH_INVITE") + state.FlagDebugger.Register(models.USERFLAG_INVALID_AMOUNT,"INVALIDAMOUNT") + state.FlagDebugger.Register(models.USERFLAG_UNLOCKFORUPDATE,"UNLOCKFORUPDATE") + state.FlagDebugger.Register(models.USERFLAG_VALIDPIN,"VALIDPIN") + state.FlagDebugger.Register(models.USERFLAG_VALIDPIN,"ACCOUNTUNLOCKED") + + rfs := resource.NewFsResource(scriptDir) ca := cache.NewCache() From 357485feed9b1c630fb57a1162519020b7783239 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Mon, 26 Aug 2024 21:55:48 +0300 Subject: [PATCH 070/201] perform quit on help and voucher option --- services/registration/main.vis | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/registration/main.vis b/services/registration/main.vis index ae46d5e..ede8296 100644 --- a/services/registration/main.vis +++ b/services/registration/main.vis @@ -8,8 +8,8 @@ MOUT help 4 MOUT quit 9 HALT INCMP send 1 -INCMP vouchers 2 +INCMP quit 2 INCMP my_account 3 -INCMP help 4 +INCMP quit 4 INCMP quit 9 INCMP . * From cb31616a8710ad8c58af7a96284ef43af0600e74 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Mon, 26 Aug 2024 21:58:21 +0300 Subject: [PATCH 071/201] check for 4 digits input --- internal/handlers/ussd/menuhandler.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index a53cb54..4c1599a 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -229,7 +229,8 @@ func (h *Handlers) SaveYob(cxt context.Context, sym string, input []byte) (resou if err != nil { return res, err } - if len(input) > 0 { + yob := string(input) + if len(yob) > 4 { yob := string(input) accountData["YOB"] = yob updatedJsonData, err := json.Marshal(accountData) From db96f0e2e4be83beb5e854a55cc17c5fdb01e420 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Tue, 27 Aug 2024 10:15:11 +0300 Subject: [PATCH 072/201] add documentation lines --- internal/handlers/server/balancecheck.go | 3 +++ internal/handlers/server/createaccount.go | 7 ++++++- internal/utils/age.go | 3 ++- 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/internal/handlers/server/balancecheck.go b/internal/handlers/server/balancecheck.go index 059ced0..85355be 100644 --- a/internal/handlers/server/balancecheck.go +++ b/internal/handlers/server/balancecheck.go @@ -9,6 +9,9 @@ import ( "git.grassecon.net/urdt/ussd/internal/models" ) +// CheckBalance retrieves the balance for a given public key from the custodial balance API endpoint. +// Parameters: +// - publicKey: The public key associated with the account whose balance needs to be checked. func CheckBalance(publicKey string) (string, error) { resp, err := http.Get(config.BalanceURL + publicKey) diff --git a/internal/handlers/server/createaccount.go b/internal/handlers/server/createaccount.go index bdab01c..4b7150c 100644 --- a/internal/handlers/server/createaccount.go +++ b/internal/handlers/server/createaccount.go @@ -9,7 +9,12 @@ import ( "git.grassecon.net/urdt/ussd/internal/models" ) - +//CreateAccount creates a new account in the custodial system. +// Returns: +// - *models.AccountResponse: A pointer to an AccountResponse struct containing the details of the created account. +// If there is an error during the request or processing, this will be nil. +// - error: An error if any occurred during the HTTP request, reading the response, or unmarshalling the JSON data. +// If no error occurs, this will be nil. func CreateAccount() (*models.AccountResponse, error) { resp, err := http.Post(config.CreateAccountURL, "application/json", nil) if err != nil { diff --git a/internal/utils/age.go b/internal/utils/age.go index 56c3e2b..8d1aa24 100644 --- a/internal/utils/age.go +++ b/internal/utils/age.go @@ -2,7 +2,8 @@ package utils import "time" - +// CalculateAge calculates the age based on a given birthdate and the current date in the format dd/mm/yy +// It adjusts for cases where the current date is before the birthday in the current year. func CalculateAge(birthdate, today time.Time) int { today = today.In(birthdate.Location()) ty, tm, td := today.Date() From 5f3baa86aef2d29747441df540b9666c9393efac Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Tue, 27 Aug 2024 10:16:25 +0300 Subject: [PATCH 073/201] remove commented code --- internal/handlers/ussd/menuhandler.go | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 4c1599a..6cc260f 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -13,8 +13,8 @@ import ( "git.defalsify.org/vise.git/lang" "git.defalsify.org/vise.git/resource" "git.defalsify.org/vise.git/state" - "git.grassecon.net/urdt/ussd/internal/models" "git.grassecon.net/urdt/ussd/internal/handlers/server" + "git.grassecon.net/urdt/ussd/internal/models" "git.grassecon.net/urdt/ussd/internal/utils" ) @@ -426,8 +426,6 @@ func (h *Handlers) CheckAccountStatus(ctx context.Context, sym string, input []b if err != nil { return res, err } - - //status, err := checkAccountStatus(accountData["TrackingId"]) status, err := server.CheckAccountStatus(accountData["TrackingId"]) if err != nil { From 0aacc061466d2a4a0859450fbe69da3aaeefb334 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Tue, 27 Aug 2024 10:18:33 +0300 Subject: [PATCH 074/201] add documentation code --- internal/handlers/server/accountstatus.go | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/internal/handlers/server/accountstatus.go b/internal/handlers/server/accountstatus.go index d93b25d..f8b6541 100644 --- a/internal/handlers/server/accountstatus.go +++ b/internal/handlers/server/accountstatus.go @@ -9,6 +9,19 @@ import ( "git.grassecon.net/urdt/ussd/internal/models" ) +// CheckAccountStatus retrieves the status of an account transaction based on the provided tracking ID. +// +// Parameters: +// - trackingId: A unique identifier for the account.This should be obtained from a previous call to +// CreateAccount or a similar function that returns an AccountResponse. The `trackingId` field in the +// AccountResponse struct can be used here to check the account status. +// +// +// Returns: +// - string: The status of the transaction as a string. If there is an error during the request or processing, this will be an empty string. +// - error: An error if any occurred during the HTTP request, reading the response, or unmarshalling the JSON data. +// If no error occurs, this will be nil. +// func CheckAccountStatus(trackingId string) (string, error) { resp, err := http.Get(config.TrackStatusURL + trackingId) if err != nil { From 1a0173eee5e0e9f6d23f3a492579f198260273e8 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Tue, 27 Aug 2024 10:20:38 +0300 Subject: [PATCH 075/201] add documentation lines --- internal/handlers/server/accountstatus.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/handlers/server/accountstatus.go b/internal/handlers/server/accountstatus.go index f8b6541..400642c 100644 --- a/internal/handlers/server/accountstatus.go +++ b/internal/handlers/server/accountstatus.go @@ -14,7 +14,7 @@ import ( // Parameters: // - trackingId: A unique identifier for the account.This should be obtained from a previous call to // CreateAccount or a similar function that returns an AccountResponse. The `trackingId` field in the -// AccountResponse struct can be used here to check the account status. +// AccountResponse struct can be used here to check the account status during a transaction. // // // Returns: From 9f1eed9ab335350a1263214a358758ca909c8e09 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Tue, 27 Aug 2024 11:19:49 +0300 Subject: [PATCH 076/201] Add an account util for reading and writing data to file --- internal/handlers/ussd/menuhandler.go | 288 +++++--------------------- internal/utils/account_utils.go | 46 ++++ 2 files changed, 96 insertions(+), 238 deletions(-) create mode 100644 internal/utils/account_utils.go diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 6cc260f..0b656fc 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -3,9 +3,7 @@ package ussd import ( "bytes" "context" - "encoding/json" "fmt" - "os" "regexp" "time" @@ -24,7 +22,8 @@ type FSData struct { } type Handlers struct { - fs *FSData + fs *FSData + accountFileHandler *utils.AccountFileHandler } func NewHandlers(path string, st *state.State) *Handlers { @@ -33,6 +32,7 @@ func NewHandlers(path string, st *state.State) *Handlers { Path: path, St: st, }, + accountFileHandler: utils.NewAccountFileHandler(path + "_data"), } } @@ -56,12 +56,12 @@ func (h *Handlers) SetLanguage(ctx context.Context, sym string, input []byte) (r func (h *Handlers) CreateAccount(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - fp := h.fs.Path + "_data" - f, err := os.OpenFile(fp, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) + + err := h.accountFileHandler.EnsureFileExists() if err != nil { return res, err } - f.Close() + accountResp, err := server.CreateAccount() if err != nil { fmt.Println("Failed to create account:", err) @@ -75,15 +75,11 @@ func (h *Handlers) CreateAccount(ctx context.Context, sym string, input []byte) "Status": "PENDING", } - jsonData, err := json.Marshal(accountData) + err = h.accountFileHandler.WriteAccountData(accountData) if err != nil { return res, err } - err = os.WriteFile(fp, jsonData, 0644) - if err != nil { - return res, err - } res.FlagSet = append(res.FlagSet, models.USERFLAG_ACCOUNT_CREATED) return res, err } @@ -91,27 +87,15 @@ func (h *Handlers) CreateAccount(ctx context.Context, sym string, input []byte) func (h *Handlers) SavePin(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} accountPIN := string(input) - fp := h.fs.Path + "_data" - jsonData, err := os.ReadFile(fp) - if err != nil { - return res, err - } - - var accountData map[string]string - err = json.Unmarshal(jsonData, &accountData) + accountData, err := h.accountFileHandler.ReadAccountData() if err != nil { return res, err } accountData["AccountPIN"] = accountPIN - updatedJsonData, err := json.Marshal(accountData) - if err != nil { - return res, err - } - - err = os.WriteFile(fp, updatedJsonData, 0644) + err = h.accountFileHandler.WriteAccountData(accountData) if err != nil { return res, err } @@ -121,15 +105,8 @@ func (h *Handlers) SavePin(ctx context.Context, sym string, input []byte) (resou func (h *Handlers) VerifyPin(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - fp := h.fs.Path + "_data" - jsonData, err := os.ReadFile(fp) - if err != nil { - return res, err - } - - var accountData map[string]string - err = json.Unmarshal(jsonData, &accountData) + accountData, err := h.accountFileHandler.ReadAccountData() if err != nil { return res, err } @@ -156,27 +133,16 @@ func codeFromCtx(ctx context.Context) string { func (h *Handlers) SaveFirstname(cxt context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - fp := h.fs.Path + "_data" - jsonData, err := os.ReadFile(fp) - if err != nil { - return res, err - } - - var accountData map[string]string - err = json.Unmarshal(jsonData, &accountData) + accountData, err := h.accountFileHandler.ReadAccountData() if err != nil { return res, err } if len(input) > 0 { name := string(input) accountData["FirstName"] = name - updatedJsonData, err := json.Marshal(accountData) - if err != nil { - return res, err - } - err = os.WriteFile(fp, updatedJsonData, 0644) + err = h.accountFileHandler.WriteAccountData(accountData) if err != nil { return res, err } @@ -187,28 +153,16 @@ func (h *Handlers) SaveFirstname(cxt context.Context, sym string, input []byte) func (h *Handlers) SaveFamilyname(cxt context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - fp := h.fs.Path + "_data" - jsonData, err := os.ReadFile(fp) - if err != nil { - return res, err - } - - var accountData map[string]string - err = json.Unmarshal(jsonData, &accountData) + accountData, err := h.accountFileHandler.ReadAccountData() if err != nil { return res, err } if len(input) > 0 { - //Save name secondname := string(input) accountData["FamilyName"] = secondname - updatedJsonData, err := json.Marshal(accountData) - if err != nil { - return res, err - } - err = os.WriteFile(fp, updatedJsonData, 0644) + err = h.accountFileHandler.WriteAccountData(accountData) if err != nil { return res, err } @@ -219,26 +173,18 @@ func (h *Handlers) SaveFamilyname(cxt context.Context, sym string, input []byte) func (h *Handlers) SaveYob(cxt context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - fp := h.fs.Path + "_data" - jsonData, err := os.ReadFile(fp) - if err != nil { - return res, err - } - var accountData map[string]string - err = json.Unmarshal(jsonData, &accountData) + + accountData, err := h.accountFileHandler.ReadAccountData() if err != nil { return res, err } + yob := string(input) if len(yob) > 4 { yob := string(input) accountData["YOB"] = yob - updatedJsonData, err := json.Marshal(accountData) - if err != nil { - return res, err - } - err = os.WriteFile(fp, updatedJsonData, 0644) + err = h.accountFileHandler.WriteAccountData(accountData) if err != nil { return res, err } @@ -249,29 +195,20 @@ func (h *Handlers) SaveYob(cxt context.Context, sym string, input []byte) (resou func (h *Handlers) SaveLocation(cxt context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - fp := h.fs.Path + "_data" - jsonData, err := os.ReadFile(fp) - if err != nil { - return res, err - } - var accountData map[string]string - err = json.Unmarshal(jsonData, &accountData) + + accountData, err := h.accountFileHandler.ReadAccountData() if err != nil { return res, err } + if len(input) > 0 { location := string(input) accountData["Location"] = location - updatedJsonData, err := json.Marshal(accountData) + + err = h.accountFileHandler.WriteAccountData(accountData) if err != nil { return res, err } - - err = os.WriteFile(fp, updatedJsonData, 0644) - if err != nil { - return res, err - } - } return res, nil @@ -279,16 +216,12 @@ func (h *Handlers) SaveLocation(cxt context.Context, sym string, input []byte) ( func (h *Handlers) SaveGender(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - fp := h.fs.Path + "_data" - jsonData, err := os.ReadFile(fp) - if err != nil { - return res, err - } - var accountData map[string]string - err = json.Unmarshal(jsonData, &accountData) + + accountData, err := h.accountFileHandler.ReadAccountData() if err != nil { return res, err } + if len(input) > 0 { gender := string(input) @@ -301,12 +234,8 @@ func (h *Handlers) SaveGender(ctx context.Context, sym string, input []byte) (re gender = "Other" } accountData["Gender"] = gender - updatedJsonData, err := json.Marshal(accountData) - if err != nil { - return res, err - } - err = os.WriteFile(fp, updatedJsonData, 0644) + err = h.accountFileHandler.WriteAccountData(accountData) if err != nil { return res, err } @@ -316,24 +245,17 @@ func (h *Handlers) SaveGender(ctx context.Context, sym string, input []byte) (re func (h *Handlers) SaveOfferings(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - fp := h.fs.Path + "_data" - jsonData, err := os.ReadFile(fp) - if err != nil { - return res, err - } - var accountData map[string]string - err = json.Unmarshal(jsonData, &accountData) + + accountData, err := h.accountFileHandler.ReadAccountData() if err != nil { return res, err } + if len(input) > 0 { offerings := string(input) accountData["Offerings"] = offerings - updatedJsonData, err := json.Marshal(accountData) - if err != nil { - return res, err - } - err = os.WriteFile(fp, updatedJsonData, 0644) + + err = h.accountFileHandler.WriteAccountData(accountData) if err != nil { return res, err } @@ -355,15 +277,8 @@ func (h *Handlers) ResetAccountUnlocked(ctx context.Context, sym string, input [ func (h *Handlers) CheckIdentifier(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - fp := h.fs.Path + "_data" - jsonData, err := os.ReadFile(fp) - if err != nil { - return res, err - } - - var accountData map[string]string - err = json.Unmarshal(jsonData, &accountData) + accountData, err := h.accountFileHandler.ReadAccountData() if err != nil { return res, err } @@ -376,15 +291,8 @@ func (h *Handlers) CheckIdentifier(ctx context.Context, sym string, input []byte func (h *Handlers) Unlock(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} pin := string(input) - fp := h.fs.Path + "_data" - jsonData, err := os.ReadFile(fp) - if err != nil { - return res, err - } - - var accountData map[string]string - err = json.Unmarshal(jsonData, &accountData) + accountData, err := h.accountFileHandler.ReadAccountData() if err != nil { return res, err } @@ -414,18 +322,12 @@ func (h *Handlers) ResetIncorrectPin(ctx context.Context, sym string, input []by func (h *Handlers) CheckAccountStatus(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - fp := h.fs.Path + "_data" - jsonData, err := os.ReadFile(fp) + accountData, err := h.accountFileHandler.ReadAccountData() if err != nil { return res, err } - var accountData map[string]string - err = json.Unmarshal(jsonData, &accountData) - if err != nil { - return res, err - } status, err := server.CheckAccountStatus(accountData["TrackingId"]) if err != nil { @@ -443,12 +345,7 @@ func (h *Handlers) CheckAccountStatus(ctx context.Context, sym string, input []b res.FlagSet = append(res.FlagReset, models.USERFLAG_ACCOUNT_PENDING) } - updatedJsonData, err := json.Marshal(accountData) - if err != nil { - return res, err - } - - err = os.WriteFile(fp, updatedJsonData, 0644) + err = h.accountFileHandler.WriteAccountData(accountData) if err != nil { return res, err } @@ -492,16 +389,11 @@ func (h *Handlers) ResetIncorrectYob(ctx context.Context, sym string, input []by func (h *Handlers) CheckBalance(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - fp := h.fs.Path + "_data" - jsonData, err := os.ReadFile(fp) - if err != nil { - return res, err - } - var accountData map[string]string - err = json.Unmarshal(jsonData, &accountData) + accountData, err := h.accountFileHandler.ReadAccountData() if err != nil { return res, err } + balance, err := server.CheckBalance(accountData["PublicKey"]) if err != nil { return res, nil @@ -515,15 +407,7 @@ func (h *Handlers) ValidateRecipient(ctx context.Context, sym string, input []by res := resource.Result{} recipient := string(input) - fp := h.fs.Path + "_data" - - jsonData, err := os.ReadFile(fp) - if err != nil { - return res, err - } - - var accountData map[string]string - err = json.Unmarshal(jsonData, &accountData) + accountData, err := h.accountFileHandler.ReadAccountData() if err != nil { return res, err } @@ -539,12 +423,7 @@ func (h *Handlers) ValidateRecipient(ctx context.Context, sym string, input []by accountData["Recipient"] = recipient - updatedJsonData, err := json.Marshal(accountData) - if err != nil { - return res, err - } - - err = os.WriteFile(fp, updatedJsonData, 0644) + err = h.accountFileHandler.WriteAccountData(accountData) if err != nil { return res, err } @@ -555,15 +434,7 @@ func (h *Handlers) ValidateRecipient(ctx context.Context, sym string, input []by func (h *Handlers) TransactionReset(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - fp := h.fs.Path + "_data" - - jsonData, err := os.ReadFile(fp) - if err != nil { - return res, err - } - - var accountData map[string]string - err = json.Unmarshal(jsonData, &accountData) + accountData, err := h.accountFileHandler.ReadAccountData() if err != nil { return res, err } @@ -571,12 +442,7 @@ func (h *Handlers) TransactionReset(ctx context.Context, sym string, input []byt // reset the recipient accountData["Recipient"] = "" - updatedJsonData, err := json.Marshal(accountData) - if err != nil { - return res, err - } - - err = os.WriteFile(fp, updatedJsonData, 0644) + err = h.accountFileHandler.WriteAccountData(accountData) if err != nil { return res, err } @@ -588,15 +454,7 @@ func (h *Handlers) TransactionReset(ctx context.Context, sym string, input []byt func (h *Handlers) ResetTransactionAmount(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - fp := h.fs.Path + "_data" - - jsonData, err := os.ReadFile(fp) - if err != nil { - return res, err - } - - var accountData map[string]string - err = json.Unmarshal(jsonData, &accountData) + accountData, err := h.accountFileHandler.ReadAccountData() if err != nil { return res, err } @@ -604,12 +462,7 @@ func (h *Handlers) ResetTransactionAmount(ctx context.Context, sym string, input // reset the amount accountData["Amount"] = "" - updatedJsonData, err := json.Marshal(accountData) - if err != nil { - return res, err - } - - err = os.WriteFile(fp, updatedJsonData, 0644) + err = h.accountFileHandler.WriteAccountData(accountData) if err != nil { return res, err } @@ -632,15 +485,7 @@ func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte) res := resource.Result{} amount := string(input) - fp := h.fs.Path + "_data" - - jsonData, err := os.ReadFile(fp) - if err != nil { - return res, err - } - - var accountData map[string]string - err = json.Unmarshal(jsonData, &accountData) + accountData, err := h.accountFileHandler.ReadAccountData() if err != nil { return res, err } @@ -658,12 +503,7 @@ func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte) accountData["Amount"] = amount - updatedJsonData, err := json.Marshal(accountData) - if err != nil { - return res, err - } - - err = os.WriteFile(fp, updatedJsonData, 0644) + err = h.accountFileHandler.WriteAccountData(accountData) if err != nil { return res, err } @@ -676,15 +516,8 @@ func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte) func (h *Handlers) GetRecipient(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - fp := h.fs.Path + "_data" - jsonData, err := os.ReadFile(fp) - if err != nil { - return res, err - } - - var accountData map[string]string - err = json.Unmarshal(jsonData, &accountData) + accountData, err := h.accountFileHandler.ReadAccountData() if err != nil { return res, err } @@ -696,15 +529,8 @@ func (h *Handlers) GetRecipient(ctx context.Context, sym string, input []byte) ( func (h *Handlers) GetProfileInfo(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - fp := h.fs.Path + "_data" - jsonData, err := os.ReadFile(fp) - if err != nil { - return res, err - } - - var accountData map[string]string - err = json.Unmarshal(jsonData, &accountData) + accountData, err := h.accountFileHandler.ReadAccountData() if err != nil { return res, err } @@ -737,15 +563,8 @@ func (h *Handlers) GetProfileInfo(ctx context.Context, sym string, input []byte) func (h *Handlers) GetSender(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - fp := h.fs.Path + "_data" - jsonData, err := os.ReadFile(fp) - if err != nil { - return res, err - } - - var accountData map[string]string - err = json.Unmarshal(jsonData, &accountData) + accountData, err := h.accountFileHandler.ReadAccountData() if err != nil { return res, err } @@ -757,15 +576,8 @@ func (h *Handlers) GetSender(ctx context.Context, sym string, input []byte) (res func (h *Handlers) QuitWithBalance(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - fp := h.fs.Path + "_data" - jsonData, err := os.ReadFile(fp) - if err != nil { - return res, err - } - - var accountData map[string]string - err = json.Unmarshal(jsonData, &accountData) + accountData, err := h.accountFileHandler.ReadAccountData() if err != nil { return res, err } diff --git a/internal/utils/account_utils.go b/internal/utils/account_utils.go new file mode 100644 index 0000000..39fb66b --- /dev/null +++ b/internal/utils/account_utils.go @@ -0,0 +1,46 @@ +package utils + +import ( + "encoding/json" + "os" +) + +type AccountFileHandler struct { + FilePath string +} + +func NewAccountFileHandler(path string) *AccountFileHandler { + return &AccountFileHandler{FilePath: path} +} + +func (afh *AccountFileHandler) ReadAccountData() (map[string]string, error) { + jsonData, err := os.ReadFile(afh.FilePath) + if err != nil { + return nil, err + } + + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return nil, err + } + + return accountData, nil +} + +func (afh *AccountFileHandler) WriteAccountData(accountData map[string]string) error { + jsonData, err := json.Marshal(accountData) + if err != nil { + return err + } + + return os.WriteFile(afh.FilePath, jsonData, 0644) +} + +func (afh *AccountFileHandler) EnsureFileExists() error { + f, err := os.OpenFile(afh.FilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) + if err != nil { + return err + } + return f.Close() +} From ddde2fb4ca4429bb84a45d434a6e1c129c5877d3 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Tue, 27 Aug 2024 11:22:37 +0300 Subject: [PATCH 077/201] add documentation lines --- internal/handlers/ussd/menuhandler.go | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 6cc260f..5ffb092 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -88,6 +88,8 @@ func (h *Handlers) CreateAccount(ctx context.Context, sym string, input []byte) return res, err } + +//SavePin persists the user's PIN choice into the filesystem func (h *Handlers) SavePin(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} accountPIN := string(input) @@ -154,6 +156,7 @@ func codeFromCtx(ctx context.Context) string { return code } +//SaveFirstname updates the first name in a JSON data file with the provided input. func (h *Handlers) SaveFirstname(cxt context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} fp := h.fs.Path + "_data" @@ -185,6 +188,7 @@ func (h *Handlers) SaveFirstname(cxt context.Context, sym string, input []byte) return res, nil } +//SaveFamilyname updates the family name in a JSON data file with the provided input. func (h *Handlers) SaveFamilyname(cxt context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} fp := h.fs.Path + "_data" @@ -217,6 +221,7 @@ func (h *Handlers) SaveFamilyname(cxt context.Context, sym string, input []byte) return res, nil } +//SaveYOB updates the Year of Birth(YOB) in a JSON data file with the provided input. func (h *Handlers) SaveYob(cxt context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} fp := h.fs.Path + "_data" @@ -247,6 +252,7 @@ func (h *Handlers) SaveYob(cxt context.Context, sym string, input []byte) (resou return res, nil } +//SaveLocation updates the location in a JSON data file with the provided input. func (h *Handlers) SaveLocation(cxt context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} fp := h.fs.Path + "_data" @@ -277,6 +283,7 @@ func (h *Handlers) SaveLocation(cxt context.Context, sym string, input []byte) ( return res, nil } +//SaveGender updates the gender in a JSON data file with the provided input. func (h *Handlers) SaveGender(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} fp := h.fs.Path + "_data" @@ -314,6 +321,7 @@ func (h *Handlers) SaveGender(ctx context.Context, sym string, input []byte) (re return res, nil } +//SaveOfferings updates the offerings(goods and services provided by the user) in a JSON data file with the provided input. func (h *Handlers) SaveOfferings(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} fp := h.fs.Path + "_data" @@ -694,6 +702,7 @@ func (h *Handlers) GetRecipient(ctx context.Context, sym string, input []byte) ( return res, nil } +// GetProfileInfo retrieves and formats the profile information of a user from a JSON data file. func (h *Handlers) GetProfileInfo(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} fp := h.fs.Path + "_data" @@ -735,6 +744,8 @@ func (h *Handlers) GetProfileInfo(ctx context.Context, sym string, input []byte) return res, nil } + +// GetSender retrieves the public key from a JSON data file. func (h *Handlers) GetSender(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} fp := h.fs.Path + "_data" From 26fcdeb56a72dd2cca191b89d52fbd20b87bcf00 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Tue, 27 Aug 2024 13:28:42 +0300 Subject: [PATCH 078/201] remove call on getting profile information --- services/registration/edit_profile.vis | 1 - 1 file changed, 1 deletion(-) diff --git a/services/registration/edit_profile.vis b/services/registration/edit_profile.vis index 8f6a470..3441406 100644 --- a/services/registration/edit_profile.vis +++ b/services/registration/edit_profile.vis @@ -1,5 +1,4 @@ LOAD reset_unlocked 0 -LOAD get_profile_info 0 MOUT edit_name 1 MOUT edit_gender 2 MOUT edit_yob 3 From 7e95e7cbb3940d3e9a94c4ec0b0d63488986009c Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Tue, 27 Aug 2024 13:30:00 +0300 Subject: [PATCH 079/201] initialize fieldnames --- internal/handlers/ussd/menuhandler.go | 56 +++++++++++++++------------ 1 file changed, 32 insertions(+), 24 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index c84c093..94ea98e 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -73,8 +73,13 @@ func (h *Handlers) CreateAccount(ctx context.Context, sym string, input []byte) "PublicKey": accountResp.Result.PublicKey, "CustodialId": accountResp.Result.CustodialId.String(), "Status": "PENDING", + "Gender": "Not provided", + "YOB": "Not provided", + "Location": "Not provided", + "Offerings": "Not provided", + "FirstName": "Not provided", + "FamilyName": "Not provided", } - err = h.accountFileHandler.WriteAccountData(accountData) if err != nil { return res, err @@ -84,8 +89,7 @@ func (h *Handlers) CreateAccount(ctx context.Context, sym string, input []byte) return res, err } - -//SavePin persists the user's PIN choice into the filesystem +// SavePin persists the user's PIN choice into the filesystem func (h *Handlers) SavePin(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} accountPIN := string(input) @@ -133,7 +137,7 @@ func codeFromCtx(ctx context.Context) string { return code } -//SaveFirstname updates the first name in a JSON data file with the provided input. +// SaveFirstname updates the first name in a JSON data file with the provided input. func (h *Handlers) SaveFirstname(cxt context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} @@ -154,7 +158,7 @@ func (h *Handlers) SaveFirstname(cxt context.Context, sym string, input []byte) return res, nil } -//SaveFamilyname updates the family name in a JSON data file with the provided input. +// SaveFamilyname updates the family name in a JSON data file with the provided input. func (h *Handlers) SaveFamilyname(cxt context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} @@ -175,7 +179,7 @@ func (h *Handlers) SaveFamilyname(cxt context.Context, sym string, input []byte) return res, nil } -//SaveYOB updates the Year of Birth(YOB) in a JSON data file with the provided input. +// SaveYOB updates the Year of Birth(YOB) in a JSON data file with the provided input. func (h *Handlers) SaveYob(cxt context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} @@ -198,7 +202,7 @@ func (h *Handlers) SaveYob(cxt context.Context, sym string, input []byte) (resou return res, nil } -//SaveLocation updates the location in a JSON data file with the provided input. +// SaveLocation updates the location in a JSON data file with the provided input. func (h *Handlers) SaveLocation(cxt context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} @@ -220,7 +224,7 @@ func (h *Handlers) SaveLocation(cxt context.Context, sym string, input []byte) ( return res, nil } -//SaveGender updates the gender in a JSON data file with the provided input. +// SaveGender updates the gender in a JSON data file with the provided input. func (h *Handlers) SaveGender(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} @@ -250,7 +254,7 @@ func (h *Handlers) SaveGender(ctx context.Context, sym string, input []byte) (re return res, nil } -//SaveOfferings updates the offerings(goods and services provided by the user) in a JSON data file with the provided input. +// SaveOfferings updates the offerings(goods and services provided by the user) in a JSON data file with the provided input. func (h *Handlers) SaveOfferings(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} @@ -538,39 +542,43 @@ func (h *Handlers) GetRecipient(ctx context.Context, sym string, input []byte) ( // GetProfileInfo retrieves and formats the profile information of a user from a JSON data file. func (h *Handlers) GetProfileInfo(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - + var age string accountData, err := h.accountFileHandler.ReadAccountData() if err != nil { return res, err } - name := accountData["FirstName"] + " " + accountData["FamilyName"] + var name string + if accountData["FirstName"] == "Not provided" || accountData["FamilyName"] == "Not provided" { + name = "Not provided" + } else { + name = accountData["FirstName"] + " " + accountData["FamilyName"] + } + gender := accountData["Gender"] yob := accountData["YOB"] location := accountData["Location"] offerings := accountData["Offerings"] - layout := "02/01/2006" - birthdate, err := time.Parse(layout, yob) if err != nil { return res, err } - - currentDate := time.Now() - formattedDate := currentDate.Format(layout) - today, err := time.Parse(layout, formattedDate) - if err != nil { - return res, nil + if yob == "Not provided" { + age = "Not provided" + } else { + currentDate := time.Now() + formattedDate := currentDate.Format(layout) + today, err := time.Parse(layout, formattedDate) + if err != nil { + return res, nil + } + age = string(utils.CalculateAge(birthdate, today)) } - age := utils.CalculateAge(birthdate, today) - - formattedData := fmt.Sprintf("Name: %s\nGender: %s\nAge: %d\nLocation: %s\nYou provide: %s\n", name, gender, age, location, offerings) + formattedData := fmt.Sprintf("Name: %s\nGender: %s\nAge: %s\nLocation: %s\nYou provide: %s\n", name, gender, age, location, offerings) res.Content = formattedData - return res, nil } - // GetSender retrieves the public key from a JSON data file. func (h *Handlers) GetSender(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} From bf99ed84822121de076638a429acc4abb8c4ab51 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Tue, 27 Aug 2024 13:38:08 +0300 Subject: [PATCH 080/201] Added a CATCH if the account creation fails --- cmd/main.go | 5 ++--- internal/handlers/ussd/menuhandler.go | 2 +- internal/models/flags.go | 1 + services/registration/account_creation_failed | 1 + services/registration/account_creation_failed.vis | 3 +++ services/registration/account_creation_failed_swa | 1 + services/registration/create_pin.vis | 1 + 7 files changed, 10 insertions(+), 4 deletions(-) create mode 100644 services/registration/account_creation_failed create mode 100644 services/registration/account_creation_failed.vis create mode 100644 services/registration/account_creation_failed_swa diff --git a/cmd/main.go b/cmd/main.go index beddaf0..295e371 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -33,7 +33,7 @@ func main() { fmt.Fprintf(os.Stderr, "starting session at symbol '%s' using resource dir: %s\n", root, dir) ctx := context.Background() - st := state.NewState(14) + st := state.NewState(15) st.UseDebug() state.FlagDebugger.Register(models.USERFLAG_LANGUAGE_SET, "LANGUAGE_CHANGE") state.FlagDebugger.Register(models.USERFLAG_ACCOUNT_CREATED, "ACCOUNT_CREATED") @@ -49,8 +49,7 @@ func main() { state.FlagDebugger.Register(models.USERFLAG_UNLOCKFORUPDATE,"UNLOCKFORUPDATE") state.FlagDebugger.Register(models.USERFLAG_VALIDPIN,"VALIDPIN") state.FlagDebugger.Register(models.USERFLAG_VALIDPIN,"ACCOUNTUNLOCKED") - - + state.FlagDebugger.Register(models.USERFLAG_ACCOUNT_CREATION_FAILED,"ACCOUNT_CREATION_FAILED") rfs := resource.NewFsResource(scriptDir) ca := cache.NewCache() diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 94ea98e..62f6b13 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -64,7 +64,7 @@ func (h *Handlers) CreateAccount(ctx context.Context, sym string, input []byte) accountResp, err := server.CreateAccount() if err != nil { - fmt.Println("Failed to create account:", err) + res.FlagSet = append(res.FlagSet, models.USERFLAG_ACCOUNT_CREATION_FAILED) return res, err } diff --git a/internal/models/flags.go b/internal/models/flags.go index 42805a0..ad0fd15 100644 --- a/internal/models/flags.go +++ b/internal/models/flags.go @@ -17,4 +17,5 @@ const ( USERFLAG_VALIDPIN USERFLAG_PINMISMATCH USERFLAG_INCORRECTDATEFORMAT + USERFLAG_ACCOUNT_CREATION_FAILED ) diff --git a/services/registration/account_creation_failed b/services/registration/account_creation_failed new file mode 100644 index 0000000..0df00db --- /dev/null +++ b/services/registration/account_creation_failed @@ -0,0 +1 @@ +Your account creation request failed. Please try again later. \ No newline at end of file diff --git a/services/registration/account_creation_failed.vis b/services/registration/account_creation_failed.vis new file mode 100644 index 0000000..b62b797 --- /dev/null +++ b/services/registration/account_creation_failed.vis @@ -0,0 +1,3 @@ +MOUT quit 9 +HALT +INCMP quit 9 diff --git a/services/registration/account_creation_failed_swa b/services/registration/account_creation_failed_swa new file mode 100644 index 0000000..6f0ac7b --- /dev/null +++ b/services/registration/account_creation_failed_swa @@ -0,0 +1 @@ +Ombi lako la kusajiliwa haliwezi kukamilishwa. Tafadhali jaribu tena baadaye. \ No newline at end of file diff --git a/services/registration/create_pin.vis b/services/registration/create_pin.vis index 852bf47..cc6ecfe 100644 --- a/services/registration/create_pin.vis +++ b/services/registration/create_pin.vis @@ -1,4 +1,5 @@ LOAD create_account 0 +CATCH account_creation_failed 22 1 MOUT exit 0 HALT LOAD save_pin 0 From 2e9b96d3a2c2ceea076485eb81c7a847fd268da6 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Tue, 27 Aug 2024 14:56:55 +0300 Subject: [PATCH 081/201] add template for invalid date inputs --- services/registration/incorrect_date_format | 4 ++-- services/registration/incorrect_date_format_swa | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/services/registration/incorrect_date_format b/services/registration/incorrect_date_format index 517ea52..308b74c 100644 --- a/services/registration/incorrect_date_format +++ b/services/registration/incorrect_date_format @@ -1,2 +1,2 @@ -Unsuported date format -Please provide date format as 12/01/1972 +The year of birth you entered is invalid. +Please try again. diff --git a/services/registration/incorrect_date_format_swa b/services/registration/incorrect_date_format_swa index e69de29..bd85f21 100644 --- a/services/registration/incorrect_date_format_swa +++ b/services/registration/incorrect_date_format_swa @@ -0,0 +1,2 @@ +Mwaka wa kuzaliwa ulioweka sio sahihi. +Tafadhali jaribu tena. \ No newline at end of file From 674fd5773a6ca1dcc0db1e8517e0b70c2c9c278c Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Tue, 27 Aug 2024 14:57:26 +0300 Subject: [PATCH 082/201] validate date as a 4 digit input value --- internal/handlers/ussd/menuhandler.go | 30 ++++++++++++--------------- 1 file changed, 13 insertions(+), 17 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 62f6b13..5414dd2 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -4,8 +4,7 @@ import ( "bytes" "context" "fmt" - "regexp" - "time" + "strconv" "git.defalsify.org/vise.git/engine" "git.defalsify.org/vise.git/lang" @@ -189,7 +188,7 @@ func (h *Handlers) SaveYob(cxt context.Context, sym string, input []byte) (resou } yob := string(input) - if len(yob) > 4 { + if len(yob) == 4 { yob := string(input) accountData["YOB"] = yob @@ -380,13 +379,17 @@ func (h *Handlers) Quit(ctx context.Context, sym string, input []byte) (resource func (h *Handlers) VerifyYob(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} date := string(input) + _, err := strconv.Atoi(date) + if err != nil { + // If conversion fails, input is not numeric + res.FlagSet = append(res.FlagSet, models.USERFLAG_INCORRECTDATEFORMAT) + return res, nil + } - dateRegex := regexp.MustCompile(`^\d{2}/\d{2}/\d{4}$`) - isCorrectFormat := dateRegex.MatchString(date) - if !isCorrectFormat { - res.FlagSet = append(res.FlagSet, models.USERFLAG_INCORRECTDATEFORMAT) - } else { + if len(date) == 4 { res.FlagReset = append(res.FlagReset, models.USERFLAG_INCORRECTDATEFORMAT) + } else { + res.FlagSet = append(res.FlagSet, models.USERFLAG_INCORRECTDATEFORMAT) } return res, nil @@ -558,21 +561,14 @@ func (h *Handlers) GetProfileInfo(ctx context.Context, sym string, input []byte) yob := accountData["YOB"] location := accountData["Location"] offerings := accountData["Offerings"] - layout := "02/01/2006" - birthdate, err := time.Parse(layout, yob) - if err != nil { - return res, err - } if yob == "Not provided" { age = "Not provided" } else { - currentDate := time.Now() - formattedDate := currentDate.Format(layout) - today, err := time.Parse(layout, formattedDate) + ageInt, err := strconv.Atoi(yob) if err != nil { return res, nil } - age = string(utils.CalculateAge(birthdate, today)) + age = strconv.Itoa(utils.CalculateAgeWithYOB(ageInt)) } formattedData := fmt.Sprintf("Name: %s\nGender: %s\nAge: %s\nLocation: %s\nYou provide: %s\n", name, gender, age, location, offerings) res.Content = formattedData From 2a5f7517f420dab359a07a1981caedab75be4c91 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Tue, 27 Aug 2024 14:59:17 +0300 Subject: [PATCH 083/201] add function to calculate age with yob --- internal/utils/age.go | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/internal/utils/age.go b/internal/utils/age.go index 8d1aa24..6b040e7 100644 --- a/internal/utils/age.go +++ b/internal/utils/age.go @@ -19,4 +19,17 @@ func CalculateAge(birthdate, today time.Time) int { age-- } return age +} + +// CalculateAgeWithYOB calculates the age based on the given year of birth (YOB). +// It subtracts the YOB from the current year to determine the age. +// +// Parameters: +// yob: The year of birth as an integer. +// +// Returns: +// The calculated age as an integer. +func CalculateAgeWithYOB(yob int) int { + currentYear := time.Now().Year() + return currentYear - yob } \ No newline at end of file From 1d578209fc774a33076afcf1d827f1af753748fe Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Tue, 27 Aug 2024 15:41:53 +0300 Subject: [PATCH 084/201] Ensure that the user sets a PIN before proceeding to main --- cmd/main.go | 2 +- internal/handlers/ussd/menuhandler.go | 8 ++++++++ internal/models/flags.go | 2 +- services/registration/create_pin.vis | 1 + services/registration/root.vis | 1 + services/registration/terms.vis | 2 +- 6 files changed, 13 insertions(+), 3 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index 295e371..d53dfe9 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -43,7 +43,7 @@ func main() { state.FlagDebugger.Register(models.USERFLAG_INCORRECTDATEFORMAT,"INVALIDDATEFORMAT") state.FlagDebugger.Register(models.USERFLAG_INVALID_RECIPIENT,"INVALIDRECIPIENT") state.FlagDebugger.Register(models.USERFLAG_PINMISMATCH,"PINMISMATCH") - state.FlagDebugger.Register(models.USERFLAG_QUERYPIN,"QUERYPIN") + state.FlagDebugger.Register(models.USERFLAG_PIN_SET,"PIN_SET") state.FlagDebugger.Register(models.USERFLAG_INVALID_RECIPIENT_WITH_INVITE,"INVALIDRECIPIENT_WITH_INVITE") state.FlagDebugger.Register(models.USERFLAG_INVALID_AMOUNT,"INVALIDAMOUNT") state.FlagDebugger.Register(models.USERFLAG_UNLOCKFORUPDATE,"UNLOCKFORUPDATE") diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 5414dd2..897fff6 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -61,6 +61,13 @@ func (h *Handlers) CreateAccount(ctx context.Context, sym string, input []byte) return res, err } + // if an account exists, set the flag and return + existingAccountData, err := h.accountFileHandler.ReadAccountData() + if existingAccountData != nil { + res.FlagSet = append(res.FlagSet, models.USERFLAG_ACCOUNT_CREATED) + return res, err + } + accountResp, err := server.CreateAccount() if err != nil { res.FlagSet = append(res.FlagSet, models.USERFLAG_ACCOUNT_CREATION_FAILED) @@ -119,6 +126,7 @@ func (h *Handlers) VerifyPin(ctx context.Context, sym string, input []byte) (res if bytes.Equal(input, []byte(accountData["AccountPIN"])) { res.FlagSet = []uint32{models.USERFLAG_VALIDPIN} res.FlagReset = []uint32{models.USERFLAG_PINMISMATCH} + res.FlagSet = append(res.FlagSet, models.USERFLAG_PIN_SET) } else { res.FlagSet = []uint32{models.USERFLAG_PINMISMATCH} } diff --git a/internal/models/flags.go b/internal/models/flags.go index ad0fd15..5ac1107 100644 --- a/internal/models/flags.go +++ b/internal/models/flags.go @@ -13,7 +13,7 @@ const ( USERFLAG_INCORRECTPIN USERFLAG_UNLOCKFORUPDATE USERFLAG_INVALID_AMOUNT - USERFLAG_QUERYPIN + USERFLAG_PIN_SET USERFLAG_VALIDPIN USERFLAG_PINMISMATCH USERFLAG_INCORRECTDATEFORMAT diff --git a/services/registration/create_pin.vis b/services/registration/create_pin.vis index cc6ecfe..3ecc474 100644 --- a/services/registration/create_pin.vis +++ b/services/registration/create_pin.vis @@ -3,4 +3,5 @@ CATCH account_creation_failed 22 1 MOUT exit 0 HALT LOAD save_pin 0 +INCMP quit 0 INCMP confirm_create_pin * diff --git a/services/registration/root.vis b/services/registration/root.vis index f3e6216..14b77f8 100644 --- a/services/registration/root.vis +++ b/services/registration/root.vis @@ -2,5 +2,6 @@ CATCH select_language 8 0 CATCH terms 9 0 LOAD check_account_status 0 CATCH account_pending 10 1 +CATCH create_pin 18 0 CATCH main 11 1 HALT diff --git a/services/registration/terms.vis b/services/registration/terms.vis index 768efa3..dea6797 100644 --- a/services/registration/terms.vis +++ b/services/registration/terms.vis @@ -4,4 +4,4 @@ MOUT yes 0 MOUT no 1 HALT INCMP create_pin 0 -INCMP _ * +INCMP quit * From 8d9aaeedbcc06e34f15e4149b16638050a4cfa18 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Tue, 27 Aug 2024 16:02:24 +0300 Subject: [PATCH 085/201] Validate that the amount is not greater than the balance --- internal/handlers/ussd/menuhandler.go | 66 ++++++++++++++++++--------- 1 file changed, 44 insertions(+), 22 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 897fff6..df83592 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -5,6 +5,7 @@ import ( "context" "fmt" "strconv" + "strings" "git.defalsify.org/vise.git/engine" "git.defalsify.org/vise.git/lang" @@ -505,36 +506,57 @@ func (h *Handlers) MaxAmount(ctx context.Context, sym string, input []byte) (res } func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} - amount := string(input) + res := resource.Result{} + amountStr := string(input) - accountData, err := h.accountFileHandler.ReadAccountData() - if err != nil { - return res, err - } + accountData, err := h.accountFileHandler.ReadAccountData() + if err != nil { + return res, err + } - if amount != "0" { - // mimic invalid amount - if amount == "00" { - res.FlagSet = append(res.FlagSet, models.USERFLAG_INVALID_AMOUNT) - res.Content = amount + balanceStr, err := server.CheckBalance(accountData["PublicKey"]) + if err != nil { + return res, err + } + res.Content = balanceStr - return res, nil - } + // Parse the balance + balanceParts := strings.Split(balanceStr, " ") + if len(balanceParts) != 2 { + return res, fmt.Errorf("unexpected balance format: %s", balanceStr) + } + balanceValue, err := strconv.ParseFloat(balanceParts[0], 64) + if err != nil { + return res, fmt.Errorf("failed to parse balance: %v", err) + } - res.Content = amount + // Parse the input amount + if amountStr != "0" { + inputAmount, err := strconv.ParseFloat(amountStr, 64) + if err != nil { + res.FlagSet = append(res.FlagSet, models.USERFLAG_INVALID_AMOUNT) + res.Content = amountStr + return res, nil + } - accountData["Amount"] = amount + if inputAmount > balanceValue { + res.FlagSet = append(res.FlagSet, models.USERFLAG_INVALID_AMOUNT) + res.Content = amountStr + return res, nil + } - err = h.accountFileHandler.WriteAccountData(accountData) - if err != nil { - return res, err - } + res.Content = amountStr + accountData["Amount"] = amountStr - return res, nil - } + err = h.accountFileHandler.WriteAccountData(accountData) + if err != nil { + return res, err + } - return res, nil + return res, nil + } + + return res, nil } func (h *Handlers) GetRecipient(ctx context.Context, sym string, input []byte) (resource.Result, error) { From 2b10f6023f0efb91852d03568b6f4ced95a9835c Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Tue, 27 Aug 2024 16:10:43 +0300 Subject: [PATCH 086/201] Use the balance as the max_amount --- internal/handlers/ussd/menuhandler.go | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index df83592..de2e383 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -499,8 +499,17 @@ func (h *Handlers) ResetTransactionAmount(ctx context.Context, sym string, input func (h *Handlers) MaxAmount(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - // mimic a max amount - res.Content = "10.00" + accountData, err := h.accountFileHandler.ReadAccountData() + if err != nil { + return res, err + } + + balance, err := server.CheckBalance(accountData["PublicKey"]) + if err != nil { + return res, nil + } + + res.Content = balance return res, nil } From 633d56b0adb6b283435f5995d30174219d3c74f1 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Tue, 27 Aug 2024 16:16:15 +0300 Subject: [PATCH 087/201] Allow users to include 'CELO' in the amount --- internal/handlers/ussd/menuhandler.go | 100 +++++++++++++------------- 1 file changed, 52 insertions(+), 48 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index de2e383..53c5fe8 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "fmt" + "regexp" "strconv" "strings" @@ -389,11 +390,11 @@ func (h *Handlers) VerifyYob(ctx context.Context, sym string, input []byte) (res res := resource.Result{} date := string(input) _, err := strconv.Atoi(date) - if err != nil { - // If conversion fails, input is not numeric - res.FlagSet = append(res.FlagSet, models.USERFLAG_INCORRECTDATEFORMAT) - return res, nil - } + if err != nil { + // If conversion fails, input is not numeric + res.FlagSet = append(res.FlagSet, models.USERFLAG_INCORRECTDATEFORMAT) + return res, nil + } if len(date) == 4 { res.FlagReset = append(res.FlagReset, models.USERFLAG_INCORRECTDATEFORMAT) @@ -515,59 +516,62 @@ func (h *Handlers) MaxAmount(ctx context.Context, sym string, input []byte) (res } func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} - amountStr := string(input) + res := resource.Result{} + amountStr := string(input) - accountData, err := h.accountFileHandler.ReadAccountData() - if err != nil { - return res, err - } + accountData, err := h.accountFileHandler.ReadAccountData() + if err != nil { + return res, err + } - balanceStr, err := server.CheckBalance(accountData["PublicKey"]) - if err != nil { - return res, err - } - res.Content = balanceStr + balanceStr, err := server.CheckBalance(accountData["PublicKey"]) + if err != nil { + return res, err + } + res.Content = balanceStr - // Parse the balance - balanceParts := strings.Split(balanceStr, " ") - if len(balanceParts) != 2 { - return res, fmt.Errorf("unexpected balance format: %s", balanceStr) - } - balanceValue, err := strconv.ParseFloat(balanceParts[0], 64) - if err != nil { - return res, fmt.Errorf("failed to parse balance: %v", err) - } + // Parse the balance + balanceParts := strings.Split(balanceStr, " ") + if len(balanceParts) != 2 { + return res, fmt.Errorf("unexpected balance format: %s", balanceStr) + } + balanceValue, err := strconv.ParseFloat(balanceParts[0], 64) + if err != nil { + return res, fmt.Errorf("failed to parse balance: %v", err) + } - // Parse the input amount - if amountStr != "0" { - inputAmount, err := strconv.ParseFloat(amountStr, 64) - if err != nil { - res.FlagSet = append(res.FlagSet, models.USERFLAG_INVALID_AMOUNT) - res.Content = amountStr - return res, nil - } + // Extract numeric part from input + re := regexp.MustCompile(`^(\d+(\.\d+)?)\s*(?:CELO)?$`) + matches := re.FindStringSubmatch(strings.TrimSpace(amountStr)) + if len(matches) < 2 { + res.FlagSet = append(res.FlagSet, models.USERFLAG_INVALID_AMOUNT) + res.Content = amountStr + return res, nil + } - if inputAmount > balanceValue { - res.FlagSet = append(res.FlagSet, models.USERFLAG_INVALID_AMOUNT) - res.Content = amountStr - return res, nil - } + inputAmount, err := strconv.ParseFloat(matches[1], 64) + if err != nil { + res.FlagSet = append(res.FlagSet, models.USERFLAG_INVALID_AMOUNT) + res.Content = amountStr + return res, nil + } - res.Content = amountStr - accountData["Amount"] = amountStr + if inputAmount > balanceValue { + res.FlagSet = append(res.FlagSet, models.USERFLAG_INVALID_AMOUNT) + res.Content = amountStr + return res, nil + } - err = h.accountFileHandler.WriteAccountData(accountData) - if err != nil { - return res, err - } + res.Content = fmt.Sprintf("%.3f", inputAmount) // Format to 3 decimal places + accountData["Amount"] = res.Content - return res, nil - } + err = h.accountFileHandler.WriteAccountData(accountData) + if err != nil { + return res, err + } - return res, nil + return res, nil } - func (h *Handlers) GetRecipient(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} From 8d2a345d39a4669fc64f54fb08ffd91c2604e212 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Tue, 27 Aug 2024 23:11:16 +0300 Subject: [PATCH 088/201] add navigation for menu option 4 and 5 --- services/registration/edit_profile.vis | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/registration/edit_profile.vis b/services/registration/edit_profile.vis index 3441406..6fbb4c9 100644 --- a/services/registration/edit_profile.vis +++ b/services/registration/edit_profile.vis @@ -11,5 +11,6 @@ INCMP _ 0 INCMP enter_name 1 INCMP select_gender 2 INCMP enter_yob 3 -INCMP enter_loca 4 +INCMP enter_location 4 +INCMP enter_offerings 5 INCMP view_profile 6 From d6f9ee0fc3900c8a8fb3c4c13232e1462d39ebe0 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Tue, 27 Aug 2024 23:11:31 +0300 Subject: [PATCH 089/201] remove unused node --- services/registration/enter_off.vis | 6 ------ 1 file changed, 6 deletions(-) delete mode 100644 services/registration/enter_off.vis diff --git a/services/registration/enter_off.vis b/services/registration/enter_off.vis deleted file mode 100644 index 90e44da..0000000 --- a/services/registration/enter_off.vis +++ /dev/null @@ -1,6 +0,0 @@ -MOUT back 0 -HALT -INCMP _ 0 - - - From b48760760b30b6666fc80fe1eac4faf824df182a Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Wed, 28 Aug 2024 00:17:45 +0300 Subject: [PATCH 090/201] Validate that the PIN is 4 digits --- internal/handlers/ussd/menuhandler.go | 12 ++++++++++++ services/registration/create_pin.vis | 2 ++ 2 files changed, 14 insertions(+) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 53c5fe8..6279838 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -107,6 +107,13 @@ func (h *Handlers) SavePin(ctx context.Context, sym string, input []byte) (resou return res, err } + // Validate that the PIN is a 4-digit number + if !isValidPIN(accountPIN) { + res.FlagSet = append(res.FlagSet, models.USERFLAG_INCORRECTPIN) + return res, nil + } + + res.FlagReset = append(res.FlagReset, models.USERFLAG_INCORRECTPIN) accountData["AccountPIN"] = accountPIN err = h.accountFileHandler.WriteAccountData(accountData) @@ -136,6 +143,11 @@ func (h *Handlers) VerifyPin(ctx context.Context, sym string, input []byte) (res return res, nil } +func isValidPIN(pin string) bool { + match, _ := regexp.MatchString(`^\d{4}$`, pin) + return match +} + func codeFromCtx(ctx context.Context) string { var code string engine.Logg.DebugCtxf(ctx, "in msg", "ctx", ctx, "val", code) diff --git a/services/registration/create_pin.vis b/services/registration/create_pin.vis index 3ecc474..4994863 100644 --- a/services/registration/create_pin.vis +++ b/services/registration/create_pin.vis @@ -3,5 +3,7 @@ CATCH account_creation_failed 22 1 MOUT exit 0 HALT LOAD save_pin 0 +RELOAD save_pin +CATCH . 15 1 INCMP quit 0 INCMP confirm_create_pin * From 2e9d9175d99f5c311d42a942e46116a244df7fb0 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Wed, 28 Aug 2024 10:08:33 +0300 Subject: [PATCH 091/201] allow single edit on profile information --- services/registration/edit_profile.vis | 1 + services/registration/enter_location.vis | 3 +++ services/registration/enter_yob.vis | 3 +++ services/registration/select_gender.vis | 3 +++ 4 files changed, 10 insertions(+) diff --git a/services/registration/edit_profile.vis b/services/registration/edit_profile.vis index 6fbb4c9..c4d5f52 100644 --- a/services/registration/edit_profile.vis +++ b/services/registration/edit_profile.vis @@ -8,6 +8,7 @@ MOUT view 6 MOUT back 0 HALT INCMP _ 0 +LOAD set_reset_single_edit 0 INCMP enter_name 1 INCMP select_gender 2 INCMP enter_yob 3 diff --git a/services/registration/enter_location.vis b/services/registration/enter_location.vis index 9245bb1..f6ccf77 100644 --- a/services/registration/enter_location.vis +++ b/services/registration/enter_location.vis @@ -1,8 +1,11 @@ CATCH incorrect_date_format 21 1 LOAD save_yob 0 +CATCH update_success 16 1 MOUT back 0 HALT INCMP _ 0 +LOAD save_location 0 +CATCH pin_entry 23 1 INCMP enter_offerings * diff --git a/services/registration/enter_yob.vis b/services/registration/enter_yob.vis index 0a5b778..3b3f0d2 100644 --- a/services/registration/enter_yob.vis +++ b/services/registration/enter_yob.vis @@ -1,6 +1,9 @@ LOAD save_gender 0 +CATCH update_success 16 1 MOUT back 0 HALT INCMP _ 0 LOAD verify_yob 8 +LOAD save_yob 0 +CATCH pin_entry 23 1 INCMP enter_location * diff --git a/services/registration/select_gender.vis b/services/registration/select_gender.vis index e9868a5..210a0fe 100644 --- a/services/registration/select_gender.vis +++ b/services/registration/select_gender.vis @@ -1,9 +1,12 @@ LOAD save_familyname 0 +CATCH update_success 16 1 MOUT male 1 MOUT female 2 MOUT other_gender 3 MOUT back 0 HALT +LOAD save_gender 0 +CATCH pin_entry 23 1 INCMP _ 0 INCMP enter_yob 1 INCMP enter_yob 2 From c565a9dde5b2543bdc4f969cd5fea481a608d360 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Wed, 28 Aug 2024 10:09:49 +0300 Subject: [PATCH 092/201] add flag to handle single field profile edit --- internal/models/flags.go | 1 + 1 file changed, 1 insertion(+) diff --git a/internal/models/flags.go b/internal/models/flags.go index 5ac1107..5de16cd 100644 --- a/internal/models/flags.go +++ b/internal/models/flags.go @@ -18,4 +18,5 @@ const ( USERFLAG_PINMISMATCH USERFLAG_INCORRECTDATEFORMAT USERFLAG_ACCOUNT_CREATION_FAILED + USERFLAG_SINGLE_EDIT ) From 0eb1115e39fe31a7c42bd4d5ac4da4913b32994a Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Wed, 28 Aug 2024 10:10:49 +0300 Subject: [PATCH 093/201] add handler for setting and resetting single edits --- internal/handlers/ussd/menuhandler.go | 30 +++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 6279838..7116df0 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -108,10 +108,10 @@ func (h *Handlers) SavePin(ctx context.Context, sym string, input []byte) (resou } // Validate that the PIN is a 4-digit number - if !isValidPIN(accountPIN) { - res.FlagSet = append(res.FlagSet, models.USERFLAG_INCORRECTPIN) - return res, nil - } + if !isValidPIN(accountPIN) { + res.FlagSet = append(res.FlagSet, models.USERFLAG_INCORRECTPIN) + return res, nil + } res.FlagReset = append(res.FlagReset, models.USERFLAG_INCORRECTPIN) accountData["AccountPIN"] = accountPIN @@ -124,6 +124,24 @@ func (h *Handlers) SavePin(ctx context.Context, sym string, input []byte) (resou return res, nil } +func (h *Handlers) SetResetSingleEdit(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + menuOPtion := string(input) + + switch menuOPtion { + case "2": + res.FlagSet = append(res.FlagSet, models.USERFLAG_SINGLE_EDIT) + case "3": + res.FlagSet = append(res.FlagSet, models.USERFLAG_SINGLE_EDIT) + case "4": + res.FlagSet = append(res.FlagSet, models.USERFLAG_SINGLE_EDIT) + default: + res.FlagReset = append(res.FlagReset, models.USERFLAG_SINGLE_EDIT) + } + + return res, nil +} + func (h *Handlers) VerifyPin(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} @@ -144,8 +162,8 @@ func (h *Handlers) VerifyPin(ctx context.Context, sym string, input []byte) (res } func isValidPIN(pin string) bool { - match, _ := regexp.MatchString(`^\d{4}$`, pin) - return match + match, _ := regexp.MatchString(`^\d{4}$`, pin) + return match } func codeFromCtx(ctx context.Context) string { From 6e0ea07cde15b3c9250c0515ecb41795ce1f8503 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Wed, 28 Aug 2024 10:12:08 +0300 Subject: [PATCH 094/201] register single edit flag --- cmd/main.go | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index d53dfe9..ad8699c 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -12,8 +12,8 @@ import ( "git.defalsify.org/vise.git/persist" "git.defalsify.org/vise.git/resource" "git.defalsify.org/vise.git/state" - "git.grassecon.net/urdt/ussd/internal/models" "git.grassecon.net/urdt/ussd/internal/handlers/ussd" + "git.grassecon.net/urdt/ussd/internal/models" ) var ( @@ -33,23 +33,24 @@ func main() { fmt.Fprintf(os.Stderr, "starting session at symbol '%s' using resource dir: %s\n", root, dir) ctx := context.Background() - st := state.NewState(15) + st := state.NewState(16) st.UseDebug() state.FlagDebugger.Register(models.USERFLAG_LANGUAGE_SET, "LANGUAGE_CHANGE") state.FlagDebugger.Register(models.USERFLAG_ACCOUNT_CREATED, "ACCOUNT_CREATED") state.FlagDebugger.Register(models.USERFLAG_ACCOUNT_SUCCESS, "ACCOUNT_SUCCESS") state.FlagDebugger.Register(models.USERFLAG_ACCOUNT_PENDING, "ACCOUNT_PENDING") state.FlagDebugger.Register(models.USERFLAG_INCORRECTPIN, "INCORRECTPIN") - state.FlagDebugger.Register(models.USERFLAG_INCORRECTDATEFORMAT,"INVALIDDATEFORMAT") - state.FlagDebugger.Register(models.USERFLAG_INVALID_RECIPIENT,"INVALIDRECIPIENT") - state.FlagDebugger.Register(models.USERFLAG_PINMISMATCH,"PINMISMATCH") - state.FlagDebugger.Register(models.USERFLAG_PIN_SET,"PIN_SET") - state.FlagDebugger.Register(models.USERFLAG_INVALID_RECIPIENT_WITH_INVITE,"INVALIDRECIPIENT_WITH_INVITE") - state.FlagDebugger.Register(models.USERFLAG_INVALID_AMOUNT,"INVALIDAMOUNT") - state.FlagDebugger.Register(models.USERFLAG_UNLOCKFORUPDATE,"UNLOCKFORUPDATE") - state.FlagDebugger.Register(models.USERFLAG_VALIDPIN,"VALIDPIN") - state.FlagDebugger.Register(models.USERFLAG_VALIDPIN,"ACCOUNTUNLOCKED") - state.FlagDebugger.Register(models.USERFLAG_ACCOUNT_CREATION_FAILED,"ACCOUNT_CREATION_FAILED") + state.FlagDebugger.Register(models.USERFLAG_INCORRECTDATEFORMAT, "INVALIDDATEFORMAT") + state.FlagDebugger.Register(models.USERFLAG_INVALID_RECIPIENT, "INVALIDRECIPIENT") + state.FlagDebugger.Register(models.USERFLAG_PINMISMATCH, "PINMISMATCH") + state.FlagDebugger.Register(models.USERFLAG_PIN_SET, "PIN_SET") + state.FlagDebugger.Register(models.USERFLAG_INVALID_RECIPIENT_WITH_INVITE, "INVALIDRECIPIENT_WITH_INVITE") + state.FlagDebugger.Register(models.USERFLAG_INVALID_AMOUNT, "INVALIDAMOUNT") + state.FlagDebugger.Register(models.USERFLAG_UNLOCKFORUPDATE, "UNLOCKFORUPDATE") + state.FlagDebugger.Register(models.USERFLAG_VALIDPIN, "VALIDPIN") + state.FlagDebugger.Register(models.USERFLAG_VALIDPIN, "ACCOUNTUNLOCKED") + state.FlagDebugger.Register(models.USERFLAG_ACCOUNT_CREATION_FAILED, "ACCOUNT_CREATION_FAILED") + state.FlagDebugger.Register(models.USERFLAG_SINGLE_EDIT, "SINGLEEDIT") rfs := resource.NewFsResource(scriptDir) ca := cache.NewCache() @@ -113,6 +114,7 @@ func main() { rfs.AddLocalFunc("get_profile_info", ussdHandlers.GetProfileInfo) rfs.AddLocalFunc("verify_yob", ussdHandlers.VerifyYob) rfs.AddLocalFunc("reset_incorrect_date_format", ussdHandlers.ResetIncorrectYob) + rfs.AddLocalFunc("set_reset_single_edit", ussdHandlers.SetResetSingleEdit) cont, err := en.Init(ctx) en.SetDebugger(engine.NewSimpleDebug(nil)) From d87b70b292c4c3ad1977e4e97a0b903547dc499b Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Wed, 28 Aug 2024 12:19:38 +0300 Subject: [PATCH 095/201] reset unlock for update --- internal/handlers/ussd/menuhandler.go | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 7116df0..cd3c38b 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -130,10 +130,14 @@ func (h *Handlers) SetResetSingleEdit(ctx context.Context, sym string, input []b switch menuOPtion { case "2": + fmt.Println("Resetting unlock for update") + res.FlagReset = append(res.FlagSet, models.USERFLAG_UNLOCKFORUPDATE) res.FlagSet = append(res.FlagSet, models.USERFLAG_SINGLE_EDIT) case "3": + res.FlagReset = append(res.FlagSet, models.USERFLAG_UNLOCKFORUPDATE) res.FlagSet = append(res.FlagSet, models.USERFLAG_SINGLE_EDIT) case "4": + res.FlagReset = append(res.FlagSet, models.USERFLAG_UNLOCKFORUPDATE) res.FlagSet = append(res.FlagSet, models.USERFLAG_SINGLE_EDIT) default: res.FlagReset = append(res.FlagReset, models.USERFLAG_SINGLE_EDIT) @@ -339,6 +343,8 @@ func (h *Handlers) CheckIdentifier(ctx context.Context, sym string, input []byte return res, nil } +// Unlock attempts to unlock the next sequential nodes by verifying the provided PIN against the already set PIN. +// It sets the required flags that control the flow. func (h *Handlers) Unlock(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} pin := string(input) @@ -348,7 +354,7 @@ func (h *Handlers) Unlock(ctx context.Context, sym string, input []byte) (resour return res, err } - if len(input) > 1 { + if len(input) == 4 { if pin != accountData["AccountPIN"] { res.FlagSet = append(res.FlagSet, models.USERFLAG_INCORRECTPIN) res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_UNLOCKED) @@ -359,6 +365,7 @@ func (h *Handlers) Unlock(ctx context.Context, sym string, input []byte) (resour res.FlagSet = append(res.FlagSet, models.USERFLAG_UNLOCKFORUPDATE) res.FlagSet = append(res.FlagSet, models.USERFLAG_ACCOUNT_UNLOCKED) } else { + res.FlagSet = append(res.FlagSet, models.USERFLAG_UNLOCKFORUPDATE) res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_UNLOCKED) } } @@ -662,6 +669,8 @@ func (h *Handlers) GetSender(ctx context.Context, sym string, input []byte) (res return res, nil } +// QuickWithBalance retrieves the balance for a given public key from the custodial balance API endpoint before +// gracefully exiting the session. func (h *Handlers) QuitWithBalance(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} From 7b33f2f64439d9d0bd5be53ce833eeacbd9498b6 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Wed, 28 Aug 2024 14:11:20 +0300 Subject: [PATCH 096/201] Initiate a transaction once a valid PIN is provided --- cmd/main.go | 2 ++ internal/handlers/ussd/menuhandler.go | 28 ++++++++++++++++++- services/registration/transaction_initiated | 1 + .../registration/transaction_initiated.vis | 12 ++++++++ .../registration/transaction_initiated_swa | 1 + services/registration/transaction_pin.vis | 4 +++ 6 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 services/registration/transaction_initiated create mode 100644 services/registration/transaction_initiated.vis create mode 100644 services/registration/transaction_initiated_swa diff --git a/cmd/main.go b/cmd/main.go index ad8699c..bd38a3f 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -101,6 +101,7 @@ func main() { rfs.AddLocalFunc("reset_transaction_amount", ussdHandlers.ResetTransactionAmount) rfs.AddLocalFunc("get_recipient", ussdHandlers.GetRecipient) rfs.AddLocalFunc("get_sender", ussdHandlers.GetSender) + rfs.AddLocalFunc("get_amount", ussdHandlers.GetAmount) rfs.AddLocalFunc("reset_incorrect", ussdHandlers.ResetIncorrectPin) rfs.AddLocalFunc("save_firstname", ussdHandlers.SaveFirstname) rfs.AddLocalFunc("save_familyname", ussdHandlers.SaveFamilyname) @@ -115,6 +116,7 @@ func main() { rfs.AddLocalFunc("verify_yob", ussdHandlers.VerifyYob) rfs.AddLocalFunc("reset_incorrect_date_format", ussdHandlers.ResetIncorrectYob) rfs.AddLocalFunc("set_reset_single_edit", ussdHandlers.SetResetSingleEdit) + rfs.AddLocalFunc("initiate_transaction", ussdHandlers.InitiateTransaction) cont, err := en.Init(ctx) en.SetDebugger(engine.NewSimpleDebug(nil)) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 7116df0..8d40c1f 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -494,8 +494,9 @@ func (h *Handlers) TransactionReset(ctx context.Context, sym string, input []byt return res, err } - // reset the recipient + // reset the transaction accountData["Recipient"] = "" + accountData["Amount"] = "" err = h.accountFileHandler.WriteAccountData(accountData) if err != nil { @@ -662,6 +663,21 @@ func (h *Handlers) GetSender(ctx context.Context, sym string, input []byte) (res return res, nil } +// GetAmount retrieves the amount from a JSON data file. +func (h *Handlers) GetAmount(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + + accountData, err := h.accountFileHandler.ReadAccountData() + if err != nil { + return res, err + } + + res.Content = accountData["Amount"] + + return res, nil +} + + func (h *Handlers) QuitWithBalance(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} @@ -677,3 +693,13 @@ func (h *Handlers) QuitWithBalance(ctx context.Context, sym string, input []byte res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_UNLOCKED) return res, nil } + +func (h *Handlers) InitiateTransaction(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + + // TODO + // Use the amount, recipient and sender to call the API and initialize the transaction + + res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_UNLOCKED) + return res, nil +} diff --git a/services/registration/transaction_initiated b/services/registration/transaction_initiated new file mode 100644 index 0000000..2909071 --- /dev/null +++ b/services/registration/transaction_initiated @@ -0,0 +1 @@ +Your request has been sent. {{.get_recipient}} will receive {{.get_amount}} from {{.get_sender}}. \ No newline at end of file diff --git a/services/registration/transaction_initiated.vis b/services/registration/transaction_initiated.vis new file mode 100644 index 0000000..c51a441 --- /dev/null +++ b/services/registration/transaction_initiated.vis @@ -0,0 +1,12 @@ +LOAD reset_incorrect 0 +LOAD get_amount 10 +MAP get_amount +RELOAD get_recipient +MAP get_recipient +RELOAD get_sender +MAP get_sender +LOAD initiate_transaction 0 +RELOAD transaction_reset +MOUT quit 9 +HALT +INCMP quit 9 diff --git a/services/registration/transaction_initiated_swa b/services/registration/transaction_initiated_swa new file mode 100644 index 0000000..fb6125a --- /dev/null +++ b/services/registration/transaction_initiated_swa @@ -0,0 +1 @@ +Ombi lako limetumwa. {{.get_recipient}} atapokea {{.get_amount}} kutoka kwa {{.get_sender}}. \ No newline at end of file diff --git a/services/registration/transaction_pin.vis b/services/registration/transaction_pin.vis index 38347ba..5c10b3f 100644 --- a/services/registration/transaction_pin.vis +++ b/services/registration/transaction_pin.vis @@ -6,5 +6,9 @@ MAP get_sender MOUT back 0 MOUT quit 9 HALT +LOAD unlock_account 1 +RELOAD unlock_account +CATCH incorrect_pin 15 1 INCMP _ 0 INCMP quit 9 +MOVE transaction_initiated From 915333641281183028c4bfdeb6a260a87a8ff3d7 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Wed, 28 Aug 2024 14:14:02 +0300 Subject: [PATCH 097/201] setup additional checks to reset flags --- services/registration/edit_profile.vis | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/services/registration/edit_profile.vis b/services/registration/edit_profile.vis index c4d5f52..d85bbc4 100644 --- a/services/registration/edit_profile.vis +++ b/services/registration/edit_profile.vis @@ -1,4 +1,6 @@ -LOAD reset_unlocked 0 +LOAD reset_unlocked 16 +LOAD reset_unlock_for_update 0 +RELOAD reset_unlock_for_update MOUT edit_name 1 MOUT edit_gender 2 MOUT edit_yob 3 @@ -9,6 +11,7 @@ MOUT back 0 HALT INCMP _ 0 LOAD set_reset_single_edit 0 +RELOAD set_reset_single_edit INCMP enter_name 1 INCMP select_gender 2 INCMP enter_yob 3 From 54bc09b7e917c4a1e54f7cf36d4443f6b4da5d39 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Wed, 28 Aug 2024 14:14:28 +0300 Subject: [PATCH 098/201] initialize testing for menu handlers --- internal/handlers/ussd/menuhandler_test.go | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 internal/handlers/ussd/menuhandler_test.go diff --git a/internal/handlers/ussd/menuhandler_test.go b/internal/handlers/ussd/menuhandler_test.go new file mode 100644 index 0000000..94ef85d --- /dev/null +++ b/internal/handlers/ussd/menuhandler_test.go @@ -0,0 +1,11 @@ +package ussd + +import "testing" + + + + + +func CreateAccountTest(t *testing.T){ + +} \ No newline at end of file From 768535b5403f5317d6644dfb2cf04534f39bb22b Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Wed, 28 Aug 2024 14:54:39 +0300 Subject: [PATCH 099/201] Quit with the transaction confirmation --- internal/handlers/ussd/menuhandler.go | 21 +++++++++++++++++++ services/registration/transaction_initiated | 1 - .../registration/transaction_initiated.vis | 3 --- .../registration/transaction_initiated_swa | 1 - 4 files changed, 21 insertions(+), 5 deletions(-) delete mode 100644 services/registration/transaction_initiated delete mode 100644 services/registration/transaction_initiated_swa diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 894d0f1..81ac382 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -706,9 +706,30 @@ func (h *Handlers) QuitWithBalance(ctx context.Context, sym string, input []byte func (h *Handlers) InitiateTransaction(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} + accountData, err := h.accountFileHandler.ReadAccountData() + if err != nil { + return res, err + } + // TODO // Use the amount, recipient and sender to call the API and initialize the transaction + switch codeFromCtx(ctx) { + case "swa": + res.Content = fmt.Sprintf("Ombi lako limetumwa. %s atapokea %s kutoka kwa %s.", accountData["Recipient"], accountData["Amount"], accountData["PublicKey"]) + default: + res.Content = fmt.Sprintf("Your request has been sent. %s will receive %s from %s.", accountData["Recipient"], accountData["Amount"], accountData["PublicKey"]) + } + + // reset the transaction + accountData["Recipient"] = "" + accountData["Amount"] = "" + + err = h.accountFileHandler.WriteAccountData(accountData) + if err != nil { + return res, err + } + res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_UNLOCKED) return res, nil } diff --git a/services/registration/transaction_initiated b/services/registration/transaction_initiated deleted file mode 100644 index 2909071..0000000 --- a/services/registration/transaction_initiated +++ /dev/null @@ -1 +0,0 @@ -Your request has been sent. {{.get_recipient}} will receive {{.get_amount}} from {{.get_sender}}. \ No newline at end of file diff --git a/services/registration/transaction_initiated.vis b/services/registration/transaction_initiated.vis index c51a441..b1042f5 100644 --- a/services/registration/transaction_initiated.vis +++ b/services/registration/transaction_initiated.vis @@ -6,7 +6,4 @@ MAP get_recipient RELOAD get_sender MAP get_sender LOAD initiate_transaction 0 -RELOAD transaction_reset -MOUT quit 9 HALT -INCMP quit 9 diff --git a/services/registration/transaction_initiated_swa b/services/registration/transaction_initiated_swa deleted file mode 100644 index fb6125a..0000000 --- a/services/registration/transaction_initiated_swa +++ /dev/null @@ -1 +0,0 @@ -Ombi lako limetumwa. {{.get_recipient}} atapokea {{.get_amount}} kutoka kwa {{.get_sender}}. \ No newline at end of file From 9f0ef131981f0aafca02124edd85a4206285e0e1 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Wed, 28 Aug 2024 16:23:52 +0300 Subject: [PATCH 100/201] Added documentation lines on functions --- internal/handlers/ussd/menuhandler.go | 28 ++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 81ac382..e771749 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -37,6 +37,7 @@ func NewHandlers(path string, st *state.State) *Handlers { } } +// SetLanguage sets the language across the menu func (h *Handlers) SetLanguage(ctx context.Context, sym string, input []byte) (resource.Result, error) { inputStr := string(input) res := resource.Result{} @@ -55,6 +56,9 @@ func (h *Handlers) SetLanguage(ctx context.Context, sym string, input []byte) (r return res, nil } +// CreateAccount checks if any account exists on the JSON data file, and if not +// creates an account on the API, +// sets the default values and flags func (h *Handlers) CreateAccount(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} @@ -146,6 +150,9 @@ func (h *Handlers) SetResetSingleEdit(ctx context.Context, sym string, input []b return res, nil } +// VerifyPin checks whether the confirmation PIN is similar to the account PIN +// If similar, it sets the USERFLAG_PIN_SET flag allowing the user +// to access the main menu func (h *Handlers) VerifyPin(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} @@ -165,6 +172,7 @@ func (h *Handlers) VerifyPin(ctx context.Context, sym string, input []byte) (res return res, nil } +// isValidPIN checks whether the given input is a 4 digit number func isValidPIN(pin string) bool { match, _ := regexp.MatchString(`^\d{4}$`, pin) return match @@ -330,6 +338,7 @@ func (h *Handlers) ResetAccountUnlocked(ctx context.Context, sym string, input [ return res, nil } +// CheckIdentifier retrieves the PublicKey from the JSON data file. func (h *Handlers) CheckIdentifier(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} @@ -378,6 +387,8 @@ func (h *Handlers) ResetIncorrectPin(ctx context.Context, sym string, input []by return res, nil } +// CheckAccountStatus queries the API using the TrackingId and sets flags +// based on the account status func (h *Handlers) CheckAccountStatus(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} @@ -411,6 +422,7 @@ func (h *Handlers) CheckAccountStatus(ctx context.Context, sym string, input []b return res, nil } +// Quit displays the Thank you message and exits the menu func (h *Handlers) Quit(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} switch codeFromCtx(ctx) { @@ -423,6 +435,7 @@ func (h *Handlers) Quit(ctx context.Context, sym string, input []byte) (resource return res, nil } +// VerifyYob verifies the length of the given input func (h *Handlers) VerifyYob(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} date := string(input) @@ -448,6 +461,8 @@ func (h *Handlers) ResetIncorrectYob(ctx context.Context, sym string, input []by return res, nil } +// CheckBalance retrieves the balance from the API using the "PublicKey" and sets +// the balance as the result content func (h *Handlers) CheckBalance(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} @@ -465,6 +480,7 @@ func (h *Handlers) CheckBalance(ctx context.Context, sym string, input []byte) ( return res, nil } +// ValidateRecipient validates that the given input is a valid phone number. func (h *Handlers) ValidateRecipient(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} recipient := string(input) @@ -494,6 +510,8 @@ func (h *Handlers) ValidateRecipient(ctx context.Context, sym string, input []by return res, nil } +// TransactionReset resets the previous transaction data (Recipient and Amount) +// as well as the invalid flags func (h *Handlers) TransactionReset(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} accountData, err := h.accountFileHandler.ReadAccountData() @@ -515,6 +533,7 @@ func (h *Handlers) TransactionReset(ctx context.Context, sym string, input []byt return res, nil } +// ResetTransactionAmount resets the transaction amount and invalid flag func (h *Handlers) ResetTransactionAmount(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} accountData, err := h.accountFileHandler.ReadAccountData() @@ -535,6 +554,8 @@ func (h *Handlers) ResetTransactionAmount(ctx context.Context, sym string, input return res, nil } +// MaxAmount gets the current balance from the API and sets it as +// the result content. func (h *Handlers) MaxAmount(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} @@ -553,6 +574,8 @@ func (h *Handlers) MaxAmount(ctx context.Context, sym string, input []byte) (res return res, nil } +// ValidateAmount ensures that the given input is a valid amount and that +// it is not more than the current balance. func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} amountStr := string(input) @@ -610,6 +633,8 @@ func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte) return res, nil } + +// GetRecipient returns the transaction recipient from a JSON data file. func (h *Handlers) GetRecipient(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} @@ -684,7 +709,6 @@ func (h *Handlers) GetAmount(ctx context.Context, sym string, input []byte) (res return res, nil } - // QuickWithBalance retrieves the balance for a given public key from the custodial balance API endpoint before // gracefully exiting the session. func (h *Handlers) QuitWithBalance(ctx context.Context, sym string, input []byte) (resource.Result, error) { @@ -703,6 +727,8 @@ func (h *Handlers) QuitWithBalance(ctx context.Context, sym string, input []byte return res, nil } +// InitiateTransaction returns a confirmation and resets the transaction data +// on the JSON file. func (h *Handlers) InitiateTransaction(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} From 16f00bcf0912a4577f71746b935817dd8c4be969 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Wed, 28 Aug 2024 18:13:49 +0300 Subject: [PATCH 101/201] use getText for external functions translation --- internal/handlers/ussd/menuhandler.go | 20 ++++++++++++++------ services/registration/locale/swa/default.po | 3 +++ 2 files changed, 17 insertions(+), 6 deletions(-) create mode 100644 services/registration/locale/swa/default.po diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 894d0f1..5c5d4a5 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "fmt" + "path" "regexp" "strconv" "strings" @@ -15,6 +16,12 @@ import ( "git.grassecon.net/urdt/ussd/internal/handlers/server" "git.grassecon.net/urdt/ussd/internal/models" "git.grassecon.net/urdt/ussd/internal/utils" + "gopkg.in/leonelquinteros/gotext.v1" +) + +var ( + scriptDir = path.Join( "services", "registration") + translationDir = path.Join(scriptDir, "locale") ) type FSData struct { @@ -126,11 +133,9 @@ func (h *Handlers) SavePin(ctx context.Context, sym string, input []byte) (resou func (h *Handlers) SetResetSingleEdit(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - menuOPtion := string(input) - - switch menuOPtion { + menuOption := string(input) + switch menuOption { case "2": - fmt.Println("Resetting unlock for update") res.FlagReset = append(res.FlagSet, models.USERFLAG_UNLOCKFORUPDATE) res.FlagSet = append(res.FlagSet, models.USERFLAG_SINGLE_EDIT) case "3": @@ -685,11 +690,14 @@ func (h *Handlers) GetAmount(ctx context.Context, sym string, input []byte) (res } + // QuickWithBalance retrieves the balance for a given public key from the custodial balance API endpoint before // gracefully exiting the session. func (h *Handlers) QuitWithBalance(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - + code := codeFromCtx(ctx) + l := gotext.NewLocale(translationDir, code) + l.AddDomain("default") accountData, err := h.accountFileHandler.ReadAccountData() if err != nil { return res, err @@ -698,7 +706,7 @@ func (h *Handlers) QuitWithBalance(ctx context.Context, sym string, input []byte if err != nil { return res, nil } - res.Content = fmt.Sprintf("Your account balance is: %s", balance) + res.Content = l.Get("Your account balance is %s", balance) res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_UNLOCKED) return res, nil } diff --git a/services/registration/locale/swa/default.po b/services/registration/locale/swa/default.po new file mode 100644 index 0000000..2c59406 --- /dev/null +++ b/services/registration/locale/swa/default.po @@ -0,0 +1,3 @@ +msgid "Your account balance is %s" +msgstr "Salio lako ni %s" + From 3fdd702e936216ecc56ec297c3252a71dba814aa Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Wed, 28 Aug 2024 18:26:41 +0300 Subject: [PATCH 102/201] Use getText for the language switch --- internal/handlers/ussd/menuhandler.go | 10 ++++------ services/registration/locale/swa/default.po | 2 ++ 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index e038a49..0cd635f 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -739,6 +739,9 @@ func (h *Handlers) QuitWithBalance(ctx context.Context, sym string, input []byte // on the JSON file. func (h *Handlers) InitiateTransaction(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} + code := codeFromCtx(ctx) + l := gotext.NewLocale(translationDir, code) + l.AddDomain("default") accountData, err := h.accountFileHandler.ReadAccountData() if err != nil { @@ -748,12 +751,7 @@ func (h *Handlers) InitiateTransaction(ctx context.Context, sym string, input [] // TODO // Use the amount, recipient and sender to call the API and initialize the transaction - switch codeFromCtx(ctx) { - case "swa": - res.Content = fmt.Sprintf("Ombi lako limetumwa. %s atapokea %s kutoka kwa %s.", accountData["Recipient"], accountData["Amount"], accountData["PublicKey"]) - default: - res.Content = fmt.Sprintf("Your request has been sent. %s will receive %s from %s.", accountData["Recipient"], accountData["Amount"], accountData["PublicKey"]) - } + res.Content = l.Get("Your request has been sent. %s will receive %s from %s.", accountData["Recipient"], accountData["Amount"], accountData["PublicKey"]) // reset the transaction accountData["Recipient"] = "" diff --git a/services/registration/locale/swa/default.po b/services/registration/locale/swa/default.po index 2c59406..12f6e6c 100644 --- a/services/registration/locale/swa/default.po +++ b/services/registration/locale/swa/default.po @@ -1,3 +1,5 @@ msgid "Your account balance is %s" msgstr "Salio lako ni %s" +msgid "Your request has been sent. %s will receive %s from %s." +msgstr "Ombi lako limetumwa. %s atapokea %s kutoka kwa %s." From b344720fdc11a17a08dfe9bbda7b8d275b36834c Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Wed, 28 Aug 2024 21:01:25 +0300 Subject: [PATCH 103/201] add documentation lines --- internal/handlers/ussd/menuhandler.go | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 0cd635f..115185f 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -135,6 +135,7 @@ func (h *Handlers) SavePin(ctx context.Context, sym string, input []byte) (resou return res, nil } +//SetResetSingleEdit sets and resets flags to allow gradual editing of profile information. func (h *Handlers) SetResetSingleEdit(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} menuOption := string(input) @@ -183,6 +184,8 @@ func isValidPIN(pin string) bool { return match } + +//codeFromCtx retrieves language codes from the context that can be used for handling translations func codeFromCtx(ctx context.Context) string { var code string engine.Logg.DebugCtxf(ctx, "in msg", "ctx", ctx, "val", code) @@ -331,12 +334,14 @@ func (h *Handlers) SaveOfferings(ctx context.Context, sym string, input []byte) return res, nil } +//ResetUnlockForUpdate resets the unlockforupdate flag to correctly show appropriate nodes as a user provides the profile data. func (h *Handlers) ResetUnlockForUpdate(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} res.FlagReset = append(res.FlagReset, models.USERFLAG_UNLOCKFORUPDATE) return res, nil } +//ResetAccountUnlocked locks an account that had already been unlocked. func (h *Handlers) ResetAccountUnlocked(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_UNLOCKED) @@ -386,6 +391,7 @@ func (h *Handlers) Unlock(ctx context.Context, sym string, input []byte) (resour return res, nil } +//ResetIncorrectPin resets the incorrect pin flag after a new PIN attempt. func (h *Handlers) ResetIncorrectPin(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} res.FlagReset = append(res.FlagReset, models.USERFLAG_INCORRECTPIN) @@ -460,6 +466,7 @@ func (h *Handlers) VerifyYob(ctx context.Context, sym string, input []byte) (res return res, nil } +//ResetIncorrectYob resets the incorrect date format after a new attempt func (h *Handlers) ResetIncorrectYob(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} res.FlagReset = append(res.FlagReset, models.USERFLAG_INCORRECTDATEFORMAT) From 802c3f92df3a3310f8878dc710d6f29cf1c86a3a Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Thu, 29 Aug 2024 19:24:43 +0300 Subject: [PATCH 104/201] Added tests for CreateAccount and SavePin --- internal/handlers/ussd/menuhandler.go | 15 +- internal/handlers/ussd/menuhandler_test.go | 278 ++++++++++++++++++++- 2 files changed, 288 insertions(+), 5 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 115185f..ac2edf4 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -29,9 +29,21 @@ type FSData struct { St *state.State } +type AccountCreator interface { + CreateAccount() (*models.AccountResponse, error) +} + +// ServerAccountCreator implements AccountCreator using the server package +type ServerAccountCreator struct{} + +func (s *ServerAccountCreator) CreateAccount() (*models.AccountResponse, error) { + return server.CreateAccount() +} + type Handlers struct { fs *FSData accountFileHandler *utils.AccountFileHandler + accountCreator AccountCreator } func NewHandlers(path string, st *state.State) *Handlers { @@ -41,6 +53,7 @@ func NewHandlers(path string, st *state.State) *Handlers { St: st, }, accountFileHandler: utils.NewAccountFileHandler(path + "_data"), + accountCreator: &ServerAccountCreator{}, } } @@ -81,7 +94,7 @@ func (h *Handlers) CreateAccount(ctx context.Context, sym string, input []byte) return res, err } - accountResp, err := server.CreateAccount() + accountResp, err := h.accountCreator.CreateAccount() if err != nil { res.FlagSet = append(res.FlagSet, models.USERFLAG_ACCOUNT_CREATION_FAILED) return res, err diff --git a/internal/handlers/ussd/menuhandler_test.go b/internal/handlers/ussd/menuhandler_test.go index 94ef85d..1b22411 100644 --- a/internal/handlers/ussd/menuhandler_test.go +++ b/internal/handlers/ussd/menuhandler_test.go @@ -1,11 +1,281 @@ package ussd -import "testing" +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "testing" + "git.defalsify.org/vise.git/resource" + "git.grassecon.net/urdt/ussd/internal/models" + "git.grassecon.net/urdt/ussd/internal/utils" +) +// MockAccountCreator implements AccountCreator for testing +type MockAccountCreator struct { + mockResponse *models.AccountResponse + mockError error +} +func (m *MockAccountCreator) CreateAccount() (*models.AccountResponse, error) { + return m.mockResponse, m.mockError +} +func TestCreateAccount(t *testing.T) { + // Setup + tempDir, err := os.MkdirTemp("", "test_create_account") + if err != nil { + t.Fatalf("Failed to create temp directory: %v", err) + } + defer os.RemoveAll(tempDir) // Clean up after the test run -func CreateAccountTest(t *testing.T){ - -} \ No newline at end of file + sessionID := "07xxxxxxxx" + + // Set up the data file path using the session ID + accountFilePath := filepath.Join(tempDir, sessionID+"_data") + + // Initialize account file handler + accountFileHandler := utils.NewAccountFileHandler(accountFilePath) + + // Create a mock account creator + mockAccountCreator := &MockAccountCreator{ + mockResponse: &models.AccountResponse{ + Ok: true, + Result: struct { + CustodialId json.Number `json:"custodialId"` + PublicKey string `json:"publicKey"` + TrackingId string `json:"trackingId"` + }{ + CustodialId: "test-custodial-id", + PublicKey: "test-public-key", + TrackingId: "test-tracking-id", + }, + }, + } + + // Initialize Handlers with mock account creator + h := &Handlers{ + accountFileHandler: accountFileHandler, + accountCreator: mockAccountCreator, + } + + tests := []struct { + name string + existingData map[string]string + expectedResult resource.Result + expectedData map[string]string + }{ + { + name: "New account creation", + existingData: nil, + expectedResult: resource.Result{ + FlagSet: []uint32{models.USERFLAG_ACCOUNT_CREATED}, + }, + expectedData: map[string]string{ + "TrackingId": "test-tracking-id", + "PublicKey": "test-public-key", + "CustodialId": "test-custodial-id", + "Status": "PENDING", + "Gender": "Not provided", + "YOB": "Not provided", + "Location": "Not provided", + "Offerings": "Not provided", + "FirstName": "Not provided", + "FamilyName": "Not provided", + }, + }, + { + name: "Existing account", + existingData: map[string]string{ + "TrackingId": "test-tracking-id", + "PublicKey": "test-public-key", + "CustodialId": "test-custodial-id", + "Status": "PENDING", + "Gender": "Not provided", + "YOB": "Not provided", + "Location": "Not provided", + "Offerings": "Not provided", + "FirstName": "Not provided", + "FamilyName": "Not provided", + }, + expectedResult: resource.Result{ + FlagSet: []uint32{models.USERFLAG_ACCOUNT_CREATED}, + }, + expectedData: map[string]string{ + "TrackingId": "test-tracking-id", + "PublicKey": "test-public-key", + "CustodialId": "test-custodial-id", + "Status": "PENDING", + "Gender": "Not provided", + "YOB": "Not provided", + "Location": "Not provided", + "Offerings": "Not provided", + "FirstName": "Not provided", + "FamilyName": "Not provided", + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Set up the data file path using the session ID + accountFilePath := filepath.Join(tempDir, sessionID+"_data") + + // Setup existing data if any + if tt.existingData != nil { + data, _ := json.Marshal(tt.existingData) + err := os.WriteFile(accountFilePath, data, 0644) + if err != nil { + t.Fatalf("Failed to write existing data: %v", err) + } + } + + // Call the function + result, err := h.CreateAccount(context.Background(), "", nil) + + // Check for errors + if err != nil { + t.Fatalf("CreateAccount returned an error: %v", err) + } + + // Check the result + if len(result.FlagSet) != len(tt.expectedResult.FlagSet) { + t.Errorf("Expected %d flags, got %d", len(tt.expectedResult.FlagSet), len(result.FlagSet)) + } + for i, flag := range tt.expectedResult.FlagSet { + if result.FlagSet[i] != flag { + t.Errorf("Expected flag %d, got %d", flag, result.FlagSet[i]) + } + } + + // Check the stored data + data, err := os.ReadFile(accountFilePath) + if err != nil { + t.Fatalf("Failed to read account data file: %v", err) + } + + var storedData map[string]string + err = json.Unmarshal(data, &storedData) + if err != nil { + t.Fatalf("Failed to unmarshal stored data: %v", err) + } + + for key, expectedValue := range tt.expectedData { + if storedValue, ok := storedData[key]; !ok || storedValue != expectedValue { + t.Errorf("Expected %s to be %s, got %s", key, expectedValue, storedValue) + } + } + }) + } +} + +func TestSavePin(t *testing.T) { + // Setup + tempDir, err := os.MkdirTemp("", "test_save_pin") + if err != nil { + t.Fatalf("Failed to create temp directory: %v", err) + } + defer os.RemoveAll(tempDir) + + sessionID := "07xxxxxxxx" + + // Set up the data file path using the session ID + accountFilePath := filepath.Join(tempDir, sessionID+"_data") + initialAccountData := map[string]string{ + "TrackingId": "test-tracking-id", + "PublicKey": "test-public-key", + } + data, _ := json.Marshal(initialAccountData) + err = os.WriteFile(accountFilePath, data, 0644) + if err != nil { + t.Fatalf("Failed to write initial account data: %v", err) + } + + // Create a new AccountFileHandler and set it in the Handlers struct + accountFileHandler := utils.NewAccountFileHandler(accountFilePath) + h := &Handlers{ + accountFileHandler: accountFileHandler, + } + + tests := []struct { + name string + input []byte + expectedFlags []uint32 + expectedData map[string]string + expectedErrors bool + }{ + { + name: "Valid PIN", + input: []byte("1234"), + expectedFlags: []uint32{}, + expectedData: map[string]string{ + "TrackingId": "test-tracking-id", + "PublicKey": "test-public-key", + "AccountPIN": "1234", + }, + }, + { + name: "Invalid PIN - non-numeric", + input: []byte("12ab"), + expectedFlags: []uint32{models.USERFLAG_INCORRECTPIN}, + expectedData: initialAccountData, // No changes expected + expectedErrors: false, + }, + { + name: "Invalid PIN - less than 4 digits", + input: []byte("123"), + expectedFlags: []uint32{models.USERFLAG_INCORRECTPIN}, + expectedData: initialAccountData, // No changes expected + expectedErrors: false, + }, + { + name: "Invalid PIN - more than 4 digits", + input: []byte("12345"), + expectedFlags: []uint32{models.USERFLAG_INCORRECTPIN}, + expectedData: initialAccountData, // No changes expected + expectedErrors: false, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Ensure the file exists before running the test + err := accountFileHandler.EnsureFileExists() + if err != nil { + t.Fatalf("Failed to ensure account file exists: %v", err) + } + + result, err := h.SavePin(context.Background(), "", tt.input) + if err != nil && !tt.expectedErrors { + t.Fatalf("SavePin returned an unexpected error: %v", err) + } + + if len(result.FlagSet) != len(tt.expectedFlags) { + t.Errorf("Expected %d flags, got %d", len(tt.expectedFlags), len(result.FlagSet)) + } + for i, flag := range tt.expectedFlags { + if result.FlagSet[i] != flag { + t.Errorf("Expected flag %d, got %d", flag, result.FlagSet[i]) + } + } + + data, err := os.ReadFile(accountFilePath) + if err != nil { + t.Fatalf("Failed to read account data file: %v", err) + } + + var storedData map[string]string + err = json.Unmarshal(data, &storedData) + if err != nil { + t.Fatalf("Failed to unmarshal stored data: %v", err) + } + + for key, expectedValue := range tt.expectedData { + if storedValue, ok := storedData[key]; !ok || storedValue != expectedValue { + t.Errorf("Expected %s to be %s, got %s", key, expectedValue, storedValue) + } + } + }) + } +} From 195f003d69016ad65e62a23d78d4a632cca9ba5a Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Thu, 29 Aug 2024 19:53:55 +0300 Subject: [PATCH 105/201] create mocks --- internal/handlers/ussd/mocks/mocks.go | 44 +++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 internal/handlers/ussd/mocks/mocks.go diff --git a/internal/handlers/ussd/mocks/mocks.go b/internal/handlers/ussd/mocks/mocks.go new file mode 100644 index 0000000..3c7eb1e --- /dev/null +++ b/internal/handlers/ussd/mocks/mocks.go @@ -0,0 +1,44 @@ +package mocks + +import ( + "git.grassecon.net/urdt/ussd/internal/models" + "github.com/stretchr/testify/mock" +) + +type MockAccountFileHandler struct { + mock.Mock +} + +func (m *MockAccountFileHandler) EnsureFileExists() error { + args := m.Called() + return args.Error(0) +} + +func (m *MockAccountFileHandler) ReadAccountData() (map[string]string, error) { + args := m.Called() + return args.Get(0).(map[string]string), args.Error(1) +} + +func (m *MockAccountFileHandler) WriteAccountData(data map[string]string) error { + args := m.Called(data) + return args.Error(0) +} + +type MockAccountService struct { + mock.Mock +} + +func (m *MockAccountService) CreateAccount() (*models.AccountResponse, error) { + args := m.Called() + return args.Get(0).(*models.AccountResponse), args.Error(1) +} + +func (m *MockAccountService) CheckAccountStatus(TrackingId string) (string, error) { + args := m.Called() + return args.Get(0).(string), args.Error(1) +} + +func (m *MockAccountService) CheckBalance(PublicKey string) (string, error) { + args := m.Called() + return args.Get(0).(string), args.Error(1) +} From a64291bb3131a72488227560153a62c16fe953e2 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Thu, 29 Aug 2024 19:54:26 +0300 Subject: [PATCH 106/201] setup test for successful account creation --- internal/handlers/ussd/menuhandler_test.go | 48 ++++++++++++++++++++-- 1 file changed, 45 insertions(+), 3 deletions(-) diff --git a/internal/handlers/ussd/menuhandler_test.go b/internal/handlers/ussd/menuhandler_test.go index 94ef85d..98b8dc4 100644 --- a/internal/handlers/ussd/menuhandler_test.go +++ b/internal/handlers/ussd/menuhandler_test.go @@ -1,11 +1,53 @@ package ussd -import "testing" +import ( + "encoding/json" + "testing" + "git.grassecon.net/urdt/ussd/internal/handlers/ussd/mocks" + "git.grassecon.net/urdt/ussd/internal/models" + "github.com/alecthomas/assert/v2" + "github.com/stretchr/testify/mock" +) +func TestCreateAccount_Success(t *testing.T) { + mockAccountFileHandler := new(mocks.MockAccountFileHandler) + mockCreateAccountService := new(mocks.MockAccountService) + mockAccountFileHandler.On("EnsureFileExists").Return(nil) + // Mock that no account data exists + mockAccountFileHandler.On("ReadAccountData").Return(nil, nil) + + // Define expected account response after api call + expectedAccountResp := &models.AccountResponse{ + Ok: true, + Result: struct { + CustodialId json.Number `json:"custodialId"` + PublicKey string `json:"publicKey"` + TrackingId string `json:"trackingId"` + }{ + CustodialId: "12", + PublicKey: "some-public-key", + TrackingId: "some-tracking-id", + }, + } + mockCreateAccountService.On("CreateAccount").Return(expectedAccountResp, nil) + + // Mock WriteAccountData to not error + mockAccountFileHandler.On("WriteAccountData", mock.Anything).Return(nil) + + handlers := &Handlers{ + accountService: mockCreateAccountService, + } -func CreateAccountTest(t *testing.T){ -} \ No newline at end of file + actualResponse, err := handlers.accountService.CreateAccount() + + // Assert results + assert.NoError(t, err) + assert.Equal(t,expectedAccountResp.Ok,true) + assert.Equal(t,expectedAccountResp,actualResponse) + + +} From 7b5d82c7bfc7f5d563ec1b4cd242d558ab4a81aa Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Thu, 29 Aug 2024 19:55:08 +0300 Subject: [PATCH 107/201] setup service for handling account activities --- internal/handlers/server/accountservice.go | 86 ++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 internal/handlers/server/accountservice.go diff --git a/internal/handlers/server/accountservice.go b/internal/handlers/server/accountservice.go new file mode 100644 index 0000000..791f2e7 --- /dev/null +++ b/internal/handlers/server/accountservice.go @@ -0,0 +1,86 @@ +package server + +import ( + "encoding/json" + "io" + "net/http" + + "git.grassecon.net/urdt/ussd/config" + "git.grassecon.net/urdt/ussd/internal/models" +) + +type AccountServiceInterface interface { + CheckBalance(publicKey string) (string, error) + CreateAccount() (*models.AccountResponse, error) + CheckAccountStatus(trackingId string) (string, error) +} + +type AccountService struct { +} + +func (as *AccountService) CheckAccountStatus(trackingId string) (string, error) { + resp, err := http.Get(config.TrackStatusURL + trackingId) + if err != nil { + return "", err + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return "", err + } + + var trackResp models.TrackStatusResponse + err = json.Unmarshal(body, &trackResp) + if err != nil { + return "", err + } + + status := trackResp.Result.Transaction.Status + + return status, nil +} + +func (as *AccountService) CheckBalance(publicKey string) (string, error) { + + resp, err := http.Get(config.BalanceURL + publicKey) + if err != nil { + return "0.0", err + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return "0.0", err + } + + var balanceResp models.BalanceResponse + err = json.Unmarshal(body, &balanceResp) + if err != nil { + return "0.0", err + } + + balance := balanceResp.Result.Balance + return balance, nil +} + +func (as *AccountService) CreateAccount() (*models.AccountResponse, error) { + resp, err := http.Post(config.CreateAccountURL, "application/json", nil) + if err != nil { + return nil, err + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, err + } + + var accountResp models.AccountResponse + err = json.Unmarshal(body, &accountResp) + if err != nil { + return nil, err + } + + return &accountResp, nil +} From 08fcb7cdba7f180c8b37f47f7fdf755ddc457aac Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Thu, 29 Aug 2024 19:56:25 +0300 Subject: [PATCH 108/201] use interfaces for the handler --- internal/handlers/ussd/menuhandler.go | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 115185f..42acd90 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -31,7 +31,9 @@ type FSData struct { type Handlers struct { fs *FSData - accountFileHandler *utils.AccountFileHandler + //accountFileHandler *utils.AccountFileHandler + accountFileHandler utils.AccountFileHandlerInterface + accountService server.AccountServiceInterface } func NewHandlers(path string, st *state.State) *Handlers { @@ -41,6 +43,7 @@ func NewHandlers(path string, st *state.State) *Handlers { St: st, }, accountFileHandler: utils.NewAccountFileHandler(path + "_data"), + accountService: &server.AccountService{}, } } @@ -81,7 +84,7 @@ func (h *Handlers) CreateAccount(ctx context.Context, sym string, input []byte) return res, err } - accountResp, err := server.CreateAccount() + accountResp, err := h.accountService.CreateAccount() if err != nil { res.FlagSet = append(res.FlagSet, models.USERFLAG_ACCOUNT_CREATION_FAILED) return res, err From 20cf7bdb443c4146edf78bda9f8878287407a679 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Thu, 29 Aug 2024 19:56:50 +0300 Subject: [PATCH 109/201] setup interface for file operations --- internal/utils/filehandler.go | 50 +++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 internal/utils/filehandler.go diff --git a/internal/utils/filehandler.go b/internal/utils/filehandler.go new file mode 100644 index 0000000..9b768fd --- /dev/null +++ b/internal/utils/filehandler.go @@ -0,0 +1,50 @@ +package utils + +import ( + "encoding/json" + "os" +) + + +type AccountFileHandlerInterface interface { + EnsureFileExists() error + ReadAccountData() (map[string]string, error) + WriteAccountData(data map[string]string) error +} + + + +type AccountFileHandler2 struct { + FilePath string +} + +// Implement the methods required by AccountFileHandlerInterface. +func (afh *AccountFileHandler2) EnsureFileExists() error { + f, err := os.OpenFile(afh.FilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) + if err != nil { + return err + } + return f.Close() +} +func (afh *AccountFileHandler2) ReadAccountData() (map[string]string, error) { + jsonData, err := os.ReadFile(afh.FilePath) + if err != nil { + return nil, err + } + + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return nil, err + } + + return accountData, nil +} +func (afh *AccountFileHandler2) WriteAccountData(data map[string]string) error { + jsonData, err := json.Marshal(data) + if err != nil { + return err + } + + return os.WriteFile(afh.FilePath, jsonData, 0644) +} \ No newline at end of file From a1f31efd191dfd7f403dedca38748867138bee1c Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Thu, 29 Aug 2024 19:57:07 +0300 Subject: [PATCH 110/201] add testify --- go.mod | 2 ++ go.sum | 2 ++ 2 files changed, 4 insertions(+) create mode 100644 go.sum diff --git a/go.mod b/go.mod index 8358c8c..de33912 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,5 @@ module git.grassecon.net/urdt/ussd go 1.22.6 + +require github.com/stretchr/testify v1.9.0 // indirect diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..f203383 --- /dev/null +++ b/go.sum @@ -0,0 +1,2 @@ +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= From 22d076ea50bace140191d49cedb9239658182cd7 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Thu, 29 Aug 2024 20:07:50 +0300 Subject: [PATCH 111/201] setup test for successful account creation --- internal/handlers/ussd/menuhandler_test.go | 48 ++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/internal/handlers/ussd/menuhandler_test.go b/internal/handlers/ussd/menuhandler_test.go index 1b22411..8fd3dbe 100644 --- a/internal/handlers/ussd/menuhandler_test.go +++ b/internal/handlers/ussd/menuhandler_test.go @@ -8,8 +8,11 @@ import ( "testing" "git.defalsify.org/vise.git/resource" + "git.grassecon.net/urdt/ussd/internal/handlers/ussd/mocks" "git.grassecon.net/urdt/ussd/internal/models" "git.grassecon.net/urdt/ussd/internal/utils" + "github.com/alecthomas/assert/v2" + "github.com/stretchr/testify/mock" ) // MockAccountCreator implements AccountCreator for testing @@ -170,6 +173,51 @@ func TestCreateAccount(t *testing.T) { } } + + +func TestCreateAccount_Success(t *testing.T) { + mockAccountFileHandler := new(mocks.MockAccountFileHandler) + mockCreateAccountService := new(mocks.MockAccountService) + + mockAccountFileHandler.On("EnsureFileExists").Return(nil) + + // Mock that no account data exists + mockAccountFileHandler.On("ReadAccountData").Return(nil, nil) + + // Define expected account response after api call + expectedAccountResp := &models.AccountResponse{ + Ok: true, + Result: struct { + CustodialId json.Number `json:"custodialId"` + PublicKey string `json:"publicKey"` + TrackingId string `json:"trackingId"` + }{ + CustodialId: "12", + PublicKey: "some-public-key", + TrackingId: "some-tracking-id", + }, + } + mockCreateAccountService.On("CreateAccount").Return(expectedAccountResp, nil) + + // Mock WriteAccountData to not error + mockAccountFileHandler.On("WriteAccountData", mock.Anything).Return(nil) + + handlers := &Handlers{ + accountService: mockCreateAccountService, + } + + + actualResponse, err := handlers.accountService.CreateAccount() + + // Assert results + assert.NoError(t, err) + assert.Equal(t,expectedAccountResp.Ok,true) + assert.Equal(t,expectedAccountResp,actualResponse) + + +} + + func TestSavePin(t *testing.T) { // Setup tempDir, err := os.MkdirTemp("", "test_save_pin") From 64e182fd44f204dc8ee5104d9427ea2bbb458821 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Thu, 29 Aug 2024 20:08:36 +0300 Subject: [PATCH 112/201] use interfaces for handlers --- internal/handlers/ussd/menuhandler.go | 1 - 1 file changed, 1 deletion(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index a70a033..5b53b73 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -42,7 +42,6 @@ func (s *ServerAccountCreator) CreateAccount() (*models.AccountResponse, error) type Handlers struct { fs *FSData - //accountFileHandler *utils.AccountFileHandler accountCreator AccountCreator accountFileHandler utils.AccountFileHandlerInterface accountService server.AccountServiceInterface From 3da2949d38a77067f525115c6e368951e59b9553 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Thu, 29 Aug 2024 20:17:38 +0300 Subject: [PATCH 113/201] use fake fields for the response --- internal/handlers/ussd/menuhandler_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/handlers/ussd/menuhandler_test.go b/internal/handlers/ussd/menuhandler_test.go index 8fd3dbe..6fbd27f 100644 --- a/internal/handlers/ussd/menuhandler_test.go +++ b/internal/handlers/ussd/menuhandler_test.go @@ -193,8 +193,8 @@ func TestCreateAccount_Success(t *testing.T) { TrackingId string `json:"trackingId"` }{ CustodialId: "12", - PublicKey: "some-public-key", - TrackingId: "some-tracking-id", + PublicKey: "0x8E0XSCSVA", + TrackingId: "d95a7e83-196c-4fd0-866fSGAGA", }, } mockCreateAccountService.On("CreateAccount").Return(expectedAccountResp, nil) From 1a7c992e5b89bdb1fef02fd2187dc9fec6f3217f Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Thu, 29 Aug 2024 22:54:52 +0300 Subject: [PATCH 114/201] Return without setting the flag that's already set --- internal/handlers/ussd/menuhandler.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 5b53b73..7dbdec8 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -89,10 +89,9 @@ func (h *Handlers) CreateAccount(ctx context.Context, sym string, input []byte) return res, err } - // if an account exists, set the flag and return + // if an account exists, return to prevent duplicate account creation existingAccountData, err := h.accountFileHandler.ReadAccountData() if existingAccountData != nil { - res.FlagSet = append(res.FlagSet, models.USERFLAG_ACCOUNT_CREATED) return res, err } From 75ca39b01298446c46061b51a7de5c58b2db581f Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Thu, 29 Aug 2024 22:57:19 +0300 Subject: [PATCH 115/201] Define the regex pattern as a constant --- internal/handlers/ussd/menuhandler.go | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 7dbdec8..d4cd430 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -59,6 +59,15 @@ func NewHandlers(path string, st *state.State) *Handlers { } } +// Define the regex pattern as a constant +const pinPattern = `^\d{4}$` + +// isValidPIN checks whether the given input is a 4 digit number +func isValidPIN(pin string) bool { + match, _ := regexp.MatchString(pinPattern, pin) + return match +} + // SetLanguage sets the language across the menu func (h *Handlers) SetLanguage(ctx context.Context, sym string, input []byte) (resource.Result, error) { inputStr := string(input) @@ -192,13 +201,6 @@ func (h *Handlers) VerifyPin(ctx context.Context, sym string, input []byte) (res return res, nil } -// isValidPIN checks whether the given input is a 4 digit number -func isValidPIN(pin string) bool { - match, _ := regexp.MatchString(`^\d{4}$`, pin) - return match -} - - //codeFromCtx retrieves language codes from the context that can be used for handling translations func codeFromCtx(ctx context.Context) string { var code string From ca86ef15073f10c91386f3b0587b240671c7d9b3 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Thu, 29 Aug 2024 23:05:41 +0300 Subject: [PATCH 116/201] Use gettext for the Quit function --- internal/handlers/ussd/menuhandler.go | 12 ++++++------ services/registration/locale/swa/default.po | 3 +++ 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index d4cd430..87447e7 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -452,12 +452,12 @@ func (h *Handlers) CheckAccountStatus(ctx context.Context, sym string, input []b // Quit displays the Thank you message and exits the menu func (h *Handlers) Quit(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - switch codeFromCtx(ctx) { - case "swa": - res.Content = "Asante kwa kutumia huduma ya Sarafu. Kwaheri!" - default: - res.Content = "Thank you for using Sarafu. Goodbye!" - } + + code := codeFromCtx(ctx) + l := gotext.NewLocale(translationDir, code) + l.AddDomain("default") + + res.Content = l.Get("Thank you for using Sarafu. Goodbye!") res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_UNLOCKED) return res, nil } diff --git a/services/registration/locale/swa/default.po b/services/registration/locale/swa/default.po index 12f6e6c..0a63d07 100644 --- a/services/registration/locale/swa/default.po +++ b/services/registration/locale/swa/default.po @@ -3,3 +3,6 @@ msgstr "Salio lako ni %s" msgid "Your request has been sent. %s will receive %s from %s." msgstr "Ombi lako limetumwa. %s atapokea %s kutoka kwa %s." + +msgid "Thank you for using Sarafu. Goodbye!" +msgstr "Asante kwa kutumia huduma ya Sarafu. Kwaheri!" From 43bca6bddf04bda2f892aef1a0fdb833777f2030 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Thu, 29 Aug 2024 23:13:38 +0300 Subject: [PATCH 117/201] use unspecified menu option --- services/registration/other_gender_menu | 1 - services/registration/other_gender_menu_swa | 1 - services/registration/select_gender.vis | 2 +- services/registration/unspecified_menu_swa | 1 + 4 files changed, 2 insertions(+), 3 deletions(-) delete mode 100644 services/registration/other_gender_menu delete mode 100644 services/registration/other_gender_menu_swa create mode 100644 services/registration/unspecified_menu_swa diff --git a/services/registration/other_gender_menu b/services/registration/other_gender_menu deleted file mode 100644 index 2212621..0000000 --- a/services/registration/other_gender_menu +++ /dev/null @@ -1 +0,0 @@ -Other \ No newline at end of file diff --git a/services/registration/other_gender_menu_swa b/services/registration/other_gender_menu_swa deleted file mode 100644 index 28ac5ec..0000000 --- a/services/registration/other_gender_menu_swa +++ /dev/null @@ -1 +0,0 @@ -Nyingineo \ No newline at end of file diff --git a/services/registration/select_gender.vis b/services/registration/select_gender.vis index 210a0fe..3029406 100644 --- a/services/registration/select_gender.vis +++ b/services/registration/select_gender.vis @@ -2,7 +2,7 @@ LOAD save_familyname 0 CATCH update_success 16 1 MOUT male 1 MOUT female 2 -MOUT other_gender 3 +MOUT unspecified 3 MOUT back 0 HALT LOAD save_gender 0 diff --git a/services/registration/unspecified_menu_swa b/services/registration/unspecified_menu_swa new file mode 100644 index 0000000..009301f --- /dev/null +++ b/services/registration/unspecified_menu_swa @@ -0,0 +1 @@ +Haijabainishwa \ No newline at end of file From 09c3c012da70462e19ead76cbb76938288d40576 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Thu, 29 Aug 2024 23:14:36 +0300 Subject: [PATCH 118/201] rename flags --- internal/models/flags.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/models/flags.go b/internal/models/flags.go index 5de16cd..ba6d617 100644 --- a/internal/models/flags.go +++ b/internal/models/flags.go @@ -7,11 +7,11 @@ const ( USERFLAG_ACCOUNT_CREATED USERFLAG_ACCOUNT_PENDING USERFLAG_ACCOUNT_SUCCESS - USERFLAG_ACCOUNT_UNLOCKED + USERFLAG_ACCOUNT_AUTHORIZED USERFLAG_INVALID_RECIPIENT USERFLAG_INVALID_RECIPIENT_WITH_INVITE USERFLAG_INCORRECTPIN - USERFLAG_UNLOCKFORUPDATE + USERFLAG_ALLOW_UPDATE USERFLAG_INVALID_AMOUNT USERFLAG_PIN_SET USERFLAG_VALIDPIN From 7229241df5afe02d3b48a1bae3a47591789c4c2d Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Thu, 29 Aug 2024 23:15:07 +0300 Subject: [PATCH 119/201] add unspecified menu option --- services/registration/unspecified_menu | 1 + 1 file changed, 1 insertion(+) create mode 100644 services/registration/unspecified_menu diff --git a/services/registration/unspecified_menu b/services/registration/unspecified_menu new file mode 100644 index 0000000..0e1d0c3 --- /dev/null +++ b/services/registration/unspecified_menu @@ -0,0 +1 @@ +Unspecified From 23680846b42a25b9c33da18895b7d9161ba9b1b4 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Thu, 29 Aug 2024 23:15:58 +0300 Subject: [PATCH 120/201] rename unlock flags --- cmd/main.go | 8 ++-- internal/handlers/ussd/menuhandler.go | 64 +++++++++++++-------------- 2 files changed, 35 insertions(+), 37 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index bd38a3f..4c67a32 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -46,7 +46,7 @@ func main() { state.FlagDebugger.Register(models.USERFLAG_PIN_SET, "PIN_SET") state.FlagDebugger.Register(models.USERFLAG_INVALID_RECIPIENT_WITH_INVITE, "INVALIDRECIPIENT_WITH_INVITE") state.FlagDebugger.Register(models.USERFLAG_INVALID_AMOUNT, "INVALIDAMOUNT") - state.FlagDebugger.Register(models.USERFLAG_UNLOCKFORUPDATE, "UNLOCKFORUPDATE") + state.FlagDebugger.Register(models.USERFLAG_ALLOW_UPDATE, "UNLOCKFORUPDATE") state.FlagDebugger.Register(models.USERFLAG_VALIDPIN, "VALIDPIN") state.FlagDebugger.Register(models.USERFLAG_VALIDPIN, "ACCOUNTUNLOCKED") state.FlagDebugger.Register(models.USERFLAG_ACCOUNT_CREATION_FAILED, "ACCOUNT_CREATION_FAILED") @@ -91,7 +91,7 @@ func main() { rfs.AddLocalFunc("verify_pin", ussdHandlers.VerifyPin) rfs.AddLocalFunc("check_identifier", ussdHandlers.CheckIdentifier) rfs.AddLocalFunc("check_account_status", ussdHandlers.CheckAccountStatus) - rfs.AddLocalFunc("unlock_account", ussdHandlers.Unlock) + rfs.AddLocalFunc("unlock_account", ussdHandlers.Authorize) rfs.AddLocalFunc("quit", ussdHandlers.Quit) rfs.AddLocalFunc("check_balance", ussdHandlers.CheckBalance) rfs.AddLocalFunc("validate_recipient", ussdHandlers.ValidateRecipient) @@ -110,8 +110,8 @@ func main() { rfs.AddLocalFunc("save_yob", ussdHandlers.SaveYob) rfs.AddLocalFunc("save_offerings", ussdHandlers.SaveOfferings) rfs.AddLocalFunc("quit_with_balance", ussdHandlers.QuitWithBalance) - rfs.AddLocalFunc("reset_unlocked", ussdHandlers.ResetAccountUnlocked) - rfs.AddLocalFunc("reset_unlock_for_update", ussdHandlers.ResetUnlockForUpdate) + rfs.AddLocalFunc("reset_unlocked", ussdHandlers.ResetAccountAuthorized) + rfs.AddLocalFunc("reset_unlock_for_update", ussdHandlers.ResetAllowUpdate) rfs.AddLocalFunc("get_profile_info", ussdHandlers.GetProfileInfo) rfs.AddLocalFunc("verify_yob", ussdHandlers.VerifyYob) rfs.AddLocalFunc("reset_incorrect_date_format", ussdHandlers.ResetIncorrectYob) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 5b53b73..f66c262 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -20,7 +20,7 @@ import ( ) var ( - scriptDir = path.Join( "services", "registration") + scriptDir = path.Join("services", "registration") translationDir = path.Join(scriptDir, "locale") ) @@ -44,7 +44,7 @@ type Handlers struct { fs *FSData accountCreator AccountCreator accountFileHandler utils.AccountFileHandlerInterface - accountService server.AccountServiceInterface + accountService server.AccountServiceInterface } func NewHandlers(path string, st *state.State) *Handlers { @@ -55,7 +55,7 @@ func NewHandlers(path string, st *state.State) *Handlers { }, accountFileHandler: utils.NewAccountFileHandler(path + "_data"), accountCreator: &ServerAccountCreator{}, - accountService: &server.AccountService{}, + accountService: &server.AccountService{}, } } @@ -150,19 +150,19 @@ func (h *Handlers) SavePin(ctx context.Context, sym string, input []byte) (resou return res, nil } -//SetResetSingleEdit sets and resets flags to allow gradual editing of profile information. +// SetResetSingleEdit sets and resets flags to allow gradual editing of profile information. func (h *Handlers) SetResetSingleEdit(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} menuOption := string(input) switch menuOption { case "2": - res.FlagReset = append(res.FlagSet, models.USERFLAG_UNLOCKFORUPDATE) + res.FlagReset = append(res.FlagSet, models.USERFLAG_ALLOW_UPDATE) res.FlagSet = append(res.FlagSet, models.USERFLAG_SINGLE_EDIT) case "3": - res.FlagReset = append(res.FlagSet, models.USERFLAG_UNLOCKFORUPDATE) + res.FlagReset = append(res.FlagSet, models.USERFLAG_ALLOW_UPDATE) res.FlagSet = append(res.FlagSet, models.USERFLAG_SINGLE_EDIT) case "4": - res.FlagReset = append(res.FlagSet, models.USERFLAG_UNLOCKFORUPDATE) + res.FlagReset = append(res.FlagSet, models.USERFLAG_ALLOW_UPDATE) res.FlagSet = append(res.FlagSet, models.USERFLAG_SINGLE_EDIT) default: res.FlagReset = append(res.FlagReset, models.USERFLAG_SINGLE_EDIT) @@ -172,7 +172,7 @@ func (h *Handlers) SetResetSingleEdit(ctx context.Context, sym string, input []b } // VerifyPin checks whether the confirmation PIN is similar to the account PIN -// If similar, it sets the USERFLAG_PIN_SET flag allowing the user +// If similar, it sets the USERFLAG_PIN_SET flag allowing the user // to access the main menu func (h *Handlers) VerifyPin(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} @@ -199,8 +199,7 @@ func isValidPIN(pin string) bool { return match } - -//codeFromCtx retrieves language codes from the context that can be used for handling translations +// codeFromCtx retrieves language codes from the context that can be used for handling translations func codeFromCtx(ctx context.Context) string { var code string engine.Logg.DebugCtxf(ctx, "in msg", "ctx", ctx, "val", code) @@ -316,7 +315,7 @@ func (h *Handlers) SaveGender(ctx context.Context, sym string, input []byte) (re case "2": gender = "Female" case "3": - gender = "Other" + gender = "Unspecified" } accountData["Gender"] = gender @@ -349,17 +348,17 @@ func (h *Handlers) SaveOfferings(ctx context.Context, sym string, input []byte) return res, nil } -//ResetUnlockForUpdate resets the unlockforupdate flag to correctly show appropriate nodes as a user provides the profile data. -func (h *Handlers) ResetUnlockForUpdate(ctx context.Context, sym string, input []byte) (resource.Result, error) { +// ResetAllowUpdate resets the allowupdate flag that allows a user to update profile data. +func (h *Handlers) ResetAllowUpdate(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - res.FlagReset = append(res.FlagReset, models.USERFLAG_UNLOCKFORUPDATE) + res.FlagReset = append(res.FlagReset, models.USERFLAG_ALLOW_UPDATE) return res, nil } -//ResetAccountUnlocked locks an account that had already been unlocked. -func (h *Handlers) ResetAccountUnlocked(ctx context.Context, sym string, input []byte) (resource.Result, error) { +// ResetAccountAuthorized resets the account authorization flag after a successful PIN entry. +func (h *Handlers) ResetAccountAuthorized(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_UNLOCKED) + res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_AUTHORIZED) return res, nil } @@ -377,9 +376,9 @@ func (h *Handlers) CheckIdentifier(ctx context.Context, sym string, input []byte return res, nil } -// Unlock attempts to unlock the next sequential nodes by verifying the provided PIN against the already set PIN. +// Authorize attempts to unlock the next sequential nodes by verifying the provided PIN against the already set PIN. // It sets the required flags that control the flow. -func (h *Handlers) Unlock(ctx context.Context, sym string, input []byte) (resource.Result, error) { +func (h *Handlers) Authorize(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} pin := string(input) @@ -391,22 +390,22 @@ func (h *Handlers) Unlock(ctx context.Context, sym string, input []byte) (resour if len(input) == 4 { if pin != accountData["AccountPIN"] { res.FlagSet = append(res.FlagSet, models.USERFLAG_INCORRECTPIN) - res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_UNLOCKED) + res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_AUTHORIZED) return res, nil } - if h.fs.St.MatchFlag(models.USERFLAG_ACCOUNT_UNLOCKED, false) { + if h.fs.St.MatchFlag(models.USERFLAG_ACCOUNT_AUTHORIZED, false) { res.FlagReset = append(res.FlagReset, models.USERFLAG_INCORRECTPIN) - res.FlagSet = append(res.FlagSet, models.USERFLAG_UNLOCKFORUPDATE) - res.FlagSet = append(res.FlagSet, models.USERFLAG_ACCOUNT_UNLOCKED) + res.FlagSet = append(res.FlagSet, models.USERFLAG_ALLOW_UPDATE) + res.FlagSet = append(res.FlagSet, models.USERFLAG_ACCOUNT_AUTHORIZED) } else { - res.FlagSet = append(res.FlagSet, models.USERFLAG_UNLOCKFORUPDATE) - res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_UNLOCKED) + res.FlagSet = append(res.FlagSet, models.USERFLAG_ALLOW_UPDATE) + res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_AUTHORIZED) } } return res, nil } -//ResetIncorrectPin resets the incorrect pin flag after a new PIN attempt. +// ResetIncorrectPin resets the incorrect pin flag after a new PIN attempt. func (h *Handlers) ResetIncorrectPin(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} res.FlagReset = append(res.FlagReset, models.USERFLAG_INCORRECTPIN) @@ -457,7 +456,7 @@ func (h *Handlers) Quit(ctx context.Context, sym string, input []byte) (resource default: res.Content = "Thank you for using Sarafu. Goodbye!" } - res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_UNLOCKED) + res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_AUTHORIZED) return res, nil } @@ -481,14 +480,14 @@ func (h *Handlers) VerifyYob(ctx context.Context, sym string, input []byte) (res return res, nil } -//ResetIncorrectYob resets the incorrect date format after a new attempt +// ResetIncorrectYob resets the incorrect date format after a new attempt func (h *Handlers) ResetIncorrectYob(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} res.FlagReset = append(res.FlagReset, models.USERFLAG_INCORRECTDATEFORMAT) return res, nil } -// CheckBalance retrieves the balance from the API using the "PublicKey" and sets +// CheckBalance retrieves the balance from the API using the "PublicKey" and sets // the balance as the result content func (h *Handlers) CheckBalance(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} @@ -581,7 +580,7 @@ func (h *Handlers) ResetTransactionAmount(ctx context.Context, sym string, input return res, nil } -// MaxAmount gets the current balance from the API and sets it as +// MaxAmount gets the current balance from the API and sets it as // the result content. func (h *Handlers) MaxAmount(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} @@ -736,7 +735,6 @@ func (h *Handlers) GetAmount(ctx context.Context, sym string, input []byte) (res return res, nil } - // QuickWithBalance retrieves the balance for a given public key from the custodial balance API endpoint before // gracefully exiting the session. func (h *Handlers) QuitWithBalance(ctx context.Context, sym string, input []byte) (resource.Result, error) { @@ -753,7 +751,7 @@ func (h *Handlers) QuitWithBalance(ctx context.Context, sym string, input []byte return res, nil } res.Content = l.Get("Your account balance is %s", balance) - res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_UNLOCKED) + res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_AUTHORIZED) return res, nil } @@ -784,6 +782,6 @@ func (h *Handlers) InitiateTransaction(ctx context.Context, sym string, input [] return res, err } - res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_UNLOCKED) + res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_AUTHORIZED) return res, nil } From dd0b0ce5a300f2503b940fd581ccec1db0d2e904 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Thu, 29 Aug 2024 23:22:27 +0300 Subject: [PATCH 121/201] use authorize flag instead of unlock --- internal/handlers/ussd/menuhandler.go | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 0ffa209..872117a 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -59,14 +59,7 @@ func NewHandlers(path string, st *state.State) *Handlers { } } -// Define the regex pattern as a constant -const pinPattern = `^\d{4}$` -// isValidPIN checks whether the given input is a 4 digit number -func isValidPIN(pin string) bool { - match, _ := regexp.MatchString(pinPattern, pin) - return match -} // Define the regex pattern as a constant const pinPattern = `^\d{4}$` @@ -467,7 +460,7 @@ func (h *Handlers) Quit(ctx context.Context, sym string, input []byte) (resource l.AddDomain("default") res.Content = l.Get("Thank you for using Sarafu. Goodbye!") - res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_UNLOCKED) + res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_AUTHORIZED) return res, nil } From 241fe9e5fe6900e6bc68e46e7ae2f62bd111ca26 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Fri, 30 Aug 2024 09:14:17 +0300 Subject: [PATCH 122/201] remove repeated code --- internal/handlers/server/accountstatus.go | 46 ----------------------- internal/handlers/server/balancecheck.go | 36 ------------------ internal/handlers/server/createaccount.go | 37 ------------------ 3 files changed, 119 deletions(-) delete mode 100644 internal/handlers/server/accountstatus.go delete mode 100644 internal/handlers/server/balancecheck.go delete mode 100644 internal/handlers/server/createaccount.go diff --git a/internal/handlers/server/accountstatus.go b/internal/handlers/server/accountstatus.go deleted file mode 100644 index 400642c..0000000 --- a/internal/handlers/server/accountstatus.go +++ /dev/null @@ -1,46 +0,0 @@ -package server - -import ( - "encoding/json" - "io" - "net/http" - - "git.grassecon.net/urdt/ussd/config" - "git.grassecon.net/urdt/ussd/internal/models" -) - -// CheckAccountStatus retrieves the status of an account transaction based on the provided tracking ID. -// -// Parameters: -// - trackingId: A unique identifier for the account.This should be obtained from a previous call to -// CreateAccount or a similar function that returns an AccountResponse. The `trackingId` field in the -// AccountResponse struct can be used here to check the account status during a transaction. -// -// -// Returns: -// - string: The status of the transaction as a string. If there is an error during the request or processing, this will be an empty string. -// - error: An error if any occurred during the HTTP request, reading the response, or unmarshalling the JSON data. -// If no error occurs, this will be nil. -// -func CheckAccountStatus(trackingId string) (string, error) { - resp, err := http.Get(config.TrackStatusURL + trackingId) - if err != nil { - return "", err - } - defer resp.Body.Close() - - body, err := io.ReadAll(resp.Body) - if err != nil { - return "", err - } - - var trackResp models.TrackStatusResponse - err = json.Unmarshal(body, &trackResp) - if err != nil { - return "", err - } - - status := trackResp.Result.Transaction.Status - - return status, nil -} diff --git a/internal/handlers/server/balancecheck.go b/internal/handlers/server/balancecheck.go deleted file mode 100644 index 85355be..0000000 --- a/internal/handlers/server/balancecheck.go +++ /dev/null @@ -1,36 +0,0 @@ -package server - -import ( - "encoding/json" - "io" - "net/http" - - "git.grassecon.net/urdt/ussd/config" - "git.grassecon.net/urdt/ussd/internal/models" -) - -// CheckBalance retrieves the balance for a given public key from the custodial balance API endpoint. -// Parameters: -// - publicKey: The public key associated with the account whose balance needs to be checked. -func CheckBalance(publicKey string) (string, error) { - - resp, err := http.Get(config.BalanceURL + publicKey) - if err != nil { - return "0.0", err - } - defer resp.Body.Close() - - body, err := io.ReadAll(resp.Body) - if err != nil { - return "0.0", err - } - - var balanceResp models.BalanceResponse - err = json.Unmarshal(body, &balanceResp) - if err != nil { - return "0.0", err - } - - balance := balanceResp.Result.Balance - return balance, nil -} diff --git a/internal/handlers/server/createaccount.go b/internal/handlers/server/createaccount.go deleted file mode 100644 index 4b7150c..0000000 --- a/internal/handlers/server/createaccount.go +++ /dev/null @@ -1,37 +0,0 @@ -package server - -import ( - "encoding/json" - "io" - "net/http" - - "git.grassecon.net/urdt/ussd/config" - "git.grassecon.net/urdt/ussd/internal/models" -) - -//CreateAccount creates a new account in the custodial system. -// Returns: -// - *models.AccountResponse: A pointer to an AccountResponse struct containing the details of the created account. -// If there is an error during the request or processing, this will be nil. -// - error: An error if any occurred during the HTTP request, reading the response, or unmarshalling the JSON data. -// If no error occurs, this will be nil. -func CreateAccount() (*models.AccountResponse, error) { - resp, err := http.Post(config.CreateAccountURL, "application/json", nil) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := io.ReadAll(resp.Body) - if err != nil { - return nil, err - } - - var accountResp models.AccountResponse - err = json.Unmarshal(body, &accountResp) - if err != nil { - return nil, err - } - - return &accountResp, nil -} \ No newline at end of file From 23bfdf4483f6ebf25fe72df2b3b7c6ee376e0202 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Fri, 30 Aug 2024 09:15:04 +0300 Subject: [PATCH 123/201] add documentation lines --- internal/handlers/server/accountservice.go | 26 ++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/internal/handlers/server/accountservice.go b/internal/handlers/server/accountservice.go index 791f2e7..f4375a1 100644 --- a/internal/handlers/server/accountservice.go +++ b/internal/handlers/server/accountservice.go @@ -18,6 +18,21 @@ type AccountServiceInterface interface { type AccountService struct { } + + +// CheckAccountStatus retrieves the status of an account transaction based on the provided tracking ID. +// +// Parameters: +// - trackingId: A unique identifier for the account.This should be obtained from a previous call to +// CreateAccount or a similar function that returns an AccountResponse. The `trackingId` field in the +// AccountResponse struct can be used here to check the account status during a transaction. +// +// +// Returns: +// - string: The status of the transaction as a string. If there is an error during the request or processing, this will be an empty string. +// - error: An error if any occurred during the HTTP request, reading the response, or unmarshalling the JSON data. +// If no error occurs, this will be nil. +// func (as *AccountService) CheckAccountStatus(trackingId string) (string, error) { resp, err := http.Get(config.TrackStatusURL + trackingId) if err != nil { @@ -41,6 +56,10 @@ func (as *AccountService) CheckAccountStatus(trackingId string) (string, error) return status, nil } + +// CheckBalance retrieves the balance for a given public key from the custodial balance API endpoint. +// Parameters: +// - publicKey: The public key associated with the account whose balance needs to be checked. func (as *AccountService) CheckBalance(publicKey string) (string, error) { resp, err := http.Get(config.BalanceURL + publicKey) @@ -64,6 +83,13 @@ func (as *AccountService) CheckBalance(publicKey string) (string, error) { return balance, nil } + +//CreateAccount creates a new account in the custodial system. +// Returns: +// - *models.AccountResponse: A pointer to an AccountResponse struct containing the details of the created account. +// If there is an error during the request or processing, this will be nil. +// - error: An error if any occurred during the HTTP request, reading the response, or unmarshalling the JSON data. +// If no error occurs, this will be nil. func (as *AccountService) CreateAccount() (*models.AccountResponse, error) { resp, err := http.Post(config.CreateAccountURL, "application/json", nil) if err != nil { From 00d582c0174c5f183b89e42fa6b28554cda8ab7e Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Fri, 30 Aug 2024 09:15:38 +0300 Subject: [PATCH 124/201] setup account file interface --- internal/utils/filehandler.go | 39 +---------------------------------- 1 file changed, 1 insertion(+), 38 deletions(-) diff --git a/internal/utils/filehandler.go b/internal/utils/filehandler.go index 9b768fd..8b11e29 100644 --- a/internal/utils/filehandler.go +++ b/internal/utils/filehandler.go @@ -1,9 +1,6 @@ package utils -import ( - "encoding/json" - "os" -) + type AccountFileHandlerInterface interface { @@ -14,37 +11,3 @@ type AccountFileHandlerInterface interface { -type AccountFileHandler2 struct { - FilePath string -} - -// Implement the methods required by AccountFileHandlerInterface. -func (afh *AccountFileHandler2) EnsureFileExists() error { - f, err := os.OpenFile(afh.FilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) - if err != nil { - return err - } - return f.Close() -} -func (afh *AccountFileHandler2) ReadAccountData() (map[string]string, error) { - jsonData, err := os.ReadFile(afh.FilePath) - if err != nil { - return nil, err - } - - var accountData map[string]string - err = json.Unmarshal(jsonData, &accountData) - if err != nil { - return nil, err - } - - return accountData, nil -} -func (afh *AccountFileHandler2) WriteAccountData(data map[string]string) error { - jsonData, err := json.Marshal(data) - if err != nil { - return err - } - - return os.WriteFile(afh.FilePath, jsonData, 0644) -} \ No newline at end of file From 1ded359b594c7f05848dc13761acfe38db709d18 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Fri, 30 Aug 2024 09:17:09 +0300 Subject: [PATCH 125/201] refactor --- internal/handlers/ussd/menuhandler.go | 22 +++++----------------- 1 file changed, 5 insertions(+), 17 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 872117a..4eb2a83 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -29,20 +29,9 @@ type FSData struct { St *state.State } -type AccountCreator interface { - CreateAccount() (*models.AccountResponse, error) -} - -// ServerAccountCreator implements AccountCreator using the server package -type ServerAccountCreator struct{} - -func (s *ServerAccountCreator) CreateAccount() (*models.AccountResponse, error) { - return server.CreateAccount() -} type Handlers struct { fs *FSData - accountCreator AccountCreator accountFileHandler utils.AccountFileHandlerInterface accountService server.AccountServiceInterface } @@ -54,7 +43,6 @@ func NewHandlers(path string, st *state.State) *Handlers { St: st, }, accountFileHandler: utils.NewAccountFileHandler(path + "_data"), - accountCreator: &ServerAccountCreator{}, accountService: &server.AccountService{}, } } @@ -426,7 +414,7 @@ func (h *Handlers) CheckAccountStatus(ctx context.Context, sym string, input []b return res, err } - status, err := server.CheckAccountStatus(accountData["TrackingId"]) + status, err := h.accountService.CheckAccountStatus(accountData["TrackingId"]) if err != nil { fmt.Println("Error checking account status:", err) @@ -501,7 +489,7 @@ func (h *Handlers) CheckBalance(ctx context.Context, sym string, input []byte) ( return res, err } - balance, err := server.CheckBalance(accountData["PublicKey"]) + balance, err := h.accountService.CheckBalance(accountData["PublicKey"]) if err != nil { return res, nil } @@ -594,7 +582,7 @@ func (h *Handlers) MaxAmount(ctx context.Context, sym string, input []byte) (res return res, err } - balance, err := server.CheckBalance(accountData["PublicKey"]) + balance, err := h.accountService.CheckBalance(accountData["PublicKey"]) if err != nil { return res, nil } @@ -615,7 +603,7 @@ func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte) return res, err } - balanceStr, err := server.CheckBalance(accountData["PublicKey"]) + balanceStr, err := h.accountService.CheckBalance(accountData["PublicKey"]) if err != nil { return res, err } @@ -750,7 +738,7 @@ func (h *Handlers) QuitWithBalance(ctx context.Context, sym string, input []byte if err != nil { return res, err } - balance, err := server.CheckBalance(accountData["PublicKey"]) + balance, err := h.accountService.CheckBalance(accountData["PublicKey"]) if err != nil { return res, nil } From 76185c3aa154ba6d459563db2b8c33ca1b217629 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Fri, 30 Aug 2024 10:45:04 +0300 Subject: [PATCH 126/201] Use AccountService in the TestCreateAccount --- internal/handlers/ussd/menuhandler_test.go | 71 ++++++++++++---------- 1 file changed, 38 insertions(+), 33 deletions(-) diff --git a/internal/handlers/ussd/menuhandler_test.go b/internal/handlers/ussd/menuhandler_test.go index 6fbd27f..bce359d 100644 --- a/internal/handlers/ussd/menuhandler_test.go +++ b/internal/handlers/ussd/menuhandler_test.go @@ -15,14 +15,24 @@ import ( "github.com/stretchr/testify/mock" ) -// MockAccountCreator implements AccountCreator for testing -type MockAccountCreator struct { - mockResponse *models.AccountResponse - mockError error +// MockAccountService implements AccountServiceInterface for testing +type MockAccountService struct { + mock.Mock } -func (m *MockAccountCreator) CreateAccount() (*models.AccountResponse, error) { - return m.mockResponse, m.mockError +func (m *MockAccountService) CreateAccount() (*models.AccountResponse, error) { + args := m.Called() + return args.Get(0).(*models.AccountResponse), args.Error(1) +} + +func (m *MockAccountService) CheckBalance(publicKey string) (string, error) { + args := m.Called(publicKey) + return args.String(0), args.Error(1) +} + +func (m *MockAccountService) CheckAccountStatus(trackingId string) (string, error) { + args := m.Called(trackingId) + return args.String(0), args.Error(1) } func TestCreateAccount(t *testing.T) { @@ -41,26 +51,29 @@ func TestCreateAccount(t *testing.T) { // Initialize account file handler accountFileHandler := utils.NewAccountFileHandler(accountFilePath) - // Create a mock account creator - mockAccountCreator := &MockAccountCreator{ - mockResponse: &models.AccountResponse{ - Ok: true, - Result: struct { - CustodialId json.Number `json:"custodialId"` - PublicKey string `json:"publicKey"` - TrackingId string `json:"trackingId"` - }{ - CustodialId: "test-custodial-id", - PublicKey: "test-public-key", - TrackingId: "test-tracking-id", - }, + // Create a mock account service + mockAccountService := &MockAccountService{} + mockAccountResponse := &models.AccountResponse{ + Ok: true, + Result: struct { + CustodialId json.Number `json:"custodialId"` + PublicKey string `json:"publicKey"` + TrackingId string `json:"trackingId"` + }{ + CustodialId: "test-custodial-id", + PublicKey: "test-public-key", + TrackingId: "test-tracking-id", }, } - // Initialize Handlers with mock account creator + // Set up expectations for the mock account service + mockAccountService.On("CreateAccount").Return(mockAccountResponse, nil) + + // Initialize Handlers with mock account service h := &Handlers{ + fs: &FSData{Path: accountFilePath}, accountFileHandler: accountFileHandler, - accountCreator: mockAccountCreator, + accountService: mockAccountService, } tests := []struct { @@ -102,9 +115,7 @@ func TestCreateAccount(t *testing.T) { "FirstName": "Not provided", "FamilyName": "Not provided", }, - expectedResult: resource.Result{ - FlagSet: []uint32{models.USERFLAG_ACCOUNT_CREATED}, - }, + expectedResult: resource.Result{}, expectedData: map[string]string{ "TrackingId": "test-tracking-id", "PublicKey": "test-public-key", @@ -173,8 +184,6 @@ func TestCreateAccount(t *testing.T) { } } - - func TestCreateAccount_Success(t *testing.T) { mockAccountFileHandler := new(mocks.MockAccountFileHandler) mockCreateAccountService := new(mocks.MockAccountService) @@ -203,21 +212,17 @@ func TestCreateAccount_Success(t *testing.T) { mockAccountFileHandler.On("WriteAccountData", mock.Anything).Return(nil) handlers := &Handlers{ - accountService: mockCreateAccountService, + accountService: mockCreateAccountService, } - actualResponse, err := handlers.accountService.CreateAccount() // Assert results assert.NoError(t, err) - assert.Equal(t,expectedAccountResp.Ok,true) - assert.Equal(t,expectedAccountResp,actualResponse) - - + assert.Equal(t, expectedAccountResp.Ok, true) + assert.Equal(t, expectedAccountResp, actualResponse) } - func TestSavePin(t *testing.T) { // Setup tempDir, err := os.MkdirTemp("", "test_save_pin") From 95e142860efb281d7fbff4f0d0d19f7e650d9f82 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Fri, 30 Aug 2024 11:15:08 +0300 Subject: [PATCH 127/201] rename unlock flags to authorize --- cmd/main.go | 6 +++--- services/registration/edit_profile.vis | 6 +++--- services/registration/my_account.vis | 2 +- services/registration/pin_entry.vis | 4 ++-- services/registration/transaction_pin.vis | 5 +++-- 5 files changed, 12 insertions(+), 11 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index 4c67a32..2daee8c 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -91,7 +91,7 @@ func main() { rfs.AddLocalFunc("verify_pin", ussdHandlers.VerifyPin) rfs.AddLocalFunc("check_identifier", ussdHandlers.CheckIdentifier) rfs.AddLocalFunc("check_account_status", ussdHandlers.CheckAccountStatus) - rfs.AddLocalFunc("unlock_account", ussdHandlers.Authorize) + rfs.AddLocalFunc("authorize_account", ussdHandlers.Authorize) rfs.AddLocalFunc("quit", ussdHandlers.Quit) rfs.AddLocalFunc("check_balance", ussdHandlers.CheckBalance) rfs.AddLocalFunc("validate_recipient", ussdHandlers.ValidateRecipient) @@ -110,8 +110,8 @@ func main() { rfs.AddLocalFunc("save_yob", ussdHandlers.SaveYob) rfs.AddLocalFunc("save_offerings", ussdHandlers.SaveOfferings) rfs.AddLocalFunc("quit_with_balance", ussdHandlers.QuitWithBalance) - rfs.AddLocalFunc("reset_unlocked", ussdHandlers.ResetAccountAuthorized) - rfs.AddLocalFunc("reset_unlock_for_update", ussdHandlers.ResetAllowUpdate) + rfs.AddLocalFunc("reset_account_authorized", ussdHandlers.ResetAccountAuthorized) + rfs.AddLocalFunc("reset_allow_update", ussdHandlers.ResetAllowUpdate) rfs.AddLocalFunc("get_profile_info", ussdHandlers.GetProfileInfo) rfs.AddLocalFunc("verify_yob", ussdHandlers.VerifyYob) rfs.AddLocalFunc("reset_incorrect_date_format", ussdHandlers.ResetIncorrectYob) diff --git a/services/registration/edit_profile.vis b/services/registration/edit_profile.vis index d85bbc4..566b827 100644 --- a/services/registration/edit_profile.vis +++ b/services/registration/edit_profile.vis @@ -1,6 +1,6 @@ -LOAD reset_unlocked 16 -LOAD reset_unlock_for_update 0 -RELOAD reset_unlock_for_update +LOAD reset_account_authorized 16 +LOAD reset_allow_update 0 +RELOAD reset_allow_update MOUT edit_name 1 MOUT edit_gender 2 MOUT edit_yob 3 diff --git a/services/registration/my_account.vis b/services/registration/my_account.vis index 20eb6d5..345b1a0 100644 --- a/services/registration/my_account.vis +++ b/services/registration/my_account.vis @@ -1,4 +1,4 @@ -LOAD reset_unlock_for_update 0 +LOAD reset_allow_update 0 MOUT profile 1 MOUT change_language 2 MOUT check_balance 3 diff --git a/services/registration/pin_entry.vis b/services/registration/pin_entry.vis index cb99035..2eaf40f 100644 --- a/services/registration/pin_entry.vis +++ b/services/registration/pin_entry.vis @@ -1,4 +1,4 @@ -LOAD unlock_account 0 +LOAD authorize_account 0 HALT -RELOAD unlock_account +RELOAD authorize_account MOVE _ diff --git a/services/registration/transaction_pin.vis b/services/registration/transaction_pin.vis index 5c10b3f..5113b6c 100644 --- a/services/registration/transaction_pin.vis +++ b/services/registration/transaction_pin.vis @@ -6,9 +6,10 @@ MAP get_sender MOUT back 0 MOUT quit 9 HALT -LOAD unlock_account 1 -RELOAD unlock_account +LOAD authorize_account 1 +RELOAD authorize_account CATCH incorrect_pin 15 1 INCMP _ 0 INCMP quit 9 MOVE transaction_initiated + From c1389b4ab38b0457f0381f43d4c62c9a3e7cc372 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Fri, 30 Aug 2024 11:17:06 +0300 Subject: [PATCH 128/201] add test case for saving location --- internal/handlers/ussd/menuhandler_test.go | 216 ++++++--------------- 1 file changed, 64 insertions(+), 152 deletions(-) diff --git a/internal/handlers/ussd/menuhandler_test.go b/internal/handlers/ussd/menuhandler_test.go index 6fbd27f..e87ef5a 100644 --- a/internal/handlers/ussd/menuhandler_test.go +++ b/internal/handlers/ussd/menuhandler_test.go @@ -21,158 +21,6 @@ type MockAccountCreator struct { mockError error } -func (m *MockAccountCreator) CreateAccount() (*models.AccountResponse, error) { - return m.mockResponse, m.mockError -} - -func TestCreateAccount(t *testing.T) { - // Setup - tempDir, err := os.MkdirTemp("", "test_create_account") - if err != nil { - t.Fatalf("Failed to create temp directory: %v", err) - } - defer os.RemoveAll(tempDir) // Clean up after the test run - - sessionID := "07xxxxxxxx" - - // Set up the data file path using the session ID - accountFilePath := filepath.Join(tempDir, sessionID+"_data") - - // Initialize account file handler - accountFileHandler := utils.NewAccountFileHandler(accountFilePath) - - // Create a mock account creator - mockAccountCreator := &MockAccountCreator{ - mockResponse: &models.AccountResponse{ - Ok: true, - Result: struct { - CustodialId json.Number `json:"custodialId"` - PublicKey string `json:"publicKey"` - TrackingId string `json:"trackingId"` - }{ - CustodialId: "test-custodial-id", - PublicKey: "test-public-key", - TrackingId: "test-tracking-id", - }, - }, - } - - // Initialize Handlers with mock account creator - h := &Handlers{ - accountFileHandler: accountFileHandler, - accountCreator: mockAccountCreator, - } - - tests := []struct { - name string - existingData map[string]string - expectedResult resource.Result - expectedData map[string]string - }{ - { - name: "New account creation", - existingData: nil, - expectedResult: resource.Result{ - FlagSet: []uint32{models.USERFLAG_ACCOUNT_CREATED}, - }, - expectedData: map[string]string{ - "TrackingId": "test-tracking-id", - "PublicKey": "test-public-key", - "CustodialId": "test-custodial-id", - "Status": "PENDING", - "Gender": "Not provided", - "YOB": "Not provided", - "Location": "Not provided", - "Offerings": "Not provided", - "FirstName": "Not provided", - "FamilyName": "Not provided", - }, - }, - { - name: "Existing account", - existingData: map[string]string{ - "TrackingId": "test-tracking-id", - "PublicKey": "test-public-key", - "CustodialId": "test-custodial-id", - "Status": "PENDING", - "Gender": "Not provided", - "YOB": "Not provided", - "Location": "Not provided", - "Offerings": "Not provided", - "FirstName": "Not provided", - "FamilyName": "Not provided", - }, - expectedResult: resource.Result{ - FlagSet: []uint32{models.USERFLAG_ACCOUNT_CREATED}, - }, - expectedData: map[string]string{ - "TrackingId": "test-tracking-id", - "PublicKey": "test-public-key", - "CustodialId": "test-custodial-id", - "Status": "PENDING", - "Gender": "Not provided", - "YOB": "Not provided", - "Location": "Not provided", - "Offerings": "Not provided", - "FirstName": "Not provided", - "FamilyName": "Not provided", - }, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - // Set up the data file path using the session ID - accountFilePath := filepath.Join(tempDir, sessionID+"_data") - - // Setup existing data if any - if tt.existingData != nil { - data, _ := json.Marshal(tt.existingData) - err := os.WriteFile(accountFilePath, data, 0644) - if err != nil { - t.Fatalf("Failed to write existing data: %v", err) - } - } - - // Call the function - result, err := h.CreateAccount(context.Background(), "", nil) - - // Check for errors - if err != nil { - t.Fatalf("CreateAccount returned an error: %v", err) - } - - // Check the result - if len(result.FlagSet) != len(tt.expectedResult.FlagSet) { - t.Errorf("Expected %d flags, got %d", len(tt.expectedResult.FlagSet), len(result.FlagSet)) - } - for i, flag := range tt.expectedResult.FlagSet { - if result.FlagSet[i] != flag { - t.Errorf("Expected flag %d, got %d", flag, result.FlagSet[i]) - } - } - - // Check the stored data - data, err := os.ReadFile(accountFilePath) - if err != nil { - t.Fatalf("Failed to read account data file: %v", err) - } - - var storedData map[string]string - err = json.Unmarshal(data, &storedData) - if err != nil { - t.Fatalf("Failed to unmarshal stored data: %v", err) - } - - for key, expectedValue := range tt.expectedData { - if storedValue, ok := storedData[key]; !ok || storedValue != expectedValue { - t.Errorf("Expected %s to be %s, got %s", key, expectedValue, storedValue) - } - } - }) - } -} - func TestCreateAccount_Success(t *testing.T) { @@ -327,3 +175,67 @@ func TestSavePin(t *testing.T) { }) } } + + + +func TestSaveLocation(t *testing.T) { + // Create a new instance of MockAccountFileHandler + mockFileHandler := new(mocks.MockAccountFileHandler) + + // Define test cases + tests := []struct { + name string + input []byte + existingData map[string]string + writeError error + expectedResult resource.Result + expectedError error + }{ + { + name: "Successful Save", + input: []byte("Mombasa"), + existingData: map[string]string{"Location": "Mombasa"}, + writeError: nil, + expectedResult: resource.Result{}, + expectedError: nil, + }, + { + name: "Empty location input", + input: []byte{}, + existingData: map[string]string{"OtherKey": "OtherValue"}, + writeError: nil, + expectedResult: resource.Result{}, + expectedError: nil, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Set up the mock expectations + mockFileHandler.On("ReadAccountData").Return(tt.existingData, tt.expectedError) + if tt.expectedError == nil && len(tt.input) > 0 { + mockFileHandler.On("WriteAccountData", mock.MatchedBy(func(data map[string]string) bool { + return data["Location"] == string(tt.input) + })).Return(tt.writeError) + }else if len(tt.input) == 0 { + // For empty input, no WriteAccountData call should be made + mockFileHandler.On("WriteAccountData", mock.Anything).Maybe().Return(tt.writeError) + } + + // Create the Handlers instance with the mock file handler + h := &Handlers{ + accountFileHandler: mockFileHandler, + } + + // Call the method + result, err := h.SaveLocation(context.Background(), "save_location", tt.input) + + // Assert the results + assert.Equal(t, tt.expectedResult, result) + assert.Equal(t, tt.expectedError, err) + + // Assert all expectations were met + mockFileHandler.AssertExpectations(t) + }) + } +} \ No newline at end of file From 2c6f70dfa5273fbd757e32594b02dd276ded81f8 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Fri, 30 Aug 2024 13:52:25 +0300 Subject: [PATCH 129/201] Add tests for GetSender and GetAmount --- internal/handlers/ussd/menuhandler_test.go | 100 ++++++++++++++++++++- 1 file changed, 96 insertions(+), 4 deletions(-) diff --git a/internal/handlers/ussd/menuhandler_test.go b/internal/handlers/ussd/menuhandler_test.go index f690873..7ff65a9 100644 --- a/internal/handlers/ussd/menuhandler_test.go +++ b/internal/handlers/ussd/menuhandler_test.go @@ -333,8 +333,6 @@ func TestSavePin(t *testing.T) { } } - - func TestSaveLocation(t *testing.T) { // Create a new instance of MockAccountFileHandler mockFileHandler := new(mocks.MockAccountFileHandler) @@ -374,7 +372,7 @@ func TestSaveLocation(t *testing.T) { mockFileHandler.On("WriteAccountData", mock.MatchedBy(func(data map[string]string) bool { return data["Location"] == string(tt.input) })).Return(tt.writeError) - }else if len(tt.input) == 0 { + } else if len(tt.input) == 0 { // For empty input, no WriteAccountData call should be made mockFileHandler.On("WriteAccountData", mock.Anything).Maybe().Return(tt.writeError) } @@ -395,4 +393,98 @@ func TestSaveLocation(t *testing.T) { mockFileHandler.AssertExpectations(t) }) } -} \ No newline at end of file +} + +func TestGetSender(t *testing.T) { + mockAccountFileHandler := new(mocks.MockAccountFileHandler) + h := &Handlers{ + accountFileHandler: mockAccountFileHandler, + } + + tests := []struct { + name string + expectedResult resource.Result + accountData map[string]string + }{ + { + name: "Valid public key", + expectedResult: resource.Result{ + Content: "test-public-key", + }, + accountData: map[string]string{ + "PublicKey": "test-public-key", + }, + }, + { + name: "Missing public key", + expectedResult: resource.Result{ + Content: "", + }, + accountData: map[string]string{}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Reset the mock state + mockAccountFileHandler.Mock = mock.Mock{} + + mockAccountFileHandler.On("ReadAccountData").Return(tt.accountData, nil) + + result, err := h.GetSender(context.Background(), "", nil) + + if err != nil { + t.Fatalf("Error occurred: %v", err) + } + + assert.Equal(t, tt.expectedResult.Content, result.Content) + mockAccountFileHandler.AssertCalled(t, "ReadAccountData") + }) + } +} + +func TestGetAmount(t *testing.T) { + mockAccountFileHandler := new(mocks.MockAccountFileHandler) + h := &Handlers{ + accountFileHandler: mockAccountFileHandler, + } + + tests := []struct { + name string + expectedResult resource.Result + accountData map[string]string + }{ + { + name: "Valid amount", + expectedResult: resource.Result{ + Content: "0.003", + }, + accountData: map[string]string{ + "Amount": "0.003", + }, + }, + { + name: "Missing amount", + expectedResult: resource.Result{}, + accountData: map[string]string{ + "Amount": "", + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Reset the mock state + mockAccountFileHandler.Mock = mock.Mock{} + + mockAccountFileHandler.On("ReadAccountData").Return(tt.accountData, nil) + + result, err := h.GetAmount(context.Background(), "", nil) + + assert.NoError(t, err) + assert.Equal(t, tt.expectedResult.Content, result.Content) + + mockAccountFileHandler.AssertCalled(t, "ReadAccountData") + }) + } +} From 1dbd3c0b8ebcdaf4159c0baa38fe5ee6363df95f Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Fri, 30 Aug 2024 14:01:58 +0300 Subject: [PATCH 130/201] add more test cases --- internal/handlers/ussd/menuhandler_test.go | 395 ++++++++++++++++++++- 1 file changed, 390 insertions(+), 5 deletions(-) diff --git a/internal/handlers/ussd/menuhandler_test.go b/internal/handlers/ussd/menuhandler_test.go index f690873..df60eb5 100644 --- a/internal/handlers/ussd/menuhandler_test.go +++ b/internal/handlers/ussd/menuhandler_test.go @@ -333,8 +333,6 @@ func TestSavePin(t *testing.T) { } } - - func TestSaveLocation(t *testing.T) { // Create a new instance of MockAccountFileHandler mockFileHandler := new(mocks.MockAccountFileHandler) @@ -374,7 +372,387 @@ func TestSaveLocation(t *testing.T) { mockFileHandler.On("WriteAccountData", mock.MatchedBy(func(data map[string]string) bool { return data["Location"] == string(tt.input) })).Return(tt.writeError) - }else if len(tt.input) == 0 { + } else if len(tt.input) == 0 { + // For empty input, no WriteAccountData call should be made + mockFileHandler.On("WriteAccountData", mock.Anything).Maybe().Return(tt.writeError) + return + } + + // Create the Handlers instance with the mock file handler + h := &Handlers{ + accountFileHandler: mockFileHandler, + } + + // Call Save Location + result, err := h.SaveLocation(context.Background(), "save_location", tt.input) + + if err != nil { + t.Fatalf("Failed to save location with error: %v", err) + } + + savedData, err := h.accountFileHandler.ReadAccountData() + if err == nil { + //Assert that the input provided is what was saved into the file + assert.Equal(t, string(tt.input), savedData["Location"]) + } + + // Assert the results + assert.Equal(t, tt.expectedResult, result) + assert.Equal(t, tt.expectedError, err) + + // Assert all expectations were met + mockFileHandler.AssertExpectations(t) + }) + } +} + +func TestSaveFirstname(t *testing.T) { + // Create a new instance of MockAccountFileHandler + mockFileHandler := new(mocks.MockAccountFileHandler) + + // Define test cases + tests := []struct { + name string + input []byte + existingData map[string]string + writeError error + expectedResult resource.Result + expectedError error + }{ + { + name: "Successful Save", + input: []byte("Joe"), + existingData: map[string]string{"Name": "Joe"}, + writeError: nil, + expectedResult: resource.Result{}, + expectedError: nil, + }, + { + name: "Empty Input", + input: []byte{}, + existingData: map[string]string{"OtherKey": "OtherValue"}, + writeError: nil, + expectedError: nil, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Set up the mock expectations + mockFileHandler.On("ReadAccountData").Return(tt.existingData, tt.expectedError) + if tt.expectedError == nil && len(tt.input) > 0 { + mockFileHandler.On("WriteAccountData", mock.MatchedBy(func(data map[string]string) bool { + return data["FirstName"] == string(tt.input) + })).Return(tt.writeError) + } else if len(tt.input) == 0 { + // For empty input, no WriteAccountData call should be made + mockFileHandler.On("WriteAccountData", mock.Anything).Maybe().Return(tt.writeError) + return + } + + // Create the Handlers instance with the mock file handler + h := &Handlers{ + accountFileHandler: mockFileHandler, + } + + // Call save location + result, err := h.SaveFirstname(context.Background(), "save_location", tt.input) + + if err != nil { + t.Fatalf("Failed to save first name with error: %v", err) + } + savedData, err := h.accountFileHandler.ReadAccountData() + if err == nil { + //Assert that the input provided is what was saved into the file + assert.Equal(t, string(tt.input), savedData["FirstName"]) + } + + // Assert the results + assert.Equal(t, tt.expectedResult, result) + assert.Equal(t, tt.expectedError, err) + + // Assert all expectations were met + mockFileHandler.AssertExpectations(t) + }) + } +} + +func TestSaveFamilyName(t *testing.T) { + // Create a new instance of MockAccountFileHandler + mockFileHandler := new(mocks.MockAccountFileHandler) + + // Define test cases + tests := []struct { + name string + input []byte + existingData map[string]string + writeError error + expectedResult resource.Result + expectedError error + }{ + { + name: "Successful Save", + input: []byte("Doe"), + existingData: map[string]string{"FamilyName": "Doe"}, + writeError: nil, + expectedResult: resource.Result{}, + expectedError: nil, + }, + { + name: "Empty Input", + input: []byte{}, + existingData: map[string]string{"FamilyName": "Doe"}, + writeError: nil, + expectedError: nil, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Set up the mock expectations + mockFileHandler.On("ReadAccountData").Return(tt.existingData, tt.expectedError) + if tt.expectedError == nil && len(tt.input) > 0 { + mockFileHandler.On("WriteAccountData", mock.MatchedBy(func(data map[string]string) bool { + return data["FamilyName"] == string(tt.input) + })).Return(tt.writeError) + } else if len(tt.input) == 0 { + // For empty input, no WriteAccountData call should be made + mockFileHandler.On("WriteAccountData", mock.Anything).Maybe().Return(tt.writeError) + return + } + + // Create the Handlers instance with the mock file handler + h := &Handlers{ + accountFileHandler: mockFileHandler, + } + + // Call save familyname + result, err := h.SaveFamilyname(context.Background(), "save_familyname", tt.input) + + if err != nil { + t.Fatalf("Failed to save family name with error: %v", err) + } + savedData, err := h.accountFileHandler.ReadAccountData() + if err == nil { + //Assert that the input provided is what was saved into the file + assert.Equal(t, string(tt.input), savedData["FamilyName"]) + } + + // Assert the results + assert.Equal(t, tt.expectedResult, result) + assert.Equal(t, tt.expectedError, err) + + // Assert all expectations were met + mockFileHandler.AssertExpectations(t) + }) + } +} + +func TestSaveYOB(t *testing.T) { + // Create a new instance of MockAccountFileHandler + mockFileHandler := new(mocks.MockAccountFileHandler) + + // Define test cases + tests := []struct { + name string + input []byte + existingData map[string]string + writeError error + expectedResult resource.Result + expectedError error + }{ + { + name: "Successful Save", + input: []byte("2006"), + existingData: map[string]string{"": ""}, + writeError: nil, + expectedResult: resource.Result{}, + expectedError: nil, + }, + { + name: "YOB less than 4 digits(invalid date entry)", + input: []byte{}, + existingData: map[string]string{"": ""}, + writeError: nil, + expectedError: nil, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Set up the mock expectations + mockFileHandler.On("ReadAccountData").Return(tt.existingData, tt.expectedError) + if tt.expectedError == nil && len(tt.input) > 0 { + mockFileHandler.On("WriteAccountData", mock.MatchedBy(func(data map[string]string) bool { + return data["YOB"] == string(tt.input) + })).Return(tt.writeError) + } else if len(tt.input) != 4 { + // For input whose input is not a valid yob, no WriteAccountData call should be made + mockFileHandler.On("WriteAccountData", mock.Anything).Maybe().Return(tt.writeError) + return + } + + // Create the Handlers instance with the mock file handler + h := &Handlers{ + accountFileHandler: mockFileHandler, + } + + // Call save yob + result, err := h.SaveYob(context.Background(), "save_yob", tt.input) + + if err != nil { + t.Fatalf("Failed to save family name with error: %v", err) + } + savedData, err := h.accountFileHandler.ReadAccountData() + if err == nil { + //Assert that the input provided is what was saved into the file + assert.Equal(t, string(tt.input), savedData["YOB"]) + } + + // Assert the results + assert.Equal(t, tt.expectedResult, result) + assert.Equal(t, tt.expectedError, err) + + // Assert all expectations were met + mockFileHandler.AssertExpectations(t) + }) + } +} + +func TestSaveOfferings(t *testing.T) { + // Create a new instance of MockAccountFileHandler + mockFileHandler := new(mocks.MockAccountFileHandler) + + // Define test cases + tests := []struct { + name string + input []byte + existingData map[string]string + writeError error + expectedResult resource.Result + expectedError error + }{ + { + name: "Successful Save", + input: []byte("Bananas"), + existingData: map[string]string{"": ""}, + writeError: nil, + expectedResult: resource.Result{}, + expectedError: nil, + }, + { + name: "Empty input", + input: []byte{}, + existingData: map[string]string{"": ""}, + writeError: nil, + expectedError: nil, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Set up the mock expectations + mockFileHandler.On("ReadAccountData").Return(tt.existingData, tt.expectedError) + if tt.expectedError == nil && len(tt.input) > 0 { + mockFileHandler.On("WriteAccountData", mock.MatchedBy(func(data map[string]string) bool { + return data["Offerings"] == string(tt.input) + })).Return(tt.writeError) + } else if len(tt.input) != 4 { + // For input whose input is not a valid yob, no WriteAccountData call should be made + mockFileHandler.On("WriteAccountData", mock.Anything).Maybe().Return(tt.writeError) + return + } + + // Create the Handlers instance with the mock file handler + h := &Handlers{ + accountFileHandler: mockFileHandler, + } + + // Call save yob + result, err := h.SaveOfferings(context.Background(), "save_offerings", tt.input) + + if err != nil { + t.Fatalf("Failed to save offerings with error: %v", err) + } + savedData, err := h.accountFileHandler.ReadAccountData() + if err == nil { + //Assert that the input provided is what was saved into the file + assert.Equal(t, string(tt.input), savedData["Offerings"]) + } + + // Assert the results + assert.Equal(t, tt.expectedResult, result) + assert.Equal(t, tt.expectedError, err) + + // Assert all expectations were met + mockFileHandler.AssertExpectations(t) + }) + } +} + + +func TestSaveGender(t *testing.T) { + // Create a new instance of MockAccountFileHandler + mockFileHandler := new(mocks.MockAccountFileHandler) + + // Define test cases + tests := []struct { + name string + input []byte + existingData map[string]string + writeError error + expectedResult resource.Result + expectedError error + expectedGender string + }{ + { + name: "Successful Save - Male", + input: []byte("1"), + existingData: map[string]string{"OtherKey": "OtherValue"}, + writeError: nil, + expectedResult: resource.Result{}, + expectedError: nil, + expectedGender: "Male", + }, + { + name: "Successful Save - Female", + input: []byte("2"), + existingData: map[string]string{"OtherKey": "OtherValue"}, + writeError: nil, + expectedResult: resource.Result{}, + expectedError: nil, + expectedGender: "Female", + }, + { + name: "Successful Save - Unspecified", + input: []byte("3"), + existingData: map[string]string{"OtherKey": "OtherValue"}, + writeError: nil, + expectedResult: resource.Result{}, + expectedError: nil, + expectedGender: "Unspecified", + }, + + { + name: "Empty Input", + input: []byte{}, + existingData: map[string]string{"OtherKey": "OtherValue"}, + writeError: nil, + expectedResult: resource.Result{}, + expectedError: nil, + expectedGender: "", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Set up the mock expectations + mockFileHandler.On("ReadAccountData").Return(tt.existingData, tt.expectedError) + if tt.expectedError == nil && len(tt.input) > 0 { + mockFileHandler.On("WriteAccountData", mock.MatchedBy(func(data map[string]string) bool { + return data["Gender"] == tt.expectedGender + })).Return(tt.writeError) + } else if len(tt.input) == 0 { // For empty input, no WriteAccountData call should be made mockFileHandler.On("WriteAccountData", mock.Anything).Maybe().Return(tt.writeError) } @@ -385,14 +763,21 @@ func TestSaveLocation(t *testing.T) { } // Call the method - result, err := h.SaveLocation(context.Background(), "save_location", tt.input) + result, err := h.SaveGender(context.Background(), "save_gender", tt.input) // Assert the results assert.Equal(t, tt.expectedResult, result) assert.Equal(t, tt.expectedError, err) + // Verify WriteAccountData was called with the expected data + if len(tt.input) > 0 && tt.expectedError == nil { + mockFileHandler.AssertCalled(t, "WriteAccountData", mock.MatchedBy(func(data map[string]string) bool { + return data["Gender"] == tt.expectedGender + })) + } + // Assert all expectations were met mockFileHandler.AssertExpectations(t) }) } -} \ No newline at end of file +} From cc323707fc77e70c6e99d5236ae1bac60f90f6cf Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Sat, 31 Aug 2024 10:21:20 +0300 Subject: [PATCH 131/201] setup parser --- cmd/main.go | 6 +++++- internal/handlers/ussd/menuhandler.go | 24 +++++++++++++++--------- 2 files changed, 20 insertions(+), 10 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index 2daee8c..39136a9 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -83,7 +83,11 @@ func main() { fp := path.Join(dp, sessionId) - ussdHandlers := ussd.NewHandlers(fp, &st) + ussdHandlers,err := ussd.NewHandlers(fp, &st) + + if(err != nil){ + fmt.Fprintf(os.Stderr, "handler setup failed with error: %v\n", err) + } rfs.AddLocalFunc("select_language", ussdHandlers.SetLanguage) rfs.AddLocalFunc("create_account", ussdHandlers.CreateAccount) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 4eb2a83..f5776f1 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -9,6 +9,7 @@ import ( "strconv" "strings" + "git.defalsify.org/vise.git/asm" "git.defalsify.org/vise.git/engine" "git.defalsify.org/vise.git/lang" "git.defalsify.org/vise.git/resource" @@ -29,26 +30,31 @@ type FSData struct { St *state.State } - type Handlers struct { fs *FSData + parser *asm.FlagParser accountFileHandler utils.AccountFileHandlerInterface accountService server.AccountServiceInterface } -func NewHandlers(path string, st *state.State) *Handlers { +func NewHandlers(dir string, st *state.State) (*Handlers, error) { + pfp := path.Join(dir, "pp.csv") + parser := asm.NewFlagParser() + _, err := parser.Load(pfp) + if err != nil { + return nil, err + } return &Handlers{ fs: &FSData{ - Path: path, + Path: dir, St: st, }, - accountFileHandler: utils.NewAccountFileHandler(path + "_data"), + parser: parser, + accountFileHandler: utils.NewAccountFileHandler(dir + "_data"), accountService: &server.AccountService{}, - } + }, nil } - - // Define the regex pattern as a constant const pinPattern = `^\d{4}$` @@ -191,7 +197,7 @@ func (h *Handlers) VerifyPin(ctx context.Context, sym string, input []byte) (res return res, nil } -//codeFromCtx retrieves language codes from the context that can be used for handling translations +// codeFromCtx retrieves language codes from the context that can be used for handling translations func codeFromCtx(ctx context.Context) string { var code string engine.Logg.DebugCtxf(ctx, "in msg", "ctx", ctx, "val", code) @@ -446,7 +452,7 @@ func (h *Handlers) Quit(ctx context.Context, sym string, input []byte) (resource code := codeFromCtx(ctx) l := gotext.NewLocale(translationDir, code) l.AddDomain("default") - + res.Content = l.Get("Thank you for using Sarafu. Goodbye!") res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_AUTHORIZED) return res, nil From de4aaeb02b15aecb79e581460c5aef97e8712ade Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Sat, 31 Aug 2024 10:26:49 +0300 Subject: [PATCH 132/201] use script dir for parser --- internal/handlers/ussd/menuhandler.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index f5776f1..91f4a4e 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -38,7 +38,7 @@ type Handlers struct { } func NewHandlers(dir string, st *state.State) (*Handlers, error) { - pfp := path.Join(dir, "pp.csv") + pfp := path.Join(scriptDir, "pp.csv") parser := asm.NewFlagParser() _, err := parser.Load(pfp) if err != nil { From 828f9a17fc749336976243745b3ecc7ebed849fb Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Sat, 31 Aug 2024 10:28:11 +0300 Subject: [PATCH 133/201] Added the csv containing string flags --- services/registration/pp.csv | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 services/registration/pp.csv diff --git a/services/registration/pp.csv b/services/registration/pp.csv new file mode 100644 index 0000000..e9626cf --- /dev/null +++ b/services/registration/pp.csv @@ -0,0 +1,16 @@ +flag,language_set,8,checks whether the user has set their prefered language +flag,account_created,9,this is set when an account has been created on the API +flag,account_pending,10,this is set when an account does not have a status of SUCCESS +flag,account_success,11,this is set when an account has a status of SUCCESS +flag,account_authorized,12,this is set to allow a user access guarded nodes after providing a correct PIN +flag,invalid_recipient,13,this is set when the transaction recipient is invalid +flag,invalid_recipient_with_invite,14,this is set when the transaction recipient is valid but not on the platform +flag,incorrect_pin,15,this is set when the provided PIN is invalid or does not match the current account's PIN +flag,allow_update,16,this is set to allow a user to update their profile data +flag,invalid_amount,17,this is set when the given transaction amount is invalid +flag,pin_set,18,this is set when a newly registered user sets a PIN. This must be present for an account to access the main menu +flag,valid_pin,19,this is set when the given PIN is valid +flag,pin_mismatch,20,this is set when the confirmation PIN matches the initial PIN during registration +flag,incorrect_date_format,21,this is set when the given year of birth is invalid +flag,account_creation_failed,22,this is set when there's an error from the API during account creation +flag,single_edit,23,this is set to allow a user to edit a single profile item such as familyName From bcc73dec2353fc66c322c4a10929be45c525c29f Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Sat, 31 Aug 2024 11:27:47 +0300 Subject: [PATCH 134/201] Add the flag file during build --- services/registration/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/registration/Makefile b/services/registration/Makefile index 578ebc6..1863b0b 100644 --- a/services/registration/Makefile +++ b/services/registration/Makefile @@ -4,7 +4,7 @@ TXTS = $(wildcard ./*.txt.orig) # Rule to build .bin files from .vis files %.vis: - go run ../../go-vise/dev/asm $(basename $@).vis > $(basename $@).bin + go run ../../go-vise/dev/asm -f pp.csv $(basename $@).vis > $(basename $@).bin @echo "Built $(basename $@).bin from $(basename $@).vis" # Rule to copy .orig files to .txt From ec4201139a783e11f1859ec8927c86009597e115 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Sat, 31 Aug 2024 11:35:29 +0300 Subject: [PATCH 135/201] add _flag suffix --- services/registration/pp.csv | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/services/registration/pp.csv b/services/registration/pp.csv index e9626cf..538870a 100644 --- a/services/registration/pp.csv +++ b/services/registration/pp.csv @@ -1,16 +1,16 @@ -flag,language_set,8,checks whether the user has set their prefered language -flag,account_created,9,this is set when an account has been created on the API -flag,account_pending,10,this is set when an account does not have a status of SUCCESS -flag,account_success,11,this is set when an account has a status of SUCCESS -flag,account_authorized,12,this is set to allow a user access guarded nodes after providing a correct PIN -flag,invalid_recipient,13,this is set when the transaction recipient is invalid -flag,invalid_recipient_with_invite,14,this is set when the transaction recipient is valid but not on the platform -flag,incorrect_pin,15,this is set when the provided PIN is invalid or does not match the current account's PIN -flag,allow_update,16,this is set to allow a user to update their profile data -flag,invalid_amount,17,this is set when the given transaction amount is invalid -flag,pin_set,18,this is set when a newly registered user sets a PIN. This must be present for an account to access the main menu -flag,valid_pin,19,this is set when the given PIN is valid -flag,pin_mismatch,20,this is set when the confirmation PIN matches the initial PIN during registration -flag,incorrect_date_format,21,this is set when the given year of birth is invalid -flag,account_creation_failed,22,this is set when there's an error from the API during account creation -flag,single_edit,23,this is set to allow a user to edit a single profile item such as familyName +flag,language_set_flag,8,checks whether the user has set their prefered language +flag,account_created_flag,9,this is set when an account has been created on the API +flag,account_pending_flag,10,this is set when an account does not have a status of SUCCESS +flag,account_success_flag,11,this is set when an account has a status of SUCCESS +flag,account_authorized_flag,12,this is set to allow a user access guarded nodes after providing a correct PIN +flag,invalid_recipient_flag,13,this is set when the transaction recipient is invalid +flag,invalid_recipient_with_invite_flag,14,this is set when the transaction recipient is valid but not on the platform +flag,incorrect_pin_flag,15,this is set when the provided PIN is invalid or does not match the current account's PIN +flag,allow_update_flag,16,this is set to allow a user to update their profile data +flag,invalid_amount_flag,17,this is set when the given transaction amount is invalid +flag,pin_set_flag,18,this is set when a newly registered user sets a PIN. This must be present for an account to access the main menu +flag,valid_pin_flag,19,this is set when the given PIN is valid +flag,pin_mismatch_flag,20,this is set when the confirmation PIN matches the initial PIN during registration +flag,incorrect_date_format_flag,21,this is set when the given year of birth is invalid +flag,account_creation_failed_flag,22,this is set when there's an error from the API during account creation +flag,single_edit_flag,23,this is set to allow a user to edit a single profile item such as familyName From 9fb3ef8e2a5fbb6a715f865fd721f299a18b7e03 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Sat, 31 Aug 2024 11:56:36 +0300 Subject: [PATCH 136/201] Use preprocessor flags --- services/registration/account_creation.vis | 2 +- services/registration/account_pending.vis | 2 +- services/registration/amount.vis | 2 +- services/registration/create_pin.vis | 4 ++-- services/registration/send.vis | 2 +- services/registration/transaction_pin.vis | 2 +- 6 files changed, 7 insertions(+), 7 deletions(-) diff --git a/services/registration/account_creation.vis b/services/registration/account_creation.vis index e3ecebb..1aca453 100644 --- a/services/registration/account_creation.vis +++ b/services/registration/account_creation.vis @@ -1,4 +1,4 @@ RELOAD verify_pin -CATCH create_pin_mismatch 20 1 +CATCH create_pin_mismatch pin_mismatch_flag 1 LOAD quit 0 HALT diff --git a/services/registration/account_pending.vis b/services/registration/account_pending.vis index 19e308c..a4baae5 100644 --- a/services/registration/account_pending.vis +++ b/services/registration/account_pending.vis @@ -1,3 +1,3 @@ RELOAD check_account_status -CATCH main 11 1 +CATCH main account_success_flag 1 HALT diff --git a/services/registration/amount.vis b/services/registration/amount.vis index 884c8a5..e134735 100644 --- a/services/registration/amount.vis +++ b/services/registration/amount.vis @@ -5,7 +5,7 @@ MOUT back 0 HALT LOAD validate_amount 64 RELOAD validate_amount -CATCH invalid_amount 17 1 +CATCH invalid_amount invalid_amount_flag 1 INCMP _ 0 LOAD get_recipient 12 LOAD get_sender 64 diff --git a/services/registration/create_pin.vis b/services/registration/create_pin.vis index 4994863..2755b1d 100644 --- a/services/registration/create_pin.vis +++ b/services/registration/create_pin.vis @@ -1,9 +1,9 @@ LOAD create_account 0 -CATCH account_creation_failed 22 1 +CATCH account_creation_failed account_creation_failed_flag 1 MOUT exit 0 HALT LOAD save_pin 0 RELOAD save_pin -CATCH . 15 1 +CATCH . incorrect_pin_flag 1 INCMP quit 0 INCMP confirm_create_pin * diff --git a/services/registration/send.vis b/services/registration/send.vis index d0fe211..5db5287 100644 --- a/services/registration/send.vis +++ b/services/registration/send.vis @@ -3,6 +3,6 @@ MOUT back 0 HALT LOAD validate_recipient 20 RELOAD validate_recipient -CATCH invalid_recipient 13 1 +CATCH invalid_recipient invalid_recipient_flag 1 INCMP _ 0 INCMP amount * diff --git a/services/registration/transaction_pin.vis b/services/registration/transaction_pin.vis index 5113b6c..19e0fcc 100644 --- a/services/registration/transaction_pin.vis +++ b/services/registration/transaction_pin.vis @@ -8,7 +8,7 @@ MOUT quit 9 HALT LOAD authorize_account 1 RELOAD authorize_account -CATCH incorrect_pin 15 1 +CATCH incorrect_pin incorrect_pin_flag 1 INCMP _ 0 INCMP quit 9 MOVE transaction_initiated From 4e69fa454d4b0df6603f8a987ffa9c42b3d7063c Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Sat, 31 Aug 2024 12:02:44 +0300 Subject: [PATCH 137/201] use string flags --- services/registration/community_balance.vis | 4 ++-- services/registration/enter_location.vis | 4 ++-- services/registration/enter_offerings.vis | 4 ++-- services/registration/enter_yob.vis | 4 ++-- services/registration/my_balance.vis | 4 ++-- services/registration/select_gender.vis | 4 ++-- services/registration/view_profile.vis | 4 ++-- 7 files changed, 14 insertions(+), 14 deletions(-) diff --git a/services/registration/community_balance.vis b/services/registration/community_balance.vis index 4894944..c25ced3 100644 --- a/services/registration/community_balance.vis +++ b/services/registration/community_balance.vis @@ -1,5 +1,5 @@ LOAD reset_incorrect 0 -CATCH incorrect_pin 15 1 -CATCH pin_entry 12 0 +CATCH incorrect_pin incorrect_pin_flag 1 +CATCH pin_entry account_authorized_flag 0 LOAD quit_with_balance 0 HALT diff --git a/services/registration/enter_location.vis b/services/registration/enter_location.vis index f6ccf77..6d9bc03 100644 --- a/services/registration/enter_location.vis +++ b/services/registration/enter_location.vis @@ -1,11 +1,11 @@ CATCH incorrect_date_format 21 1 LOAD save_yob 0 -CATCH update_success 16 1 +CATCH update_success allow_update_flag 1 MOUT back 0 HALT INCMP _ 0 LOAD save_location 0 -CATCH pin_entry 23 1 +CATCH pin_entry single_edit_flag 1 INCMP enter_offerings * diff --git a/services/registration/enter_offerings.vis b/services/registration/enter_offerings.vis index f48f1ea..9bc4407 100644 --- a/services/registration/enter_offerings.vis +++ b/services/registration/enter_offerings.vis @@ -1,6 +1,6 @@ LOAD save_location 0 -CATCH incorrect_pin 15 1 -CATCH update_success 16 1 +CATCH incorrect_pin incorrect_pin_flag 1 +CATCH update_success allow_update_flag 1 MOUT back 0 HALT LOAD save_offerings 0 diff --git a/services/registration/enter_yob.vis b/services/registration/enter_yob.vis index 3b3f0d2..46a3771 100644 --- a/services/registration/enter_yob.vis +++ b/services/registration/enter_yob.vis @@ -1,9 +1,9 @@ LOAD save_gender 0 -CATCH update_success 16 1 +CATCH update_success allow_update_flag 1 MOUT back 0 HALT INCMP _ 0 LOAD verify_yob 8 LOAD save_yob 0 -CATCH pin_entry 23 1 +CATCH pin_entry single_edit_flag 1 INCMP enter_location * diff --git a/services/registration/my_balance.vis b/services/registration/my_balance.vis index 4894944..c25ced3 100644 --- a/services/registration/my_balance.vis +++ b/services/registration/my_balance.vis @@ -1,5 +1,5 @@ LOAD reset_incorrect 0 -CATCH incorrect_pin 15 1 -CATCH pin_entry 12 0 +CATCH incorrect_pin incorrect_pin_flag 1 +CATCH pin_entry account_authorized_flag 0 LOAD quit_with_balance 0 HALT diff --git a/services/registration/select_gender.vis b/services/registration/select_gender.vis index 3029406..1159c64 100644 --- a/services/registration/select_gender.vis +++ b/services/registration/select_gender.vis @@ -1,12 +1,12 @@ LOAD save_familyname 0 -CATCH update_success 16 1 +CATCH update_success allow_update_flag 1 MOUT male 1 MOUT female 2 MOUT unspecified 3 MOUT back 0 HALT LOAD save_gender 0 -CATCH pin_entry 23 1 +CATCH pin_entry single_edit_flag 1 INCMP _ 0 INCMP enter_yob 1 INCMP enter_yob 2 diff --git a/services/registration/view_profile.vis b/services/registration/view_profile.vis index 8bf2b76..bf1196b 100644 --- a/services/registration/view_profile.vis +++ b/services/registration/view_profile.vis @@ -1,8 +1,8 @@ LOAD get_profile_info 0 MAP get_profile_info LOAD reset_incorrect 0 -CATCH incorrect_pin 15 1 -CATCH pin_entry 12 0 +CATCH incorrect_pin incorrect_pin_flag 1 +CATCH pin_entry account_authorized_flag 0 MOUT back 0 HALT INCMP _ 0 From 26959be149949d2dc16e1451cbdaa19996777099 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Sat, 31 Aug 2024 12:07:46 +0300 Subject: [PATCH 138/201] Fixed bug on transaction pin node --- services/registration/transaction_pin.vis | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/services/registration/transaction_pin.vis b/services/registration/transaction_pin.vis index 19e0fcc..5fcf2e7 100644 --- a/services/registration/transaction_pin.vis +++ b/services/registration/transaction_pin.vis @@ -11,5 +11,4 @@ RELOAD authorize_account CATCH incorrect_pin incorrect_pin_flag 1 INCMP _ 0 INCMP quit 9 -MOVE transaction_initiated - +INCMP transaction_initiated * From 42ab2dd577ebc0aabbc01a99fc5c0f6d18f59c99 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Sat, 31 Aug 2024 12:16:36 +0300 Subject: [PATCH 139/201] Use preprocessor flags --- services/registration/enter_location.vis | 5 +---- services/registration/root.vis | 10 +++++----- 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/services/registration/enter_location.vis b/services/registration/enter_location.vis index 6d9bc03..45c5c9a 100644 --- a/services/registration/enter_location.vis +++ b/services/registration/enter_location.vis @@ -1,4 +1,4 @@ -CATCH incorrect_date_format 21 1 +CATCH incorrect_date_format incorrect_date_format_flag 1 LOAD save_yob 0 CATCH update_success allow_update_flag 1 MOUT back 0 @@ -7,6 +7,3 @@ INCMP _ 0 LOAD save_location 0 CATCH pin_entry single_edit_flag 1 INCMP enter_offerings * - - - diff --git a/services/registration/root.vis b/services/registration/root.vis index 14b77f8..3074d25 100644 --- a/services/registration/root.vis +++ b/services/registration/root.vis @@ -1,7 +1,7 @@ -CATCH select_language 8 0 -CATCH terms 9 0 +CATCH select_language language_set_flag 0 +CATCH terms account_created_flag 0 LOAD check_account_status 0 -CATCH account_pending 10 1 -CATCH create_pin 18 0 -CATCH main 11 1 +CATCH account_pending account_pending_flag 1 +CATCH create_pin pin_set_flag 0 +CATCH main account_success_flag 1 HALT From 143c9b14a1745bce6394fce7486ed5bed9a415cb Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Sat, 31 Aug 2024 12:58:48 +0300 Subject: [PATCH 140/201] Renamed the flags --- services/registration/account_creation.vis | 2 +- services/registration/account_pending.vis | 2 +- services/registration/amount.vis | 2 +- services/registration/community_balance.vis | 4 +-- services/registration/create_pin.vis | 4 +-- services/registration/enter_location.vis | 6 ++-- services/registration/enter_offerings.vis | 4 +-- services/registration/enter_yob.vis | 4 +-- services/registration/my_balance.vis | 4 +-- services/registration/pp.csv | 32 ++++++++++----------- services/registration/root.vis | 10 +++---- services/registration/select_gender.vis | 4 +-- services/registration/send.vis | 2 +- services/registration/transaction_pin.vis | 2 +- services/registration/view_profile.vis | 4 +-- 15 files changed, 43 insertions(+), 43 deletions(-) diff --git a/services/registration/account_creation.vis b/services/registration/account_creation.vis index 1aca453..f4f326b 100644 --- a/services/registration/account_creation.vis +++ b/services/registration/account_creation.vis @@ -1,4 +1,4 @@ RELOAD verify_pin -CATCH create_pin_mismatch pin_mismatch_flag 1 +CATCH create_pin_mismatch flag_pin_mismatch 1 LOAD quit 0 HALT diff --git a/services/registration/account_pending.vis b/services/registration/account_pending.vis index a4baae5..d122613 100644 --- a/services/registration/account_pending.vis +++ b/services/registration/account_pending.vis @@ -1,3 +1,3 @@ RELOAD check_account_status -CATCH main account_success_flag 1 +CATCH main flag_account_success 1 HALT diff --git a/services/registration/amount.vis b/services/registration/amount.vis index e134735..9b2970a 100644 --- a/services/registration/amount.vis +++ b/services/registration/amount.vis @@ -5,7 +5,7 @@ MOUT back 0 HALT LOAD validate_amount 64 RELOAD validate_amount -CATCH invalid_amount invalid_amount_flag 1 +CATCH invalid_amount flag_invalid_amount 1 INCMP _ 0 LOAD get_recipient 12 LOAD get_sender 64 diff --git a/services/registration/community_balance.vis b/services/registration/community_balance.vis index c25ced3..151c6d8 100644 --- a/services/registration/community_balance.vis +++ b/services/registration/community_balance.vis @@ -1,5 +1,5 @@ LOAD reset_incorrect 0 -CATCH incorrect_pin incorrect_pin_flag 1 -CATCH pin_entry account_authorized_flag 0 +CATCH incorrect_pin flag_incorrect_pin 1 +CATCH pin_entry flag_account_authorized 0 LOAD quit_with_balance 0 HALT diff --git a/services/registration/create_pin.vis b/services/registration/create_pin.vis index 2755b1d..e0e330f 100644 --- a/services/registration/create_pin.vis +++ b/services/registration/create_pin.vis @@ -1,9 +1,9 @@ LOAD create_account 0 -CATCH account_creation_failed account_creation_failed_flag 1 +CATCH account_creation_failed flag_account_creation_failed 1 MOUT exit 0 HALT LOAD save_pin 0 RELOAD save_pin -CATCH . incorrect_pin_flag 1 +CATCH . flag_incorrect_pin 1 INCMP quit 0 INCMP confirm_create_pin * diff --git a/services/registration/enter_location.vis b/services/registration/enter_location.vis index 45c5c9a..00bed3d 100644 --- a/services/registration/enter_location.vis +++ b/services/registration/enter_location.vis @@ -1,9 +1,9 @@ -CATCH incorrect_date_format incorrect_date_format_flag 1 +CATCH incorrect_date_format flag_incorrect_date_format 1 LOAD save_yob 0 -CATCH update_success allow_update_flag 1 +CATCH update_success flag_allow_update 1 MOUT back 0 HALT INCMP _ 0 LOAD save_location 0 -CATCH pin_entry single_edit_flag 1 +CATCH pin_entry flag_single_edit 1 INCMP enter_offerings * diff --git a/services/registration/enter_offerings.vis b/services/registration/enter_offerings.vis index 9bc4407..e590321 100644 --- a/services/registration/enter_offerings.vis +++ b/services/registration/enter_offerings.vis @@ -1,6 +1,6 @@ LOAD save_location 0 -CATCH incorrect_pin incorrect_pin_flag 1 -CATCH update_success allow_update_flag 1 +CATCH incorrect_pin flag_incorrect_pin 1 +CATCH update_success flag_allow_update 1 MOUT back 0 HALT LOAD save_offerings 0 diff --git a/services/registration/enter_yob.vis b/services/registration/enter_yob.vis index 46a3771..3b27846 100644 --- a/services/registration/enter_yob.vis +++ b/services/registration/enter_yob.vis @@ -1,9 +1,9 @@ LOAD save_gender 0 -CATCH update_success allow_update_flag 1 +CATCH update_success flag_allow_update 1 MOUT back 0 HALT INCMP _ 0 LOAD verify_yob 8 LOAD save_yob 0 -CATCH pin_entry single_edit_flag 1 +CATCH pin_entry flag_single_edit 1 INCMP enter_location * diff --git a/services/registration/my_balance.vis b/services/registration/my_balance.vis index c25ced3..151c6d8 100644 --- a/services/registration/my_balance.vis +++ b/services/registration/my_balance.vis @@ -1,5 +1,5 @@ LOAD reset_incorrect 0 -CATCH incorrect_pin incorrect_pin_flag 1 -CATCH pin_entry account_authorized_flag 0 +CATCH incorrect_pin flag_incorrect_pin 1 +CATCH pin_entry flag_account_authorized 0 LOAD quit_with_balance 0 HALT diff --git a/services/registration/pp.csv b/services/registration/pp.csv index 538870a..0501c1a 100644 --- a/services/registration/pp.csv +++ b/services/registration/pp.csv @@ -1,16 +1,16 @@ -flag,language_set_flag,8,checks whether the user has set their prefered language -flag,account_created_flag,9,this is set when an account has been created on the API -flag,account_pending_flag,10,this is set when an account does not have a status of SUCCESS -flag,account_success_flag,11,this is set when an account has a status of SUCCESS -flag,account_authorized_flag,12,this is set to allow a user access guarded nodes after providing a correct PIN -flag,invalid_recipient_flag,13,this is set when the transaction recipient is invalid -flag,invalid_recipient_with_invite_flag,14,this is set when the transaction recipient is valid but not on the platform -flag,incorrect_pin_flag,15,this is set when the provided PIN is invalid or does not match the current account's PIN -flag,allow_update_flag,16,this is set to allow a user to update their profile data -flag,invalid_amount_flag,17,this is set when the given transaction amount is invalid -flag,pin_set_flag,18,this is set when a newly registered user sets a PIN. This must be present for an account to access the main menu -flag,valid_pin_flag,19,this is set when the given PIN is valid -flag,pin_mismatch_flag,20,this is set when the confirmation PIN matches the initial PIN during registration -flag,incorrect_date_format_flag,21,this is set when the given year of birth is invalid -flag,account_creation_failed_flag,22,this is set when there's an error from the API during account creation -flag,single_edit_flag,23,this is set to allow a user to edit a single profile item such as familyName +flag,flag_language_set,8,checks whether the user has set their prefered language +flag,flag_account_created,9,this is set when an account has been created on the API +flag,flag_account_pending,10,this is set when an account does not have a status of SUCCESS +flag,flag_account_success,11,this is set when an account has a status of SUCCESS +flag,flag_account_authorized,12,this is set to allow a user access guarded nodes after providing a correct PIN +flag,flag_invalid_recipient,13,this is set when the transaction recipient is invalid +flag,flag_invalid_recipient_with_invite,14,this is set when the transaction recipient is valid but not on the platform +flag,flag_incorrect_pin,15,this is set when the provided PIN is invalid or does not match the current account's PIN +flag,flag_allow_update,16,this is set to allow a user to update their profile data +flag,flag_invalid_amount,17,this is set when the given transaction amount is invalid +flag,flag_pin_set,18,this is set when a newly registered user sets a PIN. This must be present for an account to access the main menu +flag,flag_valid_pin,19,this is set when the given PIN is valid +flag,flag_pin_mismatch,20,this is set when the confirmation PIN matches the initial PIN during registration +flag,flag_incorrect_date_format,21,this is set when the given year of birth is invalid +flag,flag_account_creation_failed,22,this is set when there's an error from the API during account creation +flag,flag_single_edit,23,this is set to allow a user to edit a single profile item such as year of birth diff --git a/services/registration/root.vis b/services/registration/root.vis index 3074d25..6e3b79d 100644 --- a/services/registration/root.vis +++ b/services/registration/root.vis @@ -1,7 +1,7 @@ -CATCH select_language language_set_flag 0 -CATCH terms account_created_flag 0 +CATCH select_language flag_language_set 0 +CATCH terms flag_account_created 0 LOAD check_account_status 0 -CATCH account_pending account_pending_flag 1 -CATCH create_pin pin_set_flag 0 -CATCH main account_success_flag 1 +CATCH account_pending flag_account_pending 1 +CATCH create_pin flag_pin_set 0 +CATCH main flag_account_success 1 HALT diff --git a/services/registration/select_gender.vis b/services/registration/select_gender.vis index 1159c64..dd354fc 100644 --- a/services/registration/select_gender.vis +++ b/services/registration/select_gender.vis @@ -1,12 +1,12 @@ LOAD save_familyname 0 -CATCH update_success allow_update_flag 1 +CATCH update_success flag_allow_update 1 MOUT male 1 MOUT female 2 MOUT unspecified 3 MOUT back 0 HALT LOAD save_gender 0 -CATCH pin_entry single_edit_flag 1 +CATCH pin_entry flag_single_edit 1 INCMP _ 0 INCMP enter_yob 1 INCMP enter_yob 2 diff --git a/services/registration/send.vis b/services/registration/send.vis index 5db5287..e120302 100644 --- a/services/registration/send.vis +++ b/services/registration/send.vis @@ -3,6 +3,6 @@ MOUT back 0 HALT LOAD validate_recipient 20 RELOAD validate_recipient -CATCH invalid_recipient invalid_recipient_flag 1 +CATCH invalid_recipient flag_invalid_recipient 1 INCMP _ 0 INCMP amount * diff --git a/services/registration/transaction_pin.vis b/services/registration/transaction_pin.vis index 5fcf2e7..878104c 100644 --- a/services/registration/transaction_pin.vis +++ b/services/registration/transaction_pin.vis @@ -8,7 +8,7 @@ MOUT quit 9 HALT LOAD authorize_account 1 RELOAD authorize_account -CATCH incorrect_pin incorrect_pin_flag 1 +CATCH incorrect_pin flag_incorrect_pin 1 INCMP _ 0 INCMP quit 9 INCMP transaction_initiated * diff --git a/services/registration/view_profile.vis b/services/registration/view_profile.vis index bf1196b..2d0a508 100644 --- a/services/registration/view_profile.vis +++ b/services/registration/view_profile.vis @@ -1,8 +1,8 @@ LOAD get_profile_info 0 MAP get_profile_info LOAD reset_incorrect 0 -CATCH incorrect_pin incorrect_pin_flag 1 -CATCH pin_entry account_authorized_flag 0 +CATCH incorrect_pin flag_incorrect_pin 1 +CATCH pin_entry flag_account_authorized 0 MOUT back 0 HALT INCMP _ 0 From c3c5c836629c0006045581a92e85ef4ec063c6aa Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Sat, 31 Aug 2024 14:48:02 +0300 Subject: [PATCH 141/201] Change the order of flags --- internal/models/flags.go | 12 ++++++------ services/registration/pp.csv | 28 ++++++++++++++-------------- 2 files changed, 20 insertions(+), 20 deletions(-) diff --git a/internal/models/flags.go b/internal/models/flags.go index ba6d617..b64222c 100644 --- a/internal/models/flags.go +++ b/internal/models/flags.go @@ -5,18 +5,18 @@ import "git.defalsify.org/vise.git/state" const ( USERFLAG_LANGUAGE_SET = iota + state.FLAG_USERSTART USERFLAG_ACCOUNT_CREATED + USERFLAG_ACCOUNT_CREATION_FAILED USERFLAG_ACCOUNT_PENDING USERFLAG_ACCOUNT_SUCCESS + USERFLAG_PINMISMATCH + USERFLAG_PIN_SET USERFLAG_ACCOUNT_AUTHORIZED USERFLAG_INVALID_RECIPIENT USERFLAG_INVALID_RECIPIENT_WITH_INVITE - USERFLAG_INCORRECTPIN - USERFLAG_ALLOW_UPDATE USERFLAG_INVALID_AMOUNT - USERFLAG_PIN_SET + USERFLAG_INCORRECTPIN USERFLAG_VALIDPIN - USERFLAG_PINMISMATCH - USERFLAG_INCORRECTDATEFORMAT - USERFLAG_ACCOUNT_CREATION_FAILED + USERFLAG_ALLOW_UPDATE USERFLAG_SINGLE_EDIT + USERFLAG_INCORRECTDATEFORMAT ) diff --git a/services/registration/pp.csv b/services/registration/pp.csv index 0501c1a..fd552e4 100644 --- a/services/registration/pp.csv +++ b/services/registration/pp.csv @@ -1,16 +1,16 @@ flag,flag_language_set,8,checks whether the user has set their prefered language flag,flag_account_created,9,this is set when an account has been created on the API -flag,flag_account_pending,10,this is set when an account does not have a status of SUCCESS -flag,flag_account_success,11,this is set when an account has a status of SUCCESS -flag,flag_account_authorized,12,this is set to allow a user access guarded nodes after providing a correct PIN -flag,flag_invalid_recipient,13,this is set when the transaction recipient is invalid -flag,flag_invalid_recipient_with_invite,14,this is set when the transaction recipient is valid but not on the platform -flag,flag_incorrect_pin,15,this is set when the provided PIN is invalid or does not match the current account's PIN -flag,flag_allow_update,16,this is set to allow a user to update their profile data -flag,flag_invalid_amount,17,this is set when the given transaction amount is invalid -flag,flag_pin_set,18,this is set when a newly registered user sets a PIN. This must be present for an account to access the main menu -flag,flag_valid_pin,19,this is set when the given PIN is valid -flag,flag_pin_mismatch,20,this is set when the confirmation PIN matches the initial PIN during registration -flag,flag_incorrect_date_format,21,this is set when the given year of birth is invalid -flag,flag_account_creation_failed,22,this is set when there's an error from the API during account creation -flag,flag_single_edit,23,this is set to allow a user to edit a single profile item such as year of birth +flag,flag_account_creation_failed,10,this is set when there's an error from the API during account creation +flag,flag_account_pending,11,this is set when an account does not have a status of SUCCESS +flag,flag_account_success,12,this is set when an account has a status of SUCCESS +flag,flag_pin_mismatch,13,this is set when the confirmation PIN matches the initial PIN during registration +flag,flag_pin_set,14,this is set when a newly registered user sets a PIN. This must be present for an account to access the main menu +flag,flag_account_authorized,15,this is set to allow a user access guarded nodes after providing a correct PIN +flag,flag_invalid_recipient,16,this is set when the transaction recipient is invalid +flag,flag_invalid_recipient_with_invite,17,this is set when the transaction recipient is valid but not on the platform +flag,flag_invalid_amount,18,this is set when the given transaction amount is invalid +flag,flag_incorrect_pin,19,this is set when the provided PIN is invalid or does not match the current account's PIN +flag,flag_valid_pin,20,this is set when the given PIN is valid +flag,flag_allow_update,21,this is set to allow a user to update their profile data +flag,flag_single_edit,22,this is set to allow a user to edit a single profile item such as year of birth +flag,flag_incorrect_date_format,23,this is set when the given year of birth is invalid From 460e6fa2c8b46519393f3713ea4fe0aa85faad82 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Sat, 31 Aug 2024 14:50:45 +0300 Subject: [PATCH 142/201] Renamed duplicate flag --- cmd/main.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/main.go b/cmd/main.go index 39136a9..26ad520 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -48,7 +48,7 @@ func main() { state.FlagDebugger.Register(models.USERFLAG_INVALID_AMOUNT, "INVALIDAMOUNT") state.FlagDebugger.Register(models.USERFLAG_ALLOW_UPDATE, "UNLOCKFORUPDATE") state.FlagDebugger.Register(models.USERFLAG_VALIDPIN, "VALIDPIN") - state.FlagDebugger.Register(models.USERFLAG_VALIDPIN, "ACCOUNTUNLOCKED") + state.FlagDebugger.Register(models.USERFLAG_ACCOUNT_AUTHORIZED, "ACCOUNT_AUTHORIZED") state.FlagDebugger.Register(models.USERFLAG_ACCOUNT_CREATION_FAILED, "ACCOUNT_CREATION_FAILED") state.FlagDebugger.Register(models.USERFLAG_SINGLE_EDIT, "SINGLEEDIT") From 2559b4e6048d7007c6095f95dd5aa041811fa495 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Sat, 31 Aug 2024 14:55:54 +0300 Subject: [PATCH 143/201] add test profile --- internal/handlers/ussd/menuhandler_test.go | 98 +++++++++++++++++++++- 1 file changed, 95 insertions(+), 3 deletions(-) diff --git a/internal/handlers/ussd/menuhandler_test.go b/internal/handlers/ussd/menuhandler_test.go index 5755092..79c0c47 100644 --- a/internal/handlers/ussd/menuhandler_test.go +++ b/internal/handlers/ussd/menuhandler_test.go @@ -3,6 +3,7 @@ package ussd import ( "context" "encoding/json" + "fmt" "os" "path/filepath" "testing" @@ -690,7 +691,6 @@ func TestSaveOfferings(t *testing.T) { } } - func TestSaveGender(t *testing.T) { // Create a new instance of MockAccountFileHandler mockFileHandler := new(mocks.MockAccountFileHandler) @@ -732,7 +732,7 @@ func TestSaveGender(t *testing.T) { expectedError: nil, expectedGender: "Unspecified", }, - + { name: "Empty Input", input: []byte{}, @@ -752,7 +752,7 @@ func TestSaveGender(t *testing.T) { mockFileHandler.On("WriteAccountData", mock.MatchedBy(func(data map[string]string) bool { return data["Gender"] == tt.expectedGender })).Return(tt.writeError) - } else if len(tt.input) == 0 { + } else if len(tt.input) == 0 { // For empty input, no WriteAccountData call should be made mockFileHandler.On("WriteAccountData", mock.Anything).Maybe().Return(tt.writeError) } @@ -876,3 +876,95 @@ func TestGetAmount(t *testing.T) { } } +func TestGetProfileInfo(t *testing.T) { + tests := []struct { + name string + accountData map[string]string + readError error + expectedResult resource.Result + expectedError error + }{ + { + name: "Complete Profile", + accountData: map[string]string{ + "FirstName": "John", + "FamilyName": "Doe", + "Gender": "Male", + "YOB": "1980", + "Location": "Mombasa", + "Offerings": "Product A", + }, + readError: nil, + expectedResult: resource.Result{ + Content: fmt.Sprintf( + "Name: %s %s\nGender: %s\nAge: %d\nLocation: %s\nYou provide: %s\n", + "John", "Doe", "Male", 44, "Mombasa", "Product A", + ), + }, + expectedError: nil, + }, + { + name: "Profile with Not Provided Fields", + accountData: map[string]string{ + "FirstName": "Not provided", + "FamilyName": "Doe", + "Gender": "Female", + "YOB": "1995", + "Location": "Not provided", + "Offerings": "Service B", + }, + readError: nil, + expectedResult: resource.Result{ + Content: fmt.Sprintf( + "Name: %s\nGender: %s\nAge: %d\nLocation: %s\nYou provide: %s\n", + "Not provided", "Female", 29, "Not provided", "Service B", + ), + }, + expectedError: nil, + }, + { + name: "Profile with YOB as Not provided", + accountData: map[string]string{ + "FirstName": "Not provided", + "FamilyName": "Doe", + "Gender": "Female", + "YOB": "Not provided", + "Location": "Not provided", + "Offerings": "Service B", + }, + readError: nil, + expectedResult: resource.Result{ + Content: fmt.Sprintf( + "Name: %s\nGender: %s\nAge: %s\nLocation: %s\nYou provide: %s\n", + "Not provided", "Female", "Not provided", "Not provided", "Service B", + ), + }, + expectedError: nil, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Create a new instance of MockAccountFileHandler + mockFileHandler := new(mocks.MockAccountFileHandler) + + // Set up the mock expectations + mockFileHandler.On("ReadAccountData").Return(tt.accountData, tt.readError) + + // Create the Handlers instance with the mock file handler + h := &Handlers{ + accountFileHandler: mockFileHandler, + } + + // Call the method + result, err := h.GetProfileInfo(context.Background(), "get_profile_info", nil) + + // Assert the results + assert.Equal(t, tt.expectedResult, result) + assert.Equal(t, tt.expectedError, err) + + // Assert all expectations were met + mockFileHandler.AssertExpectations(t) + }) + } +} \ No newline at end of file From 07c8638a6d312463ce0f87ff79b52c9dda3c8ea0 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Sat, 31 Aug 2024 15:09:34 +0300 Subject: [PATCH 144/201] use correct symbol name --- services/registration/balances.vis | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/registration/balances.vis b/services/registration/balances.vis index 552acdb..dd14501 100644 --- a/services/registration/balances.vis +++ b/services/registration/balances.vis @@ -1,4 +1,4 @@ -LOAD reset_unlocked 0 +LOAD reset_account_authorized 0 MOUT my_balance 1 MOUT community_balance 2 MOUT back 0 From 632dd860ffdfde2c61bcf99b95eef1a46dc50f58 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Sat, 31 Aug 2024 17:16:57 +0300 Subject: [PATCH 145/201] Use flags from pp.csv on the Authorize function --- internal/handlers/ussd/menuhandler.go | 41 +++++++++++++++++++++------ 1 file changed, 32 insertions(+), 9 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 91f4a4e..a0ce8b5 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -64,6 +64,18 @@ func isValidPIN(pin string) bool { return match } +func (h *Handlers) PreloadFlags(flagKeys []string) (map[string]uint32, error) { + flags := make(map[string]uint32) + for _, key := range flagKeys { + flag, err := h.parser.GetFlag(key) + if err != nil { + return nil, err + } + flags[key] = flag + } + return flags, nil +} + // SetLanguage sets the language across the menu func (h *Handlers) SetLanguage(ctx context.Context, sym string, input []byte) (resource.Result, error) { inputStr := string(input) @@ -385,19 +397,25 @@ func (h *Handlers) Authorize(ctx context.Context, sym string, input []byte) (res return res, err } + // Preload the required flags + flagKeys := []string{"flag_incorrect_pin", "flag_account_authorized", "flag_allow_update"} + flags, err := h.PreloadFlags(flagKeys) + if err != nil { + return res, err + } + if len(input) == 4 { if pin != accountData["AccountPIN"] { - res.FlagSet = append(res.FlagSet, models.USERFLAG_INCORRECTPIN) - res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_AUTHORIZED) + res.FlagSet = append(res.FlagSet, flags["flag_incorrect_pin"]) + res.FlagReset = append(res.FlagReset, flags["flag_account_authorized"]) return res, nil } - if h.fs.St.MatchFlag(models.USERFLAG_ACCOUNT_AUTHORIZED, false) { - res.FlagReset = append(res.FlagReset, models.USERFLAG_INCORRECTPIN) - res.FlagSet = append(res.FlagSet, models.USERFLAG_ALLOW_UPDATE) - res.FlagSet = append(res.FlagSet, models.USERFLAG_ACCOUNT_AUTHORIZED) + if h.fs.St.MatchFlag(flags["flag_account_authorized"], false) { + res.FlagReset = append(res.FlagReset, flags["flag_incorrect_pin"]) + res.FlagSet = append(res.FlagSet, flags["flag_allow_update"], flags["flag_account_authorized"]) } else { - res.FlagSet = append(res.FlagSet, models.USERFLAG_ALLOW_UPDATE) - res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_AUTHORIZED) + res.FlagSet = append(res.FlagSet, flags["flag_allow_update"]) + res.FlagReset = append(res.FlagReset, flags["flag_account_authorized"]) } } return res, nil @@ -780,6 +798,11 @@ func (h *Handlers) InitiateTransaction(ctx context.Context, sym string, input [] return res, err } - res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_AUTHORIZED) + account_authorized_flag, err := h.parser.GetFlag("flag_account_authorized") + + if err != nil { + res.FlagReset = append(res.FlagReset, account_authorized_flag) + } + return res, nil } From ba4d0abcdadfc378879e7a2e0270640c367f4e6b Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Mon, 2 Sep 2024 10:03:57 +0300 Subject: [PATCH 146/201] improve doc line --- internal/handlers/ussd/menuhandler.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index a0ce8b5..8c85414 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -496,7 +496,7 @@ func (h *Handlers) VerifyYob(ctx context.Context, sym string, input []byte) (res return res, nil } -// ResetIncorrectYob resets the incorrect date format after a new attempt +// ResetIncorrectYob resets the incorrect date format flag after a new attempt func (h *Handlers) ResetIncorrectYob(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} res.FlagReset = append(res.FlagReset, models.USERFLAG_INCORRECTDATEFORMAT) From 31be1fa22107ba12443eda7d1395a78aad71a9ce Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Mon, 2 Sep 2024 14:00:02 +0300 Subject: [PATCH 147/201] Use flags from pp.csv on the menuhandler functions and tests --- internal/handlers/ussd/menuhandler.go | 258 ++++++++++++++++----- internal/handlers/ussd/menuhandler_test.go | 55 +++-- 2 files changed, 236 insertions(+), 77 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index a0ce8b5..843b900 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -15,7 +15,6 @@ import ( "git.defalsify.org/vise.git/resource" "git.defalsify.org/vise.git/state" "git.grassecon.net/urdt/ussd/internal/handlers/server" - "git.grassecon.net/urdt/ussd/internal/models" "git.grassecon.net/urdt/ussd/internal/utils" "gopkg.in/leonelquinteros/gotext.v1" ) @@ -30,29 +29,33 @@ type FSData struct { St *state.State } +type FlagParserInterface interface { + GetFlag(key string) (uint32, error) +} + type Handlers struct { fs *FSData - parser *asm.FlagParser + parser FlagParserInterface accountFileHandler utils.AccountFileHandlerInterface accountService server.AccountServiceInterface } func NewHandlers(dir string, st *state.State) (*Handlers, error) { - pfp := path.Join(scriptDir, "pp.csv") - parser := asm.NewFlagParser() - _, err := parser.Load(pfp) - if err != nil { - return nil, err - } - return &Handlers{ - fs: &FSData{ - Path: dir, - St: st, - }, - parser: parser, - accountFileHandler: utils.NewAccountFileHandler(dir + "_data"), - accountService: &server.AccountService{}, - }, nil + pfp := path.Join(scriptDir, "pp.csv") + parser := asm.NewFlagParser() + _, err := parser.Load(pfp) + if err != nil { + return nil, err + } + return &Handlers{ + fs: &FSData{ + Path: dir, + St: st, + }, + parser: parser, + accountFileHandler: utils.NewAccountFileHandler(dir + "_data"), + accountService: &server.AccountService{}, + }, nil } // Define the regex pattern as a constant @@ -78,8 +81,16 @@ func (h *Handlers) PreloadFlags(flagKeys []string) (map[string]uint32, error) { // SetLanguage sets the language across the menu func (h *Handlers) SetLanguage(ctx context.Context, sym string, input []byte) (resource.Result, error) { - inputStr := string(input) res := resource.Result{} + + // Preload the required flag + flagKeys := []string{"flag_language_set"} + flags, err := h.PreloadFlags(flagKeys) + if err != nil { + return res, err + } + + inputStr := string(input) switch inputStr { case "0": res.FlagSet = []uint32{state.FLAG_LANG} @@ -90,7 +101,7 @@ func (h *Handlers) SetLanguage(ctx context.Context, sym string, input []byte) (r default: } - res.FlagSet = append(res.FlagSet, models.USERFLAG_LANGUAGE_SET) + res.FlagSet = append(res.FlagSet, flags["flag_language_set"]) return res, nil } @@ -101,7 +112,14 @@ func (h *Handlers) SetLanguage(ctx context.Context, sym string, input []byte) (r func (h *Handlers) CreateAccount(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - err := h.accountFileHandler.EnsureFileExists() + // Preload the required flags + flagKeys := []string{"flag_account_created", "flag_account_creation_failed"} + flags, err := h.PreloadFlags(flagKeys) + if err != nil { + return res, err + } + + err = h.accountFileHandler.EnsureFileExists() if err != nil { return res, err } @@ -114,7 +132,7 @@ func (h *Handlers) CreateAccount(ctx context.Context, sym string, input []byte) accountResp, err := h.accountService.CreateAccount() if err != nil { - res.FlagSet = append(res.FlagSet, models.USERFLAG_ACCOUNT_CREATION_FAILED) + res.FlagSet = append(res.FlagSet, flags["flag_account_creation_failed"]) return res, err } @@ -135,13 +153,21 @@ func (h *Handlers) CreateAccount(ctx context.Context, sym string, input []byte) return res, err } - res.FlagSet = append(res.FlagSet, models.USERFLAG_ACCOUNT_CREATED) + res.FlagSet = append(res.FlagSet, flags["flag_account_created"]) return res, err } // SavePin persists the user's PIN choice into the filesystem func (h *Handlers) SavePin(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} + + // Preload the required flags + flagKeys := []string{"flag_incorrect_pin"} + flags, err := h.PreloadFlags(flagKeys) + if err != nil { + return res, err + } + accountPIN := string(input) accountData, err := h.accountFileHandler.ReadAccountData() @@ -151,11 +177,11 @@ func (h *Handlers) SavePin(ctx context.Context, sym string, input []byte) (resou // Validate that the PIN is a 4-digit number if !isValidPIN(accountPIN) { - res.FlagSet = append(res.FlagSet, models.USERFLAG_INCORRECTPIN) + res.FlagSet = append(res.FlagSet, flags["flag_incorrect_pin"]) return res, nil } - res.FlagReset = append(res.FlagReset, models.USERFLAG_INCORRECTPIN) + res.FlagReset = append(res.FlagReset, flags["flag_incorrect_pin"]) accountData["AccountPIN"] = accountPIN err = h.accountFileHandler.WriteAccountData(accountData) @@ -170,18 +196,26 @@ func (h *Handlers) SavePin(ctx context.Context, sym string, input []byte) (resou func (h *Handlers) SetResetSingleEdit(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} menuOption := string(input) + + // Preload the required flags + flagKeys := []string{"flag_allow_update", "flag_single_edit"} + flags, err := h.PreloadFlags(flagKeys) + if err != nil { + return res, err + } + switch menuOption { case "2": - res.FlagReset = append(res.FlagSet, models.USERFLAG_ALLOW_UPDATE) - res.FlagSet = append(res.FlagSet, models.USERFLAG_SINGLE_EDIT) + res.FlagReset = append(res.FlagSet, flags["flag_allow_update"]) + res.FlagSet = append(res.FlagSet, flags["flag_single_edit"]) case "3": - res.FlagReset = append(res.FlagSet, models.USERFLAG_ALLOW_UPDATE) - res.FlagSet = append(res.FlagSet, models.USERFLAG_SINGLE_EDIT) + res.FlagReset = append(res.FlagSet, flags["flag_allow_update"]) + res.FlagSet = append(res.FlagSet, flags["flag_single_edit"]) case "4": - res.FlagReset = append(res.FlagSet, models.USERFLAG_ALLOW_UPDATE) - res.FlagSet = append(res.FlagSet, models.USERFLAG_SINGLE_EDIT) + res.FlagReset = append(res.FlagSet, flags["flag_allow_update"]) + res.FlagSet = append(res.FlagSet, flags["flag_single_edit"]) default: - res.FlagReset = append(res.FlagReset, models.USERFLAG_SINGLE_EDIT) + res.FlagReset = append(res.FlagReset, flags["flag_single_edit"]) } return res, nil @@ -193,17 +227,24 @@ func (h *Handlers) SetResetSingleEdit(ctx context.Context, sym string, input []b func (h *Handlers) VerifyPin(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} + // Preload the required flags + flagKeys := []string{"flag_valid_pin", "flag_pin_mismatch", "flag_pin_set"} + flags, err := h.PreloadFlags(flagKeys) + if err != nil { + return res, err + } + accountData, err := h.accountFileHandler.ReadAccountData() if err != nil { return res, err } if bytes.Equal(input, []byte(accountData["AccountPIN"])) { - res.FlagSet = []uint32{models.USERFLAG_VALIDPIN} - res.FlagReset = []uint32{models.USERFLAG_PINMISMATCH} - res.FlagSet = append(res.FlagSet, models.USERFLAG_PIN_SET) + res.FlagSet = []uint32{flags["flag_valid_pin"]} + res.FlagReset = []uint32{flags["flag_pin_mismatch"]} + res.FlagSet = append(res.FlagSet, flags["flag_pin_set"]) } else { - res.FlagSet = []uint32{models.USERFLAG_PINMISMATCH} + res.FlagSet = []uint32{flags["flag_pin_mismatch"]} } return res, nil @@ -361,14 +402,30 @@ func (h *Handlers) SaveOfferings(ctx context.Context, sym string, input []byte) // ResetAllowUpdate resets the allowupdate flag that allows a user to update profile data. func (h *Handlers) ResetAllowUpdate(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - res.FlagReset = append(res.FlagReset, models.USERFLAG_ALLOW_UPDATE) + + // Preload the required flag + flagKeys := []string{"flag_allow_update"} + flags, err := h.PreloadFlags(flagKeys) + if err != nil { + return res, err + } + + res.FlagReset = append(res.FlagReset, flags["flag_allow_update"]) return res, nil } // ResetAccountAuthorized resets the account authorization flag after a successful PIN entry. func (h *Handlers) ResetAccountAuthorized(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_AUTHORIZED) + + // Preload the required flags + flagKeys := []string{"flag_account_authorized"} + flags, err := h.PreloadFlags(flagKeys) + if err != nil { + return res, err + } + + res.FlagReset = append(res.FlagReset, flags["flag_account_authorized"]) return res, nil } @@ -390,12 +447,6 @@ func (h *Handlers) CheckIdentifier(ctx context.Context, sym string, input []byte // It sets the required flags that control the flow. func (h *Handlers) Authorize(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - pin := string(input) - - accountData, err := h.accountFileHandler.ReadAccountData() - if err != nil { - return res, err - } // Preload the required flags flagKeys := []string{"flag_incorrect_pin", "flag_account_authorized", "flag_allow_update"} @@ -404,6 +455,13 @@ func (h *Handlers) Authorize(ctx context.Context, sym string, input []byte) (res return res, err } + pin := string(input) + + accountData, err := h.accountFileHandler.ReadAccountData() + if err != nil { + return res, err + } + if len(input) == 4 { if pin != accountData["AccountPIN"] { res.FlagSet = append(res.FlagSet, flags["flag_incorrect_pin"]) @@ -424,7 +482,15 @@ func (h *Handlers) Authorize(ctx context.Context, sym string, input []byte) (res // ResetIncorrectPin resets the incorrect pin flag after a new PIN attempt. func (h *Handlers) ResetIncorrectPin(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - res.FlagReset = append(res.FlagReset, models.USERFLAG_INCORRECTPIN) + + // Preload the required flag + flagKeys := []string{"flag_incorrect_pin"} + flags, err := h.PreloadFlags(flagKeys) + if err != nil { + return res, err + } + + res.FlagReset = append(res.FlagReset, flags["flag_incorrect_pin"]) return res, nil } @@ -433,6 +499,13 @@ func (h *Handlers) ResetIncorrectPin(ctx context.Context, sym string, input []by func (h *Handlers) CheckAccountStatus(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} + // Preload the required flags + flagKeys := []string{"flag_account_success", "flag_account_pending"} + flags, err := h.PreloadFlags(flagKeys) + if err != nil { + return res, err + } + accountData, err := h.accountFileHandler.ReadAccountData() if err != nil { return res, err @@ -448,11 +521,11 @@ func (h *Handlers) CheckAccountStatus(ctx context.Context, sym string, input []b accountData["Status"] = status if status == "SUCCESS" { - res.FlagSet = append(res.FlagSet, models.USERFLAG_ACCOUNT_SUCCESS) - res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_PENDING) + res.FlagSet = append(res.FlagSet, flags["flag_account_success"]) + res.FlagReset = append(res.FlagReset, flags["flag_account_pending"]) } else { - res.FlagReset = append(res.FlagSet, models.USERFLAG_ACCOUNT_SUCCESS) - res.FlagSet = append(res.FlagReset, models.USERFLAG_ACCOUNT_PENDING) + res.FlagReset = append(res.FlagSet, flags["flag_account_success"]) + res.FlagSet = append(res.FlagReset, flags["flag_account_pending"]) } err = h.accountFileHandler.WriteAccountData(accountData) @@ -467,30 +540,45 @@ func (h *Handlers) CheckAccountStatus(ctx context.Context, sym string, input []b func (h *Handlers) Quit(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} + // Preload the required flags + flagKeys := []string{"flag_account_authorized"} + flags, err := h.PreloadFlags(flagKeys) + if err != nil { + return res, err + } + code := codeFromCtx(ctx) l := gotext.NewLocale(translationDir, code) l.AddDomain("default") res.Content = l.Get("Thank you for using Sarafu. Goodbye!") - res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_AUTHORIZED) + res.FlagReset = append(res.FlagReset, flags["flag_account_authorized"]) return res, nil } // VerifyYob verifies the length of the given input func (h *Handlers) VerifyYob(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} + + // Preload the required flag + flagKeys := []string{"flag_incorrect_date_format"} + flags, err := h.PreloadFlags(flagKeys) + if err != nil { + return res, err + } + date := string(input) - _, err := strconv.Atoi(date) + _, err = strconv.Atoi(date) if err != nil { // If conversion fails, input is not numeric - res.FlagSet = append(res.FlagSet, models.USERFLAG_INCORRECTDATEFORMAT) + res.FlagSet = append(res.FlagSet, flags["flag_incorrect_date_format"]) return res, nil } if len(date) == 4 { - res.FlagReset = append(res.FlagReset, models.USERFLAG_INCORRECTDATEFORMAT) + res.FlagReset = append(res.FlagReset, flags["flag_incorrect_date_format"]) } else { - res.FlagSet = append(res.FlagSet, models.USERFLAG_INCORRECTDATEFORMAT) + res.FlagSet = append(res.FlagSet, flags["flag_incorrect_date_format"]) } return res, nil @@ -499,7 +587,15 @@ func (h *Handlers) VerifyYob(ctx context.Context, sym string, input []byte) (res // ResetIncorrectYob resets the incorrect date format after a new attempt func (h *Handlers) ResetIncorrectYob(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - res.FlagReset = append(res.FlagReset, models.USERFLAG_INCORRECTDATEFORMAT) + + // Preload the required flags + flagKeys := []string{"flag_incorrect_date_format"} + flags, err := h.PreloadFlags(flagKeys) + if err != nil { + return res, err + } + + res.FlagReset = append(res.FlagReset, flags["flag_incorrect_date_format"]) return res, nil } @@ -525,6 +621,14 @@ func (h *Handlers) CheckBalance(ctx context.Context, sym string, input []byte) ( // ValidateRecipient validates that the given input is a valid phone number. func (h *Handlers) ValidateRecipient(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} + + // Preload the required flags + flagKeys := []string{"flag_invalid_recipient"} + flags, err := h.PreloadFlags(flagKeys) + if err != nil { + return res, err + } + recipient := string(input) accountData, err := h.accountFileHandler.ReadAccountData() @@ -535,7 +639,7 @@ func (h *Handlers) ValidateRecipient(ctx context.Context, sym string, input []by if recipient != "0" { // mimic invalid number check if recipient == "000" { - res.FlagSet = append(res.FlagSet, models.USERFLAG_INVALID_RECIPIENT) + res.FlagSet = append(res.FlagSet, flags["flag_invalid_recipient"]) res.Content = recipient return res, nil @@ -556,6 +660,14 @@ func (h *Handlers) ValidateRecipient(ctx context.Context, sym string, input []by // as well as the invalid flags func (h *Handlers) TransactionReset(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} + + // Preload the required flags + flagKeys := []string{"flag_invalid_recipient", "flag_invalid_recipient_with_invite"} + flags, err := h.PreloadFlags(flagKeys) + if err != nil { + return res, err + } + accountData, err := h.accountFileHandler.ReadAccountData() if err != nil { return res, err @@ -570,7 +682,7 @@ func (h *Handlers) TransactionReset(ctx context.Context, sym string, input []byt return res, err } - res.FlagReset = append(res.FlagReset, models.USERFLAG_INVALID_RECIPIENT, models.USERFLAG_INVALID_RECIPIENT_WITH_INVITE) + res.FlagReset = append(res.FlagReset, flags["flag_invalid_recipient"], flags["flag_invalid_recipient_with_invite"]) return res, nil } @@ -578,6 +690,14 @@ func (h *Handlers) TransactionReset(ctx context.Context, sym string, input []byt // ResetTransactionAmount resets the transaction amount and invalid flag func (h *Handlers) ResetTransactionAmount(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} + + // Preload the required flag + flagKeys := []string{"flag_invalid_amount"} + flags, err := h.PreloadFlags(flagKeys) + if err != nil { + return res, err + } + accountData, err := h.accountFileHandler.ReadAccountData() if err != nil { return res, err @@ -591,7 +711,7 @@ func (h *Handlers) ResetTransactionAmount(ctx context.Context, sym string, input return res, err } - res.FlagReset = append(res.FlagReset, models.USERFLAG_INVALID_AMOUNT) + res.FlagReset = append(res.FlagReset, flags["flag_invalid_amount"]) return res, nil } @@ -620,6 +740,14 @@ func (h *Handlers) MaxAmount(ctx context.Context, sym string, input []byte) (res // it is not more than the current balance. func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} + + // Preload the required flag + flagKeys := []string{"flag_invalid_amount"} + flags, err := h.PreloadFlags(flagKeys) + if err != nil { + return res, err + } + amountStr := string(input) accountData, err := h.accountFileHandler.ReadAccountData() @@ -647,20 +775,20 @@ func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte) re := regexp.MustCompile(`^(\d+(\.\d+)?)\s*(?:CELO)?$`) matches := re.FindStringSubmatch(strings.TrimSpace(amountStr)) if len(matches) < 2 { - res.FlagSet = append(res.FlagSet, models.USERFLAG_INVALID_AMOUNT) + res.FlagSet = append(res.FlagSet, flags["flag_invalid_amount"]) res.Content = amountStr return res, nil } inputAmount, err := strconv.ParseFloat(matches[1], 64) if err != nil { - res.FlagSet = append(res.FlagSet, models.USERFLAG_INVALID_AMOUNT) + res.FlagSet = append(res.FlagSet, flags["flag_invalid_amount"]) res.Content = amountStr return res, nil } if inputAmount > balanceValue { - res.FlagSet = append(res.FlagSet, models.USERFLAG_INVALID_AMOUNT) + res.FlagSet = append(res.FlagSet, flags["flag_invalid_amount"]) res.Content = amountStr return res, nil } @@ -755,6 +883,14 @@ func (h *Handlers) GetAmount(ctx context.Context, sym string, input []byte) (res // gracefully exiting the session. func (h *Handlers) QuitWithBalance(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} + + // Preload the required flag + flagKeys := []string{"flag_account_authorized"} + flags, err := h.PreloadFlags(flagKeys) + if err != nil { + return res, err + } + code := codeFromCtx(ctx) l := gotext.NewLocale(translationDir, code) l.AddDomain("default") @@ -767,7 +903,7 @@ func (h *Handlers) QuitWithBalance(ctx context.Context, sym string, input []byte return res, nil } res.Content = l.Get("Your account balance is %s", balance) - res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_AUTHORIZED) + res.FlagReset = append(res.FlagReset, flags["flag_account_authorized"]) return res, nil } diff --git a/internal/handlers/ussd/menuhandler_test.go b/internal/handlers/ussd/menuhandler_test.go index 79c0c47..5bcf7c1 100644 --- a/internal/handlers/ussd/menuhandler_test.go +++ b/internal/handlers/ussd/menuhandler_test.go @@ -21,6 +21,15 @@ type MockAccountService struct { mock.Mock } +type MockFlagParser struct { + mock.Mock +} + +func (m *MockFlagParser) GetFlag(key string) (uint32, error) { + args := m.Called(key) + return args.Get(0).(uint32), args.Error(1) +} + func (m *MockAccountService) CreateAccount() (*models.AccountResponse, error) { args := m.Called() return args.Get(0).(*models.AccountResponse), args.Error(1) @@ -70,11 +79,20 @@ func TestCreateAccount(t *testing.T) { // Set up expectations for the mock account service mockAccountService.On("CreateAccount").Return(mockAccountResponse, nil) + mockParser := new(MockFlagParser) + + flag_account_created := uint32(1) + flag_account_creation_failed := uint32(2) + + mockParser.On("GetFlag", "flag_account_created").Return(flag_account_created, nil) + mockParser.On("GetFlag", "flag_account_creation_failed").Return(flag_account_creation_failed, nil) + // Initialize Handlers with mock account service h := &Handlers{ fs: &FSData{Path: accountFilePath}, accountFileHandler: accountFileHandler, accountService: mockAccountService, + parser: mockParser, } tests := []struct { @@ -87,7 +105,7 @@ func TestCreateAccount(t *testing.T) { name: "New account creation", existingData: nil, expectedResult: resource.Result{ - FlagSet: []uint32{models.USERFLAG_ACCOUNT_CREATED}, + FlagSet: []uint32{flag_account_created}, }, expectedData: map[string]string{ "TrackingId": "test-tracking-id", @@ -248,10 +266,16 @@ func TestSavePin(t *testing.T) { // Create a new AccountFileHandler and set it in the Handlers struct accountFileHandler := utils.NewAccountFileHandler(accountFilePath) + mockParser := new(MockFlagParser) + h := &Handlers{ accountFileHandler: accountFileHandler, + parser: mockParser, } + flag_incorrect_pin := uint32(1) + mockParser.On("GetFlag", "flag_incorrect_pin").Return(flag_incorrect_pin, nil) + tests := []struct { name string input []byte @@ -272,21 +296,21 @@ func TestSavePin(t *testing.T) { { name: "Invalid PIN - non-numeric", input: []byte("12ab"), - expectedFlags: []uint32{models.USERFLAG_INCORRECTPIN}, + expectedFlags: []uint32{flag_incorrect_pin}, expectedData: initialAccountData, // No changes expected expectedErrors: false, }, { name: "Invalid PIN - less than 4 digits", input: []byte("123"), - expectedFlags: []uint32{models.USERFLAG_INCORRECTPIN}, + expectedFlags: []uint32{flag_incorrect_pin}, expectedData: initialAccountData, // No changes expected expectedErrors: false, }, { name: "Invalid PIN - more than 4 digits", input: []byte("12345"), - expectedFlags: []uint32{models.USERFLAG_INCORRECTPIN}, + expectedFlags: []uint32{flag_incorrect_pin}, expectedData: initialAccountData, // No changes expected expectedErrors: false, }, @@ -294,7 +318,6 @@ func TestSavePin(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - // Ensure the file exists before running the test err := accountFileHandler.EnsureFileExists() if err != nil { t.Fatalf("Failed to ensure account file exists: %v", err) @@ -906,12 +929,12 @@ func TestGetProfileInfo(t *testing.T) { { name: "Profile with Not Provided Fields", accountData: map[string]string{ - "FirstName": "Not provided", + "FirstName": "Not provided", "FamilyName": "Doe", - "Gender": "Female", - "YOB": "1995", - "Location": "Not provided", - "Offerings": "Service B", + "Gender": "Female", + "YOB": "1995", + "Location": "Not provided", + "Offerings": "Service B", }, readError: nil, expectedResult: resource.Result{ @@ -925,12 +948,12 @@ func TestGetProfileInfo(t *testing.T) { { name: "Profile with YOB as Not provided", accountData: map[string]string{ - "FirstName": "Not provided", + "FirstName": "Not provided", "FamilyName": "Doe", - "Gender": "Female", - "YOB": "Not provided", - "Location": "Not provided", - "Offerings": "Service B", + "Gender": "Female", + "YOB": "Not provided", + "Location": "Not provided", + "Offerings": "Service B", }, readError: nil, expectedResult: resource.Result{ @@ -967,4 +990,4 @@ func TestGetProfileInfo(t *testing.T) { mockFileHandler.AssertExpectations(t) }) } -} \ No newline at end of file +} From fe4df78f800ccf1d745ae15cd070acc5f8b1aaad Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Mon, 2 Sep 2024 16:04:53 +0300 Subject: [PATCH 148/201] use gdbm for user info storage --- internal/handlers/ussd/menuhandler.go | 421 ++++++++++++++------------ 1 file changed, 232 insertions(+), 189 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 8c85414..6e8501d 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -3,6 +3,7 @@ package ussd import ( "bytes" "context" + "errors" "fmt" "path" "regexp" @@ -17,14 +18,36 @@ import ( "git.grassecon.net/urdt/ussd/internal/handlers/server" "git.grassecon.net/urdt/ussd/internal/models" "git.grassecon.net/urdt/ussd/internal/utils" + "github.com/graygnuorg/go-gdbm" "gopkg.in/leonelquinteros/gotext.v1" ) var ( scriptDir = path.Join("services", "registration") translationDir = path.Join(scriptDir, "locale") + dbFile = path.Join(scriptDir, "vise.gdbm") ) +const ( + TrackingIdKey = "TRACKINGID" + PublicKeyKey = "PUBLICKEY" + CustodialIdKey = "CUSTODIALID" + AccountPin = "ACCOUNTPIN" + AccountStatus = "ACCOUNTSTATUS" + FirstName = "FIRSTNAME" + FamilyName = "FAMILYNAME" + YearOfBirth = "YOB" + Location = "LOCATION" + Gender = "GENDER" + Offerings = "OFFERINGS" + Recipient = "RECIPIENT" + Amount = "AMOUNT" +) + +func toBytes(s string) []byte { + return []byte(s) +} + type FSData struct { Path string St *state.State @@ -32,19 +55,25 @@ type FSData struct { type Handlers struct { fs *FSData + db *gdbm.Database parser *asm.FlagParser accountFileHandler utils.AccountFileHandlerInterface accountService server.AccountServiceInterface } func NewHandlers(dir string, st *state.State) (*Handlers, error) { + db, err := gdbm.Open(dbFile, gdbm.ModeWrcreat) + if err != nil { + panic(err) + } pfp := path.Join(scriptDir, "pp.csv") parser := asm.NewFlagParser() - _, err := parser.Load(pfp) + _, err = parser.Load(pfp) if err != nil { return nil, err } return &Handlers{ + db: db, fs: &FSData{ Path: dir, St: st, @@ -117,22 +146,18 @@ func (h *Handlers) CreateAccount(ctx context.Context, sym string, input []byte) res.FlagSet = append(res.FlagSet, models.USERFLAG_ACCOUNT_CREATION_FAILED) return res, err } - - accountData := map[string]string{ - "TrackingId": accountResp.Result.TrackingId, - "PublicKey": accountResp.Result.PublicKey, - "CustodialId": accountResp.Result.CustodialId.String(), - "Status": "PENDING", - "Gender": "Not provided", - "YOB": "Not provided", - "Location": "Not provided", - "Offerings": "Not provided", - "FirstName": "Not provided", - "FamilyName": "Not provided", + data := map[string]string{ + TrackingIdKey: accountResp.Result.TrackingId, + PublicKeyKey: accountResp.Result.PublicKey, + CustodialIdKey: accountResp.Result.CustodialId.String(), } - err = h.accountFileHandler.WriteAccountData(accountData) - if err != nil { - return res, err + + for key, value := range data { + err := h.db.Store(toBytes(key), toBytes(value), true) + if err != nil { + return res, err + + } } res.FlagSet = append(res.FlagSet, models.USERFLAG_ACCOUNT_CREATED) @@ -144,10 +169,10 @@ func (h *Handlers) SavePin(ctx context.Context, sym string, input []byte) (resou res := resource.Result{} accountPIN := string(input) - accountData, err := h.accountFileHandler.ReadAccountData() - if err != nil { - return res, err - } + // accountData, err := h.accountFileHandler.ReadAccountData() + // if err != nil { + // return res, err + // } // Validate that the PIN is a 4-digit number if !isValidPIN(accountPIN) { @@ -156,12 +181,17 @@ func (h *Handlers) SavePin(ctx context.Context, sym string, input []byte) (resou } res.FlagReset = append(res.FlagReset, models.USERFLAG_INCORRECTPIN) - accountData["AccountPIN"] = accountPIN + //accountData["AccountPIN"] = accountPIN - err = h.accountFileHandler.WriteAccountData(accountData) - if err != nil { - return res, err - } + key := []byte(AccountPin) + value := []byte(accountPIN) + + h.db.Store(key, value, true) + + // err = h.accountFileHandler.WriteAccountData(accountData) + // if err != nil { + // return res, err + // } return res, nil } @@ -192,20 +222,20 @@ func (h *Handlers) SetResetSingleEdit(ctx context.Context, sym string, input []b // to access the main menu func (h *Handlers) VerifyPin(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - - accountData, err := h.accountFileHandler.ReadAccountData() - if err != nil { + pin, err := h.db.Fetch([]byte(AccountPin)) + if err == nil { + if bytes.Equal(input, pin) { + res.FlagSet = []uint32{models.USERFLAG_VALIDPIN} + res.FlagReset = []uint32{models.USERFLAG_PINMISMATCH} + res.FlagSet = append(res.FlagSet, models.USERFLAG_PIN_SET) + } else { + res.FlagSet = []uint32{models.USERFLAG_PINMISMATCH} + } + } else if errors.Is(err, gdbm.ErrItemNotFound) { + //PIN not set yet + } else { return res, err } - - if bytes.Equal(input, []byte(accountData["AccountPIN"])) { - res.FlagSet = []uint32{models.USERFLAG_VALIDPIN} - res.FlagReset = []uint32{models.USERFLAG_PINMISMATCH} - res.FlagSet = append(res.FlagSet, models.USERFLAG_PIN_SET) - } else { - res.FlagSet = []uint32{models.USERFLAG_PINMISMATCH} - } - return res, nil } @@ -224,18 +254,23 @@ func codeFromCtx(ctx context.Context) string { func (h *Handlers) SaveFirstname(cxt context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - accountData, err := h.accountFileHandler.ReadAccountData() - if err != nil { - return res, err - } + // accountData, err := h.accountFileHandler.ReadAccountData() + // if err != nil { + // return res, err + // } if len(input) > 0 { name := string(input) - accountData["FirstName"] = name + //accountData["FirstName"] = name - err = h.accountFileHandler.WriteAccountData(accountData) - if err != nil { - return res, err - } + key := []byte(FirstName) + value := []byte(name) + + h.db.Store(key, value, true) + + // err = h.accountFileHandler.WriteAccountData(accountData) + // if err != nil { + // return res, err + // } } return res, nil @@ -244,19 +279,12 @@ func (h *Handlers) SaveFirstname(cxt context.Context, sym string, input []byte) // SaveFamilyname updates the family name in a JSON data file with the provided input. func (h *Handlers) SaveFamilyname(cxt context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - - accountData, err := h.accountFileHandler.ReadAccountData() - if err != nil { - return res, err - } if len(input) > 0 { secondname := string(input) - accountData["FamilyName"] = secondname + key := []byte(FamilyName) + value := []byte(secondname) - err = h.accountFileHandler.WriteAccountData(accountData) - if err != nil { - return res, err - } + h.db.Store(key, value, true) } return res, nil @@ -266,20 +294,18 @@ func (h *Handlers) SaveFamilyname(cxt context.Context, sym string, input []byte) func (h *Handlers) SaveYob(cxt context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - accountData, err := h.accountFileHandler.ReadAccountData() - if err != nil { - return res, err - } - yob := string(input) if len(yob) == 4 { yob := string(input) - accountData["YOB"] = yob + //accountData["YOB"] = yob + key := []byte(YearOfBirth) + value := []byte(yob) - err = h.accountFileHandler.WriteAccountData(accountData) - if err != nil { - return res, err - } + h.db.Store(key, value, true) + // err = h.accountFileHandler.WriteAccountData(accountData) + // if err != nil { + // return res, err + // } } return res, nil @@ -289,19 +315,17 @@ func (h *Handlers) SaveYob(cxt context.Context, sym string, input []byte) (resou func (h *Handlers) SaveLocation(cxt context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - accountData, err := h.accountFileHandler.ReadAccountData() - if err != nil { - return res, err - } + // accountData, err := h.accountFileHandler.ReadAccountData() + // if err != nil { + // return res, err + // } if len(input) > 0 { location := string(input) - accountData["Location"] = location + key := []byte(Location) + value := []byte(location) - err = h.accountFileHandler.WriteAccountData(accountData) - if err != nil { - return res, err - } + h.db.Store(key, value, true) } return res, nil @@ -310,12 +334,6 @@ func (h *Handlers) SaveLocation(cxt context.Context, sym string, input []byte) ( // SaveGender updates the gender in a JSON data file with the provided input. func (h *Handlers) SaveGender(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - - accountData, err := h.accountFileHandler.ReadAccountData() - if err != nil { - return res, err - } - if len(input) > 0 { gender := string(input) @@ -327,12 +345,16 @@ func (h *Handlers) SaveGender(ctx context.Context, sym string, input []byte) (re case "3": gender = "Unspecified" } - accountData["Gender"] = gender + //accountData["Gender"] = gender + key := []byte(Gender) + value := []byte(gender) - err = h.accountFileHandler.WriteAccountData(accountData) - if err != nil { - return res, err - } + h.db.Store(key, value, true) + + // err = h.accountFileHandler.WriteAccountData(accountData) + // if err != nil { + // return res, err + // } } return res, nil } @@ -341,19 +363,23 @@ func (h *Handlers) SaveGender(ctx context.Context, sym string, input []byte) (re func (h *Handlers) SaveOfferings(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - accountData, err := h.accountFileHandler.ReadAccountData() - if err != nil { - return res, err - } + // accountData, err := h.accountFileHandler.ReadAccountData() + // if err != nil { + // return res, err + // } if len(input) > 0 { offerings := string(input) - accountData["Offerings"] = offerings + //accountData["Offerings"] = offerings + key := []byte(Offerings) + value := []byte(offerings) - err = h.accountFileHandler.WriteAccountData(accountData) - if err != nil { - return res, err - } + h.db.Store(key, value, true) + + // err = h.accountFileHandler.WriteAccountData(accountData) + // if err != nil { + // return res, err + // } } return res, nil } @@ -376,12 +402,16 @@ func (h *Handlers) ResetAccountAuthorized(ctx context.Context, sym string, input func (h *Handlers) CheckIdentifier(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - accountData, err := h.accountFileHandler.ReadAccountData() + // accountData, err := h.accountFileHandler.ReadAccountData() + // if err != nil { + // return res, err + // } + publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) if err != nil { return res, err } - res.Content = accountData["PublicKey"] + res.Content = string(publicKey) return res, nil } @@ -390,12 +420,12 @@ func (h *Handlers) CheckIdentifier(ctx context.Context, sym string, input []byte // It sets the required flags that control the flow. func (h *Handlers) Authorize(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - pin := string(input) + //pin := string(input) - accountData, err := h.accountFileHandler.ReadAccountData() - if err != nil { - return res, err - } + // accountData, err := h.accountFileHandler.ReadAccountData() + // if err != nil { + // return res, err + // } // Preload the required flags flagKeys := []string{"flag_incorrect_pin", "flag_account_authorized", "flag_allow_update"} @@ -404,20 +434,43 @@ func (h *Handlers) Authorize(ctx context.Context, sym string, input []byte) (res return res, err } - if len(input) == 4 { - if pin != accountData["AccountPIN"] { - res.FlagSet = append(res.FlagSet, flags["flag_incorrect_pin"]) - res.FlagReset = append(res.FlagReset, flags["flag_account_authorized"]) - return res, nil - } - if h.fs.St.MatchFlag(flags["flag_account_authorized"], false) { - res.FlagReset = append(res.FlagReset, flags["flag_incorrect_pin"]) - res.FlagSet = append(res.FlagSet, flags["flag_allow_update"], flags["flag_account_authorized"]) - } else { - res.FlagSet = append(res.FlagSet, flags["flag_allow_update"]) - res.FlagReset = append(res.FlagReset, flags["flag_account_authorized"]) + storedpin, err := h.db.Fetch([]byte(AccountPin)) + if err == nil { + if len(input) == 4 { + if bytes.Equal(input, storedpin) { + if h.fs.St.MatchFlag(flags["flag_account_authorized"], false) { + res.FlagReset = append(res.FlagReset, flags["flag_incorrect_pin"]) + res.FlagSet = append(res.FlagSet, flags["flag_allow_update"], flags["flag_account_authorized"]) + } else { + res.FlagSet = append(res.FlagSet, flags["flag_allow_update"]) + res.FlagReset = append(res.FlagReset, flags["flag_account_authorized"]) + } + } else { + res.FlagSet = append(res.FlagSet, flags["flag_incorrect_pin"]) + res.FlagReset = append(res.FlagReset, flags["flag_account_authorized"]) + return res, nil + } } + } else if errors.Is(err, gdbm.ErrItemNotFound) { + //PIN not set yet + } else { + return res, err } + + // if len(input) == 4 { + // if pin != accountData["AccountPIN"] { + // res.FlagSet = append(res.FlagSet, flags["flag_incorrect_pin"]) + // res.FlagReset = append(res.FlagReset, flags["flag_account_authorized"]) + // return res, nil + // } + // if h.fs.St.MatchFlag(flags["flag_account_authorized"], false) { + // res.FlagReset = append(res.FlagReset, flags["flag_incorrect_pin"]) + // res.FlagSet = append(res.FlagSet, flags["flag_allow_update"], flags["flag_account_authorized"]) + // } else { + // res.FlagSet = append(res.FlagSet, flags["flag_allow_update"]) + // res.FlagReset = append(res.FlagReset, flags["flag_account_authorized"]) + // } + // } return res, nil } @@ -433,19 +486,29 @@ func (h *Handlers) ResetIncorrectPin(ctx context.Context, sym string, input []by func (h *Handlers) CheckAccountStatus(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - accountData, err := h.accountFileHandler.ReadAccountData() + // accountData, err := h.accountFileHandler.ReadAccountData() + // if err != nil { + // return res, err + // } + trackingId, err := h.db.Fetch([]byte(TrackingIdKey)) + if err != nil { return res, err } - status, err := h.accountService.CheckAccountStatus(accountData["TrackingId"]) + status, err := h.accountService.CheckAccountStatus(string(trackingId)) if err != nil { fmt.Println("Error checking account status:", err) - return res, nil + return res, err } - accountData["Status"] = status + //accountData["Status"] = status + err = h.db.Store(toBytes(TrackingIdKey), toBytes(status), true) + + if err != nil { + return res, nil + } if status == "SUCCESS" { res.FlagSet = append(res.FlagSet, models.USERFLAG_ACCOUNT_SUCCESS) @@ -455,10 +518,10 @@ func (h *Handlers) CheckAccountStatus(ctx context.Context, sym string, input []b res.FlagSet = append(res.FlagReset, models.USERFLAG_ACCOUNT_PENDING) } - err = h.accountFileHandler.WriteAccountData(accountData) - if err != nil { - return res, err - } + // err = h.accountFileHandler.WriteAccountData(accountData) + // if err != nil { + // return res, err + // } return res, nil } @@ -507,13 +570,13 @@ func (h *Handlers) ResetIncorrectYob(ctx context.Context, sym string, input []by // the balance as the result content func (h *Handlers) CheckBalance(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} + publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) - accountData, err := h.accountFileHandler.ReadAccountData() if err != nil { return res, err } - balance, err := h.accountService.CheckBalance(accountData["PublicKey"]) + balance, err := h.accountService.CheckBalance(string(publicKey)) if err != nil { return res, nil } @@ -526,12 +589,6 @@ func (h *Handlers) CheckBalance(ctx context.Context, sym string, input []byte) ( func (h *Handlers) ValidateRecipient(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} recipient := string(input) - - accountData, err := h.accountFileHandler.ReadAccountData() - if err != nil { - return res, err - } - if recipient != "0" { // mimic invalid number check if recipient == "000" { @@ -541,12 +598,11 @@ func (h *Handlers) ValidateRecipient(ctx context.Context, sym string, input []by return res, nil } - accountData["Recipient"] = recipient + // accountData["Recipient"] = recipient + key := []byte(Recipient) + value := []byte(recipient) - err = h.accountFileHandler.WriteAccountData(accountData) - if err != nil { - return res, err - } + h.db.Store(key, value, true) } return res, nil @@ -556,20 +612,14 @@ func (h *Handlers) ValidateRecipient(ctx context.Context, sym string, input []by // as well as the invalid flags func (h *Handlers) TransactionReset(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - accountData, err := h.accountFileHandler.ReadAccountData() - if err != nil { - return res, err + err := h.db.Delete([]byte(Amount)) + if err != nil && !errors.Is(err, gdbm.ErrItemNotFound) { + panic(err) } - - // reset the transaction - accountData["Recipient"] = "" - accountData["Amount"] = "" - - err = h.accountFileHandler.WriteAccountData(accountData) - if err != nil { - return res, err + err = h.db.Delete([]byte(Recipient)) + if err != nil && !errors.Is(err, gdbm.ErrItemNotFound) { + panic(err) } - res.FlagReset = append(res.FlagReset, models.USERFLAG_INVALID_RECIPIENT, models.USERFLAG_INVALID_RECIPIENT_WITH_INVITE) return res, nil @@ -578,21 +628,11 @@ func (h *Handlers) TransactionReset(ctx context.Context, sym string, input []byt // ResetTransactionAmount resets the transaction amount and invalid flag func (h *Handlers) ResetTransactionAmount(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - accountData, err := h.accountFileHandler.ReadAccountData() - if err != nil { - return res, err + err := h.db.Delete([]byte(Amount)) + if err != nil && !errors.Is(err, gdbm.ErrItemNotFound) { + panic(err) } - - // reset the amount - accountData["Amount"] = "" - - err = h.accountFileHandler.WriteAccountData(accountData) - if err != nil { - return res, err - } - res.FlagReset = append(res.FlagReset, models.USERFLAG_INVALID_AMOUNT) - return res, nil } @@ -600,13 +640,12 @@ func (h *Handlers) ResetTransactionAmount(ctx context.Context, sym string, input // the result content. func (h *Handlers) MaxAmount(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - - accountData, err := h.accountFileHandler.ReadAccountData() + publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) if err != nil { return res, err } - balance, err := h.accountService.CheckBalance(accountData["PublicKey"]) + balance, err := h.accountService.CheckBalance(string(publicKey)) if err != nil { return res, nil } @@ -621,13 +660,12 @@ func (h *Handlers) MaxAmount(ctx context.Context, sym string, input []byte) (res func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} amountStr := string(input) - - accountData, err := h.accountFileHandler.ReadAccountData() + publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) if err != nil { return res, err } - balanceStr, err := h.accountService.CheckBalance(accountData["PublicKey"]) + balanceStr, err := h.accountService.CheckBalance(string(publicKey)) if err != nil { return res, err } @@ -666,9 +704,10 @@ func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte) } res.Content = fmt.Sprintf("%.3f", inputAmount) // Format to 3 decimal places - accountData["Amount"] = res.Content + key := []byte(Amount) + value := []byte(res.Content) + h.db.Store(key, value, true) - err = h.accountFileHandler.WriteAccountData(accountData) if err != nil { return res, err } @@ -679,13 +718,12 @@ func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte) // GetRecipient returns the transaction recipient from a JSON data file. func (h *Handlers) GetRecipient(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - - accountData, err := h.accountFileHandler.ReadAccountData() + recipient, err := h.db.Fetch([]byte(Recipient)) if err != nil { return res, err } - res.Content = accountData["Recipient"] + res.Content = string(recipient) return res, nil } @@ -727,12 +765,13 @@ func (h *Handlers) GetProfileInfo(ctx context.Context, sym string, input []byte) func (h *Handlers) GetSender(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - accountData, err := h.accountFileHandler.ReadAccountData() + //accountData, err := h.accountFileHandler.ReadAccountData() + publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) if err != nil { return res, err } - res.Content = accountData["PublicKey"] + res.Content = string(publicKey) return res, nil } @@ -741,12 +780,13 @@ func (h *Handlers) GetSender(ctx context.Context, sym string, input []byte) (res func (h *Handlers) GetAmount(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - accountData, err := h.accountFileHandler.ReadAccountData() + //accountData, err := h.accountFileHandler.ReadAccountData() + amount, err := h.db.Fetch([]byte(Amount)) if err != nil { return res, err } - res.Content = accountData["Amount"] + res.Content = string(amount) return res, nil } @@ -758,11 +798,15 @@ func (h *Handlers) QuitWithBalance(ctx context.Context, sym string, input []byte code := codeFromCtx(ctx) l := gotext.NewLocale(translationDir, code) l.AddDomain("default") - accountData, err := h.accountFileHandler.ReadAccountData() + // accountData, err := h.accountFileHandler.ReadAccountData() + // if err != nil { + // return res, err + // } + publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) if err != nil { return res, err } - balance, err := h.accountService.CheckBalance(accountData["PublicKey"]) + balance, err := h.accountService.CheckBalance(string(publicKey)) if err != nil { return res, nil } @@ -779,24 +823,23 @@ func (h *Handlers) InitiateTransaction(ctx context.Context, sym string, input [] l := gotext.NewLocale(translationDir, code) l.AddDomain("default") - accountData, err := h.accountFileHandler.ReadAccountData() - if err != nil { - return res, err - } - // TODO // Use the amount, recipient and sender to call the API and initialize the transaction - res.Content = l.Get("Your request has been sent. %s will receive %s from %s.", accountData["Recipient"], accountData["Amount"], accountData["PublicKey"]) - - // reset the transaction - accountData["Recipient"] = "" - accountData["Amount"] = "" - - err = h.accountFileHandler.WriteAccountData(accountData) + publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) if err != nil { return res, err } + amount, err := h.db.Fetch([]byte(Amount)) + if err != nil { + return res, err + } + recipient, err := h.db.Fetch([]byte(Recipient)) + if err != nil { + return res, err + } + + res.Content = l.Get("Your request has been sent. %s will receive %s from %s.", string(recipient), string(amount), string(publicKey)) account_authorized_flag, err := h.parser.GetFlag("flag_account_authorized") From 0c96831378d12237cd26a4e6a055999f7767d6c5 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Mon, 2 Sep 2024 16:05:13 +0300 Subject: [PATCH 149/201] use gdbm --- cmd/main.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index 26ad520..68b468a 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -83,9 +83,9 @@ func main() { fp := path.Join(dp, sessionId) - ussdHandlers,err := ussd.NewHandlers(fp, &st) + ussdHandlers, err := ussd.NewHandlers(fp, &st) - if(err != nil){ + if err != nil { fmt.Fprintf(os.Stderr, "handler setup failed with error: %v\n", err) } From 2b511aba4cd74b3443da3ea26b8020c66d098f21 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Mon, 2 Sep 2024 16:39:04 +0300 Subject: [PATCH 150/201] remove commented code --- internal/handlers/ussd/menuhandler.go | 54 ++++++++------------------- 1 file changed, 15 insertions(+), 39 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index a956d6b..b7789b0 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -483,12 +483,12 @@ func (h *Handlers) Authorize(ctx context.Context, sym string, input []byte) (res return res, err } - pin := string(input) + // pin := string(input) - accountData, err := h.accountFileHandler.ReadAccountData() - if err != nil { - return res, err - } + // accountData, err := h.accountFileHandler.ReadAccountData() + // if err != nil { + // return res, err + // } storedpin, err := h.db.Fetch([]byte(AccountPin)) if err == nil { @@ -512,21 +512,6 @@ func (h *Handlers) Authorize(ctx context.Context, sym string, input []byte) (res } else { return res, err } - - // if len(input) == 4 { - // if pin != accountData["AccountPIN"] { - // res.FlagSet = append(res.FlagSet, flags["flag_incorrect_pin"]) - // res.FlagReset = append(res.FlagReset, flags["flag_account_authorized"]) - // return res, nil - // } - // if h.fs.St.MatchFlag(flags["flag_account_authorized"], false) { - // res.FlagReset = append(res.FlagReset, flags["flag_incorrect_pin"]) - // res.FlagSet = append(res.FlagSet, flags["flag_allow_update"], flags["flag_account_authorized"]) - // } else { - // res.FlagSet = append(res.FlagSet, flags["flag_allow_update"]) - // res.FlagReset = append(res.FlagReset, flags["flag_account_authorized"]) - // } - // } return res, nil } @@ -550,14 +535,6 @@ func (h *Handlers) ResetIncorrectPin(ctx context.Context, sym string, input []by func (h *Handlers) CheckAccountStatus(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - // Preload the required flags - - flagKeys := []string{"flag_account_success", "flag_account_pending"} - flags, err := h.PreloadFlags(flagKeys) - if err != nil { - return res, err - } - // Preload the required flags flagKeys := []string{"flag_account_success", "flag_account_pending"} flags, err := h.PreloadFlags(flagKeys) @@ -693,13 +670,12 @@ func (h *Handlers) ValidateRecipient(ctx context.Context, sym string, input []by res := resource.Result{} recipient := string(input) - accountData, err := h.accountFileHandler.ReadAccountData() + flagKeys := []string{"flag_invalid_recipient"} + flags, err := h.PreloadFlags(flagKeys) if err != nil { return res, err } - - recipient := string(input) if recipient != "0" { // mimic invalid number check if recipient == "000" { @@ -731,7 +707,7 @@ func (h *Handlers) TransactionReset(ctx context.Context, sym string, input []byt return res, err } - err := h.db.Delete([]byte(Amount)) + err = h.db.Delete([]byte(Amount)) if err != nil && !errors.Is(err, gdbm.ErrItemNotFound) { panic(err) } @@ -756,7 +732,7 @@ func (h *Handlers) ResetTransactionAmount(ctx context.Context, sym string, input return res, err } - err := h.db.Delete([]byte(Amount)) + err = h.db.Delete([]byte(Amount)) if err != nil && !errors.Is(err, gdbm.ErrItemNotFound) { panic(err) } @@ -789,7 +765,7 @@ func (h *Handlers) MaxAmount(ctx context.Context, sym string, input []byte) (res // it is not more than the current balance. func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} -// Preload the required flag + // Preload the required flag flagKeys := []string{"flag_invalid_amount"} flags, err := h.PreloadFlags(flagKeys) if err != nil { @@ -970,11 +946,11 @@ func (h *Handlers) InitiateTransaction(ctx context.Context, sym string, input [] l := gotext.NewLocale(translationDir, code) l.AddDomain("default") // Preload the required flags - flagKeys := []string{"flag_invalid_recipient"} - flags, err := h.PreloadFlags(flagKeys) - if err != nil { - return res, err - } + // flagKeys := []string{"flag_invalid_recipient"} + // flags, err := h.PreloadFlags(flagKeys) + // if err != nil { + // return res, err + // } // TODO // Use the amount, recipient and sender to call the API and initialize the transaction From b6e4ba7ede0ae0aaf0856ba6dbe8c7e95d5b0f74 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Mon, 2 Sep 2024 17:08:57 +0300 Subject: [PATCH 151/201] Verify PIN using the one in the db --- internal/handlers/ussd/menuhandler.go | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index b7789b0..be9fe73 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -262,12 +262,11 @@ func (h *Handlers) VerifyPin(ctx context.Context, sym string, input []byte) (res return res, err } - accountData, err := h.accountFileHandler.ReadAccountData() + AccountPin, err := h.db.Fetch([]byte(AccountPin)) if err != nil { return res, err } - - if bytes.Equal(input, []byte(accountData["AccountPIN"])) { + if bytes.Equal(input, AccountPin) { res.FlagSet = []uint32{flags["flag_valid_pin"]} res.FlagReset = []uint32{flags["flag_pin_mismatch"]} res.FlagSet = append(res.FlagSet, flags["flag_pin_set"]) From 14c8230fd4235b61508574acdaa0a58ca44e3ff5 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Mon, 2 Sep 2024 17:11:08 +0300 Subject: [PATCH 152/201] code cleanup --- internal/handlers/ussd/menuhandler.go | 35 ++++++++------------------- 1 file changed, 10 insertions(+), 25 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index b7789b0..a8c48db 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -148,16 +148,16 @@ func (h *Handlers) CreateAccount(ctx context.Context, sym string, input []byte) return res, err } - err = h.accountFileHandler.EnsureFileExists() - if err != nil { - return res, err - } + // err = h.accountFileHandler.EnsureFileExists() + // if err != nil { + // return res, err + // } // if an account exists, return to prevent duplicate account creation - existingAccountData, err := h.accountFileHandler.ReadAccountData() - if existingAccountData != nil { - return res, err - } + // existingAccountData, err := h.accountFileHandler.ReadAccountData() + // if existingAccountData != nil { + // return res, err + // } accountResp, err := h.accountService.CreateAccount() if err != nil { @@ -190,14 +190,7 @@ func (h *Handlers) SavePin(ctx context.Context, sym string, input []byte) (resou if err != nil { return res, err } - accountPIN := string(input) - - // accountData, err := h.accountFileHandler.ReadAccountData() - // if err != nil { - // return res, err - // } - // Validate that the PIN is a 4-digit number if !isValidPIN(accountPIN) { res.FlagSet = append(res.FlagSet, flags["flag_incorrect_pin"]) @@ -205,18 +198,11 @@ func (h *Handlers) SavePin(ctx context.Context, sym string, input []byte) (resou } res.FlagReset = append(res.FlagReset, flags["flag_incorrect_pin"]) - //accountData["AccountPIN"] = accountPIN key := []byte(AccountPin) value := []byte(accountPIN) h.db.Store(key, value, true) - - // err = h.accountFileHandler.WriteAccountData(accountData) - // if err != nil { - // return res, err - // } - return res, nil } @@ -261,13 +247,12 @@ func (h *Handlers) VerifyPin(ctx context.Context, sym string, input []byte) (res if err != nil { return res, err } - - accountData, err := h.accountFileHandler.ReadAccountData() + storedpin, err := h.db.Fetch([]byte(AccountPin)) if err != nil { return res, err } - if bytes.Equal(input, []byte(accountData["AccountPIN"])) { + if bytes.Equal(input, storedpin) { res.FlagSet = []uint32{flags["flag_valid_pin"]} res.FlagReset = []uint32{flags["flag_pin_mismatch"]} res.FlagSet = append(res.FlagSet, flags["flag_pin_set"]) From 3a3ddc9922d237035d53662b47445dd3707c401d Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Mon, 2 Sep 2024 21:06:42 +0300 Subject: [PATCH 153/201] Use FlagParser on main.go and delete the flags.go file --- cmd/main.go | 60 ++++++++++++++++++++++++++++------------ internal/models/flags.go | 22 --------------- 2 files changed, 42 insertions(+), 40 deletions(-) delete mode 100644 internal/models/flags.go diff --git a/cmd/main.go b/cmd/main.go index 68b468a..ea38272 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -7,13 +7,13 @@ import ( "os" "path" + "git.defalsify.org/vise.git/asm" "git.defalsify.org/vise.git/cache" "git.defalsify.org/vise.git/engine" "git.defalsify.org/vise.git/persist" "git.defalsify.org/vise.git/resource" "git.defalsify.org/vise.git/state" "git.grassecon.net/urdt/ussd/internal/handlers/ussd" - "git.grassecon.net/urdt/ussd/internal/models" ) var ( @@ -35,22 +35,46 @@ func main() { ctx := context.Background() st := state.NewState(16) st.UseDebug() - state.FlagDebugger.Register(models.USERFLAG_LANGUAGE_SET, "LANGUAGE_CHANGE") - state.FlagDebugger.Register(models.USERFLAG_ACCOUNT_CREATED, "ACCOUNT_CREATED") - state.FlagDebugger.Register(models.USERFLAG_ACCOUNT_SUCCESS, "ACCOUNT_SUCCESS") - state.FlagDebugger.Register(models.USERFLAG_ACCOUNT_PENDING, "ACCOUNT_PENDING") - state.FlagDebugger.Register(models.USERFLAG_INCORRECTPIN, "INCORRECTPIN") - state.FlagDebugger.Register(models.USERFLAG_INCORRECTDATEFORMAT, "INVALIDDATEFORMAT") - state.FlagDebugger.Register(models.USERFLAG_INVALID_RECIPIENT, "INVALIDRECIPIENT") - state.FlagDebugger.Register(models.USERFLAG_PINMISMATCH, "PINMISMATCH") - state.FlagDebugger.Register(models.USERFLAG_PIN_SET, "PIN_SET") - state.FlagDebugger.Register(models.USERFLAG_INVALID_RECIPIENT_WITH_INVITE, "INVALIDRECIPIENT_WITH_INVITE") - state.FlagDebugger.Register(models.USERFLAG_INVALID_AMOUNT, "INVALIDAMOUNT") - state.FlagDebugger.Register(models.USERFLAG_ALLOW_UPDATE, "UNLOCKFORUPDATE") - state.FlagDebugger.Register(models.USERFLAG_VALIDPIN, "VALIDPIN") - state.FlagDebugger.Register(models.USERFLAG_ACCOUNT_AUTHORIZED, "ACCOUNT_AUTHORIZED") - state.FlagDebugger.Register(models.USERFLAG_ACCOUNT_CREATION_FAILED, "ACCOUNT_CREATION_FAILED") - state.FlagDebugger.Register(models.USERFLAG_SINGLE_EDIT, "SINGLEEDIT") + + // Initialize the FlagParser + pfp := path.Join(scriptDir, "pp.csv") + parser := asm.NewFlagParser() + + // Load flags from the pp.csv file + _, err := parser.Load(pfp) + if err != nil { + fmt.Fprintf(os.Stderr, "Failed to load flags: %v\n", err) + os.Exit(1) + } + + // Register all flags loaded from pp.csv + flagKeys := []string{ + "flag_language_set", + "flag_account_created", + "flag_account_creation_failed", + "flag_account_pending", + "flag_account_success", + "flag_pin_mismatch", + "flag_pin_set", + "flag_account_authorized", + "flag_invalid_recipient", + "flag_invalid_recipient_with_invite", + "flag_invalid_amount", + "flag_incorrect_pin", + "flag_valid_pin", + "flag_allow_update", + "flag_single_edit", + "flag_incorrect_date_format", + } + + for _, key := range flagKeys { + id, err := parser.GetFlag(key) + if err != nil { + fmt.Fprintf(os.Stderr, "Failed to get flag %s: %v\n", key, err) + continue + } + state.FlagDebugger.Register(id, key) + } rfs := resource.NewFsResource(scriptDir) ca := cache.NewCache() @@ -60,7 +84,7 @@ func main() { } dp := path.Join(scriptDir, ".state") - err := os.MkdirAll(dp, 0700) + err = os.MkdirAll(dp, 0700) if err != nil { fmt.Fprintf(os.Stderr, "state dir create exited with error: %v\n", err) os.Exit(1) diff --git a/internal/models/flags.go b/internal/models/flags.go deleted file mode 100644 index b64222c..0000000 --- a/internal/models/flags.go +++ /dev/null @@ -1,22 +0,0 @@ -package models - -import "git.defalsify.org/vise.git/state" - -const ( - USERFLAG_LANGUAGE_SET = iota + state.FLAG_USERSTART - USERFLAG_ACCOUNT_CREATED - USERFLAG_ACCOUNT_CREATION_FAILED - USERFLAG_ACCOUNT_PENDING - USERFLAG_ACCOUNT_SUCCESS - USERFLAG_PINMISMATCH - USERFLAG_PIN_SET - USERFLAG_ACCOUNT_AUTHORIZED - USERFLAG_INVALID_RECIPIENT - USERFLAG_INVALID_RECIPIENT_WITH_INVITE - USERFLAG_INVALID_AMOUNT - USERFLAG_INCORRECTPIN - USERFLAG_VALIDPIN - USERFLAG_ALLOW_UPDATE - USERFLAG_SINGLE_EDIT - USERFLAG_INCORRECTDATEFORMAT -) From d4c4db09f3303199566f1f5575602c5c6aedca4a Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Mon, 2 Sep 2024 21:09:39 +0300 Subject: [PATCH 154/201] load profile data from gdbm --- internal/handlers/ussd/menuhandler.go | 185 ++++++++++---------------- 1 file changed, 68 insertions(+), 117 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 3ae0f28..d10b551 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -277,24 +277,11 @@ func codeFromCtx(ctx context.Context) string { // SaveFirstname updates the first name in a JSON data file with the provided input. func (h *Handlers) SaveFirstname(cxt context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - - // accountData, err := h.accountFileHandler.ReadAccountData() - // if err != nil { - // return res, err - // } if len(input) > 0 { name := string(input) - //accountData["FirstName"] = name - key := []byte(FirstName) value := []byte(name) - h.db.Store(key, value, true) - - // err = h.accountFileHandler.WriteAccountData(accountData) - // if err != nil { - // return res, err - // } } return res, nil @@ -307,7 +294,6 @@ func (h *Handlers) SaveFamilyname(cxt context.Context, sym string, input []byte) secondname := string(input) key := []byte(FamilyName) value := []byte(secondname) - h.db.Store(key, value, true) } @@ -317,19 +303,12 @@ func (h *Handlers) SaveFamilyname(cxt context.Context, sym string, input []byte) // SaveYOB updates the Year of Birth(YOB) in a JSON data file with the provided input. func (h *Handlers) SaveYob(cxt context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - yob := string(input) if len(yob) == 4 { yob := string(input) - //accountData["YOB"] = yob key := []byte(YearOfBirth) value := []byte(yob) - h.db.Store(key, value, true) - // err = h.accountFileHandler.WriteAccountData(accountData) - // if err != nil { - // return res, err - // } } return res, nil @@ -338,12 +317,6 @@ func (h *Handlers) SaveYob(cxt context.Context, sym string, input []byte) (resou // SaveLocation updates the location in a JSON data file with the provided input. func (h *Handlers) SaveLocation(cxt context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - - // accountData, err := h.accountFileHandler.ReadAccountData() - // if err != nil { - // return res, err - // } - if len(input) > 0 { location := string(input) key := []byte(Location) @@ -360,7 +333,6 @@ func (h *Handlers) SaveGender(ctx context.Context, sym string, input []byte) (re res := resource.Result{} if len(input) > 0 { gender := string(input) - switch gender { case "1": gender = "Male" @@ -369,16 +341,9 @@ func (h *Handlers) SaveGender(ctx context.Context, sym string, input []byte) (re case "3": gender = "Unspecified" } - //accountData["Gender"] = gender key := []byte(Gender) value := []byte(gender) - h.db.Store(key, value, true) - - // err = h.accountFileHandler.WriteAccountData(accountData) - // if err != nil { - // return res, err - // } } return res, nil } @@ -386,24 +351,11 @@ func (h *Handlers) SaveGender(ctx context.Context, sym string, input []byte) (re // SaveOfferings updates the offerings(goods and services provided by the user) in a JSON data file with the provided input. func (h *Handlers) SaveOfferings(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - - // accountData, err := h.accountFileHandler.ReadAccountData() - // if err != nil { - // return res, err - // } - if len(input) > 0 { offerings := string(input) - //accountData["Offerings"] = offerings key := []byte(Offerings) value := []byte(offerings) - h.db.Store(key, value, true) - - // err = h.accountFileHandler.WriteAccountData(accountData) - // if err != nil { - // return res, err - // } } return res, nil } @@ -441,18 +393,11 @@ func (h *Handlers) ResetAccountAuthorized(ctx context.Context, sym string, input // CheckIdentifier retrieves the PublicKey from the JSON data file. func (h *Handlers) CheckIdentifier(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - - // accountData, err := h.accountFileHandler.ReadAccountData() - // if err != nil { - // return res, err - // } publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) if err != nil { return res, err } - res.Content = string(publicKey) - return res, nil } @@ -460,21 +405,12 @@ func (h *Handlers) CheckIdentifier(ctx context.Context, sym string, input []byte // It sets the required flags that control the flow. func (h *Handlers) Authorize(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - // Preload the required flags flagKeys := []string{"flag_incorrect_pin", "flag_account_authorized", "flag_allow_update"} flags, err := h.PreloadFlags(flagKeys) if err != nil { return res, err } - - // pin := string(input) - - // accountData, err := h.accountFileHandler.ReadAccountData() - // if err != nil { - // return res, err - // } - storedpin, err := h.db.Fetch([]byte(AccountPin)) if err == nil { if len(input) == 4 { @@ -526,11 +462,6 @@ func (h *Handlers) CheckAccountStatus(ctx context.Context, sym string, input []b if err != nil { return res, err } - - // accountData, err := h.accountFileHandler.ReadAccountData() - // if err != nil { - // return res, err - // } trackingId, err := h.db.Fetch([]byte(TrackingIdKey)) if err != nil { @@ -545,9 +476,12 @@ func (h *Handlers) CheckAccountStatus(ctx context.Context, sym string, input []b } - //accountData["Status"] = status - err = h.db.Store(toBytes(TrackingIdKey), toBytes(status), true) + err = h.db.Store(toBytes(AccountStatus), toBytes(status), true) + if err != nil { + return res, nil + } + err = h.db.Store(toBytes(TrackingIdKey), toBytes(status), true) if err != nil { return res, nil } @@ -828,39 +762,6 @@ func (h *Handlers) GetRecipient(ctx context.Context, sym string, input []byte) ( return res, nil } -// GetProfileInfo retrieves and formats the profile information of a user from a JSON data file. -func (h *Handlers) GetProfileInfo(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} - var age string - accountData, err := h.accountFileHandler.ReadAccountData() - if err != nil { - return res, err - } - var name string - if accountData["FirstName"] == "Not provided" || accountData["FamilyName"] == "Not provided" { - name = "Not provided" - } else { - name = accountData["FirstName"] + " " + accountData["FamilyName"] - } - - gender := accountData["Gender"] - yob := accountData["YOB"] - location := accountData["Location"] - offerings := accountData["Offerings"] - if yob == "Not provided" { - age = "Not provided" - } else { - ageInt, err := strconv.Atoi(yob) - if err != nil { - return res, nil - } - age = strconv.Itoa(utils.CalculateAgeWithYOB(ageInt)) - } - formattedData := fmt.Sprintf("Name: %s\nGender: %s\nAge: %s\nLocation: %s\nYou provide: %s\n", name, gender, age, location, offerings) - res.Content = formattedData - return res, nil -} - // GetSender retrieves the public key from a JSON data file. func (h *Handlers) GetSender(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} @@ -879,13 +780,10 @@ func (h *Handlers) GetSender(ctx context.Context, sym string, input []byte) (res // GetAmount retrieves the amount from a JSON data file. func (h *Handlers) GetAmount(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - - //accountData, err := h.accountFileHandler.ReadAccountData() amount, err := h.db.Fetch([]byte(Amount)) if err != nil { return res, err } - res.Content = string(amount) return res, nil @@ -906,10 +804,6 @@ func (h *Handlers) QuitWithBalance(ctx context.Context, sym string, input []byte code := codeFromCtx(ctx) l := gotext.NewLocale(translationDir, code) l.AddDomain("default") - // accountData, err := h.accountFileHandler.ReadAccountData() - // if err != nil { - // return res, err - // } publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) if err != nil { return res, err @@ -930,12 +824,6 @@ func (h *Handlers) InitiateTransaction(ctx context.Context, sym string, input [] code := codeFromCtx(ctx) l := gotext.NewLocale(translationDir, code) l.AddDomain("default") - // Preload the required flags - // flagKeys := []string{"flag_invalid_recipient"} - // flags, err := h.PreloadFlags(flagKeys) - // if err != nil { - // return res, err - // } // TODO // Use the amount, recipient and sender to call the API and initialize the transaction @@ -962,3 +850,66 @@ func (h *Handlers) InitiateTransaction(ctx context.Context, sym string, input [] return res, nil } + +// GetProfileInfo retrieves and formats the profile information of a user from a JSON data file. +func (h *Handlers) GetProfileInfo(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res := resource.Result{} + + // Define default values + defaultValue := "Not provided" + name := defaultValue + familyName := defaultValue + yob := defaultValue + gender := defaultValue + location := defaultValue + offerings := defaultValue + + // Fetch data using a map for better organization + dataKeys := map[string]*string{ + FirstName: &name, + FamilyName: &familyName, + YearOfBirth: &yob, + Location: &location, + Gender: &gender, + Offerings: &offerings, + } + + // Iterate over keys and fetch values + //iter := h.db.Iterator() + next := h.db.Iterator() + //defer iter.Close() // Ensure the iterator is closed + for key, err := next(); err == nil; key, err = next() { + if valuePointer, ok := dataKeys[string(key)]; ok { + value, fetchErr := h.db.Fetch(key) + if fetchErr == nil { + *valuePointer = string(value) + } + } + } + + // Construct the full name + if familyName != defaultValue { + if name == defaultValue { + name = familyName + } else { + name = name + " " + familyName + } + } + + // Calculate age from year of birth + var age string + if yob != defaultValue { + yobInt, err := strconv.Atoi(yob) + if err != nil { + return res, fmt.Errorf("invalid year of birth: %v", err) + } + age = strconv.Itoa(utils.CalculateAgeWithYOB(yobInt)) + } else { + age = defaultValue + } + + // Format the result + formattedData := fmt.Sprintf("Name: %s\nGender: %s\nAge: %s\nLocation: %s\nYou provide: %s\n", name, gender, age, location, offerings) + res.Content = formattedData + return res, nil +} From c365eaa1d1a0d4049b6225c329c6ae1a6c132074 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Mon, 2 Sep 2024 21:24:16 +0300 Subject: [PATCH 155/201] remove unused code --- internal/handlers/ussd/menuhandler.go | 21 +-------------------- 1 file changed, 1 insertion(+), 20 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index d10b551..ebcc7f3 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -140,25 +140,12 @@ func (h *Handlers) SetLanguage(ctx context.Context, sym string, input []byte) (r // sets the default values and flags func (h *Handlers) CreateAccount(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - // Preload the required flags flagKeys := []string{"flag_account_created", "flag_account_creation_failed"} flags, err := h.PreloadFlags(flagKeys) if err != nil { return res, err } - - // err = h.accountFileHandler.EnsureFileExists() - // if err != nil { - // return res, err - // } - - // if an account exists, return to prevent duplicate account creation - // existingAccountData, err := h.accountFileHandler.ReadAccountData() - // if existingAccountData != nil { - // return res, err - // } - accountResp, err := h.accountService.CreateAccount() if err != nil { res.FlagSet = append(res.FlagSet, flags["flag_account_creation_failed"]) @@ -493,12 +480,6 @@ func (h *Handlers) CheckAccountStatus(ctx context.Context, sym string, input []b res.FlagReset = append(res.FlagSet, flags["flag_account_success"]) res.FlagSet = append(res.FlagReset, flags["flag_account_pending"]) } - - // err = h.accountFileHandler.WriteAccountData(accountData) - // if err != nil { - // return res, err - // } - return res, nil } @@ -851,7 +832,7 @@ func (h *Handlers) InitiateTransaction(ctx context.Context, sym string, input [] return res, nil } -// GetProfileInfo retrieves and formats the profile information of a user from a JSON data file. +// GetProfileInfo retrieves and formats the profile information of a user from a Gdbm backed storage. func (h *Handlers) GetProfileInfo(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} From 560714838f20dbbd6726312fe5a8e226cb8a44f8 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Tue, 3 Sep 2024 11:51:14 +0300 Subject: [PATCH 156/201] fix menu termination on invalid pin entry --- services/registration/view_profile.vis | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/registration/view_profile.vis b/services/registration/view_profile.vis index 2d0a508..a7ffee4 100644 --- a/services/registration/view_profile.vis +++ b/services/registration/view_profile.vis @@ -1,6 +1,6 @@ LOAD get_profile_info 0 MAP get_profile_info -LOAD reset_incorrect 0 +LOAD reset_incorrect 6 CATCH incorrect_pin flag_incorrect_pin 1 CATCH pin_entry flag_account_authorized 0 MOUT back 0 From 0c360c0cc4cfa8872336b2add44b626f5eb74487 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Tue, 3 Sep 2024 13:19:32 +0300 Subject: [PATCH 157/201] remove panics after failed execution --- internal/handlers/ussd/menuhandler.go | 49 ++++++++++++++++----------- 1 file changed, 30 insertions(+), 19 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index ebcc7f3..cb2a913 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -41,6 +41,7 @@ const ( Offerings = "OFFERINGS" Recipient = "RECIPIENT" Amount = "AMOUNT" + AccountCreated = "ACCOUNTCREATED" ) func toBytes(s string) []byte { @@ -146,27 +147,37 @@ func (h *Handlers) CreateAccount(ctx context.Context, sym string, input []byte) if err != nil { return res, err } - accountResp, err := h.accountService.CreateAccount() + _, err = h.db.Fetch([]byte(AccountCreated)) if err != nil { - res.FlagSet = append(res.FlagSet, flags["flag_account_creation_failed"]) - return res, err - } - data := map[string]string{ - TrackingIdKey: accountResp.Result.TrackingId, - PublicKeyKey: accountResp.Result.PublicKey, - CustodialIdKey: accountResp.Result.CustodialId.String(), - } + if errors.Is(err, gdbm.ErrItemNotFound) { + accountResp, err := h.accountService.CreateAccount() + if err != nil { + res.FlagSet = append(res.FlagSet, flags["flag_account_creation_failed"]) + return res, err + } + data := map[string]string{ + TrackingIdKey: accountResp.Result.TrackingId, + PublicKeyKey: accountResp.Result.PublicKey, + CustodialIdKey: accountResp.Result.CustodialId.String(), + } - for key, value := range data { - err := h.db.Store(toBytes(key), toBytes(value), true) - if err != nil { + for key, value := range data { + err := h.db.Store(toBytes(key), toBytes(value), true) + if err != nil { + return res, err + } + } + key := []byte(AccountCreated) + value := []byte("1") + h.db.Store(key, value, true) + res.FlagSet = append(res.FlagSet, flags["flag_account_created"]) + return res, err + } else { return res, err - } + } else { + return res, nil } - - res.FlagSet = append(res.FlagSet, flags["flag_account_created"]) - return res, err } // SavePin persists the user's PIN choice into the filesystem @@ -609,11 +620,11 @@ func (h *Handlers) TransactionReset(ctx context.Context, sym string, input []byt err = h.db.Delete([]byte(Amount)) if err != nil && !errors.Is(err, gdbm.ErrItemNotFound) { - panic(err) + return res,err } err = h.db.Delete([]byte(Recipient)) if err != nil && !errors.Is(err, gdbm.ErrItemNotFound) { - panic(err) + return res,err } res.FlagReset = append(res.FlagReset, flags["flag_invalid_recipient"], flags["flag_invalid_recipient_with_invite"]) @@ -634,7 +645,7 @@ func (h *Handlers) ResetTransactionAmount(ctx context.Context, sym string, input err = h.db.Delete([]byte(Amount)) if err != nil && !errors.Is(err, gdbm.ErrItemNotFound) { - panic(err) + return res,err } res.FlagReset = append(res.FlagReset, flags["flag_invalid_amount"]) From ab6433168a2c4d73e316b98129e91200788c8478 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Tue, 3 Sep 2024 15:02:31 +0300 Subject: [PATCH 158/201] Resolve bug on transaction confirmation PIN --- internal/handlers/ussd/menuhandler.go | 3 ++- services/registration/transaction_initiated.vis | 4 +++- services/registration/transaction_pin.vis | 2 +- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index cb2a913..2491d5f 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -837,9 +837,10 @@ func (h *Handlers) InitiateTransaction(ctx context.Context, sym string, input [] account_authorized_flag, err := h.parser.GetFlag("flag_account_authorized") if err != nil { - res.FlagReset = append(res.FlagReset, account_authorized_flag) + return res, nil } + res.FlagReset = append(res.FlagReset, account_authorized_flag) return res, nil } diff --git a/services/registration/transaction_initiated.vis b/services/registration/transaction_initiated.vis index b1042f5..3b8b9f6 100644 --- a/services/registration/transaction_initiated.vis +++ b/services/registration/transaction_initiated.vis @@ -1,4 +1,6 @@ -LOAD reset_incorrect 0 +LOAD reset_incorrect 6 +CATCH incorrect_pin flag_incorrect_pin 1 +CATCH _ flag_account_authorized 0 LOAD get_amount 10 MAP get_amount RELOAD get_recipient diff --git a/services/registration/transaction_pin.vis b/services/registration/transaction_pin.vis index 878104c..cadbdcf 100644 --- a/services/registration/transaction_pin.vis +++ b/services/registration/transaction_pin.vis @@ -6,7 +6,7 @@ MAP get_sender MOUT back 0 MOUT quit 9 HALT -LOAD authorize_account 1 +LOAD authorize_account 6 RELOAD authorize_account CATCH incorrect_pin flag_incorrect_pin 1 INCMP _ 0 From f90fde90fb70b3352f5bd5d5a110149f064c2ecc Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Tue, 3 Sep 2024 15:04:09 +0300 Subject: [PATCH 159/201] Register flags in debugger from the csv --- cmd/main.go | 60 ++++++++++++++++++++++++++--------------------------- 1 file changed, 29 insertions(+), 31 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index ea38272..a696850 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -2,12 +2,14 @@ package main import ( "context" + "encoding/csv" "flag" "fmt" + "io" "os" "path" + "strconv" - "git.defalsify.org/vise.git/asm" "git.defalsify.org/vise.git/cache" "git.defalsify.org/vise.git/engine" "git.defalsify.org/vise.git/persist" @@ -36,44 +38,40 @@ func main() { st := state.NewState(16) st.UseDebug() - // Initialize the FlagParser pfp := path.Join(scriptDir, "pp.csv") - parser := asm.NewFlagParser() - - // Load flags from the pp.csv file - _, err := parser.Load(pfp) + file, err := os.Open(pfp) if err != nil { - fmt.Fprintf(os.Stderr, "Failed to load flags: %v\n", err) + fmt.Fprintf(os.Stderr, "Failed to open CSV file: %v\n", err) os.Exit(1) } + defer file.Close() + reader := csv.NewReader(file) - // Register all flags loaded from pp.csv - flagKeys := []string{ - "flag_language_set", - "flag_account_created", - "flag_account_creation_failed", - "flag_account_pending", - "flag_account_success", - "flag_pin_mismatch", - "flag_pin_set", - "flag_account_authorized", - "flag_invalid_recipient", - "flag_invalid_recipient_with_invite", - "flag_invalid_amount", - "flag_incorrect_pin", - "flag_valid_pin", - "flag_allow_update", - "flag_single_edit", - "flag_incorrect_date_format", - } - - for _, key := range flagKeys { - id, err := parser.GetFlag(key) + // Iterate through the CSV records and register the flags + for { + record, err := reader.Read() if err != nil { - fmt.Fprintf(os.Stderr, "Failed to get flag %s: %v\n", key, err) + if err == io.EOF { + break + } + fmt.Fprintf(os.Stderr, "Error reading CSV file: %v\n", err) + os.Exit(1) + } + + // Ensure the record starts with "flag" and has at least 3 columns + if len(record) < 3 || record[0] != "flag" { continue } - state.FlagDebugger.Register(id, key) + + flagName := record[1] + flagValue, err := strconv.Atoi(record[2]) + if err != nil { + fmt.Fprintf(os.Stderr, "Failed to convert flag value %s to integer: %v\n", record[2], err) + continue + } + + // Register the flag + state.FlagDebugger.Register(uint32(flagValue), flagName) } rfs := resource.NewFsResource(scriptDir) From fee51edadeae7d685da7c899c1805c4f4711203d Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Tue, 3 Sep 2024 15:07:49 +0300 Subject: [PATCH 160/201] append sessionid to the gdbm file --- cmd/main.go | 2 +- internal/handlers/ussd/menuhandler.go | 18 +++++++++++------- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index ea38272..2ecdd12 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -107,7 +107,7 @@ func main() { fp := path.Join(dp, sessionId) - ussdHandlers, err := ussd.NewHandlers(fp, &st) + ussdHandlers, err := ussd.NewHandlers(fp, &st,sessionId) if err != nil { fmt.Fprintf(os.Stderr, "handler setup failed with error: %v\n", err) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index cb2a913..4544f2c 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -24,7 +24,7 @@ import ( var ( scriptDir = path.Join("services", "registration") translationDir = path.Join(scriptDir, "locale") - dbFile = path.Join(scriptDir, "vise.gdbm") + //dbFile = path.Join(scriptDir, "userdata.gdbm") ) const ( @@ -65,8 +65,9 @@ type Handlers struct { accountService server.AccountServiceInterface } -func NewHandlers(dir string, st *state.State) (*Handlers, error) { - db, err := gdbm.Open(dbFile, gdbm.ModeWrcreat) +func NewHandlers(dir string, st *state.State, sessionId string) (*Handlers, error) { + filename := path.Join(scriptDir, sessionId+"_userdata.gdbm") + db, err := gdbm.Open(filename, gdbm.ModeWrcreat) if err != nil { panic(err) } @@ -425,9 +426,12 @@ func (h *Handlers) Authorize(ctx context.Context, sym string, input []byte) (res res.FlagReset = append(res.FlagReset, flags["flag_account_authorized"]) return res, nil } + } else { + res.FlagSet = append(res.FlagSet, flags["flag_incorrect_pin"]) + res.FlagReset = append(res.FlagReset, flags["flag_account_authorized"]) } } else if errors.Is(err, gdbm.ErrItemNotFound) { - //PIN not set yet + return res, err } else { return res, err } @@ -620,11 +624,11 @@ func (h *Handlers) TransactionReset(ctx context.Context, sym string, input []byt err = h.db.Delete([]byte(Amount)) if err != nil && !errors.Is(err, gdbm.ErrItemNotFound) { - return res,err + return res, err } err = h.db.Delete([]byte(Recipient)) if err != nil && !errors.Is(err, gdbm.ErrItemNotFound) { - return res,err + return res, err } res.FlagReset = append(res.FlagReset, flags["flag_invalid_recipient"], flags["flag_invalid_recipient_with_invite"]) @@ -645,7 +649,7 @@ func (h *Handlers) ResetTransactionAmount(ctx context.Context, sym string, input err = h.db.Delete([]byte(Amount)) if err != nil && !errors.Is(err, gdbm.ErrItemNotFound) { - return res,err + return res, err } res.FlagReset = append(res.FlagReset, flags["flag_invalid_amount"]) From a07a8703f4bf7ec918210b9fd0b7087ff46fb663 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Tue, 3 Sep 2024 15:13:55 +0300 Subject: [PATCH 161/201] remove flag setting invalid pin entry --- internal/handlers/ussd/menuhandler.go | 3 --- 1 file changed, 3 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 34228db..912bd17 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -426,9 +426,6 @@ func (h *Handlers) Authorize(ctx context.Context, sym string, input []byte) (res res.FlagReset = append(res.FlagReset, flags["flag_account_authorized"]) return res, nil } - } else { - res.FlagSet = append(res.FlagSet, flags["flag_incorrect_pin"]) - res.FlagReset = append(res.FlagReset, flags["flag_account_authorized"]) } } else if errors.Is(err, gdbm.ErrItemNotFound) { return res, err From 99d18322b28ecfd660d74b6fd1ca4f237b871c10 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Tue, 3 Sep 2024 15:34:19 +0300 Subject: [PATCH 162/201] Append to the correct flag set/reset --- internal/handlers/ussd/menuhandler.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 912bd17..6ed2c4e 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -219,13 +219,13 @@ func (h *Handlers) SetResetSingleEdit(ctx context.Context, sym string, input []b switch menuOption { case "2": - res.FlagReset = append(res.FlagSet, flags["flag_allow_update"]) + res.FlagReset = append(res.FlagReset, flags["flag_allow_update"]) res.FlagSet = append(res.FlagSet, flags["flag_single_edit"]) case "3": - res.FlagReset = append(res.FlagSet, flags["flag_allow_update"]) + res.FlagReset = append(res.FlagReset, flags["flag_allow_update"]) res.FlagSet = append(res.FlagSet, flags["flag_single_edit"]) case "4": - res.FlagReset = append(res.FlagSet, flags["flag_allow_update"]) + res.FlagReset = append(res.FlagReset, flags["flag_allow_update"]) res.FlagSet = append(res.FlagSet, flags["flag_single_edit"]) default: res.FlagReset = append(res.FlagReset, flags["flag_single_edit"]) @@ -489,8 +489,8 @@ func (h *Handlers) CheckAccountStatus(ctx context.Context, sym string, input []b res.FlagSet = append(res.FlagSet, flags["flag_account_success"]) res.FlagReset = append(res.FlagReset, flags["flag_account_pending"]) } else { - res.FlagReset = append(res.FlagSet, flags["flag_account_success"]) - res.FlagSet = append(res.FlagReset, flags["flag_account_pending"]) + res.FlagReset = append(res.FlagReset, flags["flag_account_success"]) + res.FlagSet = append(res.FlagSet, flags["flag_account_pending"]) } return res, nil } From ee4db50e00e10f6384a1653f5f71720dfddc24bc Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Tue, 3 Sep 2024 17:59:03 +0300 Subject: [PATCH 163/201] remove unused code --- internal/handlers/ussd/menuhandler.go | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 912bd17..87a2a3e 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -24,7 +24,6 @@ import ( var ( scriptDir = path.Join("services", "registration") translationDir = path.Join(scriptDir, "locale") - //dbFile = path.Join(scriptDir, "userdata.gdbm") ) const ( @@ -219,13 +218,13 @@ func (h *Handlers) SetResetSingleEdit(ctx context.Context, sym string, input []b switch menuOption { case "2": - res.FlagReset = append(res.FlagSet, flags["flag_allow_update"]) + res.FlagReset = append(res.FlagReset, flags["flag_allow_update"]) res.FlagSet = append(res.FlagSet, flags["flag_single_edit"]) case "3": - res.FlagReset = append(res.FlagSet, flags["flag_allow_update"]) + res.FlagReset = append(res.FlagReset, flags["flag_allow_update"]) res.FlagSet = append(res.FlagSet, flags["flag_single_edit"]) case "4": - res.FlagReset = append(res.FlagSet, flags["flag_allow_update"]) + res.FlagReset = append(res.FlagReset, flags["flag_allow_update"]) res.FlagSet = append(res.FlagSet, flags["flag_single_edit"]) default: res.FlagReset = append(res.FlagReset, flags["flag_single_edit"]) @@ -755,11 +754,9 @@ func (h *Handlers) GetRecipient(ctx context.Context, sym string, input []byte) ( return res, nil } -// GetSender retrieves the public key from a JSON data file. +// GetSender retrieves the public key from the Gdbm Db func (h *Handlers) GetSender(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - - //accountData, err := h.accountFileHandler.ReadAccountData() publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) if err != nil { return res, err @@ -770,7 +767,7 @@ func (h *Handlers) GetSender(ctx context.Context, sym string, input []byte) (res return res, nil } -// GetAmount retrieves the amount from a JSON data file. +// GetAmount retrieves the amount from teh Gdbm Db func (h *Handlers) GetAmount(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} amount, err := h.db.Fetch([]byte(Amount)) From 5105e902f1419953b7f1c9c88c687c243e34c1bf Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Tue, 3 Sep 2024 19:06:37 +0300 Subject: [PATCH 164/201] Process flags once and make them available across functions --- internal/handlers/ussd/menuhandler.go | 279 +++++++++++--------------- 1 file changed, 117 insertions(+), 162 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index d66a87d..d7a98ef 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -9,6 +9,7 @@ import ( "regexp" "strconv" "strings" + "sync" "git.defalsify.org/vise.git/asm" "git.defalsify.org/vise.git/engine" @@ -52,6 +53,33 @@ type FSData struct { St *state.State } +// FlagManager handles centralized flag management +type FlagManager struct { + parser *asm.FlagParser + mu sync.RWMutex +} + +// NewFlagManager creates a new FlagManager instance +func NewFlagManager(csvPath string) (*FlagManager, error) { + parser := asm.NewFlagParser() + _, err := parser.Load(csvPath) + if err != nil { + return nil, fmt.Errorf("failed to load flag parser: %v", err) + } + + return &FlagManager{ + parser: parser, + }, nil +} + +// GetFlag retrieves a flag value by its label +func (fm *FlagManager) GetFlag(label string) (uint32, error) { + fm.mu.RLock() + defer fm.mu.RUnlock() + + return fm.parser.GetFlag(label) +} + type FlagParserInterface interface { GetFlag(key string) (uint32, error) } @@ -59,7 +87,7 @@ type FlagParserInterface interface { type Handlers struct { fs *FSData db *gdbm.Database - parser FlagParserInterface + flagManager *FlagManager accountFileHandler utils.AccountFileHandlerInterface accountService server.AccountServiceInterface } @@ -71,10 +99,9 @@ func NewHandlers(dir string, st *state.State, sessionId string) (*Handlers, erro panic(err) } pfp := path.Join(scriptDir, "pp.csv") - parser := asm.NewFlagParser() - _, err = parser.Load(pfp) + flagManager, err := NewFlagManager(pfp) if err != nil { - return nil, err + return nil, fmt.Errorf("failed to create flag manager: %v", err) } return &Handlers{ db: db, @@ -82,7 +109,7 @@ func NewHandlers(dir string, st *state.State, sessionId string) (*Handlers, erro Path: dir, St: st, }, - parser: parser, + flagManager: flagManager, accountFileHandler: utils.NewAccountFileHandler(dir + "_data"), accountService: &server.AccountService{}, }, nil @@ -100,7 +127,7 @@ func isValidPIN(pin string) bool { func (h *Handlers) PreloadFlags(flagKeys []string) (map[string]uint32, error) { flags := make(map[string]uint32) for _, key := range flagKeys { - flag, err := h.parser.GetFlag(key) + flag, err := h.flagManager.GetFlag(key) if err != nil { return nil, err } @@ -113,13 +140,6 @@ func (h *Handlers) PreloadFlags(flagKeys []string) (map[string]uint32, error) { func (h *Handlers) SetLanguage(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - // Preload the required flag - flagKeys := []string{"flag_language_set"} - flags, err := h.PreloadFlags(flagKeys) - if err != nil { - return res, err - } - inputStr := string(input) switch inputStr { case "0": @@ -131,7 +151,11 @@ func (h *Handlers) SetLanguage(ctx context.Context, sym string, input []byte) (r default: } - res.FlagSet = append(res.FlagSet, flags["flag_language_set"]) + languageSetFlag, err := h.flagManager.GetFlag("flag_language_set") + if err != nil { + return res, err + } + res.FlagSet = append(res.FlagSet, languageSetFlag) return res, nil } @@ -141,18 +165,14 @@ func (h *Handlers) SetLanguage(ctx context.Context, sym string, input []byte) (r // sets the default values and flags func (h *Handlers) CreateAccount(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - // Preload the required flags - flagKeys := []string{"flag_account_created", "flag_account_creation_failed"} - flags, err := h.PreloadFlags(flagKeys) - if err != nil { - return res, err - } - _, err = h.db.Fetch([]byte(AccountCreated)) + + _, err := h.db.Fetch([]byte(AccountCreated)) if err != nil { if errors.Is(err, gdbm.ErrItemNotFound) { accountResp, err := h.accountService.CreateAccount() if err != nil { - res.FlagSet = append(res.FlagSet, flags["flag_account_creation_failed"]) + flag_account_creation_failed, _ := h.flagManager.GetFlag("flag_account_creation_failed") + res.FlagSet = append(res.FlagSet, flag_account_creation_failed) return res, err } data := map[string]string{ @@ -170,7 +190,8 @@ func (h *Handlers) CreateAccount(ctx context.Context, sym string, input []byte) key := []byte(AccountCreated) value := []byte("1") h.db.Store(key, value, true) - res.FlagSet = append(res.FlagSet, flags["flag_account_created"]) + flag_account_created, _ := h.flagManager.GetFlag("flag_account_created") + res.FlagSet = append(res.FlagSet, flag_account_created) return res, err } else { return res, err @@ -183,19 +204,17 @@ func (h *Handlers) CreateAccount(ctx context.Context, sym string, input []byte) // SavePin persists the user's PIN choice into the filesystem func (h *Handlers) SavePin(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - flagKeys := []string{"flag_incorrect_pin"} - flags, err := h.PreloadFlags(flagKeys) - if err != nil { - return res, err - } + + flag_incorrect_pin, _ := h.flagManager.GetFlag("flag_incorrect_pin") + accountPIN := string(input) // Validate that the PIN is a 4-digit number if !isValidPIN(accountPIN) { - res.FlagSet = append(res.FlagSet, flags["flag_incorrect_pin"]) + res.FlagSet = append(res.FlagSet, flag_incorrect_pin) return res, nil } - res.FlagReset = append(res.FlagReset, flags["flag_incorrect_pin"]) + res.FlagReset = append(res.FlagReset, flag_incorrect_pin) key := []byte(AccountPin) value := []byte(accountPIN) @@ -209,25 +228,21 @@ func (h *Handlers) SetResetSingleEdit(ctx context.Context, sym string, input []b res := resource.Result{} menuOption := string(input) - // Preload the required flags - flagKeys := []string{"flag_allow_update", "flag_single_edit"} - flags, err := h.PreloadFlags(flagKeys) - if err != nil { - return res, err - } + flag_allow_update, _ := h.flagManager.GetFlag("flag_allow_update") + flag_single_edit, _ := h.flagManager.GetFlag("flag_single_edit") switch menuOption { case "2": - res.FlagReset = append(res.FlagReset, flags["flag_allow_update"]) - res.FlagSet = append(res.FlagSet, flags["flag_single_edit"]) + res.FlagReset = append(res.FlagReset, flag_allow_update) + res.FlagSet = append(res.FlagSet, flag_single_edit) case "3": - res.FlagReset = append(res.FlagReset, flags["flag_allow_update"]) - res.FlagSet = append(res.FlagSet, flags["flag_single_edit"]) + res.FlagReset = append(res.FlagReset, flag_allow_update) + res.FlagSet = append(res.FlagSet, flag_single_edit) case "4": - res.FlagReset = append(res.FlagReset, flags["flag_allow_update"]) - res.FlagSet = append(res.FlagSet, flags["flag_single_edit"]) + res.FlagReset = append(res.FlagReset, flag_allow_update) + res.FlagSet = append(res.FlagSet, flag_single_edit) default: - res.FlagReset = append(res.FlagReset, flags["flag_single_edit"]) + res.FlagReset = append(res.FlagReset, flag_single_edit) } return res, nil @@ -239,23 +254,20 @@ func (h *Handlers) SetResetSingleEdit(ctx context.Context, sym string, input []b func (h *Handlers) VerifyPin(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - // Preload the required flags - flagKeys := []string{"flag_valid_pin", "flag_pin_mismatch", "flag_pin_set"} - flags, err := h.PreloadFlags(flagKeys) - if err != nil { - return res, err - } + flag_valid_pin, _ := h.flagManager.GetFlag("flag_valid_pin") + flag_pin_mismatch, _ := h.flagManager.GetFlag("flag_pin_mismatch") + flag_pin_set, _ := h.flagManager.GetFlag("flag_pin_set") AccountPin, err := h.db.Fetch([]byte(AccountPin)) if err != nil { return res, err } if bytes.Equal(input, AccountPin) { - res.FlagSet = []uint32{flags["flag_valid_pin"]} - res.FlagReset = []uint32{flags["flag_pin_mismatch"]} - res.FlagSet = append(res.FlagSet, flags["flag_pin_set"]) + res.FlagSet = []uint32{flag_valid_pin} + res.FlagReset = []uint32{flag_pin_mismatch} + res.FlagSet = append(res.FlagSet, flag_pin_set) } else { - res.FlagSet = []uint32{flags["flag_pin_mismatch"]} + res.FlagSet = []uint32{flag_pin_mismatch} } return res, nil @@ -362,14 +374,9 @@ func (h *Handlers) SaveOfferings(ctx context.Context, sym string, input []byte) func (h *Handlers) ResetAllowUpdate(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - // Preload the required flag - flagKeys := []string{"flag_allow_update"} - flags, err := h.PreloadFlags(flagKeys) - if err != nil { - return res, err - } + flag_allow_update, _ := h.flagManager.GetFlag("flag_allow_update") - res.FlagReset = append(res.FlagReset, flags["flag_allow_update"]) + res.FlagReset = append(res.FlagReset, flag_allow_update) return res, nil } @@ -377,14 +384,9 @@ func (h *Handlers) ResetAllowUpdate(ctx context.Context, sym string, input []byt func (h *Handlers) ResetAccountAuthorized(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - // Preload the required flags - flagKeys := []string{"flag_account_authorized"} - flags, err := h.PreloadFlags(flagKeys) - if err != nil { - return res, err - } + flag_account_authorized, _ := h.flagManager.GetFlag("flag_account_authorized") - res.FlagReset = append(res.FlagReset, flags["flag_account_authorized"]) + res.FlagReset = append(res.FlagReset, flag_account_authorized) return res, nil } @@ -403,26 +405,25 @@ func (h *Handlers) CheckIdentifier(ctx context.Context, sym string, input []byte // It sets the required flags that control the flow. func (h *Handlers) Authorize(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - // Preload the required flags - flagKeys := []string{"flag_incorrect_pin", "flag_account_authorized", "flag_allow_update"} - flags, err := h.PreloadFlags(flagKeys) - if err != nil { - return res, err - } + + flag_incorrect_pin, _ := h.flagManager.GetFlag("flag_incorrect_pin") + flag_account_authorized, _ := h.flagManager.GetFlag("flag_account_authorized") + flag_allow_update, _ := h.flagManager.GetFlag("flag_allow_update") + storedpin, err := h.db.Fetch([]byte(AccountPin)) if err == nil { if len(input) == 4 { if bytes.Equal(input, storedpin) { - if h.fs.St.MatchFlag(flags["flag_account_authorized"], false) { - res.FlagReset = append(res.FlagReset, flags["flag_incorrect_pin"]) - res.FlagSet = append(res.FlagSet, flags["flag_allow_update"], flags["flag_account_authorized"]) + if h.fs.St.MatchFlag(flag_account_authorized, false) { + res.FlagReset = append(res.FlagReset, flag_incorrect_pin) + res.FlagSet = append(res.FlagSet, flag_allow_update, flag_account_authorized) } else { - res.FlagSet = append(res.FlagSet, flags["flag_allow_update"]) - res.FlagReset = append(res.FlagReset, flags["flag_account_authorized"]) + res.FlagSet = append(res.FlagSet, flag_allow_update) + res.FlagReset = append(res.FlagReset, flag_account_authorized) } } else { - res.FlagSet = append(res.FlagSet, flags["flag_incorrect_pin"]) - res.FlagReset = append(res.FlagReset, flags["flag_account_authorized"]) + res.FlagSet = append(res.FlagSet, flag_incorrect_pin) + res.FlagReset = append(res.FlagReset, flag_account_authorized) return res, nil } } @@ -438,14 +439,9 @@ func (h *Handlers) Authorize(ctx context.Context, sym string, input []byte) (res func (h *Handlers) ResetIncorrectPin(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - // Preload the required flag - flagKeys := []string{"flag_incorrect_pin"} - flags, err := h.PreloadFlags(flagKeys) - if err != nil { - return res, err - } + flag_incorrect_pin, _ := h.flagManager.GetFlag("flag_incorrect_pin") - res.FlagReset = append(res.FlagReset, flags["flag_incorrect_pin"]) + res.FlagReset = append(res.FlagReset, flag_incorrect_pin) return res, nil } @@ -454,12 +450,9 @@ func (h *Handlers) ResetIncorrectPin(ctx context.Context, sym string, input []by func (h *Handlers) CheckAccountStatus(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - // Preload the required flags - flagKeys := []string{"flag_account_success", "flag_account_pending"} - flags, err := h.PreloadFlags(flagKeys) - if err != nil { - return res, err - } + flag_account_success, _ := h.flagManager.GetFlag("flag_account_success") + flag_account_pending, _ := h.flagManager.GetFlag("flag_account_pending") + trackingId, err := h.db.Fetch([]byte(TrackingIdKey)) if err != nil { @@ -485,11 +478,11 @@ func (h *Handlers) CheckAccountStatus(ctx context.Context, sym string, input []b } if status == "SUCCESS" { - res.FlagSet = append(res.FlagSet, flags["flag_account_success"]) - res.FlagReset = append(res.FlagReset, flags["flag_account_pending"]) + res.FlagSet = append(res.FlagSet, flag_account_success) + res.FlagReset = append(res.FlagReset, flag_account_pending) } else { - res.FlagReset = append(res.FlagReset, flags["flag_account_success"]) - res.FlagSet = append(res.FlagSet, flags["flag_account_pending"]) + res.FlagReset = append(res.FlagReset, flag_account_success) + res.FlagSet = append(res.FlagSet, flag_account_pending) } return res, nil } @@ -498,19 +491,14 @@ func (h *Handlers) CheckAccountStatus(ctx context.Context, sym string, input []b func (h *Handlers) Quit(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - // Preload the required flags - flagKeys := []string{"flag_account_authorized"} - flags, err := h.PreloadFlags(flagKeys) - if err != nil { - return res, err - } + flag_account_authorized, _ := h.flagManager.GetFlag("flag_account_authorized") code := codeFromCtx(ctx) l := gotext.NewLocale(translationDir, code) l.AddDomain("default") res.Content = l.Get("Thank you for using Sarafu. Goodbye!") - res.FlagReset = append(res.FlagReset, flags["flag_account_authorized"]) + res.FlagReset = append(res.FlagReset, flag_account_authorized) return res, nil } @@ -518,25 +506,20 @@ func (h *Handlers) Quit(ctx context.Context, sym string, input []byte) (resource func (h *Handlers) VerifyYob(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - // Preload the required flag - flagKeys := []string{"flag_incorrect_date_format"} - flags, err := h.PreloadFlags(flagKeys) - if err != nil { - return res, err - } + flag_incorrect_date_format, _ := h.flagManager.GetFlag("flag_incorrect_date_format") date := string(input) - _, err = strconv.Atoi(date) + _, err := strconv.Atoi(date) if err != nil { // If conversion fails, input is not numeric - res.FlagSet = append(res.FlagSet, flags["flag_incorrect_date_format"]) + res.FlagSet = append(res.FlagSet, flag_incorrect_date_format) return res, nil } if len(date) == 4 { - res.FlagReset = append(res.FlagReset, flags["flag_incorrect_date_format"]) + res.FlagReset = append(res.FlagReset, flag_incorrect_date_format) } else { - res.FlagSet = append(res.FlagSet, flags["flag_incorrect_date_format"]) + res.FlagSet = append(res.FlagSet, flag_incorrect_date_format) } return res, nil @@ -546,14 +529,9 @@ func (h *Handlers) VerifyYob(ctx context.Context, sym string, input []byte) (res func (h *Handlers) ResetIncorrectYob(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - // Preload the required flags - flagKeys := []string{"flag_incorrect_date_format"} - flags, err := h.PreloadFlags(flagKeys) - if err != nil { - return res, err - } + flag_incorrect_date_format, _ := h.flagManager.GetFlag("flag_incorrect_date_format") - res.FlagReset = append(res.FlagReset, flags["flag_incorrect_date_format"]) + res.FlagReset = append(res.FlagReset, flag_incorrect_date_format) return res, nil } @@ -581,16 +559,12 @@ func (h *Handlers) ValidateRecipient(ctx context.Context, sym string, input []by res := resource.Result{} recipient := string(input) - flagKeys := []string{"flag_invalid_recipient"} - flags, err := h.PreloadFlags(flagKeys) - if err != nil { - return res, err - } + flag_invalid_recipient, _ := h.flagManager.GetFlag("flag_invalid_recipient") if recipient != "0" { // mimic invalid number check if recipient == "000" { - res.FlagSet = append(res.FlagSet, flags["flag_invalid_recipient"]) + res.FlagSet = append(res.FlagSet, flag_invalid_recipient) res.Content = recipient return res, nil @@ -611,14 +585,10 @@ func (h *Handlers) ValidateRecipient(ctx context.Context, sym string, input []by func (h *Handlers) TransactionReset(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - // Preload the required flags - flagKeys := []string{"flag_invalid_recipient", "flag_invalid_recipient_with_invite"} - flags, err := h.PreloadFlags(flagKeys) - if err != nil { - return res, err - } + flag_invalid_recipient, _ := h.flagManager.GetFlag("flag_invalid_recipient") + flag_invalid_recipient_with_invite, _ := h.flagManager.GetFlag("flag_invalid_recipient_with_invite") - err = h.db.Delete([]byte(Amount)) + err := h.db.Delete([]byte(Amount)) if err != nil && !errors.Is(err, gdbm.ErrItemNotFound) { return res, err } @@ -627,7 +597,7 @@ func (h *Handlers) TransactionReset(ctx context.Context, sym string, input []byt return res, err } - res.FlagReset = append(res.FlagReset, flags["flag_invalid_recipient"], flags["flag_invalid_recipient_with_invite"]) + res.FlagReset = append(res.FlagReset, flag_invalid_recipient, flag_invalid_recipient_with_invite) return res, nil } @@ -636,19 +606,14 @@ func (h *Handlers) TransactionReset(ctx context.Context, sym string, input []byt func (h *Handlers) ResetTransactionAmount(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - // Preload the required flag - flagKeys := []string{"flag_invalid_amount"} - flags, err := h.PreloadFlags(flagKeys) - if err != nil { - return res, err - } + flag_invalid_amount, _ := h.flagManager.GetFlag("flag_invalid_amount") - err = h.db.Delete([]byte(Amount)) + err := h.db.Delete([]byte(Amount)) if err != nil && !errors.Is(err, gdbm.ErrItemNotFound) { return res, err } - res.FlagReset = append(res.FlagReset, flags["flag_invalid_amount"]) + res.FlagReset = append(res.FlagReset, flag_invalid_amount) return res, nil } @@ -676,12 +641,8 @@ func (h *Handlers) MaxAmount(ctx context.Context, sym string, input []byte) (res // it is not more than the current balance. func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - // Preload the required flag - flagKeys := []string{"flag_invalid_amount"} - flags, err := h.PreloadFlags(flagKeys) - if err != nil { - return res, err - } + + flag_invalid_amount, _ := h.flagManager.GetFlag("flag_invalid_amount") amountStr := string(input) publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) @@ -711,20 +672,20 @@ func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte) re := regexp.MustCompile(`^(\d+(\.\d+)?)\s*(?:CELO)?$`) matches := re.FindStringSubmatch(strings.TrimSpace(amountStr)) if len(matches) < 2 { - res.FlagSet = append(res.FlagSet, flags["flag_invalid_amount"]) + res.FlagSet = append(res.FlagSet, flag_invalid_amount) res.Content = amountStr return res, nil } inputAmount, err := strconv.ParseFloat(matches[1], 64) if err != nil { - res.FlagSet = append(res.FlagSet, flags["flag_invalid_amount"]) + res.FlagSet = append(res.FlagSet, flag_invalid_amount) res.Content = amountStr return res, nil } if inputAmount > balanceValue { - res.FlagSet = append(res.FlagSet, flags["flag_invalid_amount"]) + res.FlagSet = append(res.FlagSet, flag_invalid_amount) res.Content = amountStr return res, nil } @@ -784,12 +745,7 @@ func (h *Handlers) GetAmount(ctx context.Context, sym string, input []byte) (res func (h *Handlers) QuitWithBalance(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - // Preload the required flag - flagKeys := []string{"flag_account_authorized"} - flags, err := h.PreloadFlags(flagKeys) - if err != nil { - return res, err - } + flag_account_authorized, _ := h.flagManager.GetFlag("flag_account_authorized") code := codeFromCtx(ctx) l := gotext.NewLocale(translationDir, code) @@ -803,7 +759,7 @@ func (h *Handlers) QuitWithBalance(ctx context.Context, sym string, input []byte return res, nil } res.Content = l.Get("Your account balance is %s", balance) - res.FlagReset = append(res.FlagReset, flags["flag_account_authorized"]) + res.FlagReset = append(res.FlagReset, flag_account_authorized) return res, nil } @@ -832,10 +788,9 @@ func (h *Handlers) InitiateTransaction(ctx context.Context, sym string, input [] res.Content = l.Get("Your request has been sent. %s will receive %s from %s.", string(recipient), string(amount), string(publicKey)) - account_authorized_flag, err := h.parser.GetFlag("flag_account_authorized") - + account_authorized_flag, err := h.flagManager.GetFlag("flag_account_authorized") if err != nil { - return res, nil + return res, err } res.FlagReset = append(res.FlagReset, account_authorized_flag) From 2d7b6bd125c6bbe8a831ad9170aabdc706097631 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Tue, 3 Sep 2024 22:28:48 +0300 Subject: [PATCH 165/201] Removed unused code --- internal/handlers/ussd/menuhandler.go | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index d7a98ef..12ddcde 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -80,10 +80,6 @@ func (fm *FlagManager) GetFlag(label string) (uint32, error) { return fm.parser.GetFlag(label) } -type FlagParserInterface interface { - GetFlag(key string) (uint32, error) -} - type Handlers struct { fs *FSData db *gdbm.Database @@ -124,18 +120,6 @@ func isValidPIN(pin string) bool { return match } -func (h *Handlers) PreloadFlags(flagKeys []string) (map[string]uint32, error) { - flags := make(map[string]uint32) - for _, key := range flagKeys { - flag, err := h.flagManager.GetFlag(key) - if err != nil { - return nil, err - } - flags[key] = flag - } - return flags, nil -} - // SetLanguage sets the language across the menu func (h *Handlers) SetLanguage(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} From 8ffc5d67ccb00973dccb117fe9ce16466ab29501 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Wed, 4 Sep 2024 12:01:51 +0300 Subject: [PATCH 166/201] Removed mutex --- internal/handlers/ussd/menuhandler.go | 5 ----- 1 file changed, 5 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 12ddcde..c47f2e0 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -9,7 +9,6 @@ import ( "regexp" "strconv" "strings" - "sync" "git.defalsify.org/vise.git/asm" "git.defalsify.org/vise.git/engine" @@ -56,7 +55,6 @@ type FSData struct { // FlagManager handles centralized flag management type FlagManager struct { parser *asm.FlagParser - mu sync.RWMutex } // NewFlagManager creates a new FlagManager instance @@ -74,9 +72,6 @@ func NewFlagManager(csvPath string) (*FlagManager, error) { // GetFlag retrieves a flag value by its label func (fm *FlagManager) GetFlag(label string) (uint32, error) { - fm.mu.RLock() - defer fm.mu.RUnlock() - return fm.parser.GetFlag(label) } From 2fc8a0e5a7cbffafce8fa1904c5c200d1d9919c7 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Wed, 4 Sep 2024 19:57:08 +0300 Subject: [PATCH 167/201] use fsDb for the resources --- cmd/main.go | 62 ++++++++++++++++++++++++++--------------------------- 1 file changed, 30 insertions(+), 32 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index 72d1d11..017f150 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -11,6 +11,7 @@ import ( "strconv" "git.defalsify.org/vise.git/cache" + fsdb "git.defalsify.org/vise.git/db/fs" "git.defalsify.org/vise.git/engine" "git.defalsify.org/vise.git/persist" "git.defalsify.org/vise.git/resource" @@ -20,8 +21,20 @@ import ( var ( scriptDir = path.Join("services", "registration") + store = fsdb.NewFsDb() + pr = persist.NewPersister(store) ) +type menuResource struct { + *resource.DbResource +} + +func newMenuResource(rs *resource.DbResource) resource.Resource { + return &menuResource{ + rs, + } +} + func main() { var dir string var root string @@ -35,8 +48,6 @@ func main() { fmt.Fprintf(os.Stderr, "starting session at symbol '%s' using resource dir: %s\n", root, dir) ctx := context.Background() - st := state.NewState(16) - st.UseDebug() pfp := path.Join(scriptDir, "pp.csv") file, err := os.Open(pfp) @@ -74,11 +85,11 @@ func main() { state.FlagDebugger.Register(uint32(flagValue), flagName) } - rfs := resource.NewFsResource(scriptDir) ca := cache.NewCache() cfg := engine.Config{ Root: "root", SessionId: sessionId, + FlagCount: uint32(16), } dp := path.Join(scriptDir, ".state") @@ -87,25 +98,26 @@ func main() { fmt.Fprintf(os.Stderr, "state dir create exited with error: %v\n", err) os.Exit(1) } - pr := persist.NewFsPersister(dp) - en, err := engine.NewPersistedEngine(ctx, cfg, pr, rfs) + store := fsdb.NewFsDb() + err = store.Connect(ctx, scriptDir) if err != nil { - pr = pr.WithContent(&st, ca) - err = pr.Save(cfg.SessionId) - if err != nil { - fmt.Fprintf(os.Stderr, "Failed to save state with error: %v\n", err) - } - en, err = engine.NewPersistedEngine(ctx, cfg, pr, rfs) - if err != nil { - fmt.Fprintf(os.Stderr, "engine create exited with error: %v\n", err) - os.Exit(1) - } + panic(err) } + rfs := resource.NewDbResource(store) + + rs, ok := newMenuResource(rfs).(*menuResource) + if !ok { + os.Exit(1) + } + en := engine.NewEngine(cfg, rs) + en = en.WithMemory(ca) + en = en.WithPersister(pr) + fp := path.Join(dp, sessionId) - ussdHandlers, err := ussd.NewHandlers(fp, &st,sessionId) + ussdHandlers, err := ussd.NewHandlers(fp, pr.State, sessionId) if err != nil { fmt.Fprintf(os.Stderr, "handler setup failed with error: %v\n", err) @@ -144,26 +156,12 @@ func main() { rfs.AddLocalFunc("set_reset_single_edit", ussdHandlers.SetResetSingleEdit) rfs.AddLocalFunc("initiate_transaction", ussdHandlers.InitiateTransaction) - cont, err := en.Init(ctx) - en.SetDebugger(engine.NewSimpleDebug(nil)) + _, err = en.Init(ctx) if err != nil { fmt.Fprintf(os.Stderr, "engine init exited with error: %v\n", err) os.Exit(1) } - if !cont { - _, err = en.WriteResult(ctx, os.Stdout) - if err != nil { - fmt.Fprintf(os.Stderr, "dead init write error: %v\n", err) - os.Exit(1) - } - err = en.Finish() - if err != nil { - fmt.Fprintf(os.Stderr, "engine finish error: %v\n", err) - os.Exit(1) - } - os.Stdout.Write([]byte{0x0a}) - os.Exit(0) - } + err = engine.Loop(ctx, en, os.Stdin, os.Stdout) if err != nil { fmt.Fprintf(os.Stderr, "loop exited with error: %v\n", err) From 220c5b2081a8eeacf1c3ae4c822336ebffe3b405 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Wed, 4 Sep 2024 20:22:25 +0300 Subject: [PATCH 168/201] remove commented code --- internal/handlers/ussd/menuhandler.go | 2 -- 1 file changed, 2 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index c47f2e0..004f8b2 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -11,7 +11,6 @@ import ( "strings" "git.defalsify.org/vise.git/asm" - "git.defalsify.org/vise.git/engine" "git.defalsify.org/vise.git/lang" "git.defalsify.org/vise.git/resource" "git.defalsify.org/vise.git/state" @@ -255,7 +254,6 @@ func (h *Handlers) VerifyPin(ctx context.Context, sym string, input []byte) (res // codeFromCtx retrieves language codes from the context that can be used for handling translations func codeFromCtx(ctx context.Context) string { var code string - engine.Logg.DebugCtxf(ctx, "in msg", "ctx", ctx, "val", code) if ctx.Value("Language") != nil { lang := ctx.Value("Language").(lang.Language) code = lang.Code From 771a1e81695450f64b1c89bdeb720de986d54002 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Thu, 5 Sep 2024 17:07:20 +0300 Subject: [PATCH 169/201] code refactoring --- cmd/main.go | 230 ++++++++------ internal/handlers/ussd/menuhandler.go | 439 +++++++++++++------------- internal/utils/account_utils.go | 67 ++-- 3 files changed, 403 insertions(+), 333 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index 017f150..cf9875f 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -2,16 +2,15 @@ package main import ( "context" - "encoding/csv" "flag" "fmt" - "io" "os" "path" - "strconv" - "git.defalsify.org/vise.git/cache" + "git.defalsify.org/vise.git/asm" + "git.defalsify.org/vise.git/db" fsdb "git.defalsify.org/vise.git/db/fs" + gdbmdb "git.defalsify.org/vise.git/db/gdbm" "git.defalsify.org/vise.git/engine" "git.defalsify.org/vise.git/persist" "git.defalsify.org/vise.git/resource" @@ -25,136 +24,165 @@ var ( pr = persist.NewPersister(store) ) -type menuResource struct { - *resource.DbResource +func getFlags(fp string, debug bool) (*asm.FlagParser, error) { + flagParser := asm.NewFlagParser().WithDebug() + _, err := flagParser.Load(fp) + if err != nil { + return nil, err + } + return flagParser, nil } -func newMenuResource(rs *resource.DbResource) resource.Resource { - return &menuResource{ - rs, +func getHandler(appFlags *asm.FlagParser, rs *resource.DbResource, pe *persist.Persister, userdataStore db.Db) (*ussd.Handlers, error) { + + ussdHandlers, err := ussd.NewHandlers(appFlags, pr, store) + if err != nil { + return nil, err } + rs.AddLocalFunc("select_language", ussdHandlers.SetLanguage) + rs.AddLocalFunc("create_account", ussdHandlers.CreateAccount) + rs.AddLocalFunc("save_pin", ussdHandlers.SavePin) + rs.AddLocalFunc("verify_pin", ussdHandlers.VerifyPin) + rs.AddLocalFunc("check_identifier", ussdHandlers.CheckIdentifier) + rs.AddLocalFunc("check_account_status", ussdHandlers.CheckAccountStatus) + rs.AddLocalFunc("authorize_account", ussdHandlers.Authorize) + rs.AddLocalFunc("quit", ussdHandlers.Quit) + rs.AddLocalFunc("check_balance", ussdHandlers.CheckBalance) + rs.AddLocalFunc("validate_recipient", ussdHandlers.ValidateRecipient) + rs.AddLocalFunc("transaction_reset", ussdHandlers.TransactionReset) + rs.AddLocalFunc("max_amount", ussdHandlers.MaxAmount) + rs.AddLocalFunc("validate_amount", ussdHandlers.ValidateAmount) + rs.AddLocalFunc("reset_transaction_amount", ussdHandlers.ResetTransactionAmount) + rs.AddLocalFunc("get_recipient", ussdHandlers.GetRecipient) + rs.AddLocalFunc("get_sender", ussdHandlers.GetSender) + rs.AddLocalFunc("get_amount", ussdHandlers.GetAmount) + rs.AddLocalFunc("reset_incorrect", ussdHandlers.ResetIncorrectPin) + rs.AddLocalFunc("save_firstname", ussdHandlers.SaveFirstname) + rs.AddLocalFunc("save_familyname", ussdHandlers.SaveFamilyname) + rs.AddLocalFunc("save_gender", ussdHandlers.SaveGender) + rs.AddLocalFunc("save_location", ussdHandlers.SaveLocation) + rs.AddLocalFunc("save_yob", ussdHandlers.SaveYob) + rs.AddLocalFunc("save_offerings", ussdHandlers.SaveOfferings) + rs.AddLocalFunc("quit_with_balance", ussdHandlers.QuitWithBalance) + rs.AddLocalFunc("reset_account_authorized", ussdHandlers.ResetAccountAuthorized) + rs.AddLocalFunc("reset_allow_update", ussdHandlers.ResetAllowUpdate) + rs.AddLocalFunc("get_profile_info", ussdHandlers.GetProfileInfo) + rs.AddLocalFunc("verify_yob", ussdHandlers.VerifyYob) + rs.AddLocalFunc("reset_incorrect_date_format", ussdHandlers.ResetIncorrectYob) + rs.AddLocalFunc("set_reset_single_edit", ussdHandlers.SetResetSingleEdit) + rs.AddLocalFunc("initiate_transaction", ussdHandlers.InitiateTransaction) + + return ussdHandlers, nil +} + +func getPersister(dbDir string, ctx context.Context) (*persist.Persister, error) { + err := os.MkdirAll(dbDir, 0700) + if err != nil { + return nil, fmt.Errorf("state dir create exited with error: %v\n", err) + } + store := gdbmdb.NewGdbmDb() + storeFile := path.Join(dbDir, ".state") + store.Connect(ctx, storeFile) + pr := persist.NewPersister(store) + return pr, nil +} + +func getUserdataDb(dbDir string, ctx context.Context) db.Db { + store := gdbmdb.NewGdbmDb() + storeFile := path.Join(dbDir, "userdata.gdbm") + store.Connect(ctx, storeFile) + + return store +} + +func getResource(resourceDir string, ctx context.Context) (resource.Resource, error) { + store := fsdb.NewFsDb() + err := store.Connect(ctx, resourceDir) + if err != nil { + return nil, err + } + rfs := resource.NewDbResource(store) + return rfs, nil +} + +func getEngine(cfg engine.Config, rs resource.Resource, pr *persist.Persister) *engine.DefaultEngine { + en := engine.NewEngine(cfg, rs) + en = en.WithPersister(pr) + return en } func main() { - var dir string - var root string + //var dir string + var dbDir string + var resourceDir string + //var root string var size uint var sessionId string - flag.StringVar(&dir, "d", ".", "resource dir to read from") - flag.UintVar(&size, "s", 0, "max size of output") - flag.StringVar(&root, "root", "root", "entry point symbol") - flag.StringVar(&sessionId, "session-id", "default", "session id") - flag.Parse() - fmt.Fprintf(os.Stderr, "starting session at symbol '%s' using resource dir: %s\n", root, dir) + //flag.StringVar(&dir, "d", ".", "resource dir to read from") + // flag.UintVar(&size, "s", 0, "max size of output") + // flag.StringVar(&root, "root", "root", "entry point symbol") + flag.StringVar(&sessionId, "session-id", "075xx2123", "session id") + // flag.Parse() + // fmt.Fprintf(os.Stderr, "starting session at symbol '%s' using resource dir: %s\n", root, dir) + //logg.Infof("starting session", "symbol", root, "dbdir", dbDir, "sessionid", sessionId, "outsize", size) + + flag.StringVar(&dbDir, "dbdir", ".state", "database dir to read from") + flag.StringVar(&resourceDir, "resourcedir", path.Join("services", "registration"), "resource dir") + flag.UintVar(&size, "s", 160, "max size of output") ctx := context.Background() - + + + ctx = context.WithValue(ctx, "SessionId",sessionId) pfp := path.Join(scriptDir, "pp.csv") - file, err := os.Open(pfp) + flagParser, err := getFlags(pfp, true) + if err != nil { - fmt.Fprintf(os.Stderr, "Failed to open CSV file: %v\n", err) os.Exit(1) } - defer file.Close() - reader := csv.NewReader(file) - // Iterate through the CSV records and register the flags - for { - record, err := reader.Read() - if err != nil { - if err == io.EOF { - break - } - fmt.Fprintf(os.Stderr, "Error reading CSV file: %v\n", err) - os.Exit(1) - } - - // Ensure the record starts with "flag" and has at least 3 columns - if len(record) < 3 || record[0] != "flag" { - continue - } - - flagName := record[1] - flagValue, err := strconv.Atoi(record[2]) - if err != nil { - fmt.Fprintf(os.Stderr, "Failed to convert flag value %s to integer: %v\n", record[2], err) - continue - } - - // Register the flag - state.FlagDebugger.Register(uint32(flagValue), flagName) - } - - ca := cache.NewCache() cfg := engine.Config{ - Root: "root", - SessionId: sessionId, - FlagCount: uint32(16), + Root: "root", + SessionId: sessionId, + OutputSize: uint32(size), + FlagCount: uint32(16), } + //ca := cache.Cache{} + + rs, err := getResource(resourceDir, ctx) - dp := path.Join(scriptDir, ".state") - err = os.MkdirAll(dp, 0700) if err != nil { - fmt.Fprintf(os.Stderr, "state dir create exited with error: %v\n", err) + fmt.Fprintf(os.Stderr, err.Error()) os.Exit(1) } - store := fsdb.NewFsDb() - err = store.Connect(ctx, scriptDir) + pr, err := getPersister(dbDir, ctx) + //pr.WithContent(state.NewState(uint32(16)),&ca) + if err != nil { - panic(err) + fmt.Fprintf(os.Stderr, err.Error()) + os.Exit(1) } - rfs := resource.NewDbResource(store) + store := getUserdataDb(dbDir, ctx) + if err != nil { + fmt.Fprintf(os.Stderr, err.Error()) + os.Exit(1) + } + dbResource, ok := rs.(*resource.DbResource) - rs, ok := newMenuResource(rfs).(*menuResource) if !ok { os.Exit(1) } - en := engine.NewEngine(cfg, rs) - en = en.WithMemory(ca) - en = en.WithPersister(pr) - - fp := path.Join(dp, sessionId) - - ussdHandlers, err := ussd.NewHandlers(fp, pr.State, sessionId) + _, err = getHandler(flagParser, dbResource, pr, store) if err != nil { - fmt.Fprintf(os.Stderr, "handler setup failed with error: %v\n", err) + fmt.Fprintf(os.Stderr, err.Error()) + os.Exit(1) } - rfs.AddLocalFunc("select_language", ussdHandlers.SetLanguage) - rfs.AddLocalFunc("create_account", ussdHandlers.CreateAccount) - rfs.AddLocalFunc("save_pin", ussdHandlers.SavePin) - rfs.AddLocalFunc("verify_pin", ussdHandlers.VerifyPin) - rfs.AddLocalFunc("check_identifier", ussdHandlers.CheckIdentifier) - rfs.AddLocalFunc("check_account_status", ussdHandlers.CheckAccountStatus) - rfs.AddLocalFunc("authorize_account", ussdHandlers.Authorize) - rfs.AddLocalFunc("quit", ussdHandlers.Quit) - rfs.AddLocalFunc("check_balance", ussdHandlers.CheckBalance) - rfs.AddLocalFunc("validate_recipient", ussdHandlers.ValidateRecipient) - rfs.AddLocalFunc("transaction_reset", ussdHandlers.TransactionReset) - rfs.AddLocalFunc("max_amount", ussdHandlers.MaxAmount) - rfs.AddLocalFunc("validate_amount", ussdHandlers.ValidateAmount) - rfs.AddLocalFunc("reset_transaction_amount", ussdHandlers.ResetTransactionAmount) - rfs.AddLocalFunc("get_recipient", ussdHandlers.GetRecipient) - rfs.AddLocalFunc("get_sender", ussdHandlers.GetSender) - rfs.AddLocalFunc("get_amount", ussdHandlers.GetAmount) - rfs.AddLocalFunc("reset_incorrect", ussdHandlers.ResetIncorrectPin) - rfs.AddLocalFunc("save_firstname", ussdHandlers.SaveFirstname) - rfs.AddLocalFunc("save_familyname", ussdHandlers.SaveFamilyname) - rfs.AddLocalFunc("save_gender", ussdHandlers.SaveGender) - rfs.AddLocalFunc("save_location", ussdHandlers.SaveLocation) - rfs.AddLocalFunc("save_yob", ussdHandlers.SaveYob) - rfs.AddLocalFunc("save_offerings", ussdHandlers.SaveOfferings) - rfs.AddLocalFunc("quit_with_balance", ussdHandlers.QuitWithBalance) - rfs.AddLocalFunc("reset_account_authorized", ussdHandlers.ResetAccountAuthorized) - rfs.AddLocalFunc("reset_allow_update", ussdHandlers.ResetAllowUpdate) - rfs.AddLocalFunc("get_profile_info", ussdHandlers.GetProfileInfo) - rfs.AddLocalFunc("verify_yob", ussdHandlers.VerifyYob) - rfs.AddLocalFunc("reset_incorrect_date_format", ussdHandlers.ResetIncorrectYob) - rfs.AddLocalFunc("set_reset_single_edit", ussdHandlers.SetResetSingleEdit) - rfs.AddLocalFunc("initiate_transaction", ussdHandlers.InitiateTransaction) + en := getEngine(cfg, rs, pr) + en.WithState(state.NewState(uint32(16))) _, err = en.Init(ctx) if err != nil { diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 004f8b2..5972445 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -3,7 +3,6 @@ package ussd import ( "bytes" "context" - "errors" "fmt" "path" "regexp" @@ -11,12 +10,15 @@ import ( "strings" "git.defalsify.org/vise.git/asm" + + "git.defalsify.org/vise.git/cache" + "git.defalsify.org/vise.git/db" "git.defalsify.org/vise.git/lang" + "git.defalsify.org/vise.git/persist" "git.defalsify.org/vise.git/resource" "git.defalsify.org/vise.git/state" "git.grassecon.net/urdt/ussd/internal/handlers/server" "git.grassecon.net/urdt/ussd/internal/utils" - "github.com/graygnuorg/go-gdbm" "gopkg.in/leonelquinteros/gotext.v1" ) @@ -42,10 +44,6 @@ const ( AccountCreated = "ACCOUNTCREATED" ) -func toBytes(s string) []byte { - return []byte(s) -} - type FSData struct { Path string St *state.State @@ -74,35 +72,37 @@ func (fm *FlagManager) GetFlag(label string) (uint32, error) { return fm.parser.GetFlag(label) } +// type Handlers struct { +// fs *FSData +// db *gdbm.Database +// flagManager *FlagManager +// accountFileHandler utils.AccountFileHandlerInterface +// accountService server.AccountServiceInterface +// } + type Handlers struct { - fs *FSData - db *gdbm.Database - flagManager *FlagManager - accountFileHandler utils.AccountFileHandlerInterface + st *state.State + ca cache.Memory + userdataStore db.Db + flagManager *asm.FlagParser + accountFileHandler *utils.AccountFileHandler accountService server.AccountServiceInterface } -func NewHandlers(dir string, st *state.State, sessionId string) (*Handlers, error) { - filename := path.Join(scriptDir, sessionId+"_userdata.gdbm") - db, err := gdbm.Open(filename, gdbm.ModeWrcreat) - if err != nil { - panic(err) - } - pfp := path.Join(scriptDir, "pp.csv") - flagManager, err := NewFlagManager(pfp) - if err != nil { - return nil, fmt.Errorf("failed to create flag manager: %v", err) - } - return &Handlers{ - db: db, - fs: &FSData{ - Path: dir, - St: st, - }, - flagManager: flagManager, - accountFileHandler: utils.NewAccountFileHandler(dir + "_data"), +func NewHandlers(appFlags *asm.FlagParser, pe *persist.Persister, userdataStore db.Db) (*Handlers, error) { + h := &Handlers{ + st: state.NewState(uint32(16)), + ca: pe.GetMemory(), + userdataStore: userdataStore, + flagManager: appFlags, + accountFileHandler: utils.NewAccountFileHandler(userdataStore), accountService: &server.AccountService{}, - }, nil + } + if h.st == nil || h.ca == nil || h.userdataStore == nil || h.flagManager == nil { + //logg.Errorf("have nil for essential value in handler", "state", h.st, "cache", h.ca, "store", h.userdataStore, "flags", h.flagManager) + return nil, fmt.Errorf("have nil for essential value") + } + return h, nil } // Define the regex pattern as a constant @@ -138,45 +138,53 @@ func (h *Handlers) SetLanguage(ctx context.Context, sym string, input []byte) (r return res, nil } +func (h *Handlers) createAccountNoExist(ctx context.Context, sessionId string, res *resource.Result) error { + accountResp, err := h.accountService.CreateAccount() + data := map[utils.DataTyp]string{ + utils.DATA_TRACKING_ID: accountResp.Result.TrackingId, + utils.DATA_PUBLIC_KEY: accountResp.Result.PublicKey, + utils.DATA_CUSTODIAL_ID: accountResp.Result.CustodialId.String(), + } + + for key, value := range data { + err := utils.WriteEntry(ctx, h.userdataStore, sessionId, key, []byte(value)) + if err != nil { + return err + } + } + flag_account_created, _ := h.flagManager.GetFlag("flag_account_created") + res.FlagSet = append(res.FlagSet, flag_account_created) + return err + +} + // CreateAccount checks if any account exists on the JSON data file, and if not // creates an account on the API, // sets the default values and flags func (h *Handlers) CreateAccount(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - - _, err := h.db.Fetch([]byte(AccountCreated)) + var err error + sessionId, ok := ctx.Value("SessionId").(string) + if !ok { + return res, fmt.Errorf("missing session") + } + _, err = utils.ReadEntry(ctx, h.userdataStore, sessionId, utils.DATA_ACCOUNT_CREATED) if err != nil { - if errors.Is(err, gdbm.ErrItemNotFound) { - accountResp, err := h.accountService.CreateAccount() + if db.IsNotFound(err) { + fmt.Println("Creating an account because it doesn't exist") + err = h.createAccountNoExist(ctx, sessionId, &res) if err != nil { - flag_account_creation_failed, _ := h.flagManager.GetFlag("flag_account_creation_failed") - res.FlagSet = append(res.FlagSet, flag_account_creation_failed) return res, err } - data := map[string]string{ - TrackingIdKey: accountResp.Result.TrackingId, - PublicKeyKey: accountResp.Result.PublicKey, - CustodialIdKey: accountResp.Result.CustodialId.String(), - } - - for key, value := range data { - err := h.db.Store(toBytes(key), toBytes(value), true) - if err != nil { - return res, err - } - } - key := []byte(AccountCreated) - value := []byte("1") - h.db.Store(key, value, true) - flag_account_created, _ := h.flagManager.GetFlag("flag_account_created") - res.FlagSet = append(res.FlagSet, flag_account_created) - return res, err } else { - return res, err + fmt.Println("Error here:", err) + err = h.createAccountNoExist(ctx, sessionId, &res) + if err != nil { + return res, err + } } - } else { - return res, nil } + return res, nil } // SavePin persists the user's PIN choice into the filesystem @@ -194,10 +202,10 @@ func (h *Handlers) SavePin(ctx context.Context, sym string, input []byte) (resou res.FlagReset = append(res.FlagReset, flag_incorrect_pin) - key := []byte(AccountPin) - value := []byte(accountPIN) + // key := []byte(AccountPin) + // value := []byte(accountPIN) - h.db.Store(key, value, true) + //h.db.Store(key, value, true) return res, nil } @@ -236,10 +244,11 @@ func (h *Handlers) VerifyPin(ctx context.Context, sym string, input []byte) (res flag_pin_mismatch, _ := h.flagManager.GetFlag("flag_pin_mismatch") flag_pin_set, _ := h.flagManager.GetFlag("flag_pin_set") - AccountPin, err := h.db.Fetch([]byte(AccountPin)) - if err != nil { - return res, err - } + // AccountPin, err := h.db.Fetch([]byte(AccountPin)) + // if err != nil { + // return res, err + // } + AccountPin := []byte("2768") if bytes.Equal(input, AccountPin) { res.FlagSet = []uint32{flag_valid_pin} res.FlagReset = []uint32{flag_pin_mismatch} @@ -265,10 +274,10 @@ func codeFromCtx(ctx context.Context) string { func (h *Handlers) SaveFirstname(cxt context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} if len(input) > 0 { - name := string(input) - key := []byte(FirstName) - value := []byte(name) - h.db.Store(key, value, true) + //name := string(input) + //key := []byte(FirstName) + //value := []byte(name) + //h.db.Store(key, value, true) } return res, nil @@ -278,10 +287,10 @@ func (h *Handlers) SaveFirstname(cxt context.Context, sym string, input []byte) func (h *Handlers) SaveFamilyname(cxt context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} if len(input) > 0 { - secondname := string(input) - key := []byte(FamilyName) - value := []byte(secondname) - h.db.Store(key, value, true) + //secondname := string(input) + //key := []byte(FamilyName) + //value := []byte(secondname) + //h.db.Store(key, value, true) } return res, nil @@ -292,10 +301,10 @@ func (h *Handlers) SaveYob(cxt context.Context, sym string, input []byte) (resou res := resource.Result{} yob := string(input) if len(yob) == 4 { - yob := string(input) - key := []byte(YearOfBirth) - value := []byte(yob) - h.db.Store(key, value, true) + //yob := string(input) + //key := []byte(YearOfBirth) + //value := []byte(yob) + //h.db.Store(key, value, true) } return res, nil @@ -305,11 +314,11 @@ func (h *Handlers) SaveYob(cxt context.Context, sym string, input []byte) (resou func (h *Handlers) SaveLocation(cxt context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} if len(input) > 0 { - location := string(input) - key := []byte(Location) - value := []byte(location) + //location := string(input) + //key := []byte(Location) + //value := []byte(location) - h.db.Store(key, value, true) + //h.db.Store(key, value, true) } return res, nil @@ -328,9 +337,9 @@ func (h *Handlers) SaveGender(ctx context.Context, sym string, input []byte) (re case "3": gender = "Unspecified" } - key := []byte(Gender) - value := []byte(gender) - h.db.Store(key, value, true) + //key := []byte(Gender) + //value := []byte(gender) + //h.db.Store(key, value, true) } return res, nil } @@ -339,10 +348,10 @@ func (h *Handlers) SaveGender(ctx context.Context, sym string, input []byte) (re func (h *Handlers) SaveOfferings(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} if len(input) > 0 { - offerings := string(input) - key := []byte(Offerings) - value := []byte(offerings) - h.db.Store(key, value, true) + //offerings := string(input) + //key := []byte(Offerings) + //value := []byte(offerings) + //h.db.Store(key, value, true) } return res, nil } @@ -370,11 +379,11 @@ func (h *Handlers) ResetAccountAuthorized(ctx context.Context, sym string, input // CheckIdentifier retrieves the PublicKey from the JSON data file. func (h *Handlers) CheckIdentifier(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) - if err != nil { - return res, err - } - res.Content = string(publicKey) + //publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) + // if err != nil { + // return res, err + // } + res.Content = "string(publicKey)" return res, nil } @@ -383,32 +392,32 @@ func (h *Handlers) CheckIdentifier(ctx context.Context, sym string, input []byte func (h *Handlers) Authorize(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - flag_incorrect_pin, _ := h.flagManager.GetFlag("flag_incorrect_pin") - flag_account_authorized, _ := h.flagManager.GetFlag("flag_account_authorized") - flag_allow_update, _ := h.flagManager.GetFlag("flag_allow_update") + // flag_incorrect_pin, _ := h.flagManager.GetFlag("flag_incorrect_pin") + // flag_account_authorized, _ := h.flagManager.GetFlag("flag_account_authorized") + // flag_allow_update, _ := h.flagManager.GetFlag("flag_allow_update") - storedpin, err := h.db.Fetch([]byte(AccountPin)) - if err == nil { - if len(input) == 4 { - if bytes.Equal(input, storedpin) { - if h.fs.St.MatchFlag(flag_account_authorized, false) { - res.FlagReset = append(res.FlagReset, flag_incorrect_pin) - res.FlagSet = append(res.FlagSet, flag_allow_update, flag_account_authorized) - } else { - res.FlagSet = append(res.FlagSet, flag_allow_update) - res.FlagReset = append(res.FlagReset, flag_account_authorized) - } - } else { - res.FlagSet = append(res.FlagSet, flag_incorrect_pin) - res.FlagReset = append(res.FlagReset, flag_account_authorized) - return res, nil - } - } - } else if errors.Is(err, gdbm.ErrItemNotFound) { - return res, err - } else { - return res, err - } + // storedpin, err := h.db.Fetch([]byte(AccountPin)) + // if err == nil { + // if len(input) == 4 { + // if bytes.Equal(input, storedpin) { + // if h.fs.St.MatchFlag(flag_account_authorized, false) { + // res.FlagReset = append(res.FlagReset, flag_incorrect_pin) + // res.FlagSet = append(res.FlagSet, flag_allow_update, flag_account_authorized) + // } else { + // res.FlagSet = append(res.FlagSet, flag_allow_update) + // res.FlagReset = append(res.FlagReset, flag_account_authorized) + // } + // } else { + // res.FlagSet = append(res.FlagSet, flag_incorrect_pin) + // res.FlagReset = append(res.FlagReset, flag_account_authorized) + // return res, nil + // } + // } + // } else if errors.Is(err, gdbm.ErrItemNotFound) { + // return res, err + // } else { + // return res, err + // } return res, nil } @@ -430,13 +439,15 @@ func (h *Handlers) CheckAccountStatus(ctx context.Context, sym string, input []b flag_account_success, _ := h.flagManager.GetFlag("flag_account_success") flag_account_pending, _ := h.flagManager.GetFlag("flag_account_pending") - trackingId, err := h.db.Fetch([]byte(TrackingIdKey)) - - if err != nil { - return res, err + sessionId, ok := ctx.Value("SessionId").(string) + if !ok { + return res, fmt.Errorf("missing session") } - status, err := h.accountService.CheckAccountStatus(string(trackingId)) + trackingId, err := utils.ReadEntry(ctx, h.userdataStore, sessionId, utils.DATA_TRACKING_ID) + fmt.Println("Checking status with tracking id:", string(trackingId)) + + status, err := h.accountService.CheckAccountStatus(string("1234")) if err != nil { fmt.Println("Error checking account status:", err) @@ -444,15 +455,15 @@ func (h *Handlers) CheckAccountStatus(ctx context.Context, sym string, input []b } - err = h.db.Store(toBytes(AccountStatus), toBytes(status), true) - if err != nil { - return res, nil - } + // err = h.db.Store(toBytes(AccountStatus), toBytes(status), true) + // if err != nil { + // return res, nil + // } - err = h.db.Store(toBytes(TrackingIdKey), toBytes(status), true) - if err != nil { - return res, nil - } + // err = h.db.Store(toBytes(TrackingIdKey), toBytes(status), true) + // if err != nil { + // return res, nil + // } if status == "SUCCESS" { res.FlagSet = append(res.FlagSet, flag_account_success) @@ -516,13 +527,13 @@ func (h *Handlers) ResetIncorrectYob(ctx context.Context, sym string, input []by // the balance as the result content func (h *Handlers) CheckBalance(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) + // publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) - if err != nil { - return res, err - } + // if err != nil { + // return res, err + // } - balance, err := h.accountService.CheckBalance(string(publicKey)) + balance, err := h.accountService.CheckBalance(string("publicKey")) if err != nil { return res, nil } @@ -548,10 +559,10 @@ func (h *Handlers) ValidateRecipient(ctx context.Context, sym string, input []by } // accountData["Recipient"] = recipient - key := []byte(Recipient) - value := []byte(recipient) + // key := []byte(Recipient) + // value := []byte(recipient) - h.db.Store(key, value, true) + // h.db.Store(key, value, true) } return res, nil @@ -565,14 +576,14 @@ func (h *Handlers) TransactionReset(ctx context.Context, sym string, input []byt flag_invalid_recipient, _ := h.flagManager.GetFlag("flag_invalid_recipient") flag_invalid_recipient_with_invite, _ := h.flagManager.GetFlag("flag_invalid_recipient_with_invite") - err := h.db.Delete([]byte(Amount)) - if err != nil && !errors.Is(err, gdbm.ErrItemNotFound) { - return res, err - } - err = h.db.Delete([]byte(Recipient)) - if err != nil && !errors.Is(err, gdbm.ErrItemNotFound) { - return res, err - } + // err := h.db.Delete([]byte(Amount)) + // if err != nil && !errors.Is(err, gdbm.ErrItemNotFound) { + // return res, err + // } + // err = h.db.Delete([]byte(Recipient)) + // if err != nil && !errors.Is(err, gdbm.ErrItemNotFound) { + // return res, err + // } res.FlagReset = append(res.FlagReset, flag_invalid_recipient, flag_invalid_recipient_with_invite) @@ -585,10 +596,10 @@ func (h *Handlers) ResetTransactionAmount(ctx context.Context, sym string, input flag_invalid_amount, _ := h.flagManager.GetFlag("flag_invalid_amount") - err := h.db.Delete([]byte(Amount)) - if err != nil && !errors.Is(err, gdbm.ErrItemNotFound) { - return res, err - } + // err := h.db.Delete([]byte(Amount)) + // if err != nil && !errors.Is(err, gdbm.ErrItemNotFound) { + // return res, err + // } res.FlagReset = append(res.FlagReset, flag_invalid_amount) @@ -599,12 +610,12 @@ func (h *Handlers) ResetTransactionAmount(ctx context.Context, sym string, input // the result content. func (h *Handlers) MaxAmount(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) - if err != nil { - return res, err - } + // publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) + // if err != nil { + // return res, err + // } - balance, err := h.accountService.CheckBalance(string(publicKey)) + balance, err := h.accountService.CheckBalance(string("publicKey")) if err != nil { return res, nil } @@ -622,13 +633,13 @@ func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte) flag_invalid_amount, _ := h.flagManager.GetFlag("flag_invalid_amount") amountStr := string(input) - publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) + // publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) - if err != nil { - return res, err - } + // if err != nil { + // return res, err + // } - balanceStr, err := h.accountService.CheckBalance(string(publicKey)) + balanceStr, err := h.accountService.CheckBalance(string("publicKey")) if err != nil { return res, err @@ -668,9 +679,9 @@ func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte) } res.Content = fmt.Sprintf("%.3f", inputAmount) // Format to 3 decimal places - key := []byte(Amount) - value := []byte(res.Content) - h.db.Store(key, value, true) + // key := []byte(Amount) + // value := []byte(res.Content) + // h.db.Store(key, value, true) if err != nil { return res, err @@ -682,12 +693,12 @@ func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte) // GetRecipient returns the transaction recipient from a JSON data file. func (h *Handlers) GetRecipient(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - recipient, err := h.db.Fetch([]byte(Recipient)) - if err != nil { - return res, err - } + // recipient, err := h.db.Fetch([]byte(Recipient)) + // if err != nil { + // return res, err + // } - res.Content = string(recipient) + res.Content = string("recipient") return res, nil } @@ -695,12 +706,12 @@ func (h *Handlers) GetRecipient(ctx context.Context, sym string, input []byte) ( // GetSender retrieves the public key from the Gdbm Db func (h *Handlers) GetSender(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) - if err != nil { - return res, err - } + // publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) + // if err != nil { + // return res, err + // } - res.Content = string(publicKey) + res.Content = string("publicKey") return res, nil } @@ -708,11 +719,11 @@ func (h *Handlers) GetSender(ctx context.Context, sym string, input []byte) (res // GetAmount retrieves the amount from teh Gdbm Db func (h *Handlers) GetAmount(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - amount, err := h.db.Fetch([]byte(Amount)) - if err != nil { - return res, err - } - res.Content = string(amount) + // amount, err := h.db.Fetch([]byte(Amount)) + // if err != nil { + // return res, err + // } + res.Content = string("amount") return res, nil } @@ -727,11 +738,11 @@ func (h *Handlers) QuitWithBalance(ctx context.Context, sym string, input []byte code := codeFromCtx(ctx) l := gotext.NewLocale(translationDir, code) l.AddDomain("default") - publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) - if err != nil { - return res, err - } - balance, err := h.accountService.CheckBalance(string(publicKey)) + // publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) + // if err != nil { + // return res, err + // } + balance, err := h.accountService.CheckBalance(string("publicKey")) if err != nil { return res, nil } @@ -750,20 +761,20 @@ func (h *Handlers) InitiateTransaction(ctx context.Context, sym string, input [] // TODO // Use the amount, recipient and sender to call the API and initialize the transaction - publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) - if err != nil { - return res, err - } - amount, err := h.db.Fetch([]byte(Amount)) - if err != nil { - return res, err - } - recipient, err := h.db.Fetch([]byte(Recipient)) - if err != nil { - return res, err - } + // publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) + // if err != nil { + // return res, err + // } + // amount, err := h.db.Fetch([]byte(Amount)) + // if err != nil { + // return res, err + // } + // recipient, err := h.db.Fetch([]byte(Recipient)) + // if err != nil { + // return res, err + // } - res.Content = l.Get("Your request has been sent. %s will receive %s from %s.", string(recipient), string(amount), string(publicKey)) + //res.Content = l.Get("Your request has been sent. %s will receive %s from %s.", string(recipient), string(amount), string(publicKey)) account_authorized_flag, err := h.flagManager.GetFlag("flag_account_authorized") if err != nil { @@ -788,27 +799,27 @@ func (h *Handlers) GetProfileInfo(ctx context.Context, sym string, input []byte) offerings := defaultValue // Fetch data using a map for better organization - dataKeys := map[string]*string{ - FirstName: &name, - FamilyName: &familyName, - YearOfBirth: &yob, - Location: &location, - Gender: &gender, - Offerings: &offerings, - } + // dataKeys := map[string]*string{ + // FirstName: &name, + // FamilyName: &familyName, + // YearOfBirth: &yob, + // Location: &location, + // Gender: &gender, + // Offerings: &offerings, + // } // Iterate over keys and fetch values //iter := h.db.Iterator() - next := h.db.Iterator() - //defer iter.Close() // Ensure the iterator is closed - for key, err := next(); err == nil; key, err = next() { - if valuePointer, ok := dataKeys[string(key)]; ok { - value, fetchErr := h.db.Fetch(key) - if fetchErr == nil { - *valuePointer = string(value) - } - } - } + // next := h.db.Iterator() + // //defer iter.Close() // Ensure the iterator is closed + // for key, err := next(); err == nil; key, err = next() { + // if valuePointer, ok := dataKeys[string(key)]; ok { + // // value, fetchErr := h.db.Fetch(key) + // // if fetchErr == nil { + // // *valuePointer = string(value) + // // } + // } + // } // Construct the full name if familyName != defaultValue { diff --git a/internal/utils/account_utils.go b/internal/utils/account_utils.go index 39fb66b..1ab34b8 100644 --- a/internal/utils/account_utils.go +++ b/internal/utils/account_utils.go @@ -1,46 +1,77 @@ package utils import ( + "context" "encoding/json" - "os" + + "git.defalsify.org/vise.git/db" ) type AccountFileHandler struct { - FilePath string + //FilePath string + store db.Db } -func NewAccountFileHandler(path string) *AccountFileHandler { - return &AccountFileHandler{FilePath: path} -} +// func NewAccountFileHandler(path string) *AccountFileHandler { +// return &AccountFileHandler{FilePath: path} +// } -func (afh *AccountFileHandler) ReadAccountData() (map[string]string, error) { - jsonData, err := os.ReadFile(afh.FilePath) - if err != nil { - return nil, err +func NewAccountFileHandler(store db.Db) *AccountFileHandler { + return &AccountFileHandler{ + store: store, } +} +// func (afh *AccountFileHandler) ReadAccountData() (map[string]string, error) { +// jsonData, err := os.ReadFile(afh.FilePath) +// if err != nil { +// return nil, err +// } + +// var accountData map[string]string +// err = json.Unmarshal(jsonData, &accountData) +// if err != nil { +// return nil, err +// } + +// return accountData, nil +// } + +func (afh *AccountFileHandler) ReadAccountData(ctx context.Context, sessionId string) (map[string]string, error) { var accountData map[string]string + jsonData, err := ReadEntry(ctx, afh.store, sessionId, DATA_ACCOUNT) err = json.Unmarshal(jsonData, &accountData) if err != nil { return nil, err } - return accountData, nil } -func (afh *AccountFileHandler) WriteAccountData(accountData map[string]string) error { - jsonData, err := json.Marshal(accountData) +// func (afh *AccountFileHandler) WriteAccountData(accountData map[string]string) error { +// jsonData, err := json.Marshal(accountData) +// if err != nil { +// return err +// } + +// return os.WriteFile(afh.FilePath, jsonData, 0644) +// } + +func (afh *AccountFileHandler) WriteAccountData(ctx context.Context, sessionId string, accountData map[string]string) error { + _, err := json.Marshal(accountData) if err != nil { return err } - return os.WriteFile(afh.FilePath, jsonData, 0644) + return nil } +// func (afh *AccountFileHandler) EnsureFileExists() error { +// f, err := os.OpenFile(afh.FilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) +// if err != nil { +// return err +// } +// return f.Close() +// } func (afh *AccountFileHandler) EnsureFileExists() error { - f, err := os.OpenFile(afh.FilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) - if err != nil { - return err - } - return f.Close() + return nil } From 98c74dffc42edc887467bc93cfbe5bbc5e857dc2 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Thu, 5 Sep 2024 17:09:30 +0300 Subject: [PATCH 170/201] use state from persister --- internal/handlers/ussd/menuhandler.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 5972445..eb78919 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -91,7 +91,7 @@ type Handlers struct { func NewHandlers(appFlags *asm.FlagParser, pe *persist.Persister, userdataStore db.Db) (*Handlers, error) { h := &Handlers{ - st: state.NewState(uint32(16)), + st: pe.State, ca: pe.GetMemory(), userdataStore: userdataStore, flagManager: appFlags, From 2bf7a5c246a7a2f05bac0780017316682d14991c Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Thu, 5 Sep 2024 17:12:38 +0300 Subject: [PATCH 171/201] setup db keys --- internal/utils/db.go | 51 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 internal/utils/db.go diff --git a/internal/utils/db.go b/internal/utils/db.go new file mode 100644 index 0000000..bd8c5ee --- /dev/null +++ b/internal/utils/db.go @@ -0,0 +1,51 @@ +package utils + +import ( + "context" + "encoding/binary" + + "git.defalsify.org/vise.git/db" +) + +type DataTyp uint16 + +const ( + DATA_ACCOUNT DataTyp = iota + DATA_ACCOUNT_CREATED + DATA_TRACKING_ID + DATA_PUBLIC_KEY + DATA_CUSTODIAL_ID +) + +func typToBytes(typ DataTyp) []byte { + //var b []byte + b := make([]byte, 2) + binary.BigEndian.PutUint16(b, uint16(typ)) + return b +} + +func packKey(typ DataTyp, data []byte) []byte { + v := typToBytes(typ) + return append(v, data...) +} + +func ReadEntry(ctx context.Context, store db.Db, sessionId string, typ DataTyp) ([]byte, error) { + store.SetPrefix(db.DATATYPE_USERDATA) + store.SetSession(sessionId) + k := packKey(typ, []byte(sessionId)) + //k := []byte(sessionId) + b, err := store.Get(ctx, k) + if err != nil { + return nil, err + } + return b, nil + +} + +func WriteEntry(ctx context.Context, store db.Db, sessionId string, typ DataTyp, value []byte) error { + store.SetPrefix(db.DATATYPE_USERDATA) + store.SetSession(sessionId) + //k := packKey(typ, []byte(sessionId)) + k := []byte(sessionId) + return store.Put(ctx, k, value) +} \ No newline at end of file From 6fa5f49bc022781556bd97414c5517f0f5953567 Mon Sep 17 00:00:00 2001 From: lash Date: Thu, 5 Sep 2024 15:28:53 +0100 Subject: [PATCH 172/201] Remove impossible nil check in handler --- go-vise | 2 +- internal/handlers/ussd/menuhandler.go | 10 ++++++---- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/go-vise b/go-vise index 1f47a67..326bdb5 160000 --- a/go-vise +++ b/go-vise @@ -1 +1 @@ -Subproject commit 1f47a674d95380be8c387f410f0342eb72357df5 +Subproject commit 326bdb5018ae81ee493371b56bd4564a8b35da59 diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index eb78919..c9d42ec 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -17,12 +17,14 @@ import ( "git.defalsify.org/vise.git/persist" "git.defalsify.org/vise.git/resource" "git.defalsify.org/vise.git/state" + "git.defalsify.org/vise.git/logging" "git.grassecon.net/urdt/ussd/internal/handlers/server" "git.grassecon.net/urdt/ussd/internal/utils" "gopkg.in/leonelquinteros/gotext.v1" ) var ( + logg = logging.NewVanilla().WithDomain("ussdmenuhandler") scriptDir = path.Join("services", "registration") translationDir = path.Join(scriptDir, "locale") ) @@ -98,10 +100,10 @@ func NewHandlers(appFlags *asm.FlagParser, pe *persist.Persister, userdataStore accountFileHandler: utils.NewAccountFileHandler(userdataStore), accountService: &server.AccountService{}, } - if h.st == nil || h.ca == nil || h.userdataStore == nil || h.flagManager == nil { - //logg.Errorf("have nil for essential value in handler", "state", h.st, "cache", h.ca, "store", h.userdataStore, "flags", h.flagManager) - return nil, fmt.Errorf("have nil for essential value") - } +// if h.st == nil || h.ca == nil || h.userdataStore == nil || h.flagManager == nil { +// logg.Errorf("have nil for essential value in handler", "state", h.st, "cache", h.ca, "store", h.userdataStore, "flags", h.flagManager) +// return nil, fmt.Errorf("have nil for essential value") +// } return h, nil } From 62b7adb9671eaaf5b78b953e1c7c7b680941dfc9 Mon Sep 17 00:00:00 2001 From: lash Date: Thu, 5 Sep 2024 15:41:27 +0100 Subject: [PATCH 173/201] Fix missing byte allocation for typ serialize --- internal/utils/db.go | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/internal/utils/db.go b/internal/utils/db.go index bd8c5ee..1104452 100644 --- a/internal/utils/db.go +++ b/internal/utils/db.go @@ -18,10 +18,9 @@ const ( ) func typToBytes(typ DataTyp) []byte { - //var b []byte - b := make([]byte, 2) - binary.BigEndian.PutUint16(b, uint16(typ)) - return b + var b [2]byte + binary.BigEndian.PutUint16(b[:], uint16(typ)) + return b[:] } func packKey(typ DataTyp, data []byte) []byte { @@ -31,9 +30,8 @@ func packKey(typ DataTyp, data []byte) []byte { func ReadEntry(ctx context.Context, store db.Db, sessionId string, typ DataTyp) ([]byte, error) { store.SetPrefix(db.DATATYPE_USERDATA) - store.SetSession(sessionId) - k := packKey(typ, []byte(sessionId)) - //k := []byte(sessionId) + store.SetSession(sessionId) + k := packKey(typ, []byte(sessionId)) b, err := store.Get(ctx, k) if err != nil { return nil, err @@ -45,7 +43,6 @@ func ReadEntry(ctx context.Context, store db.Db, sessionId string, typ DataTyp) func WriteEntry(ctx context.Context, store db.Db, sessionId string, typ DataTyp, value []byte) error { store.SetPrefix(db.DATATYPE_USERDATA) store.SetSession(sessionId) - //k := packKey(typ, []byte(sessionId)) - k := []byte(sessionId) + k := packKey(typ, []byte(sessionId)) return store.Put(ctx, k, value) -} \ No newline at end of file +} From db3ec1991d7081705a1bda320e3d6ba98bca26c5 Mon Sep 17 00:00:00 2001 From: lash Date: Thu, 5 Sep 2024 16:45:35 +0100 Subject: [PATCH 174/201] Remove obsolete store and persister global --- cmd/main.go | 30 ++++++++------------------- internal/handlers/ussd/menuhandler.go | 5 ----- 2 files changed, 9 insertions(+), 26 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index cf9875f..0529e81 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -15,13 +15,13 @@ import ( "git.defalsify.org/vise.git/persist" "git.defalsify.org/vise.git/resource" "git.defalsify.org/vise.git/state" + "git.defalsify.org/vise.git/logging" "git.grassecon.net/urdt/ussd/internal/handlers/ussd" ) var ( + logg = logging.NewVanilla() scriptDir = path.Join("services", "registration") - store = fsdb.NewFsDb() - pr = persist.NewPersister(store) ) func getFlags(fp string, debug bool) (*asm.FlagParser, error) { @@ -35,7 +35,7 @@ func getFlags(fp string, debug bool) (*asm.FlagParser, error) { func getHandler(appFlags *asm.FlagParser, rs *resource.DbResource, pe *persist.Persister, userdataStore db.Db) (*ussd.Handlers, error) { - ussdHandlers, err := ussd.NewHandlers(appFlags, pr, store) + ussdHandlers, err := ussd.NewHandlers(appFlags, pe, userdataStore) if err != nil { return nil, err } @@ -81,7 +81,7 @@ func getPersister(dbDir string, ctx context.Context) (*persist.Persister, error) return nil, fmt.Errorf("state dir create exited with error: %v\n", err) } store := gdbmdb.NewGdbmDb() - storeFile := path.Join(dbDir, ".state") + storeFile := path.Join(dbDir, "state.gdbm") store.Connect(ctx, storeFile) pr := persist.NewPersister(store) return pr, nil @@ -112,28 +112,20 @@ func getEngine(cfg engine.Config, rs resource.Resource, pr *persist.Persister) * } func main() { - //var dir string var dbDir string var resourceDir string - //var root string var size uint var sessionId string - //flag.StringVar(&dir, "d", ".", "resource dir to read from") - // flag.UintVar(&size, "s", 0, "max size of output") - // flag.StringVar(&root, "root", "root", "entry point symbol") flag.StringVar(&sessionId, "session-id", "075xx2123", "session id") - // flag.Parse() - // fmt.Fprintf(os.Stderr, "starting session at symbol '%s' using resource dir: %s\n", root, dir) - //logg.Infof("starting session", "symbol", root, "dbdir", dbDir, "sessionid", sessionId, "outsize", size) - flag.StringVar(&dbDir, "dbdir", ".state", "database dir to read from") flag.StringVar(&resourceDir, "resourcedir", path.Join("services", "registration"), "resource dir") flag.UintVar(&size, "s", 160, "max size of output") + flag.Parse() + + logg.Infof("start command", "dbdir", dbDir, "resourcedir", resourceDir, "outputsize", size) ctx := context.Background() - - - ctx = context.WithValue(ctx, "SessionId",sessionId) + ctx = context.WithValue(ctx, "SessionId",sessionId) pfp := path.Join(scriptDir, "pp.csv") flagParser, err := getFlags(pfp, true) @@ -147,18 +139,14 @@ func main() { OutputSize: uint32(size), FlagCount: uint32(16), } - //ca := cache.Cache{} rs, err := getResource(resourceDir, ctx) - if err != nil { fmt.Fprintf(os.Stderr, err.Error()) os.Exit(1) } pr, err := getPersister(dbDir, ctx) - //pr.WithContent(state.NewState(uint32(16)),&ca) - if err != nil { fmt.Fprintf(os.Stderr, err.Error()) os.Exit(1) @@ -169,8 +157,8 @@ func main() { fmt.Fprintf(os.Stderr, err.Error()) os.Exit(1) } - dbResource, ok := rs.(*resource.DbResource) + dbResource, ok := rs.(*resource.DbResource) if !ok { os.Exit(1) } diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index c9d42ec..2eb11b1 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -100,10 +100,6 @@ func NewHandlers(appFlags *asm.FlagParser, pe *persist.Persister, userdataStore accountFileHandler: utils.NewAccountFileHandler(userdataStore), accountService: &server.AccountService{}, } -// if h.st == nil || h.ca == nil || h.userdataStore == nil || h.flagManager == nil { -// logg.Errorf("have nil for essential value in handler", "state", h.st, "cache", h.ca, "store", h.userdataStore, "flags", h.flagManager) -// return nil, fmt.Errorf("have nil for essential value") -// } return h, nil } @@ -179,7 +175,6 @@ func (h *Handlers) CreateAccount(ctx context.Context, sym string, input []byte) return res, err } } else { - fmt.Println("Error here:", err) err = h.createAccountNoExist(ctx, sessionId, &res) if err != nil { return res, err From 17804e764119f786193e0239dd7f338c7ae9f87c Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Thu, 5 Sep 2024 19:50:02 +0300 Subject: [PATCH 175/201] Save the actual PIN and verify it --- internal/handlers/ussd/menuhandler.go | 48 +++++++++++++-------------- internal/utils/db.go | 2 +- 2 files changed, 25 insertions(+), 25 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 2eb11b1..5ac9456 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -74,14 +74,6 @@ func (fm *FlagManager) GetFlag(label string) (uint32, error) { return fm.parser.GetFlag(label) } -// type Handlers struct { -// fs *FSData -// db *gdbm.Database -// flagManager *FlagManager -// accountFileHandler utils.AccountFileHandlerInterface -// accountService server.AccountServiceInterface -// } - type Handlers struct { st *state.State ca cache.Memory @@ -187,6 +179,10 @@ func (h *Handlers) CreateAccount(ctx context.Context, sym string, input []byte) // SavePin persists the user's PIN choice into the filesystem func (h *Handlers) SavePin(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} + sessionId, ok := ctx.Value("SessionId").(string) + if !ok { + return res, fmt.Errorf("missing session") + } flag_incorrect_pin, _ := h.flagManager.GetFlag("flag_incorrect_pin") @@ -199,10 +195,11 @@ func (h *Handlers) SavePin(ctx context.Context, sym string, input []byte) (resou res.FlagReset = append(res.FlagReset, flag_incorrect_pin) - // key := []byte(AccountPin) - // value := []byte(accountPIN) + err := utils.WriteEntry(ctx, h.userdataStore, sessionId, utils.DATA_ACCOUNT_PIN, []byte(accountPIN)) + if err != nil { + return res, nil + } - //h.db.Store(key, value, true) return res, nil } @@ -241,11 +238,13 @@ func (h *Handlers) VerifyPin(ctx context.Context, sym string, input []byte) (res flag_pin_mismatch, _ := h.flagManager.GetFlag("flag_pin_mismatch") flag_pin_set, _ := h.flagManager.GetFlag("flag_pin_set") - // AccountPin, err := h.db.Fetch([]byte(AccountPin)) - // if err != nil { - // return res, err - // } - AccountPin := []byte("2768") + sessionId, ok := ctx.Value("SessionId").(string) + if !ok { + return res, fmt.Errorf("missing session") + } + + AccountPin, _ := utils.ReadEntry(ctx, h.userdataStore, sessionId, utils.DATA_ACCOUNT_PIN) + if bytes.Equal(input, AccountPin) { res.FlagSet = []uint32{flag_valid_pin} res.FlagReset = []uint32{flag_pin_mismatch} @@ -441,10 +440,9 @@ func (h *Handlers) CheckAccountStatus(ctx context.Context, sym string, input []b return res, fmt.Errorf("missing session") } - trackingId, err := utils.ReadEntry(ctx, h.userdataStore, sessionId, utils.DATA_TRACKING_ID) - fmt.Println("Checking status with tracking id:", string(trackingId)) + trackingId, _ := utils.ReadEntry(ctx, h.userdataStore, sessionId, utils.DATA_TRACKING_ID) - status, err := h.accountService.CheckAccountStatus(string("1234")) + status, err := h.accountService.CheckAccountStatus(string(trackingId)) if err != nil { fmt.Println("Error checking account status:", err) @@ -524,13 +522,15 @@ func (h *Handlers) ResetIncorrectYob(ctx context.Context, sym string, input []by // the balance as the result content func (h *Handlers) CheckBalance(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - // publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) - // if err != nil { - // return res, err - // } + sessionId, ok := ctx.Value("SessionId").(string) + if !ok { + return res, fmt.Errorf("missing session") + } - balance, err := h.accountService.CheckBalance(string("publicKey")) + publicKey, _ := utils.ReadEntry(ctx, h.userdataStore, sessionId, utils.DATA_PUBLIC_KEY) + + balance, err := h.accountService.CheckBalance(string(publicKey)) if err != nil { return res, nil } diff --git a/internal/utils/db.go b/internal/utils/db.go index 1104452..bfaf2e1 100644 --- a/internal/utils/db.go +++ b/internal/utils/db.go @@ -15,6 +15,7 @@ const ( DATA_TRACKING_ID DATA_PUBLIC_KEY DATA_CUSTODIAL_ID + DATA_ACCOUNT_PIN ) func typToBytes(typ DataTyp) []byte { @@ -37,7 +38,6 @@ func ReadEntry(ctx context.Context, store db.Db, sessionId string, typ DataTyp) return nil, err } return b, nil - } func WriteEntry(ctx context.Context, store db.Db, sessionId string, typ DataTyp, value []byte) error { From 5abaf28f490d145532f914e2d06f54bc2e119bbb Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Thu, 5 Sep 2024 20:26:52 +0300 Subject: [PATCH 176/201] remove explicit attachment of state to engine --- cmd/main.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index 0529e81..dcb0b15 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -14,7 +14,6 @@ import ( "git.defalsify.org/vise.git/engine" "git.defalsify.org/vise.git/persist" "git.defalsify.org/vise.git/resource" - "git.defalsify.org/vise.git/state" "git.defalsify.org/vise.git/logging" "git.grassecon.net/urdt/ussd/internal/handlers/ussd" ) @@ -170,7 +169,7 @@ func main() { } en := getEngine(cfg, rs, pr) - en.WithState(state.NewState(uint32(16))) + _, err = en.Init(ctx) if err != nil { From 643b4d87a974a4c1c53e40f3db3b2c4d120809b9 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Thu, 5 Sep 2024 20:30:28 +0300 Subject: [PATCH 177/201] read account pin of gdbm store --- internal/handlers/ussd/menuhandler.go | 59 ++++++++++++++------------- 1 file changed, 31 insertions(+), 28 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 5ac9456..92c401e 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -14,17 +14,17 @@ import ( "git.defalsify.org/vise.git/cache" "git.defalsify.org/vise.git/db" "git.defalsify.org/vise.git/lang" + "git.defalsify.org/vise.git/logging" "git.defalsify.org/vise.git/persist" "git.defalsify.org/vise.git/resource" "git.defalsify.org/vise.git/state" - "git.defalsify.org/vise.git/logging" "git.grassecon.net/urdt/ussd/internal/handlers/server" "git.grassecon.net/urdt/ussd/internal/utils" "gopkg.in/leonelquinteros/gotext.v1" ) var ( - logg = logging.NewVanilla().WithDomain("ussdmenuhandler") + logg = logging.NewVanilla().WithDomain("ussdmenuhandler") scriptDir = path.Join("services", "registration") translationDir = path.Join(scriptDir, "locale") ) @@ -244,7 +244,7 @@ func (h *Handlers) VerifyPin(ctx context.Context, sym string, input []byte) (res } AccountPin, _ := utils.ReadEntry(ctx, h.userdataStore, sessionId, utils.DATA_ACCOUNT_PIN) - + if bytes.Equal(input, AccountPin) { res.FlagSet = []uint32{flag_valid_pin} res.FlagReset = []uint32{flag_pin_mismatch} @@ -388,32 +388,35 @@ func (h *Handlers) CheckIdentifier(ctx context.Context, sym string, input []byte func (h *Handlers) Authorize(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - // flag_incorrect_pin, _ := h.flagManager.GetFlag("flag_incorrect_pin") - // flag_account_authorized, _ := h.flagManager.GetFlag("flag_account_authorized") - // flag_allow_update, _ := h.flagManager.GetFlag("flag_allow_update") + flag_incorrect_pin, _ := h.flagManager.GetFlag("flag_incorrect_pin") + flag_account_authorized, _ := h.flagManager.GetFlag("flag_account_authorized") + flag_allow_update, _ := h.flagManager.GetFlag("flag_allow_update") + sessionId, ok := ctx.Value("SessionId").(string) + if !ok { + return res, fmt.Errorf("missing session") + } + AccountPin, err := utils.ReadEntry(ctx, h.userdataStore, sessionId, utils.DATA_ACCOUNT_PIN) + + if err == nil { + if len(input) == 4 { + if bytes.Equal(input, AccountPin) { + if h.st.MatchFlag(flag_account_authorized, false) { + res.FlagReset = append(res.FlagReset, flag_incorrect_pin) + res.FlagSet = append(res.FlagSet, flag_allow_update, flag_account_authorized) + } else { + res.FlagSet = append(res.FlagSet, flag_allow_update) + res.FlagReset = append(res.FlagReset, flag_account_authorized) + } + } else { + res.FlagSet = append(res.FlagSet, flag_incorrect_pin) + res.FlagReset = append(res.FlagReset, flag_account_authorized) + return res, nil + } + } + } else { + return res, nil + } - // storedpin, err := h.db.Fetch([]byte(AccountPin)) - // if err == nil { - // if len(input) == 4 { - // if bytes.Equal(input, storedpin) { - // if h.fs.St.MatchFlag(flag_account_authorized, false) { - // res.FlagReset = append(res.FlagReset, flag_incorrect_pin) - // res.FlagSet = append(res.FlagSet, flag_allow_update, flag_account_authorized) - // } else { - // res.FlagSet = append(res.FlagSet, flag_allow_update) - // res.FlagReset = append(res.FlagReset, flag_account_authorized) - // } - // } else { - // res.FlagSet = append(res.FlagSet, flag_incorrect_pin) - // res.FlagReset = append(res.FlagReset, flag_account_authorized) - // return res, nil - // } - // } - // } else if errors.Is(err, gdbm.ErrItemNotFound) { - // return res, err - // } else { - // return res, err - // } return res, nil } From 0feb013c78a7039ddbf26141b54ec56d26eb4ed2 Mon Sep 17 00:00:00 2001 From: lash Date: Thu, 5 Sep 2024 20:35:51 +0100 Subject: [PATCH 178/201] Ensure handler init when state and cache is available --- go-vise | 2 +- internal/handlers/ussd/menuhandler.go | 200 ++++++++++++++++++++------ internal/utils/filehandler.go | 13 -- services/registration/Makefile | 2 +- 4 files changed, 161 insertions(+), 56 deletions(-) delete mode 100644 internal/utils/filehandler.go diff --git a/go-vise b/go-vise index 326bdb5..2bddc36 160000 --- a/go-vise +++ b/go-vise @@ -1 +1 @@ -Subproject commit 326bdb5018ae81ee493371b56bd4564a8b35da59 +Subproject commit 2bddc363f20210ab019eec29d8ba4104d147e9b7 diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 92c401e..c43cb3b 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -75,6 +75,7 @@ func (fm *FlagManager) GetFlag(label string) (uint32, error) { } type Handlers struct { + pe *persist.Persister st *state.State ca cache.Memory userdataStore db.Db @@ -84,9 +85,14 @@ type Handlers struct { } func NewHandlers(appFlags *asm.FlagParser, pe *persist.Persister, userdataStore db.Db) (*Handlers, error) { + if pe == nil { + return nil, fmt.Errorf("cannot create handler with nil persister") + } + if userdataStore == nil { + return nil, fmt.Errorf("cannot create handler with nil userdata store") + } h := &Handlers{ - st: pe.State, - ca: pe.GetMemory(), + pe: pe, userdataStore: userdataStore, flagManager: appFlags, accountFileHandler: utils.NewAccountFileHandler(userdataStore), @@ -104,9 +110,28 @@ func isValidPIN(pin string) bool { return match } +func (h *Handlers) Init(ctx context.Context, sym string, input []byte) (resource.Result, error) { + var r resource.Result + if h.pe == nil { + logg.WarnCtxf(ctx, "handler init called before it is ready or more than once", "state", h.st, "cache", h.ca) + return r, nil + } + h.st = h.pe.GetState() + h.ca = h.pe.GetMemory() + if h.st == nil || h.ca == nil { + logg.ErrorCtxf(ctx, "perister fail in handler", "state", h.st, "cache", h.ca) + return r, fmt.Errorf("cannot get state and memory for handler") + } + h.pe = nil + return r, nil +} + // SetLanguage sets the language across the menu func (h *Handlers) SetLanguage(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} + res, err := h.Init(ctx, sym, input) + if err != nil { + return res, err + } inputStr := string(input) switch inputStr { @@ -152,8 +177,10 @@ func (h *Handlers) createAccountNoExist(ctx context.Context, sessionId string, r // creates an account on the API, // sets the default values and flags func (h *Handlers) CreateAccount(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} - var err error + res, err := h.Init(ctx, sym, input) + if err != nil { + return res, err + } sessionId, ok := ctx.Value("SessionId").(string) if !ok { return res, fmt.Errorf("missing session") @@ -178,7 +205,10 @@ func (h *Handlers) CreateAccount(ctx context.Context, sym string, input []byte) // SavePin persists the user's PIN choice into the filesystem func (h *Handlers) SavePin(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} + res, err := h.Init(ctx, sym, input) + if err != nil { + return res, err + } sessionId, ok := ctx.Value("SessionId").(string) if !ok { return res, fmt.Errorf("missing session") @@ -195,7 +225,7 @@ func (h *Handlers) SavePin(ctx context.Context, sym string, input []byte) (resou res.FlagReset = append(res.FlagReset, flag_incorrect_pin) - err := utils.WriteEntry(ctx, h.userdataStore, sessionId, utils.DATA_ACCOUNT_PIN, []byte(accountPIN)) + err = utils.WriteEntry(ctx, h.userdataStore, sessionId, utils.DATA_ACCOUNT_PIN, []byte(accountPIN)) if err != nil { return res, nil } @@ -205,7 +235,10 @@ func (h *Handlers) SavePin(ctx context.Context, sym string, input []byte) (resou // SetResetSingleEdit sets and resets flags to allow gradual editing of profile information. func (h *Handlers) SetResetSingleEdit(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} + res, err := h.Init(ctx, sym, input) + if err != nil { + return res, err + } menuOption := string(input) flag_allow_update, _ := h.flagManager.GetFlag("flag_allow_update") @@ -232,7 +265,10 @@ func (h *Handlers) SetResetSingleEdit(ctx context.Context, sym string, input []b // If similar, it sets the USERFLAG_PIN_SET flag allowing the user // to access the main menu func (h *Handlers) VerifyPin(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} + res, err := h.Init(ctx, sym, input) + if err != nil { + return res, err + } flag_valid_pin, _ := h.flagManager.GetFlag("flag_valid_pin") flag_pin_mismatch, _ := h.flagManager.GetFlag("flag_pin_mismatch") @@ -267,8 +303,11 @@ func codeFromCtx(ctx context.Context) string { } // SaveFirstname updates the first name in a JSON data file with the provided input. -func (h *Handlers) SaveFirstname(cxt context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} +func (h *Handlers) SaveFirstname(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res, err := h.Init(ctx, sym, input) + if err != nil { + return res, err + } if len(input) > 0 { //name := string(input) //key := []byte(FirstName) @@ -280,8 +319,11 @@ func (h *Handlers) SaveFirstname(cxt context.Context, sym string, input []byte) } // SaveFamilyname updates the family name in a JSON data file with the provided input. -func (h *Handlers) SaveFamilyname(cxt context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} +func (h *Handlers) SaveFamilyname(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res, err := h.Init(ctx, sym, input) + if err != nil { + return res, err + } if len(input) > 0 { //secondname := string(input) //key := []byte(FamilyName) @@ -293,8 +335,11 @@ func (h *Handlers) SaveFamilyname(cxt context.Context, sym string, input []byte) } // SaveYOB updates the Year of Birth(YOB) in a JSON data file with the provided input. -func (h *Handlers) SaveYob(cxt context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} +func (h *Handlers) SaveYob(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res, err := h.Init(ctx, sym, input) + if err != nil { + return res, err + } yob := string(input) if len(yob) == 4 { //yob := string(input) @@ -307,8 +352,11 @@ func (h *Handlers) SaveYob(cxt context.Context, sym string, input []byte) (resou } // SaveLocation updates the location in a JSON data file with the provided input. -func (h *Handlers) SaveLocation(cxt context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} +func (h *Handlers) SaveLocation(ctx context.Context, sym string, input []byte) (resource.Result, error) { + res, err := h.Init(ctx, sym, input) + if err != nil { + return res, err + } if len(input) > 0 { //location := string(input) //key := []byte(Location) @@ -322,7 +370,10 @@ func (h *Handlers) SaveLocation(cxt context.Context, sym string, input []byte) ( // SaveGender updates the gender in a JSON data file with the provided input. func (h *Handlers) SaveGender(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} + res, err := h.Init(ctx, sym, input) + if err != nil { + return res, err + } if len(input) > 0 { gender := string(input) switch gender { @@ -342,7 +393,10 @@ func (h *Handlers) SaveGender(ctx context.Context, sym string, input []byte) (re // SaveOfferings updates the offerings(goods and services provided by the user) in a JSON data file with the provided input. func (h *Handlers) SaveOfferings(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} + res, err := h.Init(ctx, sym, input) + if err != nil { + return res, err + } if len(input) > 0 { //offerings := string(input) //key := []byte(Offerings) @@ -354,7 +408,10 @@ func (h *Handlers) SaveOfferings(ctx context.Context, sym string, input []byte) // ResetAllowUpdate resets the allowupdate flag that allows a user to update profile data. func (h *Handlers) ResetAllowUpdate(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} + res, err := h.Init(ctx, sym, input) + if err != nil { + return res, err + } flag_allow_update, _ := h.flagManager.GetFlag("flag_allow_update") @@ -364,7 +421,10 @@ func (h *Handlers) ResetAllowUpdate(ctx context.Context, sym string, input []byt // ResetAccountAuthorized resets the account authorization flag after a successful PIN entry. func (h *Handlers) ResetAccountAuthorized(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} + res, err := h.Init(ctx, sym, input) + if err != nil { + return res, err + } flag_account_authorized, _ := h.flagManager.GetFlag("flag_account_authorized") @@ -374,7 +434,10 @@ func (h *Handlers) ResetAccountAuthorized(ctx context.Context, sym string, input // CheckIdentifier retrieves the PublicKey from the JSON data file. func (h *Handlers) CheckIdentifier(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} + res, err := h.Init(ctx, sym, input) + if err != nil { + return res, err + } //publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) // if err != nil { // return res, err @@ -386,7 +449,10 @@ func (h *Handlers) CheckIdentifier(ctx context.Context, sym string, input []byte // Authorize attempts to unlock the next sequential nodes by verifying the provided PIN against the already set PIN. // It sets the required flags that control the flow. func (h *Handlers) Authorize(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} + res, err := h.Init(ctx, sym, input) + if err != nil { + return res, err + } flag_incorrect_pin, _ := h.flagManager.GetFlag("flag_incorrect_pin") flag_account_authorized, _ := h.flagManager.GetFlag("flag_account_authorized") @@ -422,7 +488,10 @@ func (h *Handlers) Authorize(ctx context.Context, sym string, input []byte) (res // ResetIncorrectPin resets the incorrect pin flag after a new PIN attempt. func (h *Handlers) ResetIncorrectPin(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} + res, err := h.Init(ctx, sym, input) + if err != nil { + return res, err + } flag_incorrect_pin, _ := h.flagManager.GetFlag("flag_incorrect_pin") @@ -433,7 +502,10 @@ func (h *Handlers) ResetIncorrectPin(ctx context.Context, sym string, input []by // CheckAccountStatus queries the API using the TrackingId and sets flags // based on the account status func (h *Handlers) CheckAccountStatus(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} + res, err := h.Init(ctx, sym, input) + if err != nil { + return res, err + } flag_account_success, _ := h.flagManager.GetFlag("flag_account_success") flag_account_pending, _ := h.flagManager.GetFlag("flag_account_pending") @@ -475,7 +547,10 @@ func (h *Handlers) CheckAccountStatus(ctx context.Context, sym string, input []b // Quit displays the Thank you message and exits the menu func (h *Handlers) Quit(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} + res, err := h.Init(ctx, sym, input) + if err != nil { + return res, err + } flag_account_authorized, _ := h.flagManager.GetFlag("flag_account_authorized") @@ -490,12 +565,15 @@ func (h *Handlers) Quit(ctx context.Context, sym string, input []byte) (resource // VerifyYob verifies the length of the given input func (h *Handlers) VerifyYob(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} + res, err := h.Init(ctx, sym, input) + if err != nil { + return res, err + } flag_incorrect_date_format, _ := h.flagManager.GetFlag("flag_incorrect_date_format") date := string(input) - _, err := strconv.Atoi(date) + _, err = strconv.Atoi(date) if err != nil { // If conversion fails, input is not numeric res.FlagSet = append(res.FlagSet, flag_incorrect_date_format) @@ -513,7 +591,10 @@ func (h *Handlers) VerifyYob(ctx context.Context, sym string, input []byte) (res // ResetIncorrectYob resets the incorrect date format flag after a new attempt func (h *Handlers) ResetIncorrectYob(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} + res, err := h.Init(ctx, sym, input) + if err != nil { + return res, err + } flag_incorrect_date_format, _ := h.flagManager.GetFlag("flag_incorrect_date_format") @@ -524,7 +605,11 @@ func (h *Handlers) ResetIncorrectYob(ctx context.Context, sym string, input []by // CheckBalance retrieves the balance from the API using the "PublicKey" and sets // the balance as the result content func (h *Handlers) CheckBalance(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} + res, err := h.Init(ctx, sym, input) + if err != nil { + return res, err + } + // publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) sessionId, ok := ctx.Value("SessionId").(string) if !ok { @@ -544,7 +629,10 @@ func (h *Handlers) CheckBalance(ctx context.Context, sym string, input []byte) ( // ValidateRecipient validates that the given input is a valid phone number. func (h *Handlers) ValidateRecipient(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} + res, err := h.Init(ctx, sym, input) + if err != nil { + return res, err + } recipient := string(input) flag_invalid_recipient, _ := h.flagManager.GetFlag("flag_invalid_recipient") @@ -571,7 +659,10 @@ func (h *Handlers) ValidateRecipient(ctx context.Context, sym string, input []by // TransactionReset resets the previous transaction data (Recipient and Amount) // as well as the invalid flags func (h *Handlers) TransactionReset(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} + res, err := h.Init(ctx, sym, input) + if err != nil { + return res, err + } flag_invalid_recipient, _ := h.flagManager.GetFlag("flag_invalid_recipient") flag_invalid_recipient_with_invite, _ := h.flagManager.GetFlag("flag_invalid_recipient_with_invite") @@ -592,7 +683,10 @@ func (h *Handlers) TransactionReset(ctx context.Context, sym string, input []byt // ResetTransactionAmount resets the transaction amount and invalid flag func (h *Handlers) ResetTransactionAmount(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} + res, err := h.Init(ctx, sym, input) + if err != nil { + return res, err + } flag_invalid_amount, _ := h.flagManager.GetFlag("flag_invalid_amount") @@ -609,7 +703,10 @@ func (h *Handlers) ResetTransactionAmount(ctx context.Context, sym string, input // MaxAmount gets the current balance from the API and sets it as // the result content. func (h *Handlers) MaxAmount(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} + res, err := h.Init(ctx, sym, input) + if err != nil { + return res, err + } // publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) // if err != nil { // return res, err @@ -628,7 +725,10 @@ func (h *Handlers) MaxAmount(ctx context.Context, sym string, input []byte) (res // ValidateAmount ensures that the given input is a valid amount and that // it is not more than the current balance. func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} + res, err := h.Init(ctx, sym, input) + if err != nil { + return res, err + } flag_invalid_amount, _ := h.flagManager.GetFlag("flag_invalid_amount") @@ -692,7 +792,10 @@ func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte) // GetRecipient returns the transaction recipient from a JSON data file. func (h *Handlers) GetRecipient(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} + res, err := h.Init(ctx, sym, input) + if err != nil { + return res, err + } // recipient, err := h.db.Fetch([]byte(Recipient)) // if err != nil { // return res, err @@ -705,7 +808,10 @@ func (h *Handlers) GetRecipient(ctx context.Context, sym string, input []byte) ( // GetSender retrieves the public key from the Gdbm Db func (h *Handlers) GetSender(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} + res, err := h.Init(ctx, sym, input) + if err != nil { + return res, err + } // publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) // if err != nil { // return res, err @@ -718,7 +824,10 @@ func (h *Handlers) GetSender(ctx context.Context, sym string, input []byte) (res // GetAmount retrieves the amount from teh Gdbm Db func (h *Handlers) GetAmount(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} + res, err := h.Init(ctx, sym, input) + if err != nil { + return res, err + } // amount, err := h.db.Fetch([]byte(Amount)) // if err != nil { // return res, err @@ -731,7 +840,10 @@ func (h *Handlers) GetAmount(ctx context.Context, sym string, input []byte) (res // QuickWithBalance retrieves the balance for a given public key from the custodial balance API endpoint before // gracefully exiting the session. func (h *Handlers) QuitWithBalance(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} + res, err := h.Init(ctx, sym, input) + if err != nil { + return res, err + } flag_account_authorized, _ := h.flagManager.GetFlag("flag_account_authorized") @@ -754,7 +866,10 @@ func (h *Handlers) QuitWithBalance(ctx context.Context, sym string, input []byte // InitiateTransaction returns a confirmation and resets the transaction data // on the JSON file. func (h *Handlers) InitiateTransaction(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} + res, err := h.Init(ctx, sym, input) + if err != nil { + return res, err + } code := codeFromCtx(ctx) l := gotext.NewLocale(translationDir, code) l.AddDomain("default") @@ -787,7 +902,10 @@ func (h *Handlers) InitiateTransaction(ctx context.Context, sym string, input [] // GetProfileInfo retrieves and formats the profile information of a user from a Gdbm backed storage. func (h *Handlers) GetProfileInfo(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res := resource.Result{} + res, err := h.Init(ctx, sym, input) + if err != nil { + return res, err + } // Define default values defaultValue := "Not provided" diff --git a/internal/utils/filehandler.go b/internal/utils/filehandler.go deleted file mode 100644 index 8b11e29..0000000 --- a/internal/utils/filehandler.go +++ /dev/null @@ -1,13 +0,0 @@ -package utils - - - - -type AccountFileHandlerInterface interface { - EnsureFileExists() error - ReadAccountData() (map[string]string, error) - WriteAccountData(data map[string]string) error -} - - - diff --git a/services/registration/Makefile b/services/registration/Makefile index 1863b0b..af8b8c1 100644 --- a/services/registration/Makefile +++ b/services/registration/Makefile @@ -4,7 +4,7 @@ TXTS = $(wildcard ./*.txt.orig) # Rule to build .bin files from .vis files %.vis: - go run ../../go-vise/dev/asm -f pp.csv $(basename $@).vis > $(basename $@).bin + go run ../../go-vise/dev/asm/main.go -f pp.csv $(basename $@).vis > $(basename $@).bin @echo "Built $(basename $@).bin from $(basename $@).vis" # Rule to copy .orig files to .txt From cad8e86c8b74e55cf473a66642f69c4b6f752767 Mon Sep 17 00:00:00 2001 From: lash Date: Thu, 5 Sep 2024 23:55:51 +0100 Subject: [PATCH 179/201] Remove manual init calls in handler funcs --- cmd/main.go | 9 +- internal/handlers/ussd/menuhandler.go | 191 +++++++++----------------- 2 files changed, 70 insertions(+), 130 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index dcb0b15..a7f7174 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -115,9 +115,11 @@ func main() { var resourceDir string var size uint var sessionId string + var debug bool flag.StringVar(&sessionId, "session-id", "075xx2123", "session id") flag.StringVar(&dbDir, "dbdir", ".state", "database dir to read from") flag.StringVar(&resourceDir, "resourcedir", path.Join("services", "registration"), "resource dir") + flag.BoolVar(&debug, "d", false, "use engine debug output") flag.UintVar(&size, "s", 160, "max size of output") flag.Parse() @@ -162,14 +164,17 @@ func main() { os.Exit(1) } - _, err = getHandler(flagParser, dbResource, pr, store) + hl, err := getHandler(flagParser, dbResource, pr, store) if err != nil { fmt.Fprintf(os.Stderr, err.Error()) os.Exit(1) } en := getEngine(cfg, rs, pr) - + en = en.WithFirst(hl.Init) + if debug { + en = en.WithDebug(nil) + } _, err = en.Init(ctx) if err != nil { diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index c43cb3b..8b22753 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -112,6 +112,7 @@ func isValidPIN(pin string) bool { func (h *Handlers) Init(ctx context.Context, sym string, input []byte) (resource.Result, error) { var r resource.Result + if h.pe == nil { logg.WarnCtxf(ctx, "handler init called before it is ready or more than once", "state", h.st, "cache", h.ca) return r, nil @@ -123,15 +124,16 @@ func (h *Handlers) Init(ctx context.Context, sym string, input []byte) (resource return r, fmt.Errorf("cannot get state and memory for handler") } h.pe = nil + + logg.DebugCtxf(ctx, "handler has been initialized", "state", h.st, "cache", h.ca) + return r, nil } // SetLanguage sets the language across the menu func (h *Handlers) SetLanguage(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res, err := h.Init(ctx, sym, input) - if err != nil { - return res, err - } + var res resource.Result + var err error inputStr := string(input) switch inputStr { @@ -177,10 +179,9 @@ func (h *Handlers) createAccountNoExist(ctx context.Context, sessionId string, r // creates an account on the API, // sets the default values and flags func (h *Handlers) CreateAccount(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res, err := h.Init(ctx, sym, input) - if err != nil { - return res, err - } + var res resource.Result + var err error + sessionId, ok := ctx.Value("SessionId").(string) if !ok { return res, fmt.Errorf("missing session") @@ -205,10 +206,9 @@ func (h *Handlers) CreateAccount(ctx context.Context, sym string, input []byte) // SavePin persists the user's PIN choice into the filesystem func (h *Handlers) SavePin(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res, err := h.Init(ctx, sym, input) - if err != nil { - return res, err - } + var res resource.Result + var err error + sessionId, ok := ctx.Value("SessionId").(string) if !ok { return res, fmt.Errorf("missing session") @@ -235,10 +235,8 @@ func (h *Handlers) SavePin(ctx context.Context, sym string, input []byte) (resou // SetResetSingleEdit sets and resets flags to allow gradual editing of profile information. func (h *Handlers) SetResetSingleEdit(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res, err := h.Init(ctx, sym, input) - if err != nil { - return res, err - } + var res resource.Result + menuOption := string(input) flag_allow_update, _ := h.flagManager.GetFlag("flag_allow_update") @@ -265,10 +263,7 @@ func (h *Handlers) SetResetSingleEdit(ctx context.Context, sym string, input []b // If similar, it sets the USERFLAG_PIN_SET flag allowing the user // to access the main menu func (h *Handlers) VerifyPin(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res, err := h.Init(ctx, sym, input) - if err != nil { - return res, err - } + var res resource.Result flag_valid_pin, _ := h.flagManager.GetFlag("flag_valid_pin") flag_pin_mismatch, _ := h.flagManager.GetFlag("flag_pin_mismatch") @@ -304,10 +299,8 @@ func codeFromCtx(ctx context.Context) string { // SaveFirstname updates the first name in a JSON data file with the provided input. func (h *Handlers) SaveFirstname(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res, err := h.Init(ctx, sym, input) - if err != nil { - return res, err - } + var res resource.Result + if len(input) > 0 { //name := string(input) //key := []byte(FirstName) @@ -320,10 +313,8 @@ func (h *Handlers) SaveFirstname(ctx context.Context, sym string, input []byte) // SaveFamilyname updates the family name in a JSON data file with the provided input. func (h *Handlers) SaveFamilyname(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res, err := h.Init(ctx, sym, input) - if err != nil { - return res, err - } + var res resource.Result + if len(input) > 0 { //secondname := string(input) //key := []byte(FamilyName) @@ -336,10 +327,8 @@ func (h *Handlers) SaveFamilyname(ctx context.Context, sym string, input []byte) // SaveYOB updates the Year of Birth(YOB) in a JSON data file with the provided input. func (h *Handlers) SaveYob(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res, err := h.Init(ctx, sym, input) - if err != nil { - return res, err - } + var res resource.Result + yob := string(input) if len(yob) == 4 { //yob := string(input) @@ -353,10 +342,8 @@ func (h *Handlers) SaveYob(ctx context.Context, sym string, input []byte) (resou // SaveLocation updates the location in a JSON data file with the provided input. func (h *Handlers) SaveLocation(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res, err := h.Init(ctx, sym, input) - if err != nil { - return res, err - } + var res resource.Result + if len(input) > 0 { //location := string(input) //key := []byte(Location) @@ -370,10 +357,8 @@ func (h *Handlers) SaveLocation(ctx context.Context, sym string, input []byte) ( // SaveGender updates the gender in a JSON data file with the provided input. func (h *Handlers) SaveGender(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res, err := h.Init(ctx, sym, input) - if err != nil { - return res, err - } + var res resource.Result + if len(input) > 0 { gender := string(input) switch gender { @@ -393,10 +378,8 @@ func (h *Handlers) SaveGender(ctx context.Context, sym string, input []byte) (re // SaveOfferings updates the offerings(goods and services provided by the user) in a JSON data file with the provided input. func (h *Handlers) SaveOfferings(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res, err := h.Init(ctx, sym, input) - if err != nil { - return res, err - } + var res resource.Result + if len(input) > 0 { //offerings := string(input) //key := []byte(Offerings) @@ -408,10 +391,7 @@ func (h *Handlers) SaveOfferings(ctx context.Context, sym string, input []byte) // ResetAllowUpdate resets the allowupdate flag that allows a user to update profile data. func (h *Handlers) ResetAllowUpdate(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res, err := h.Init(ctx, sym, input) - if err != nil { - return res, err - } + var res resource.Result flag_allow_update, _ := h.flagManager.GetFlag("flag_allow_update") @@ -421,10 +401,7 @@ func (h *Handlers) ResetAllowUpdate(ctx context.Context, sym string, input []byt // ResetAccountAuthorized resets the account authorization flag after a successful PIN entry. func (h *Handlers) ResetAccountAuthorized(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res, err := h.Init(ctx, sym, input) - if err != nil { - return res, err - } + var res resource.Result flag_account_authorized, _ := h.flagManager.GetFlag("flag_account_authorized") @@ -434,10 +411,8 @@ func (h *Handlers) ResetAccountAuthorized(ctx context.Context, sym string, input // CheckIdentifier retrieves the PublicKey from the JSON data file. func (h *Handlers) CheckIdentifier(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res, err := h.Init(ctx, sym, input) - if err != nil { - return res, err - } + var res resource.Result + //publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) // if err != nil { // return res, err @@ -449,10 +424,8 @@ func (h *Handlers) CheckIdentifier(ctx context.Context, sym string, input []byte // Authorize attempts to unlock the next sequential nodes by verifying the provided PIN against the already set PIN. // It sets the required flags that control the flow. func (h *Handlers) Authorize(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res, err := h.Init(ctx, sym, input) - if err != nil { - return res, err - } + var res resource.Result + var err error flag_incorrect_pin, _ := h.flagManager.GetFlag("flag_incorrect_pin") flag_account_authorized, _ := h.flagManager.GetFlag("flag_account_authorized") @@ -488,10 +461,7 @@ func (h *Handlers) Authorize(ctx context.Context, sym string, input []byte) (res // ResetIncorrectPin resets the incorrect pin flag after a new PIN attempt. func (h *Handlers) ResetIncorrectPin(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res, err := h.Init(ctx, sym, input) - if err != nil { - return res, err - } + var res resource.Result flag_incorrect_pin, _ := h.flagManager.GetFlag("flag_incorrect_pin") @@ -502,10 +472,7 @@ func (h *Handlers) ResetIncorrectPin(ctx context.Context, sym string, input []by // CheckAccountStatus queries the API using the TrackingId and sets flags // based on the account status func (h *Handlers) CheckAccountStatus(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res, err := h.Init(ctx, sym, input) - if err != nil { - return res, err - } + var res resource.Result flag_account_success, _ := h.flagManager.GetFlag("flag_account_success") flag_account_pending, _ := h.flagManager.GetFlag("flag_account_pending") @@ -547,10 +514,7 @@ func (h *Handlers) CheckAccountStatus(ctx context.Context, sym string, input []b // Quit displays the Thank you message and exits the menu func (h *Handlers) Quit(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res, err := h.Init(ctx, sym, input) - if err != nil { - return res, err - } + var res resource.Result flag_account_authorized, _ := h.flagManager.GetFlag("flag_account_authorized") @@ -565,10 +529,8 @@ func (h *Handlers) Quit(ctx context.Context, sym string, input []byte) (resource // VerifyYob verifies the length of the given input func (h *Handlers) VerifyYob(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res, err := h.Init(ctx, sym, input) - if err != nil { - return res, err - } + var res resource.Result + var err error flag_incorrect_date_format, _ := h.flagManager.GetFlag("flag_incorrect_date_format") @@ -591,10 +553,7 @@ func (h *Handlers) VerifyYob(ctx context.Context, sym string, input []byte) (res // ResetIncorrectYob resets the incorrect date format flag after a new attempt func (h *Handlers) ResetIncorrectYob(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res, err := h.Init(ctx, sym, input) - if err != nil { - return res, err - } + var res resource.Result flag_incorrect_date_format, _ := h.flagManager.GetFlag("flag_incorrect_date_format") @@ -605,10 +564,9 @@ func (h *Handlers) ResetIncorrectYob(ctx context.Context, sym string, input []by // CheckBalance retrieves the balance from the API using the "PublicKey" and sets // the balance as the result content func (h *Handlers) CheckBalance(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res, err := h.Init(ctx, sym, input) - if err != nil { - return res, err - } + var res resource.Result + var err error + // publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) sessionId, ok := ctx.Value("SessionId").(string) @@ -629,10 +587,8 @@ func (h *Handlers) CheckBalance(ctx context.Context, sym string, input []byte) ( // ValidateRecipient validates that the given input is a valid phone number. func (h *Handlers) ValidateRecipient(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res, err := h.Init(ctx, sym, input) - if err != nil { - return res, err - } + var res resource.Result + recipient := string(input) flag_invalid_recipient, _ := h.flagManager.GetFlag("flag_invalid_recipient") @@ -659,10 +615,7 @@ func (h *Handlers) ValidateRecipient(ctx context.Context, sym string, input []by // TransactionReset resets the previous transaction data (Recipient and Amount) // as well as the invalid flags func (h *Handlers) TransactionReset(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res, err := h.Init(ctx, sym, input) - if err != nil { - return res, err - } + var res resource.Result flag_invalid_recipient, _ := h.flagManager.GetFlag("flag_invalid_recipient") flag_invalid_recipient_with_invite, _ := h.flagManager.GetFlag("flag_invalid_recipient_with_invite") @@ -683,10 +636,7 @@ func (h *Handlers) TransactionReset(ctx context.Context, sym string, input []byt // ResetTransactionAmount resets the transaction amount and invalid flag func (h *Handlers) ResetTransactionAmount(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res, err := h.Init(ctx, sym, input) - if err != nil { - return res, err - } + var res resource.Result flag_invalid_amount, _ := h.flagManager.GetFlag("flag_invalid_amount") @@ -703,10 +653,9 @@ func (h *Handlers) ResetTransactionAmount(ctx context.Context, sym string, input // MaxAmount gets the current balance from the API and sets it as // the result content. func (h *Handlers) MaxAmount(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res, err := h.Init(ctx, sym, input) - if err != nil { - return res, err - } + var res resource.Result + var err error + // publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) // if err != nil { // return res, err @@ -725,10 +674,8 @@ func (h *Handlers) MaxAmount(ctx context.Context, sym string, input []byte) (res // ValidateAmount ensures that the given input is a valid amount and that // it is not more than the current balance. func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res, err := h.Init(ctx, sym, input) - if err != nil { - return res, err - } + var res resource.Result + var err error flag_invalid_amount, _ := h.flagManager.GetFlag("flag_invalid_amount") @@ -792,10 +739,8 @@ func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte) // GetRecipient returns the transaction recipient from a JSON data file. func (h *Handlers) GetRecipient(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res, err := h.Init(ctx, sym, input) - if err != nil { - return res, err - } + var res resource.Result + // recipient, err := h.db.Fetch([]byte(Recipient)) // if err != nil { // return res, err @@ -808,10 +753,8 @@ func (h *Handlers) GetRecipient(ctx context.Context, sym string, input []byte) ( // GetSender retrieves the public key from the Gdbm Db func (h *Handlers) GetSender(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res, err := h.Init(ctx, sym, input) - if err != nil { - return res, err - } + var res resource.Result + // publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) // if err != nil { // return res, err @@ -824,10 +767,8 @@ func (h *Handlers) GetSender(ctx context.Context, sym string, input []byte) (res // GetAmount retrieves the amount from teh Gdbm Db func (h *Handlers) GetAmount(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res, err := h.Init(ctx, sym, input) - if err != nil { - return res, err - } + var res resource.Result + // amount, err := h.db.Fetch([]byte(Amount)) // if err != nil { // return res, err @@ -840,10 +781,8 @@ func (h *Handlers) GetAmount(ctx context.Context, sym string, input []byte) (res // QuickWithBalance retrieves the balance for a given public key from the custodial balance API endpoint before // gracefully exiting the session. func (h *Handlers) QuitWithBalance(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res, err := h.Init(ctx, sym, input) - if err != nil { - return res, err - } + var res resource.Result + var err error flag_account_authorized, _ := h.flagManager.GetFlag("flag_account_authorized") @@ -866,10 +805,9 @@ func (h *Handlers) QuitWithBalance(ctx context.Context, sym string, input []byte // InitiateTransaction returns a confirmation and resets the transaction data // on the JSON file. func (h *Handlers) InitiateTransaction(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res, err := h.Init(ctx, sym, input) - if err != nil { - return res, err - } + var res resource.Result + var err error + code := codeFromCtx(ctx) l := gotext.NewLocale(translationDir, code) l.AddDomain("default") @@ -902,10 +840,7 @@ func (h *Handlers) InitiateTransaction(ctx context.Context, sym string, input [] // GetProfileInfo retrieves and formats the profile information of a user from a Gdbm backed storage. func (h *Handlers) GetProfileInfo(ctx context.Context, sym string, input []byte) (resource.Result, error) { - res, err := h.Init(ctx, sym, input) - if err != nil { - return res, err - } + var res resource.Result // Define default values defaultValue := "Not provided" From de8c7ce34afb6aae954a91c4f0151688bfbbf21a Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Fri, 6 Sep 2024 08:35:01 +0300 Subject: [PATCH 180/201] Added user data to db.go util --- internal/utils/db.go | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/internal/utils/db.go b/internal/utils/db.go index bfaf2e1..32fb804 100644 --- a/internal/utils/db.go +++ b/internal/utils/db.go @@ -16,6 +16,15 @@ const ( DATA_PUBLIC_KEY DATA_CUSTODIAL_ID DATA_ACCOUNT_PIN + DATA_ACCOUNT_STATUS + DATA_FIRST_NAME + DATA_FAMILY_NAME + DATA_YOB + DATA_LOCATION + DATA_GENDER + DATA_OFFERINGS + DATA_RECIPIENT + DATA_AMOUNT ) func typToBytes(typ DataTyp) []byte { From d001c5a7fc2b50a9f5b7c11a6d018c69b71021fe Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Fri, 6 Sep 2024 09:33:39 +0300 Subject: [PATCH 181/201] Write and read data from gdbm --- internal/handlers/ussd/menuhandler.go | 325 +++++++++++++++----------- 1 file changed, 184 insertions(+), 141 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 8b22753..6217921 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -29,23 +29,6 @@ var ( translationDir = path.Join(scriptDir, "locale") ) -const ( - TrackingIdKey = "TRACKINGID" - PublicKeyKey = "PUBLICKEY" - CustodialIdKey = "CUSTODIALID" - AccountPin = "ACCOUNTPIN" - AccountStatus = "ACCOUNTSTATUS" - FirstName = "FIRSTNAME" - FamilyName = "FAMILYNAME" - YearOfBirth = "YOB" - Location = "LOCATION" - Gender = "GENDER" - Offerings = "OFFERINGS" - Recipient = "RECIPIENT" - Amount = "AMOUNT" - AccountCreated = "ACCOUNTCREATED" -) - type FSData struct { Path string St *state.State @@ -75,7 +58,7 @@ func (fm *FlagManager) GetFlag(label string) (uint32, error) { } type Handlers struct { - pe *persist.Persister + pe *persist.Persister st *state.State ca cache.Memory userdataStore db.Db @@ -92,7 +75,7 @@ func NewHandlers(appFlags *asm.FlagParser, pe *persist.Persister, userdataStore return nil, fmt.Errorf("cannot create handler with nil userdata store") } h := &Handlers{ - pe: pe, + pe: pe, userdataStore: userdataStore, flagManager: appFlags, accountFileHandler: utils.NewAccountFileHandler(userdataStore), @@ -122,7 +105,7 @@ func (h *Handlers) Init(ctx context.Context, sym string, input []byte) (resource if h.st == nil || h.ca == nil { logg.ErrorCtxf(ctx, "perister fail in handler", "state", h.st, "cache", h.ca) return r, fmt.Errorf("cannot get state and memory for handler") - } + } h.pe = nil logg.DebugCtxf(ctx, "handler has been initialized", "state", h.st, "cache", h.ca) @@ -208,7 +191,7 @@ func (h *Handlers) CreateAccount(ctx context.Context, sym string, input []byte) func (h *Handlers) SavePin(ctx context.Context, sym string, input []byte) (resource.Result, error) { var res resource.Result var err error - + sessionId, ok := ctx.Value("SessionId").(string) if !ok { return res, fmt.Errorf("missing session") @@ -236,7 +219,7 @@ func (h *Handlers) SavePin(ctx context.Context, sym string, input []byte) (resou // SetResetSingleEdit sets and resets flags to allow gradual editing of profile information. func (h *Handlers) SetResetSingleEdit(ctx context.Context, sym string, input []byte) (resource.Result, error) { var res resource.Result - + menuOption := string(input) flag_allow_update, _ := h.flagManager.GetFlag("flag_allow_update") @@ -297,67 +280,94 @@ func codeFromCtx(ctx context.Context) string { return code } -// SaveFirstname updates the first name in a JSON data file with the provided input. +// SaveFirstname updates the first name in the gdbm with the provided input. func (h *Handlers) SaveFirstname(ctx context.Context, sym string, input []byte) (resource.Result, error) { var res resource.Result + var err error + sessionId, ok := ctx.Value("SessionId").(string) + if !ok { + return res, fmt.Errorf("missing session") + } if len(input) > 0 { - //name := string(input) - //key := []byte(FirstName) - //value := []byte(name) - //h.db.Store(key, value, true) + firstName := string(input) + err = utils.WriteEntry(ctx, h.userdataStore, sessionId, utils.DATA_FIRST_NAME, []byte(firstName)) + if err != nil { + return res, nil + } } return res, nil } -// SaveFamilyname updates the family name in a JSON data file with the provided input. +// SaveFamilyname updates the family name in the gdbm with the provided input. func (h *Handlers) SaveFamilyname(ctx context.Context, sym string, input []byte) (resource.Result, error) { var res resource.Result + var err error + sessionId, ok := ctx.Value("SessionId").(string) + if !ok { + return res, fmt.Errorf("missing session") + } if len(input) > 0 { - //secondname := string(input) - //key := []byte(FamilyName) - //value := []byte(secondname) - //h.db.Store(key, value, true) + familyName := string(input) + err = utils.WriteEntry(ctx, h.userdataStore, sessionId, utils.DATA_FAMILY_NAME, []byte(familyName)) + if err != nil { + return res, nil + } } return res, nil } -// SaveYOB updates the Year of Birth(YOB) in a JSON data file with the provided input. +// SaveYOB updates the Year of Birth(YOB) in the gdbm with the provided input. func (h *Handlers) SaveYob(ctx context.Context, sym string, input []byte) (resource.Result, error) { var res resource.Result + var err error + sessionId, ok := ctx.Value("SessionId").(string) + if !ok { + return res, fmt.Errorf("missing session") + } - yob := string(input) - if len(yob) == 4 { - //yob := string(input) - //key := []byte(YearOfBirth) - //value := []byte(yob) - //h.db.Store(key, value, true) + if len(input) == 4 { + yob := string(input) + err = utils.WriteEntry(ctx, h.userdataStore, sessionId, utils.DATA_YOB, []byte(yob)) + if err != nil { + return res, nil + } } return res, nil } -// SaveLocation updates the location in a JSON data file with the provided input. +// SaveLocation updates the location in the gdbm with the provided input. func (h *Handlers) SaveLocation(ctx context.Context, sym string, input []byte) (resource.Result, error) { var res resource.Result + var err error + sessionId, ok := ctx.Value("SessionId").(string) + if !ok { + return res, fmt.Errorf("missing session") + } if len(input) > 0 { - //location := string(input) - //key := []byte(Location) - //value := []byte(location) - - //h.db.Store(key, value, true) + location := string(input) + err = utils.WriteEntry(ctx, h.userdataStore, sessionId, utils.DATA_LOCATION, []byte(location)) + if err != nil { + return res, nil + } } return res, nil } -// SaveGender updates the gender in a JSON data file with the provided input. +// SaveGender updates the gender in the gdbm with the provided input. func (h *Handlers) SaveGender(ctx context.Context, sym string, input []byte) (resource.Result, error) { var res resource.Result + var err error + sessionId, ok := ctx.Value("SessionId").(string) + if !ok { + return res, fmt.Errorf("missing session") + } if len(input) > 0 { gender := string(input) @@ -369,23 +379,32 @@ func (h *Handlers) SaveGender(ctx context.Context, sym string, input []byte) (re case "3": gender = "Unspecified" } - //key := []byte(Gender) - //value := []byte(gender) - //h.db.Store(key, value, true) + err = utils.WriteEntry(ctx, h.userdataStore, sessionId, utils.DATA_GENDER, []byte(gender)) + if err != nil { + return res, nil + } } + return res, nil } -// SaveOfferings updates the offerings(goods and services provided by the user) in a JSON data file with the provided input. +// SaveOfferings updates the offerings(goods and services provided by the user) in the gdbm with the provided input. func (h *Handlers) SaveOfferings(ctx context.Context, sym string, input []byte) (resource.Result, error) { var res resource.Result + var err error + sessionId, ok := ctx.Value("SessionId").(string) + if !ok { + return res, fmt.Errorf("missing session") + } if len(input) > 0 { - //offerings := string(input) - //key := []byte(Offerings) - //value := []byte(offerings) - //h.db.Store(key, value, true) + offerings := string(input) + err = utils.WriteEntry(ctx, h.userdataStore, sessionId, utils.DATA_OFFERINGS, []byte(offerings)) + if err != nil { + return res, nil + } } + return res, nil } @@ -413,11 +432,15 @@ func (h *Handlers) ResetAccountAuthorized(ctx context.Context, sym string, input func (h *Handlers) CheckIdentifier(ctx context.Context, sym string, input []byte) (resource.Result, error) { var res resource.Result - //publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) - // if err != nil { - // return res, err - // } - res.Content = "string(publicKey)" + sessionId, ok := ctx.Value("SessionId").(string) + if !ok { + return res, fmt.Errorf("missing session") + } + + publicKey, _ := utils.ReadEntry(ctx, h.userdataStore, sessionId, utils.DATA_PUBLIC_KEY) + + res.Content = string(publicKey) + return res, nil } @@ -427,13 +450,15 @@ func (h *Handlers) Authorize(ctx context.Context, sym string, input []byte) (res var res resource.Result var err error - flag_incorrect_pin, _ := h.flagManager.GetFlag("flag_incorrect_pin") - flag_account_authorized, _ := h.flagManager.GetFlag("flag_account_authorized") - flag_allow_update, _ := h.flagManager.GetFlag("flag_allow_update") sessionId, ok := ctx.Value("SessionId").(string) if !ok { return res, fmt.Errorf("missing session") } + + flag_incorrect_pin, _ := h.flagManager.GetFlag("flag_incorrect_pin") + flag_account_authorized, _ := h.flagManager.GetFlag("flag_account_authorized") + flag_allow_update, _ := h.flagManager.GetFlag("flag_allow_update") + AccountPin, err := utils.ReadEntry(ctx, h.userdataStore, sessionId, utils.DATA_ACCOUNT_PIN) if err == nil { @@ -485,22 +510,15 @@ func (h *Handlers) CheckAccountStatus(ctx context.Context, sym string, input []b trackingId, _ := utils.ReadEntry(ctx, h.userdataStore, sessionId, utils.DATA_TRACKING_ID) status, err := h.accountService.CheckAccountStatus(string(trackingId)) - if err != nil { fmt.Println("Error checking account status:", err) return res, err - } - // err = h.db.Store(toBytes(AccountStatus), toBytes(status), true) - // if err != nil { - // return res, nil - // } - - // err = h.db.Store(toBytes(TrackingIdKey), toBytes(status), true) - // if err != nil { - // return res, nil - // } + err = utils.WriteEntry(ctx, h.userdataStore, sessionId, utils.DATA_ACCOUNT_STATUS, []byte(status)) + if err != nil { + return res, nil + } if status == "SUCCESS" { res.FlagSet = append(res.FlagSet, flag_account_success) @@ -567,8 +585,6 @@ func (h *Handlers) CheckBalance(ctx context.Context, sym string, input []byte) ( var res resource.Result var err error - // publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) - sessionId, ok := ctx.Value("SessionId").(string) if !ok { return res, fmt.Errorf("missing session") @@ -588,6 +604,12 @@ func (h *Handlers) CheckBalance(ctx context.Context, sym string, input []byte) ( // ValidateRecipient validates that the given input is a valid phone number. func (h *Handlers) ValidateRecipient(ctx context.Context, sym string, input []byte) (resource.Result, error) { var res resource.Result + var err error + + sessionId, ok := ctx.Value("SessionId").(string) + if !ok { + return res, fmt.Errorf("missing session") + } recipient := string(input) @@ -602,11 +624,10 @@ func (h *Handlers) ValidateRecipient(ctx context.Context, sym string, input []by return res, nil } - // accountData["Recipient"] = recipient - // key := []byte(Recipient) - // value := []byte(recipient) - - // h.db.Store(key, value, true) + err = utils.WriteEntry(ctx, h.userdataStore, sessionId, utils.DATA_RECIPIENT, []byte(recipient)) + if err != nil { + return res, nil + } } return res, nil @@ -616,18 +637,25 @@ func (h *Handlers) ValidateRecipient(ctx context.Context, sym string, input []by // as well as the invalid flags func (h *Handlers) TransactionReset(ctx context.Context, sym string, input []byte) (resource.Result, error) { var res resource.Result + var err error + + sessionId, ok := ctx.Value("SessionId").(string) + if !ok { + return res, fmt.Errorf("missing session") + } flag_invalid_recipient, _ := h.flagManager.GetFlag("flag_invalid_recipient") flag_invalid_recipient_with_invite, _ := h.flagManager.GetFlag("flag_invalid_recipient_with_invite") - // err := h.db.Delete([]byte(Amount)) - // if err != nil && !errors.Is(err, gdbm.ErrItemNotFound) { - // return res, err - // } - // err = h.db.Delete([]byte(Recipient)) - // if err != nil && !errors.Is(err, gdbm.ErrItemNotFound) { - // return res, err - // } + err = utils.WriteEntry(ctx, h.userdataStore, sessionId, utils.DATA_AMOUNT, []byte("")) + if err != nil { + return res, nil + } + + err = utils.WriteEntry(ctx, h.userdataStore, sessionId, utils.DATA_RECIPIENT, []byte("")) + if err != nil { + return res, nil + } res.FlagReset = append(res.FlagReset, flag_invalid_recipient, flag_invalid_recipient_with_invite) @@ -637,13 +665,19 @@ func (h *Handlers) TransactionReset(ctx context.Context, sym string, input []byt // ResetTransactionAmount resets the transaction amount and invalid flag func (h *Handlers) ResetTransactionAmount(ctx context.Context, sym string, input []byte) (resource.Result, error) { var res resource.Result + var err error + + sessionId, ok := ctx.Value("SessionId").(string) + if !ok { + return res, fmt.Errorf("missing session") + } flag_invalid_amount, _ := h.flagManager.GetFlag("flag_invalid_amount") - // err := h.db.Delete([]byte(Amount)) - // if err != nil && !errors.Is(err, gdbm.ErrItemNotFound) { - // return res, err - // } + err = utils.WriteEntry(ctx, h.userdataStore, sessionId, utils.DATA_AMOUNT, []byte("")) + if err != nil { + return res, nil + } res.FlagReset = append(res.FlagReset, flag_invalid_amount) @@ -656,12 +690,14 @@ func (h *Handlers) MaxAmount(ctx context.Context, sym string, input []byte) (res var res resource.Result var err error - // publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) - // if err != nil { - // return res, err - // } + sessionId, ok := ctx.Value("SessionId").(string) + if !ok { + return res, fmt.Errorf("missing session") + } - balance, err := h.accountService.CheckBalance(string("publicKey")) + publicKey, _ := utils.ReadEntry(ctx, h.userdataStore, sessionId, utils.DATA_PUBLIC_KEY) + + balance, err := h.accountService.CheckBalance(string(publicKey)) if err != nil { return res, nil } @@ -677,16 +713,18 @@ func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte) var res resource.Result var err error + sessionId, ok := ctx.Value("SessionId").(string) + if !ok { + return res, fmt.Errorf("missing session") + } + flag_invalid_amount, _ := h.flagManager.GetFlag("flag_invalid_amount") + publicKey, _ := utils.ReadEntry(ctx, h.userdataStore, sessionId, utils.DATA_PUBLIC_KEY) + amountStr := string(input) - // publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) - // if err != nil { - // return res, err - // } - - balanceStr, err := h.accountService.CheckBalance(string("publicKey")) + balanceStr, err := h.accountService.CheckBalance(string(publicKey)) if err != nil { return res, err @@ -726,10 +764,8 @@ func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte) } res.Content = fmt.Sprintf("%.3f", inputAmount) // Format to 3 decimal places - // key := []byte(Amount) - // value := []byte(res.Content) - // h.db.Store(key, value, true) + err = utils.WriteEntry(ctx, h.userdataStore, sessionId, utils.DATA_AMOUNT, []byte(amountStr)) if err != nil { return res, err } @@ -737,16 +773,18 @@ func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte) return res, nil } -// GetRecipient returns the transaction recipient from a JSON data file. +// GetRecipient returns the transaction recipient from the gdbm. func (h *Handlers) GetRecipient(ctx context.Context, sym string, input []byte) (resource.Result, error) { var res resource.Result - // recipient, err := h.db.Fetch([]byte(Recipient)) - // if err != nil { - // return res, err - // } + sessionId, ok := ctx.Value("SessionId").(string) + if !ok { + return res, fmt.Errorf("missing session") + } - res.Content = string("recipient") + recipient, _ := utils.ReadEntry(ctx, h.userdataStore, sessionId, utils.DATA_RECIPIENT) + + res.Content = string(recipient) return res, nil } @@ -755,12 +793,14 @@ func (h *Handlers) GetRecipient(ctx context.Context, sym string, input []byte) ( func (h *Handlers) GetSender(ctx context.Context, sym string, input []byte) (resource.Result, error) { var res resource.Result - // publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) - // if err != nil { - // return res, err - // } + sessionId, ok := ctx.Value("SessionId").(string) + if !ok { + return res, fmt.Errorf("missing session") + } - res.Content = string("publicKey") + publicKey, _ := utils.ReadEntry(ctx, h.userdataStore, sessionId, utils.DATA_PUBLIC_KEY) + + res.Content = string(publicKey) return res, nil } @@ -769,11 +809,14 @@ func (h *Handlers) GetSender(ctx context.Context, sym string, input []byte) (res func (h *Handlers) GetAmount(ctx context.Context, sym string, input []byte) (resource.Result, error) { var res resource.Result - // amount, err := h.db.Fetch([]byte(Amount)) - // if err != nil { - // return res, err - // } - res.Content = string("amount") + sessionId, ok := ctx.Value("SessionId").(string) + if !ok { + return res, fmt.Errorf("missing session") + } + + amount, _ := utils.ReadEntry(ctx, h.userdataStore, sessionId, utils.DATA_AMOUNT) + + res.Content = string(amount) return res, nil } @@ -783,17 +826,20 @@ func (h *Handlers) GetAmount(ctx context.Context, sym string, input []byte) (res func (h *Handlers) QuitWithBalance(ctx context.Context, sym string, input []byte) (resource.Result, error) { var res resource.Result var err error + sessionId, ok := ctx.Value("SessionId").(string) + if !ok { + return res, fmt.Errorf("missing session") + } flag_account_authorized, _ := h.flagManager.GetFlag("flag_account_authorized") code := codeFromCtx(ctx) l := gotext.NewLocale(translationDir, code) l.AddDomain("default") - // publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) - // if err != nil { - // return res, err - // } - balance, err := h.accountService.CheckBalance(string("publicKey")) + + publicKey, _ := utils.ReadEntry(ctx, h.userdataStore, sessionId, utils.DATA_PUBLIC_KEY) + + balance, err := h.accountService.CheckBalance(string(publicKey)) if err != nil { return res, nil } @@ -803,10 +849,14 @@ func (h *Handlers) QuitWithBalance(ctx context.Context, sym string, input []byte } // InitiateTransaction returns a confirmation and resets the transaction data -// on the JSON file. +// on the gdbm store. func (h *Handlers) InitiateTransaction(ctx context.Context, sym string, input []byte) (resource.Result, error) { var res resource.Result var err error + sessionId, ok := ctx.Value("SessionId").(string) + if !ok { + return res, fmt.Errorf("missing session") + } code := codeFromCtx(ctx) l := gotext.NewLocale(translationDir, code) @@ -814,20 +864,13 @@ func (h *Handlers) InitiateTransaction(ctx context.Context, sym string, input [] // TODO // Use the amount, recipient and sender to call the API and initialize the transaction - // publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) - // if err != nil { - // return res, err - // } - // amount, err := h.db.Fetch([]byte(Amount)) - // if err != nil { - // return res, err - // } - // recipient, err := h.db.Fetch([]byte(Recipient)) - // if err != nil { - // return res, err - // } + publicKey, _ := utils.ReadEntry(ctx, h.userdataStore, sessionId, utils.DATA_PUBLIC_KEY) - //res.Content = l.Get("Your request has been sent. %s will receive %s from %s.", string(recipient), string(amount), string(publicKey)) + amount, _ := utils.ReadEntry(ctx, h.userdataStore, sessionId, utils.DATA_AMOUNT) + + recipient, _ := utils.ReadEntry(ctx, h.userdataStore, sessionId, utils.DATA_RECIPIENT) + + res.Content = l.Get("Your request has been sent. %s will receive %s from %s.", string(recipient), string(amount), string(publicKey)) account_authorized_flag, err := h.flagManager.GetFlag("flag_account_authorized") if err != nil { From 2cc85379cc09a20eaed1403b78f39ba21041989d Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Fri, 6 Sep 2024 11:02:33 +0300 Subject: [PATCH 182/201] update log --- internal/handlers/ussd/menuhandler.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 6217921..3482f2a 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -172,7 +172,7 @@ func (h *Handlers) CreateAccount(ctx context.Context, sym string, input []byte) _, err = utils.ReadEntry(ctx, h.userdataStore, sessionId, utils.DATA_ACCOUNT_CREATED) if err != nil { if db.IsNotFound(err) { - fmt.Println("Creating an account because it doesn't exist") + logg.Printf(logging.LVL_INFO, "Creating an account because it doesn't exist") err = h.createAccountNoExist(ctx, sessionId, &res) if err != nil { return res, err @@ -315,6 +315,8 @@ func (h *Handlers) SaveFamilyname(ctx context.Context, sym string, input []byte) if err != nil { return res, nil } + } else { + return res,fmt.Errorf("a family name cannot be less than one character") } return res, nil From 6947b1e4a41ddca05c9a403787df10a18504ecb0 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Fri, 6 Sep 2024 11:03:01 +0300 Subject: [PATCH 183/201] rename getflags to getparser --- cmd/main.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index a7f7174..906c4cc 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -23,7 +23,7 @@ var ( scriptDir = path.Join("services", "registration") ) -func getFlags(fp string, debug bool) (*asm.FlagParser, error) { +func getParser(fp string, debug bool) (*asm.FlagParser, error) { flagParser := asm.NewFlagParser().WithDebug() _, err := flagParser.Load(fp) if err != nil { @@ -128,7 +128,7 @@ func main() { ctx := context.Background() ctx = context.WithValue(ctx, "SessionId",sessionId) pfp := path.Join(scriptDir, "pp.csv") - flagParser, err := getFlags(pfp, true) + flagParser, err := getParser(pfp, true) if err != nil { os.Exit(1) From 7a12588744099303d617ea6b18e0df86add361fc Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Fri, 6 Sep 2024 12:42:24 +0300 Subject: [PATCH 184/201] remove deprecated code --- internal/utils/account_utils.go | 39 +++------------------------------ 1 file changed, 3 insertions(+), 36 deletions(-) diff --git a/internal/utils/account_utils.go b/internal/utils/account_utils.go index 1ab34b8..b9fd1e3 100644 --- a/internal/utils/account_utils.go +++ b/internal/utils/account_utils.go @@ -8,38 +8,21 @@ import ( ) type AccountFileHandler struct { - //FilePath string store db.Db } -// func NewAccountFileHandler(path string) *AccountFileHandler { -// return &AccountFileHandler{FilePath: path} -// } - func NewAccountFileHandler(store db.Db) *AccountFileHandler { return &AccountFileHandler{ store: store, } } -// func (afh *AccountFileHandler) ReadAccountData() (map[string]string, error) { -// jsonData, err := os.ReadFile(afh.FilePath) -// if err != nil { -// return nil, err -// } - -// var accountData map[string]string -// err = json.Unmarshal(jsonData, &accountData) -// if err != nil { -// return nil, err -// } - -// return accountData, nil -// } - func (afh *AccountFileHandler) ReadAccountData(ctx context.Context, sessionId string) (map[string]string, error) { var accountData map[string]string jsonData, err := ReadEntry(ctx, afh.store, sessionId, DATA_ACCOUNT) + if err != nil { + return nil,err + } err = json.Unmarshal(jsonData, &accountData) if err != nil { return nil, err @@ -47,15 +30,6 @@ func (afh *AccountFileHandler) ReadAccountData(ctx context.Context, sessionId st return accountData, nil } -// func (afh *AccountFileHandler) WriteAccountData(accountData map[string]string) error { -// jsonData, err := json.Marshal(accountData) -// if err != nil { -// return err -// } - -// return os.WriteFile(afh.FilePath, jsonData, 0644) -// } - func (afh *AccountFileHandler) WriteAccountData(ctx context.Context, sessionId string, accountData map[string]string) error { _, err := json.Marshal(accountData) if err != nil { @@ -65,13 +39,6 @@ func (afh *AccountFileHandler) WriteAccountData(ctx context.Context, sessionId s return nil } -// func (afh *AccountFileHandler) EnsureFileExists() error { -// f, err := os.OpenFile(afh.FilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) -// if err != nil { -// return err -// } -// return f.Close() -// } func (afh *AccountFileHandler) EnsureFileExists() error { return nil } From eb9f470ac568473b72aa2a5ad61d8d4eec91018f Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Fri, 6 Sep 2024 16:17:26 +0300 Subject: [PATCH 185/201] Update the GetProfileInfo to get data from gdbm --- internal/handlers/ussd/menuhandler.go | 73 ++++++++++++--------------- 1 file changed, 33 insertions(+), 40 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 3482f2a..c94a57c 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -316,7 +316,7 @@ func (h *Handlers) SaveFamilyname(ctx context.Context, sym string, input []byte) return res, nil } } else { - return res,fmt.Errorf("a family name cannot be less than one character") + return res, fmt.Errorf("a family name cannot be less than one character") } return res, nil @@ -886,62 +886,55 @@ func (h *Handlers) InitiateTransaction(ctx context.Context, sym string, input [] // GetProfileInfo retrieves and formats the profile information of a user from a Gdbm backed storage. func (h *Handlers) GetProfileInfo(ctx context.Context, sym string, input []byte) (resource.Result, error) { var res resource.Result + sessionId, ok := ctx.Value("SessionId").(string) + if !ok { + return res, fmt.Errorf("missing session") + } - // Define default values - defaultValue := "Not provided" - name := defaultValue - familyName := defaultValue - yob := defaultValue - gender := defaultValue - location := defaultValue - offerings := defaultValue + // Default value when an entry is not found + defaultValue := "Not Provided" - // Fetch data using a map for better organization - // dataKeys := map[string]*string{ - // FirstName: &name, - // FamilyName: &familyName, - // YearOfBirth: &yob, - // Location: &location, - // Gender: &gender, - // Offerings: &offerings, - // } + // Helper function to handle nil byte slices and convert them to string + getEntryOrDefault := func(entry []byte, err error) string { + if err != nil || entry == nil { + return defaultValue + } + return string(entry) + } - // Iterate over keys and fetch values - //iter := h.db.Iterator() - // next := h.db.Iterator() - // //defer iter.Close() // Ensure the iterator is closed - // for key, err := next(); err == nil; key, err = next() { - // if valuePointer, ok := dataKeys[string(key)]; ok { - // // value, fetchErr := h.db.Fetch(key) - // // if fetchErr == nil { - // // *valuePointer = string(value) - // // } - // } - // } + // Retrieve user data as strings with fallback to defaultValue + firstName := getEntryOrDefault(utils.ReadEntry(ctx, h.userdataStore, sessionId, utils.DATA_FIRST_NAME)) + familyName := getEntryOrDefault(utils.ReadEntry(ctx, h.userdataStore, sessionId, utils.DATA_FAMILY_NAME)) + yob := getEntryOrDefault(utils.ReadEntry(ctx, h.userdataStore, sessionId, utils.DATA_YOB)) + gender := getEntryOrDefault(utils.ReadEntry(ctx, h.userdataStore, sessionId, utils.DATA_GENDER)) + location := getEntryOrDefault(utils.ReadEntry(ctx, h.userdataStore, sessionId, utils.DATA_LOCATION)) + offerings := getEntryOrDefault(utils.ReadEntry(ctx, h.userdataStore, sessionId, utils.DATA_OFFERINGS)) // Construct the full name + name := defaultValue if familyName != defaultValue { - if name == defaultValue { + if firstName == defaultValue { name = familyName } else { - name = name + " " + familyName + name = firstName + " " + familyName } } // Calculate age from year of birth - var age string + age := defaultValue if yob != defaultValue { - yobInt, err := strconv.Atoi(yob) - if err != nil { + if yobInt, err := strconv.Atoi(yob); err == nil { + age = strconv.Itoa(utils.CalculateAgeWithYOB(yobInt)) + } else { return res, fmt.Errorf("invalid year of birth: %v", err) } - age = strconv.Itoa(utils.CalculateAgeWithYOB(yobInt)) - } else { - age = defaultValue } // Format the result - formattedData := fmt.Sprintf("Name: %s\nGender: %s\nAge: %s\nLocation: %s\nYou provide: %s\n", name, gender, age, location, offerings) - res.Content = formattedData + res.Content = fmt.Sprintf( + "Name: %s\nGender: %s\nAge: %s\nLocation: %s\nYou provide: %s\n", + name, gender, age, location, offerings, + ) + return res, nil } From d7376a41961b23674658a0051635ed72988c3ccc Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Fri, 6 Sep 2024 16:53:22 +0300 Subject: [PATCH 186/201] format error --- internal/handlers/ussd/menuhandler.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 3482f2a..5c25ded 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -316,7 +316,7 @@ func (h *Handlers) SaveFamilyname(ctx context.Context, sym string, input []byte) return res, nil } } else { - return res,fmt.Errorf("a family name cannot be less than one character") + return res, fmt.Errorf("a family name cannot be less than one character") } return res, nil From 8175d6ac129e877c6f616a191dd59733fc0127bd Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Fri, 6 Sep 2024 17:50:33 +0300 Subject: [PATCH 187/201] setup db mock --- internal/handlers/ussd/mocks/dbmock.go | 60 ++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 internal/handlers/ussd/mocks/dbmock.go diff --git a/internal/handlers/ussd/mocks/dbmock.go b/internal/handlers/ussd/mocks/dbmock.go new file mode 100644 index 0000000..71f7eca --- /dev/null +++ b/internal/handlers/ussd/mocks/dbmock.go @@ -0,0 +1,60 @@ +package mocks + +import ( + "context" + + "git.defalsify.org/vise.git/lang" + "git.grassecon.net/urdt/ussd/internal/utils" + "github.com/stretchr/testify/mock" +) + +type MockDb struct { + mock.Mock +} + +func (m *MockDb) SetPrefix(prefix uint8) { + m.Called(utils.DATA_FAMILY_NAME) +} + +func (m *MockDb) Prefix() uint8 { + args := m.Called() + return args.Get(0).(uint8) +} + +func (m *MockDb) Safe() bool { + args := m.Called() + return args.Get(0).(bool) +} + +func (m *MockDb) SetLanguage(language *lang.Language) { + m.Called(language) +} + +func (m *MockDb) SetLock(uint8, bool) error { + args := m.Called() + return args.Error(0) +} + +func (m *MockDb) Connect(ctx context.Context, connectionStr string) error { + args := m.Called(ctx, connectionStr) + return args.Error(0) +} + +func (m *MockDb) SetSession(sessionId string) { + m.Called(sessionId) +} + +func (m *MockDb) Put(ctx context.Context, key, value []byte) error { + args := m.Called(ctx, key, value) + return args.Error(0) +} + +func (m *MockDb) Get(ctx context.Context, key []byte) ([]byte, error) { + args := m.Called(ctx, key) + return nil, args.Error(0) +} + +func (m *MockDb) Close() error { + args := m.Called(nil) + return args.Error(0) +} From 175cbd1983a54521d8f7db6d0b3e60ae13794e7a Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Fri, 6 Sep 2024 17:51:07 +0300 Subject: [PATCH 188/201] setup template test --- internal/handlers/ussd/menuhandler_test.go | 1822 ++++++++++---------- 1 file changed, 937 insertions(+), 885 deletions(-) diff --git a/internal/handlers/ussd/menuhandler_test.go b/internal/handlers/ussd/menuhandler_test.go index 5bcf7c1..3c14a26 100644 --- a/internal/handlers/ussd/menuhandler_test.go +++ b/internal/handlers/ussd/menuhandler_test.go @@ -2,13 +2,8 @@ package ussd import ( "context" - "encoding/json" - "fmt" - "os" - "path/filepath" "testing" - "git.defalsify.org/vise.git/resource" "git.grassecon.net/urdt/ussd/internal/handlers/ussd/mocks" "git.grassecon.net/urdt/ussd/internal/models" "git.grassecon.net/urdt/ussd/internal/utils" @@ -45,949 +40,1006 @@ func (m *MockAccountService) CheckAccountStatus(trackingId string) (string, erro return args.String(0), args.Error(1) } -func TestCreateAccount(t *testing.T) { - // Setup - tempDir, err := os.MkdirTemp("", "test_create_account") - if err != nil { - t.Fatalf("Failed to create temp directory: %v", err) - } - defer os.RemoveAll(tempDir) // Clean up after the test run +// func TestCreateAccount(t *testing.T) { +// // Setup +// tempDir, err := os.MkdirTemp("", "test_create_account") +// if err != nil { +// t.Fatalf("Failed to create temp directory: %v", err) +// } +// defer os.RemoveAll(tempDir) // Clean up after the test run - sessionID := "07xxxxxxxx" +// sessionID := "07xxxxxxxx" - // Set up the data file path using the session ID - accountFilePath := filepath.Join(tempDir, sessionID+"_data") +// // Set up the data file path using the session ID +// accountFilePath := filepath.Join(tempDir, sessionID+"_data") - // Initialize account file handler - accountFileHandler := utils.NewAccountFileHandler(accountFilePath) +// // Initialize account file handler +// accountFileHandler := utils.NewAccountFileHandler(accountFilePath) - // Create a mock account service - mockAccountService := &MockAccountService{} - mockAccountResponse := &models.AccountResponse{ - Ok: true, - Result: struct { - CustodialId json.Number `json:"custodialId"` - PublicKey string `json:"publicKey"` - TrackingId string `json:"trackingId"` - }{ - CustodialId: "test-custodial-id", - PublicKey: "test-public-key", - TrackingId: "test-tracking-id", - }, - } +// // Create a mock account service +// mockAccountService := &MockAccountService{} +// mockAccountResponse := &models.AccountResponse{ +// Ok: true, +// Result: struct { +// CustodialId json.Number `json:"custodialId"` +// PublicKey string `json:"publicKey"` +// TrackingId string `json:"trackingId"` +// }{ +// CustodialId: "test-custodial-id", +// PublicKey: "test-public-key", +// TrackingId: "test-tracking-id", +// }, +// } - // Set up expectations for the mock account service - mockAccountService.On("CreateAccount").Return(mockAccountResponse, nil) +// // Set up expectations for the mock account service +// mockAccountService.On("CreateAccount").Return(mockAccountResponse, nil) - mockParser := new(MockFlagParser) +// mockParser := new(MockFlagParser) - flag_account_created := uint32(1) - flag_account_creation_failed := uint32(2) +// flag_account_created := uint32(1) +// flag_account_creation_failed := uint32(2) - mockParser.On("GetFlag", "flag_account_created").Return(flag_account_created, nil) - mockParser.On("GetFlag", "flag_account_creation_failed").Return(flag_account_creation_failed, nil) +// mockParser.On("GetFlag", "flag_account_created").Return(flag_account_created, nil) +// mockParser.On("GetFlag", "flag_account_creation_failed").Return(flag_account_creation_failed, nil) - // Initialize Handlers with mock account service - h := &Handlers{ - fs: &FSData{Path: accountFilePath}, - accountFileHandler: accountFileHandler, - accountService: mockAccountService, - parser: mockParser, - } +// // Initialize Handlers with mock account service +// h := &Handlers{ +// fs: &FSData{Path: accountFilePath}, +// accountFileHandler: accountFileHandler, +// accountService: mockAccountService, +// parser: mockParser, +// } - tests := []struct { - name string - existingData map[string]string - expectedResult resource.Result - expectedData map[string]string - }{ - { - name: "New account creation", - existingData: nil, - expectedResult: resource.Result{ - FlagSet: []uint32{flag_account_created}, - }, - expectedData: map[string]string{ - "TrackingId": "test-tracking-id", - "PublicKey": "test-public-key", - "CustodialId": "test-custodial-id", - "Status": "PENDING", - "Gender": "Not provided", - "YOB": "Not provided", - "Location": "Not provided", - "Offerings": "Not provided", - "FirstName": "Not provided", - "FamilyName": "Not provided", - }, - }, - { - name: "Existing account", - existingData: map[string]string{ - "TrackingId": "test-tracking-id", - "PublicKey": "test-public-key", - "CustodialId": "test-custodial-id", - "Status": "PENDING", - "Gender": "Not provided", - "YOB": "Not provided", - "Location": "Not provided", - "Offerings": "Not provided", - "FirstName": "Not provided", - "FamilyName": "Not provided", - }, - expectedResult: resource.Result{}, - expectedData: map[string]string{ - "TrackingId": "test-tracking-id", - "PublicKey": "test-public-key", - "CustodialId": "test-custodial-id", - "Status": "PENDING", - "Gender": "Not provided", - "YOB": "Not provided", - "Location": "Not provided", - "Offerings": "Not provided", - "FirstName": "Not provided", - "FamilyName": "Not provided", - }, - }, - } +// tests := []struct { +// name string +// existingData map[string]string +// expectedResult resource.Result +// expectedData map[string]string +// }{ +// { +// name: "New account creation", +// existingData: nil, +// expectedResult: resource.Result{ +// FlagSet: []uint32{flag_account_created}, +// }, +// expectedData: map[string]string{ +// "TrackingId": "test-tracking-id", +// "PublicKey": "test-public-key", +// "CustodialId": "test-custodial-id", +// "Status": "PENDING", +// "Gender": "Not provided", +// "YOB": "Not provided", +// "Location": "Not provided", +// "Offerings": "Not provided", +// "FirstName": "Not provided", +// "FamilyName": "Not provided", +// }, +// }, +// { +// name: "Existing account", +// existingData: map[string]string{ +// "TrackingId": "test-tracking-id", +// "PublicKey": "test-public-key", +// "CustodialId": "test-custodial-id", +// "Status": "PENDING", +// "Gender": "Not provided", +// "YOB": "Not provided", +// "Location": "Not provided", +// "Offerings": "Not provided", +// "FirstName": "Not provided", +// "FamilyName": "Not provided", +// }, +// expectedResult: resource.Result{}, +// expectedData: map[string]string{ +// "TrackingId": "test-tracking-id", +// "PublicKey": "test-public-key", +// "CustodialId": "test-custodial-id", +// "Status": "PENDING", +// "Gender": "Not provided", +// "YOB": "Not provided", +// "Location": "Not provided", +// "Offerings": "Not provided", +// "FirstName": "Not provided", +// "FamilyName": "Not provided", +// }, +// }, +// } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - // Set up the data file path using the session ID - accountFilePath := filepath.Join(tempDir, sessionID+"_data") +// for _, tt := range tests { +// t.Run(tt.name, func(t *testing.T) { +// // Set up the data file path using the session ID +// accountFilePath := filepath.Join(tempDir, sessionID+"_data") - // Setup existing data if any - if tt.existingData != nil { - data, _ := json.Marshal(tt.existingData) - err := os.WriteFile(accountFilePath, data, 0644) - if err != nil { - t.Fatalf("Failed to write existing data: %v", err) - } - } +// // Setup existing data if any +// if tt.existingData != nil { +// data, _ := json.Marshal(tt.existingData) +// err := os.WriteFile(accountFilePath, data, 0644) +// if err != nil { +// t.Fatalf("Failed to write existing data: %v", err) +// } +// } - // Call the function - result, err := h.CreateAccount(context.Background(), "", nil) +// // Call the function +// result, err := h.CreateAccount(context.Background(), "", nil) - // Check for errors - if err != nil { - t.Fatalf("CreateAccount returned an error: %v", err) - } +// // Check for errors +// if err != nil { +// t.Fatalf("CreateAccount returned an error: %v", err) +// } - // Check the result - if len(result.FlagSet) != len(tt.expectedResult.FlagSet) { - t.Errorf("Expected %d flags, got %d", len(tt.expectedResult.FlagSet), len(result.FlagSet)) - } - for i, flag := range tt.expectedResult.FlagSet { - if result.FlagSet[i] != flag { - t.Errorf("Expected flag %d, got %d", flag, result.FlagSet[i]) - } - } +// // Check the result +// if len(result.FlagSet) != len(tt.expectedResult.FlagSet) { +// t.Errorf("Expected %d flags, got %d", len(tt.expectedResult.FlagSet), len(result.FlagSet)) +// } +// for i, flag := range tt.expectedResult.FlagSet { +// if result.FlagSet[i] != flag { +// t.Errorf("Expected flag %d, got %d", flag, result.FlagSet[i]) +// } +// } - // Check the stored data - data, err := os.ReadFile(accountFilePath) - if err != nil { - t.Fatalf("Failed to read account data file: %v", err) - } +// // Check the stored data +// data, err := os.ReadFile(accountFilePath) +// if err != nil { +// t.Fatalf("Failed to read account data file: %v", err) +// } - var storedData map[string]string - err = json.Unmarshal(data, &storedData) - if err != nil { - t.Fatalf("Failed to unmarshal stored data: %v", err) - } +// var storedData map[string]string +// err = json.Unmarshal(data, &storedData) +// if err != nil { +// t.Fatalf("Failed to unmarshal stored data: %v", err) +// } - for key, expectedValue := range tt.expectedData { - if storedValue, ok := storedData[key]; !ok || storedValue != expectedValue { - t.Errorf("Expected %s to be %s, got %s", key, expectedValue, storedValue) - } - } - }) - } -} +// for key, expectedValue := range tt.expectedData { +// if storedValue, ok := storedData[key]; !ok || storedValue != expectedValue { +// t.Errorf("Expected %s to be %s, got %s", key, expectedValue, storedValue) +// } +// } +// }) +// } +// } -func TestCreateAccount_Success(t *testing.T) { - mockAccountFileHandler := new(mocks.MockAccountFileHandler) - mockCreateAccountService := new(mocks.MockAccountService) +// func TestCreateAccount_Success(t *testing.T) { +// mockAccountFileHandler := new(mocks.MockAccountFileHandler) +// mockCreateAccountService := new(mocks.MockAccountService) - mockAccountFileHandler.On("EnsureFileExists").Return(nil) +// mockAccountFileHandler.On("EnsureFileExists").Return(nil) - // Mock that no account data exists - mockAccountFileHandler.On("ReadAccountData").Return(nil, nil) +// // Mock that no account data exists +// mockAccountFileHandler.On("ReadAccountData").Return(nil, nil) - // Define expected account response after api call - expectedAccountResp := &models.AccountResponse{ - Ok: true, - Result: struct { - CustodialId json.Number `json:"custodialId"` - PublicKey string `json:"publicKey"` - TrackingId string `json:"trackingId"` - }{ - CustodialId: "12", - PublicKey: "0x8E0XSCSVA", - TrackingId: "d95a7e83-196c-4fd0-866fSGAGA", - }, - } - mockCreateAccountService.On("CreateAccount").Return(expectedAccountResp, nil) +// // Define expected account response after api call +// expectedAccountResp := &models.AccountResponse{ +// Ok: true, +// Result: struct { +// CustodialId json.Number `json:"custodialId"` +// PublicKey string `json:"publicKey"` +// TrackingId string `json:"trackingId"` +// }{ +// CustodialId: "12", +// PublicKey: "0x8E0XSCSVA", +// TrackingId: "d95a7e83-196c-4fd0-866fSGAGA", +// }, +// } +// mockCreateAccountService.On("CreateAccount").Return(expectedAccountResp, nil) - // Mock WriteAccountData to not error - mockAccountFileHandler.On("WriteAccountData", mock.Anything).Return(nil) +// // Mock WriteAccountData to not error +// mockAccountFileHandler.On("WriteAccountData", mock.Anything).Return(nil) - handlers := &Handlers{ - accountService: mockCreateAccountService, - } +// handlers := &Handlers{ +// accountService: mockCreateAccountService, +// } - actualResponse, err := handlers.accountService.CreateAccount() +// actualResponse, err := handlers.accountService.CreateAccount() - // Assert results - assert.NoError(t, err) - assert.Equal(t, expectedAccountResp.Ok, true) - assert.Equal(t, expectedAccountResp, actualResponse) -} +// // Assert results +// assert.NoError(t, err) +// assert.Equal(t, expectedAccountResp.Ok, true) +// assert.Equal(t, expectedAccountResp, actualResponse) +// } -func TestSavePin(t *testing.T) { - // Setup - tempDir, err := os.MkdirTemp("", "test_save_pin") - if err != nil { - t.Fatalf("Failed to create temp directory: %v", err) - } - defer os.RemoveAll(tempDir) +// func TestSavePin(t *testing.T) { +// // Setup +// tempDir, err := os.MkdirTemp("", "test_save_pin") +// if err != nil { +// t.Fatalf("Failed to create temp directory: %v", err) +// } +// defer os.RemoveAll(tempDir) - sessionID := "07xxxxxxxx" +// sessionID := "07xxxxxxxx" - // Set up the data file path using the session ID - accountFilePath := filepath.Join(tempDir, sessionID+"_data") - initialAccountData := map[string]string{ - "TrackingId": "test-tracking-id", - "PublicKey": "test-public-key", - } - data, _ := json.Marshal(initialAccountData) - err = os.WriteFile(accountFilePath, data, 0644) - if err != nil { - t.Fatalf("Failed to write initial account data: %v", err) - } +// // Set up the data file path using the session ID +// accountFilePath := filepath.Join(tempDir, sessionID+"_data") +// initialAccountData := map[string]string{ +// "TrackingId": "test-tracking-id", +// "PublicKey": "test-public-key", +// } +// data, _ := json.Marshal(initialAccountData) +// err = os.WriteFile(accountFilePath, data, 0644) +// if err != nil { +// t.Fatalf("Failed to write initial account data: %v", err) +// } - // Create a new AccountFileHandler and set it in the Handlers struct - accountFileHandler := utils.NewAccountFileHandler(accountFilePath) - mockParser := new(MockFlagParser) - - h := &Handlers{ - accountFileHandler: accountFileHandler, - parser: mockParser, - } +// // Create a new AccountFileHandler and set it in the Handlers struct +// accountFileHandler := utils.NewAccountFileHandler(accountFilePath) +// mockParser := new(MockFlagParser) - flag_incorrect_pin := uint32(1) - mockParser.On("GetFlag", "flag_incorrect_pin").Return(flag_incorrect_pin, nil) +// h := &Handlers{ +// accountFileHandler: accountFileHandler, +// parser: mockParser, +// } - tests := []struct { - name string - input []byte - expectedFlags []uint32 - expectedData map[string]string - expectedErrors bool - }{ - { - name: "Valid PIN", - input: []byte("1234"), - expectedFlags: []uint32{}, - expectedData: map[string]string{ - "TrackingId": "test-tracking-id", - "PublicKey": "test-public-key", - "AccountPIN": "1234", - }, - }, - { - name: "Invalid PIN - non-numeric", - input: []byte("12ab"), - expectedFlags: []uint32{flag_incorrect_pin}, - expectedData: initialAccountData, // No changes expected - expectedErrors: false, - }, - { - name: "Invalid PIN - less than 4 digits", - input: []byte("123"), - expectedFlags: []uint32{flag_incorrect_pin}, - expectedData: initialAccountData, // No changes expected - expectedErrors: false, - }, - { - name: "Invalid PIN - more than 4 digits", - input: []byte("12345"), - expectedFlags: []uint32{flag_incorrect_pin}, - expectedData: initialAccountData, // No changes expected - expectedErrors: false, - }, - } +// flag_incorrect_pin := uint32(1) +// mockParser.On("GetFlag", "flag_incorrect_pin").Return(flag_incorrect_pin, nil) - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - err := accountFileHandler.EnsureFileExists() - if err != nil { - t.Fatalf("Failed to ensure account file exists: %v", err) - } +// tests := []struct { +// name string +// input []byte +// expectedFlags []uint32 +// expectedData map[string]string +// expectedErrors bool +// }{ +// { +// name: "Valid PIN", +// input: []byte("1234"), +// expectedFlags: []uint32{}, +// expectedData: map[string]string{ +// "TrackingId": "test-tracking-id", +// "PublicKey": "test-public-key", +// "AccountPIN": "1234", +// }, +// }, +// { +// name: "Invalid PIN - non-numeric", +// input: []byte("12ab"), +// expectedFlags: []uint32{flag_incorrect_pin}, +// expectedData: initialAccountData, // No changes expected +// expectedErrors: false, +// }, +// { +// name: "Invalid PIN - less than 4 digits", +// input: []byte("123"), +// expectedFlags: []uint32{flag_incorrect_pin}, +// expectedData: initialAccountData, // No changes expected +// expectedErrors: false, +// }, +// { +// name: "Invalid PIN - more than 4 digits", +// input: []byte("12345"), +// expectedFlags: []uint32{flag_incorrect_pin}, +// expectedData: initialAccountData, // No changes expected +// expectedErrors: false, +// }, +// } - result, err := h.SavePin(context.Background(), "", tt.input) - if err != nil && !tt.expectedErrors { - t.Fatalf("SavePin returned an unexpected error: %v", err) - } +// for _, tt := range tests { +// t.Run(tt.name, func(t *testing.T) { +// err := accountFileHandler.EnsureFileExists() +// if err != nil { +// t.Fatalf("Failed to ensure account file exists: %v", err) +// } - if len(result.FlagSet) != len(tt.expectedFlags) { - t.Errorf("Expected %d flags, got %d", len(tt.expectedFlags), len(result.FlagSet)) - } - for i, flag := range tt.expectedFlags { - if result.FlagSet[i] != flag { - t.Errorf("Expected flag %d, got %d", flag, result.FlagSet[i]) - } - } +// result, err := h.SavePin(context.Background(), "", tt.input) +// if err != nil && !tt.expectedErrors { +// t.Fatalf("SavePin returned an unexpected error: %v", err) +// } - data, err := os.ReadFile(accountFilePath) - if err != nil { - t.Fatalf("Failed to read account data file: %v", err) - } +// if len(result.FlagSet) != len(tt.expectedFlags) { +// t.Errorf("Expected %d flags, got %d", len(tt.expectedFlags), len(result.FlagSet)) +// } +// for i, flag := range tt.expectedFlags { +// if result.FlagSet[i] != flag { +// t.Errorf("Expected flag %d, got %d", flag, result.FlagSet[i]) +// } +// } - var storedData map[string]string - err = json.Unmarshal(data, &storedData) - if err != nil { - t.Fatalf("Failed to unmarshal stored data: %v", err) - } +// data, err := os.ReadFile(accountFilePath) +// if err != nil { +// t.Fatalf("Failed to read account data file: %v", err) +// } - for key, expectedValue := range tt.expectedData { - if storedValue, ok := storedData[key]; !ok || storedValue != expectedValue { - t.Errorf("Expected %s to be %s, got %s", key, expectedValue, storedValue) - } - } - }) - } -} +// var storedData map[string]string +// err = json.Unmarshal(data, &storedData) +// if err != nil { +// t.Fatalf("Failed to unmarshal stored data: %v", err) +// } -func TestSaveLocation(t *testing.T) { - // Create a new instance of MockAccountFileHandler - mockFileHandler := new(mocks.MockAccountFileHandler) +// for key, expectedValue := range tt.expectedData { +// if storedValue, ok := storedData[key]; !ok || storedValue != expectedValue { +// t.Errorf("Expected %s to be %s, got %s", key, expectedValue, storedValue) +// } +// } +// }) +// } +// } +// func TestSaveLocation(t *testing.T) { +// // Create a new instance of MockAccountFileHandler +// mockFileHandler := new(mocks.MockAccountFileHandler) + +// // Define test cases +// tests := []struct { +// name string +// input []byte +// existingData map[string]string +// writeError error +// expectedResult resource.Result +// expectedError error +// }{ +// { +// name: "Successful Save", +// input: []byte("Mombasa"), +// existingData: map[string]string{"Location": "Mombasa"}, +// writeError: nil, +// expectedResult: resource.Result{}, +// expectedError: nil, +// }, +// { +// name: "Empty location input", +// input: []byte{}, +// existingData: map[string]string{"OtherKey": "OtherValue"}, +// writeError: nil, +// expectedResult: resource.Result{}, +// expectedError: nil, +// }, +// } + +// for _, tt := range tests { +// t.Run(tt.name, func(t *testing.T) { +// // Set up the mock expectations +// mockFileHandler.On("ReadAccountData").Return(tt.existingData, tt.expectedError) +// if tt.expectedError == nil && len(tt.input) > 0 { +// mockFileHandler.On("WriteAccountData", mock.MatchedBy(func(data map[string]string) bool { +// return data["Location"] == string(tt.input) +// })).Return(tt.writeError) +// } else if len(tt.input) == 0 { +// // For empty input, no WriteAccountData call should be made +// mockFileHandler.On("WriteAccountData", mock.Anything).Maybe().Return(tt.writeError) +// return +// } + +// // Create the Handlers instance with the mock file handler +// h := &Handlers{ +// accountFileHandler: mockFileHandler, +// } + +// // Call Save Location +// result, err := h.SaveLocation(context.Background(), "save_location", tt.input) + +// if err != nil { +// t.Fatalf("Failed to save location with error: %v", err) +// } + +// savedData, err := h.accountFileHandler.ReadAccountData() +// if err == nil { +// //Assert that the input provided is what was saved into the file +// assert.Equal(t, string(tt.input), savedData["Location"]) +// } + +// // Assert the results +// assert.Equal(t, tt.expectedResult, result) +// assert.Equal(t, tt.expectedError, err) + +// // Assert all expectations were met +// mockFileHandler.AssertExpectations(t) +// }) +// } +// } + +// func TestSaveFirstname(t *testing.T) { +// // Create a new instance of MockAccountFileHandler +// mockFileHandler := new(mocks.MockAccountFileHandler) + +// // Define test cases +// tests := []struct { +// name string +// input []byte +// existingData map[string]string +// writeError error +// expectedResult resource.Result +// expectedError error +// }{ +// { +// name: "Successful Save", +// input: []byte("Joe"), +// existingData: map[string]string{"Name": "Joe"}, +// writeError: nil, +// expectedResult: resource.Result{}, +// expectedError: nil, +// }, +// { +// name: "Empty Input", +// input: []byte{}, +// existingData: map[string]string{"OtherKey": "OtherValue"}, +// writeError: nil, +// expectedError: nil, +// }, +// } + +// for _, tt := range tests { +// t.Run(tt.name, func(t *testing.T) { +// // Set up the mock expectations +// mockFileHandler.On("ReadAccountData").Return(tt.existingData, tt.expectedError) +// if tt.expectedError == nil && len(tt.input) > 0 { +// mockFileHandler.On("WriteAccountData", mock.MatchedBy(func(data map[string]string) bool { +// return data["FirstName"] == string(tt.input) +// })).Return(tt.writeError) +// } else if len(tt.input) == 0 { +// // For empty input, no WriteAccountData call should be made +// mockFileHandler.On("WriteAccountData", mock.Anything).Maybe().Return(tt.writeError) +// return +// } + +// // Create the Handlers instance with the mock file handler +// h := &Handlers{ +// accountFileHandler: mockFileHandler, +// } + +// // Call save location +// result, err := h.SaveFirstname(context.Background(), "save_location", tt.input) + +// if err != nil { +// t.Fatalf("Failed to save first name with error: %v", err) +// } +// savedData, err := h.accountFileHandler.ReadAccountData() +// if err == nil { +// //Assert that the input provided is what was saved into the file +// assert.Equal(t, string(tt.input), savedData["FirstName"]) +// } + +// // Assert the results +// assert.Equal(t, tt.expectedResult, result) +// assert.Equal(t, tt.expectedError, err) + +// // Assert all expectations were met +// mockFileHandler.AssertExpectations(t) +// }) +// } +// } + +// func TestSaveFamilyName(t *testing.T) { +// // Create a new instance of MockAccountFileHandler +// mockFileHandler := new(mocks.MockAccountFileHandler) + +// // Define test cases +// tests := []struct { +// name string +// input []byte +// existingData map[string]string +// writeError error +// expectedResult resource.Result +// expectedError error +// }{ +// { +// name: "Successful Save", +// input: []byte("Doe"), +// existingData: map[string]string{"FamilyName": "Doe"}, +// writeError: nil, +// expectedResult: resource.Result{}, +// expectedError: nil, +// }, +// { +// name: "Empty Input", +// input: []byte{}, +// existingData: map[string]string{"FamilyName": "Doe"}, +// writeError: nil, +// expectedError: nil, +// }, +// } + +// for _, tt := range tests { +// t.Run(tt.name, func(t *testing.T) { +// // Set up the mock expectations +// mockFileHandler.On("ReadAccountData").Return(tt.existingData, tt.expectedError) +// if tt.expectedError == nil && len(tt.input) > 0 { +// mockFileHandler.On("WriteAccountData", mock.MatchedBy(func(data map[string]string) bool { +// return data["FamilyName"] == string(tt.input) +// })).Return(tt.writeError) +// } else if len(tt.input) == 0 { +// // For empty input, no WriteAccountData call should be made +// mockFileHandler.On("WriteAccountData", mock.Anything).Maybe().Return(tt.writeError) +// return +// } + +// // Create the Handlers instance with the mock file handler +// h := &Handlers{ +// accountFileHandler: mockFileHandler, +// } + +// // Call save familyname +// result, err := h.SaveFamilyname(context.Background(), "save_familyname", tt.input) + +// if err != nil { +// t.Fatalf("Failed to save family name with error: %v", err) +// } +// savedData, err := h.accountFileHandler.ReadAccountData() +// if err == nil { +// //Assert that the input provided is what was saved into the file +// assert.Equal(t, string(tt.input), savedData["FamilyName"]) +// } + +// // Assert the results +// assert.Equal(t, tt.expectedResult, result) +// assert.Equal(t, tt.expectedError, err) + +// // Assert all expectations were met +// mockFileHandler.AssertExpectations(t) +// }) +// } +// } + +// func TestSaveYOB(t *testing.T) { +// // Create a new instance of MockAccountFileHandler +// mockFileHandler := new(mocks.MockAccountFileHandler) + +// // Define test cases +// tests := []struct { +// name string +// input []byte +// existingData map[string]string +// writeError error +// expectedResult resource.Result +// expectedError error +// }{ +// { +// name: "Successful Save", +// input: []byte("2006"), +// existingData: map[string]string{"": ""}, +// writeError: nil, +// expectedResult: resource.Result{}, +// expectedError: nil, +// }, +// { +// name: "YOB less than 4 digits(invalid date entry)", +// input: []byte{}, +// existingData: map[string]string{"": ""}, +// writeError: nil, +// expectedError: nil, +// }, +// } + +// for _, tt := range tests { +// t.Run(tt.name, func(t *testing.T) { +// // Set up the mock expectations +// mockFileHandler.On("ReadAccountData").Return(tt.existingData, tt.expectedError) +// if tt.expectedError == nil && len(tt.input) > 0 { +// mockFileHandler.On("WriteAccountData", mock.MatchedBy(func(data map[string]string) bool { +// return data["YOB"] == string(tt.input) +// })).Return(tt.writeError) +// } else if len(tt.input) != 4 { +// // For input whose input is not a valid yob, no WriteAccountData call should be made +// mockFileHandler.On("WriteAccountData", mock.Anything).Maybe().Return(tt.writeError) +// return +// } + +// // Create the Handlers instance with the mock file handler +// h := &Handlers{ +// accountFileHandler: mockFileHandler, +// } + +// // Call save yob +// result, err := h.SaveYob(context.Background(), "save_yob", tt.input) + +// if err != nil { +// t.Fatalf("Failed to save family name with error: %v", err) +// } +// savedData, err := h.accountFileHandler.ReadAccountData() +// if err == nil { +// //Assert that the input provided is what was saved into the file +// assert.Equal(t, string(tt.input), savedData["YOB"]) +// } + +// // Assert the results +// assert.Equal(t, tt.expectedResult, result) +// assert.Equal(t, tt.expectedError, err) + +// // Assert all expectations were met +// mockFileHandler.AssertExpectations(t) +// }) +// } +// } + +// func TestSaveOfferings(t *testing.T) { +// // Create a new instance of MockAccountFileHandler +// mockFileHandler := new(mocks.MockAccountFileHandler) + +// // Define test cases +// tests := []struct { +// name string +// input []byte +// existingData map[string]string +// writeError error +// expectedResult resource.Result +// expectedError error +// }{ +// { +// name: "Successful Save", +// input: []byte("Bananas"), +// existingData: map[string]string{"": ""}, +// writeError: nil, +// expectedResult: resource.Result{}, +// expectedError: nil, +// }, +// { +// name: "Empty input", +// input: []byte{}, +// existingData: map[string]string{"": ""}, +// writeError: nil, +// expectedError: nil, +// }, +// } + +// for _, tt := range tests { +// t.Run(tt.name, func(t *testing.T) { +// // Set up the mock expectations +// mockFileHandler.On("ReadAccountData").Return(tt.existingData, tt.expectedError) +// if tt.expectedError == nil && len(tt.input) > 0 { +// mockFileHandler.On("WriteAccountData", mock.MatchedBy(func(data map[string]string) bool { +// return data["Offerings"] == string(tt.input) +// })).Return(tt.writeError) +// } else if len(tt.input) != 4 { +// // For input whose input is not a valid yob, no WriteAccountData call should be made +// mockFileHandler.On("WriteAccountData", mock.Anything).Maybe().Return(tt.writeError) +// return +// } + +// // Create the Handlers instance with the mock file handler +// h := &Handlers{ +// accountFileHandler: mockFileHandler, +// } + +// // Call save yob +// result, err := h.SaveOfferings(context.Background(), "save_offerings", tt.input) + +// if err != nil { +// t.Fatalf("Failed to save offerings with error: %v", err) +// } +// savedData, err := h.accountFileHandler.ReadAccountData() +// if err == nil { +// //Assert that the input provided is what was saved into the file +// assert.Equal(t, string(tt.input), savedData["Offerings"]) +// } + +// // Assert the results +// assert.Equal(t, tt.expectedResult, result) +// assert.Equal(t, tt.expectedError, err) + +// // Assert all expectations were met +// mockFileHandler.AssertExpectations(t) +// }) +// } +// } + +// func TestSaveGender(t *testing.T) { +// // Create a new instance of MockAccountFileHandler +// mockFileHandler := new(mocks.MockAccountFileHandler) + +// // Define test cases +// tests := []struct { +// name string +// input []byte +// existingData map[string]string +// writeError error +// expectedResult resource.Result +// expectedError error +// expectedGender string +// }{ +// { +// name: "Successful Save - Male", +// input: []byte("1"), +// existingData: map[string]string{"OtherKey": "OtherValue"}, +// writeError: nil, +// expectedResult: resource.Result{}, +// expectedError: nil, +// expectedGender: "Male", +// }, +// { +// name: "Successful Save - Female", +// input: []byte("2"), +// existingData: map[string]string{"OtherKey": "OtherValue"}, +// writeError: nil, +// expectedResult: resource.Result{}, +// expectedError: nil, +// expectedGender: "Female", +// }, +// { +// name: "Successful Save - Unspecified", +// input: []byte("3"), +// existingData: map[string]string{"OtherKey": "OtherValue"}, +// writeError: nil, +// expectedResult: resource.Result{}, +// expectedError: nil, +// expectedGender: "Unspecified", +// }, + +// { +// name: "Empty Input", +// input: []byte{}, +// existingData: map[string]string{"OtherKey": "OtherValue"}, +// writeError: nil, +// expectedResult: resource.Result{}, +// expectedError: nil, +// expectedGender: "", +// }, +// } + +// for _, tt := range tests { +// t.Run(tt.name, func(t *testing.T) { +// // Set up the mock expectations +// mockFileHandler.On("ReadAccountData").Return(tt.existingData, tt.expectedError) +// if tt.expectedError == nil && len(tt.input) > 0 { +// mockFileHandler.On("WriteAccountData", mock.MatchedBy(func(data map[string]string) bool { +// return data["Gender"] == tt.expectedGender +// })).Return(tt.writeError) +// } else if len(tt.input) == 0 { +// // For empty input, no WriteAccountData call should be made +// mockFileHandler.On("WriteAccountData", mock.Anything).Maybe().Return(tt.writeError) +// } + +// // Create the Handlers instance with the mock file handler +// h := &Handlers{ +// accountFileHandler: mockFileHandler, +// } + +// // Call the method +// result, err := h.SaveGender(context.Background(), "save_gender", tt.input) + +// // Assert the results +// assert.Equal(t, tt.expectedResult, result) +// assert.Equal(t, tt.expectedError, err) + +// // Verify WriteAccountData was called with the expected data +// if len(tt.input) > 0 && tt.expectedError == nil { +// mockFileHandler.AssertCalled(t, "WriteAccountData", mock.MatchedBy(func(data map[string]string) bool { +// return data["Gender"] == tt.expectedGender +// })) +// } + +// // Assert all expectations were met +// mockFileHandler.AssertExpectations(t) +// }) +// } +// } + +// func TestGetSender(t *testing.T) { +// mockAccountFileHandler := new(mocks.MockAccountFileHandler) +// h := &Handlers{ +// accountFileHandler: mockAccountFileHandler, +// } + +// tests := []struct { +// name string +// expectedResult resource.Result +// accountData map[string]string +// }{ +// { +// name: "Valid public key", +// expectedResult: resource.Result{ +// Content: "test-public-key", +// }, +// accountData: map[string]string{ +// "PublicKey": "test-public-key", +// }, +// }, +// { +// name: "Missing public key", +// expectedResult: resource.Result{ +// Content: "", +// }, +// accountData: map[string]string{}, +// }, +// } + +// for _, tt := range tests { +// t.Run(tt.name, func(t *testing.T) { +// // Reset the mock state +// mockAccountFileHandler.Mock = mock.Mock{} + +// mockAccountFileHandler.On("ReadAccountData").Return(tt.accountData, nil) + +// result, err := h.GetSender(context.Background(), "", nil) + +// if err != nil { +// t.Fatalf("Error occurred: %v", err) +// } + +// assert.Equal(t, tt.expectedResult.Content, result.Content) +// mockAccountFileHandler.AssertCalled(t, "ReadAccountData") +// }) +// } +// } + +// func TestGetAmount(t *testing.T) { +// mockAccountFileHandler := new(mocks.MockAccountFileHandler) +// h := &Handlers{ +// accountFileHandler: mockAccountFileHandler, +// } + +// tests := []struct { +// name string +// expectedResult resource.Result +// accountData map[string]string +// }{ +// { +// name: "Valid amount", +// expectedResult: resource.Result{ +// Content: "0.003", +// }, +// accountData: map[string]string{ +// "Amount": "0.003", +// }, +// }, +// { +// name: "Missing amount", +// expectedResult: resource.Result{}, +// accountData: map[string]string{ +// "Amount": "", +// }, +// }, +// } + +// for _, tt := range tests { +// t.Run(tt.name, func(t *testing.T) { +// // Reset the mock state +// mockAccountFileHandler.Mock = mock.Mock{} + +// mockAccountFileHandler.On("ReadAccountData").Return(tt.accountData, nil) + +// result, err := h.GetAmount(context.Background(), "", nil) + +// assert.NoError(t, err) +// assert.Equal(t, tt.expectedResult.Content, result.Content) + +// mockAccountFileHandler.AssertCalled(t, "ReadAccountData") +// }) +// } +// } + +// func TestGetProfileInfo(t *testing.T) { +// tests := []struct { +// name string +// accountData map[string]string +// readError error +// expectedResult resource.Result +// expectedError error +// }{ +// { +// name: "Complete Profile", +// accountData: map[string]string{ +// "FirstName": "John", +// "FamilyName": "Doe", +// "Gender": "Male", +// "YOB": "1980", +// "Location": "Mombasa", +// "Offerings": "Product A", +// }, +// readError: nil, +// expectedResult: resource.Result{ +// Content: fmt.Sprintf( +// "Name: %s %s\nGender: %s\nAge: %d\nLocation: %s\nYou provide: %s\n", +// "John", "Doe", "Male", 44, "Mombasa", "Product A", +// ), +// }, +// expectedError: nil, +// }, +// { +// name: "Profile with Not Provided Fields", +// accountData: map[string]string{ +// "FirstName": "Not provided", +// "FamilyName": "Doe", +// "Gender": "Female", +// "YOB": "1995", +// "Location": "Not provided", +// "Offerings": "Service B", +// }, +// readError: nil, +// expectedResult: resource.Result{ +// Content: fmt.Sprintf( +// "Name: %s\nGender: %s\nAge: %d\nLocation: %s\nYou provide: %s\n", +// "Not provided", "Female", 29, "Not provided", "Service B", +// ), +// }, +// expectedError: nil, +// }, +// { +// name: "Profile with YOB as Not provided", +// accountData: map[string]string{ +// "FirstName": "Not provided", +// "FamilyName": "Doe", +// "Gender": "Female", +// "YOB": "Not provided", +// "Location": "Not provided", +// "Offerings": "Service B", +// }, +// readError: nil, +// expectedResult: resource.Result{ +// Content: fmt.Sprintf( +// "Name: %s\nGender: %s\nAge: %s\nLocation: %s\nYou provide: %s\n", +// "Not provided", "Female", "Not provided", "Not provided", "Service B", +// ), +// }, +// expectedError: nil, +// }, +// } + +// for _, tt := range tests { +// t.Run(tt.name, func(t *testing.T) { +// // Create a new instance of MockAccountFileHandler +// mockFileHandler := new(mocks.MockAccountFileHandler) + +// // Set up the mock expectations +// mockFileHandler.On("ReadAccountData").Return(tt.accountData, tt.readError) + +// // Create the Handlers instance with the mock file handler +// h := &Handlers{ +// accountFileHandler: mockFileHandler, +// } + +// // Call the method +// result, err := h.GetProfileInfo(context.Background(), "get_profile_info", nil) + +// // Assert the results +// assert.Equal(t, tt.expectedResult, result) +// assert.Equal(t, tt.expectedError, err) + +// // Assert all expectations were met +// mockFileHandler.AssertExpectations(t) +// }) +// } +// } + +// Test SaveFirstname +func TestSaveFirstName(t *testing.T) { + // Create a new instance of MockDb + mockDb := new(mocks.MockDb) + k := utils.PackKey(utils.DATA_FAMILY_NAME, []byte("session123")) // Define test cases tests := []struct { - name string - input []byte - existingData map[string]string - writeError error - expectedResult resource.Result - expectedError error + name string + ctxValue string + input []byte + mockPutError error + expectedError error + expectedCalls []mock.Call }{ { - name: "Successful Save", - input: []byte("Mombasa"), - existingData: map[string]string{"Location": "Mombasa"}, - writeError: nil, - expectedResult: resource.Result{}, - expectedError: nil, - }, - { - name: "Empty location input", - input: []byte{}, - existingData: map[string]string{"OtherKey": "OtherValue"}, - writeError: nil, - expectedResult: resource.Result{}, - expectedError: nil, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - // Set up the mock expectations - mockFileHandler.On("ReadAccountData").Return(tt.existingData, tt.expectedError) - if tt.expectedError == nil && len(tt.input) > 0 { - mockFileHandler.On("WriteAccountData", mock.MatchedBy(func(data map[string]string) bool { - return data["Location"] == string(tt.input) - })).Return(tt.writeError) - } else if len(tt.input) == 0 { - // For empty input, no WriteAccountData call should be made - mockFileHandler.On("WriteAccountData", mock.Anything).Maybe().Return(tt.writeError) - return - } - - // Create the Handlers instance with the mock file handler - h := &Handlers{ - accountFileHandler: mockFileHandler, - } - - // Call Save Location - result, err := h.SaveLocation(context.Background(), "save_location", tt.input) - - if err != nil { - t.Fatalf("Failed to save location with error: %v", err) - } - - savedData, err := h.accountFileHandler.ReadAccountData() - if err == nil { - //Assert that the input provided is what was saved into the file - assert.Equal(t, string(tt.input), savedData["Location"]) - } - - // Assert the results - assert.Equal(t, tt.expectedResult, result) - assert.Equal(t, tt.expectedError, err) - - // Assert all expectations were met - mockFileHandler.AssertExpectations(t) - }) - } -} - -func TestSaveFirstname(t *testing.T) { - // Create a new instance of MockAccountFileHandler - mockFileHandler := new(mocks.MockAccountFileHandler) - - // Define test cases - tests := []struct { - name string - input []byte - existingData map[string]string - writeError error - expectedResult resource.Result - expectedError error - }{ - { - name: "Successful Save", - input: []byte("Joe"), - existingData: map[string]string{"Name": "Joe"}, - writeError: nil, - expectedResult: resource.Result{}, - expectedError: nil, - }, - { - name: "Empty Input", - input: []byte{}, - existingData: map[string]string{"OtherKey": "OtherValue"}, - writeError: nil, + name: "Successful save", + ctxValue: "session123", + input: []byte("John"), + mockPutError: nil, expectedError: nil, + expectedCalls: []mock.Call{ + // Expect the SetPrefix and SetSession calls + *mockDb.On("SetPrefix", utils.DATA_FAMILY_NAME).Return(), + *mockDb.On("SetSession", "session123").Return(), + // Expect the Put call + *mockDb.On("Put", context.WithValue(context.Background(), "SessionId", "session123"), k, []byte("John")).Return(nil), + }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // Set up the mock expectations - mockFileHandler.On("ReadAccountData").Return(tt.existingData, tt.expectedError) - if tt.expectedError == nil && len(tt.input) > 0 { - mockFileHandler.On("WriteAccountData", mock.MatchedBy(func(data map[string]string) bool { - return data["FirstName"] == string(tt.input) - })).Return(tt.writeError) - } else if len(tt.input) == 0 { - // For empty input, no WriteAccountData call should be made - mockFileHandler.On("WriteAccountData", mock.Anything).Maybe().Return(tt.writeError) - return + for _, call := range tt.expectedCalls { + call.Run(func(args mock.Arguments) {}) } - // Create the Handlers instance with the mock file handler + // Create the Handlers instance with the mock db h := &Handlers{ - accountFileHandler: mockFileHandler, + userdataStore: mockDb, } - // Call save location - result, err := h.SaveFirstname(context.Background(), "save_location", tt.input) - - if err != nil { - t.Fatalf("Failed to save first name with error: %v", err) - } - savedData, err := h.accountFileHandler.ReadAccountData() - if err == nil { - //Assert that the input provided is what was saved into the file - assert.Equal(t, string(tt.input), savedData["FirstName"]) - } - - // Assert the results - assert.Equal(t, tt.expectedResult, result) - assert.Equal(t, tt.expectedError, err) - - // Assert all expectations were met - mockFileHandler.AssertExpectations(t) - }) - } -} - -func TestSaveFamilyName(t *testing.T) { - // Create a new instance of MockAccountFileHandler - mockFileHandler := new(mocks.MockAccountFileHandler) - - // Define test cases - tests := []struct { - name string - input []byte - existingData map[string]string - writeError error - expectedResult resource.Result - expectedError error - }{ - { - name: "Successful Save", - input: []byte("Doe"), - existingData: map[string]string{"FamilyName": "Doe"}, - writeError: nil, - expectedResult: resource.Result{}, - expectedError: nil, - }, - { - name: "Empty Input", - input: []byte{}, - existingData: map[string]string{"FamilyName": "Doe"}, - writeError: nil, - expectedError: nil, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - // Set up the mock expectations - mockFileHandler.On("ReadAccountData").Return(tt.existingData, tt.expectedError) - if tt.expectedError == nil && len(tt.input) > 0 { - mockFileHandler.On("WriteAccountData", mock.MatchedBy(func(data map[string]string) bool { - return data["FamilyName"] == string(tt.input) - })).Return(tt.writeError) - } else if len(tt.input) == 0 { - // For empty input, no WriteAccountData call should be made - mockFileHandler.On("WriteAccountData", mock.Anything).Maybe().Return(tt.writeError) - return - } - - // Create the Handlers instance with the mock file handler - h := &Handlers{ - accountFileHandler: mockFileHandler, - } - - // Call save familyname - result, err := h.SaveFamilyname(context.Background(), "save_familyname", tt.input) - - if err != nil { - t.Fatalf("Failed to save family name with error: %v", err) - } - savedData, err := h.accountFileHandler.ReadAccountData() - if err == nil { - //Assert that the input provided is what was saved into the file - assert.Equal(t, string(tt.input), savedData["FamilyName"]) - } - - // Assert the results - assert.Equal(t, tt.expectedResult, result) - assert.Equal(t, tt.expectedError, err) - - // Assert all expectations were met - mockFileHandler.AssertExpectations(t) - }) - } -} - -func TestSaveYOB(t *testing.T) { - // Create a new instance of MockAccountFileHandler - mockFileHandler := new(mocks.MockAccountFileHandler) - - // Define test cases - tests := []struct { - name string - input []byte - existingData map[string]string - writeError error - expectedResult resource.Result - expectedError error - }{ - { - name: "Successful Save", - input: []byte("2006"), - existingData: map[string]string{"": ""}, - writeError: nil, - expectedResult: resource.Result{}, - expectedError: nil, - }, - { - name: "YOB less than 4 digits(invalid date entry)", - input: []byte{}, - existingData: map[string]string{"": ""}, - writeError: nil, - expectedError: nil, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - // Set up the mock expectations - mockFileHandler.On("ReadAccountData").Return(tt.existingData, tt.expectedError) - if tt.expectedError == nil && len(tt.input) > 0 { - mockFileHandler.On("WriteAccountData", mock.MatchedBy(func(data map[string]string) bool { - return data["YOB"] == string(tt.input) - })).Return(tt.writeError) - } else if len(tt.input) != 4 { - // For input whose input is not a valid yob, no WriteAccountData call should be made - mockFileHandler.On("WriteAccountData", mock.Anything).Maybe().Return(tt.writeError) - return - } - - // Create the Handlers instance with the mock file handler - h := &Handlers{ - accountFileHandler: mockFileHandler, - } - - // Call save yob - result, err := h.SaveYob(context.Background(), "save_yob", tt.input) - - if err != nil { - t.Fatalf("Failed to save family name with error: %v", err) - } - savedData, err := h.accountFileHandler.ReadAccountData() - if err == nil { - //Assert that the input provided is what was saved into the file - assert.Equal(t, string(tt.input), savedData["YOB"]) - } - - // Assert the results - assert.Equal(t, tt.expectedResult, result) - assert.Equal(t, tt.expectedError, err) - - // Assert all expectations were met - mockFileHandler.AssertExpectations(t) - }) - } -} - -func TestSaveOfferings(t *testing.T) { - // Create a new instance of MockAccountFileHandler - mockFileHandler := new(mocks.MockAccountFileHandler) - - // Define test cases - tests := []struct { - name string - input []byte - existingData map[string]string - writeError error - expectedResult resource.Result - expectedError error - }{ - { - name: "Successful Save", - input: []byte("Bananas"), - existingData: map[string]string{"": ""}, - writeError: nil, - expectedResult: resource.Result{}, - expectedError: nil, - }, - { - name: "Empty input", - input: []byte{}, - existingData: map[string]string{"": ""}, - writeError: nil, - expectedError: nil, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - // Set up the mock expectations - mockFileHandler.On("ReadAccountData").Return(tt.existingData, tt.expectedError) - if tt.expectedError == nil && len(tt.input) > 0 { - mockFileHandler.On("WriteAccountData", mock.MatchedBy(func(data map[string]string) bool { - return data["Offerings"] == string(tt.input) - })).Return(tt.writeError) - } else if len(tt.input) != 4 { - // For input whose input is not a valid yob, no WriteAccountData call should be made - mockFileHandler.On("WriteAccountData", mock.Anything).Maybe().Return(tt.writeError) - return - } - - // Create the Handlers instance with the mock file handler - h := &Handlers{ - accountFileHandler: mockFileHandler, - } - - // Call save yob - result, err := h.SaveOfferings(context.Background(), "save_offerings", tt.input) - - if err != nil { - t.Fatalf("Failed to save offerings with error: %v", err) - } - savedData, err := h.accountFileHandler.ReadAccountData() - if err == nil { - //Assert that the input provided is what was saved into the file - assert.Equal(t, string(tt.input), savedData["Offerings"]) - } - - // Assert the results - assert.Equal(t, tt.expectedResult, result) - assert.Equal(t, tt.expectedError, err) - - // Assert all expectations were met - mockFileHandler.AssertExpectations(t) - }) - } -} - -func TestSaveGender(t *testing.T) { - // Create a new instance of MockAccountFileHandler - mockFileHandler := new(mocks.MockAccountFileHandler) - - // Define test cases - tests := []struct { - name string - input []byte - existingData map[string]string - writeError error - expectedResult resource.Result - expectedError error - expectedGender string - }{ - { - name: "Successful Save - Male", - input: []byte("1"), - existingData: map[string]string{"OtherKey": "OtherValue"}, - writeError: nil, - expectedResult: resource.Result{}, - expectedError: nil, - expectedGender: "Male", - }, - { - name: "Successful Save - Female", - input: []byte("2"), - existingData: map[string]string{"OtherKey": "OtherValue"}, - writeError: nil, - expectedResult: resource.Result{}, - expectedError: nil, - expectedGender: "Female", - }, - { - name: "Successful Save - Unspecified", - input: []byte("3"), - existingData: map[string]string{"OtherKey": "OtherValue"}, - writeError: nil, - expectedResult: resource.Result{}, - expectedError: nil, - expectedGender: "Unspecified", - }, - - { - name: "Empty Input", - input: []byte{}, - existingData: map[string]string{"OtherKey": "OtherValue"}, - writeError: nil, - expectedResult: resource.Result{}, - expectedError: nil, - expectedGender: "", - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - // Set up the mock expectations - mockFileHandler.On("ReadAccountData").Return(tt.existingData, tt.expectedError) - if tt.expectedError == nil && len(tt.input) > 0 { - mockFileHandler.On("WriteAccountData", mock.MatchedBy(func(data map[string]string) bool { - return data["Gender"] == tt.expectedGender - })).Return(tt.writeError) - } else if len(tt.input) == 0 { - // For empty input, no WriteAccountData call should be made - mockFileHandler.On("WriteAccountData", mock.Anything).Maybe().Return(tt.writeError) - } - - // Create the Handlers instance with the mock file handler - h := &Handlers{ - accountFileHandler: mockFileHandler, - } + // Create the context with the session ID + ctx := context.WithValue(context.Background(), "SessionId", tt.ctxValue) // Call the method - result, err := h.SaveGender(context.Background(), "save_gender", tt.input) + _, err := h.SaveFamilyname(ctx, "save_familyname", []byte("John")) // Assert the results - assert.Equal(t, tt.expectedResult, result) - assert.Equal(t, tt.expectedError, err) - - // Verify WriteAccountData was called with the expected data - if len(tt.input) > 0 && tt.expectedError == nil { - mockFileHandler.AssertCalled(t, "WriteAccountData", mock.MatchedBy(func(data map[string]string) bool { - return data["Gender"] == tt.expectedGender - })) - } - - // Assert all expectations were met - mockFileHandler.AssertExpectations(t) - }) - } -} - -func TestGetSender(t *testing.T) { - mockAccountFileHandler := new(mocks.MockAccountFileHandler) - h := &Handlers{ - accountFileHandler: mockAccountFileHandler, - } - - tests := []struct { - name string - expectedResult resource.Result - accountData map[string]string - }{ - { - name: "Valid public key", - expectedResult: resource.Result{ - Content: "test-public-key", - }, - accountData: map[string]string{ - "PublicKey": "test-public-key", - }, - }, - { - name: "Missing public key", - expectedResult: resource.Result{ - Content: "", - }, - accountData: map[string]string{}, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - // Reset the mock state - mockAccountFileHandler.Mock = mock.Mock{} - - mockAccountFileHandler.On("ReadAccountData").Return(tt.accountData, nil) - - result, err := h.GetSender(context.Background(), "", nil) - - if err != nil { - t.Fatalf("Error occurred: %v", err) - } - - assert.Equal(t, tt.expectedResult.Content, result.Content) - mockAccountFileHandler.AssertCalled(t, "ReadAccountData") - }) - } -} - -func TestGetAmount(t *testing.T) { - mockAccountFileHandler := new(mocks.MockAccountFileHandler) - h := &Handlers{ - accountFileHandler: mockAccountFileHandler, - } - - tests := []struct { - name string - expectedResult resource.Result - accountData map[string]string - }{ - { - name: "Valid amount", - expectedResult: resource.Result{ - Content: "0.003", - }, - accountData: map[string]string{ - "Amount": "0.003", - }, - }, - { - name: "Missing amount", - expectedResult: resource.Result{}, - accountData: map[string]string{ - "Amount": "", - }, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - // Reset the mock state - mockAccountFileHandler.Mock = mock.Mock{} - - mockAccountFileHandler.On("ReadAccountData").Return(tt.accountData, nil) - - result, err := h.GetAmount(context.Background(), "", nil) - - assert.NoError(t, err) - assert.Equal(t, tt.expectedResult.Content, result.Content) - - mockAccountFileHandler.AssertCalled(t, "ReadAccountData") - }) - } -} - -func TestGetProfileInfo(t *testing.T) { - tests := []struct { - name string - accountData map[string]string - readError error - expectedResult resource.Result - expectedError error - }{ - { - name: "Complete Profile", - accountData: map[string]string{ - "FirstName": "John", - "FamilyName": "Doe", - "Gender": "Male", - "YOB": "1980", - "Location": "Mombasa", - "Offerings": "Product A", - }, - readError: nil, - expectedResult: resource.Result{ - Content: fmt.Sprintf( - "Name: %s %s\nGender: %s\nAge: %d\nLocation: %s\nYou provide: %s\n", - "John", "Doe", "Male", 44, "Mombasa", "Product A", - ), - }, - expectedError: nil, - }, - { - name: "Profile with Not Provided Fields", - accountData: map[string]string{ - "FirstName": "Not provided", - "FamilyName": "Doe", - "Gender": "Female", - "YOB": "1995", - "Location": "Not provided", - "Offerings": "Service B", - }, - readError: nil, - expectedResult: resource.Result{ - Content: fmt.Sprintf( - "Name: %s\nGender: %s\nAge: %d\nLocation: %s\nYou provide: %s\n", - "Not provided", "Female", 29, "Not provided", "Service B", - ), - }, - expectedError: nil, - }, - { - name: "Profile with YOB as Not provided", - accountData: map[string]string{ - "FirstName": "Not provided", - "FamilyName": "Doe", - "Gender": "Female", - "YOB": "Not provided", - "Location": "Not provided", - "Offerings": "Service B", - }, - readError: nil, - expectedResult: resource.Result{ - Content: fmt.Sprintf( - "Name: %s\nGender: %s\nAge: %s\nLocation: %s\nYou provide: %s\n", - "Not provided", "Female", "Not provided", "Not provided", "Service B", - ), - }, - expectedError: nil, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - // Create a new instance of MockAccountFileHandler - mockFileHandler := new(mocks.MockAccountFileHandler) - - // Set up the mock expectations - mockFileHandler.On("ReadAccountData").Return(tt.accountData, tt.readError) - - // Create the Handlers instance with the mock file handler - h := &Handlers{ - accountFileHandler: mockFileHandler, - } - - // Call the method - result, err := h.GetProfileInfo(context.Background(), "get_profile_info", nil) - - // Assert the results - assert.Equal(t, tt.expectedResult, result) assert.Equal(t, tt.expectedError, err) // Assert all expectations were met - mockFileHandler.AssertExpectations(t) + mockDb.AssertExpectations(t) }) } } From de24ca0648fe88a5be88336a75cfa91915649e5a Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Sat, 7 Sep 2024 09:30:20 +0300 Subject: [PATCH 189/201] Mock the gdm nd updated the TestSaveFirstname and TestSaveFamilyname --- internal/handlers/ussd/menuhandler_test.go | 348 +++++++++------------ 1 file changed, 154 insertions(+), 194 deletions(-) diff --git a/internal/handlers/ussd/menuhandler_test.go b/internal/handlers/ussd/menuhandler_test.go index 3c14a26..b13da16 100644 --- a/internal/handlers/ussd/menuhandler_test.go +++ b/internal/handlers/ussd/menuhandler_test.go @@ -4,9 +4,9 @@ import ( "context" "testing" - "git.grassecon.net/urdt/ussd/internal/handlers/ussd/mocks" + "git.defalsify.org/vise.git/lang" "git.grassecon.net/urdt/ussd/internal/models" - "git.grassecon.net/urdt/ussd/internal/utils" + "github.com/alecthomas/assert/v2" "github.com/stretchr/testify/mock" ) @@ -16,15 +16,6 @@ type MockAccountService struct { mock.Mock } -type MockFlagParser struct { - mock.Mock -} - -func (m *MockFlagParser) GetFlag(key string) (uint32, error) { - args := m.Called(key) - return args.Get(0).(uint32), args.Error(1) -} - func (m *MockAccountService) CreateAccount() (*models.AccountResponse, error) { args := m.Called() return args.Get(0).(*models.AccountResponse), args.Error(1) @@ -40,6 +31,58 @@ func (m *MockAccountService) CheckAccountStatus(trackingId string) (string, erro return args.String(0), args.Error(1) } +// MockDb is a mock implementation of the db.Db interface +type MockDb struct { + mock.Mock +} + +func (m *MockDb) SetPrefix(prefix uint8) { + m.Called(prefix) +} + +func (m *MockDb) Prefix() uint8 { + args := m.Called() + return args.Get(0).(uint8) +} + +func (m *MockDb) Safe() bool { + args := m.Called() + return args.Get(0).(bool) +} + +func (m *MockDb) SetLanguage(language *lang.Language) { + m.Called(language) +} + +func (m *MockDb) SetLock(uint8, bool) error { + args := m.Called() + return args.Error(0) +} + +func (m *MockDb) Connect(ctx context.Context, connectionStr string) error { + args := m.Called(ctx, connectionStr) + return args.Error(0) +} + +func (m *MockDb) SetSession(sessionId string) { + m.Called(sessionId) +} + +func (m *MockDb) Put(ctx context.Context, key, value []byte) error { + args := m.Called(ctx, key, value) + return args.Error(0) +} + +func (m *MockDb) Get(ctx context.Context, key []byte) ([]byte, error) { + args := m.Called(ctx, key) + return nil, args.Error(0) +} + +func (m *MockDb) Close() error { + args := m.Called(nil) + return args.Error(0) +} + // func TestCreateAccount(t *testing.T) { // // Setup // tempDir, err := os.MkdirTemp("", "test_create_account") @@ -425,147 +468,121 @@ func (m *MockAccountService) CheckAccountStatus(trackingId string) (string, erro // } // } -// func TestSaveFirstname(t *testing.T) { -// // Create a new instance of MockAccountFileHandler -// mockFileHandler := new(mocks.MockAccountFileHandler) +func TestSaveFirstname(t *testing.T) { + // Create a mock database + mockDb := new(MockDb) -// // Define test cases -// tests := []struct { -// name string -// input []byte -// existingData map[string]string -// writeError error -// expectedResult resource.Result -// expectedError error -// }{ -// { -// name: "Successful Save", -// input: []byte("Joe"), -// existingData: map[string]string{"Name": "Joe"}, -// writeError: nil, -// expectedResult: resource.Result{}, -// expectedError: nil, -// }, -// { -// name: "Empty Input", -// input: []byte{}, -// existingData: map[string]string{"OtherKey": "OtherValue"}, -// writeError: nil, -// expectedError: nil, -// }, -// } + // Create a Handlers instance with the mock database + h := &Handlers{ + userdataStore: mockDb, + } -// for _, tt := range tests { -// t.Run(tt.name, func(t *testing.T) { -// // Set up the mock expectations -// mockFileHandler.On("ReadAccountData").Return(tt.existingData, tt.expectedError) -// if tt.expectedError == nil && len(tt.input) > 0 { -// mockFileHandler.On("WriteAccountData", mock.MatchedBy(func(data map[string]string) bool { -// return data["FirstName"] == string(tt.input) -// })).Return(tt.writeError) -// } else if len(tt.input) == 0 { -// // For empty input, no WriteAccountData call should be made -// mockFileHandler.On("WriteAccountData", mock.Anything).Maybe().Return(tt.writeError) -// return -// } + // Create a context with a session ID + ctx := context.WithValue(context.Background(), "SessionId", "test-session") -// // Create the Handlers instance with the mock file handler -// h := &Handlers{ -// accountFileHandler: mockFileHandler, -// } + tests := []struct { + name string + input []byte + expectError bool + setupMock func(*MockDb) + }{ + { + name: "Valid first name", + input: []byte("John"), + expectError: false, + setupMock: func(m *MockDb) { + m.On("SetPrefix", uint8(0x20)).Return(nil) + m.On("SetSession", "test-session").Return(nil) + m.On("Put", mock.Anything, mock.Anything, []byte("John")).Return(nil) + }, + }, + { + name: "Empty first name", + input: []byte{}, + expectError: false, // Note: The function doesn't return an error for empty input + setupMock: func(m *MockDb) {}, + }, + } -// // Call save location -// result, err := h.SaveFirstname(context.Background(), "save_location", tt.input) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Setup mock expectations + tt.setupMock(mockDb) -// if err != nil { -// t.Fatalf("Failed to save first name with error: %v", err) -// } -// savedData, err := h.accountFileHandler.ReadAccountData() -// if err == nil { -// //Assert that the input provided is what was saved into the file -// assert.Equal(t, string(tt.input), savedData["FirstName"]) -// } + // Call the function + _, err := h.SaveFirstname(ctx, "", tt.input) -// // Assert the results -// assert.Equal(t, tt.expectedResult, result) -// assert.Equal(t, tt.expectedError, err) + if tt.expectError { + assert.Error(t, err) + } else { + assert.NoError(t, err) + mockDb.AssertExpectations(t) + } -// // Assert all expectations were met -// mockFileHandler.AssertExpectations(t) -// }) -// } -// } + // Clear mock for the next test + mockDb.ExpectedCalls = nil + mockDb.Calls = nil + }) + } +} -// func TestSaveFamilyName(t *testing.T) { -// // Create a new instance of MockAccountFileHandler -// mockFileHandler := new(mocks.MockAccountFileHandler) +func TestSaveFamilyname(t *testing.T) { + // Create a mock database + mockDb := new(MockDb) -// // Define test cases -// tests := []struct { -// name string -// input []byte -// existingData map[string]string -// writeError error -// expectedResult resource.Result -// expectedError error -// }{ -// { -// name: "Successful Save", -// input: []byte("Doe"), -// existingData: map[string]string{"FamilyName": "Doe"}, -// writeError: nil, -// expectedResult: resource.Result{}, -// expectedError: nil, -// }, -// { -// name: "Empty Input", -// input: []byte{}, -// existingData: map[string]string{"FamilyName": "Doe"}, -// writeError: nil, -// expectedError: nil, -// }, -// } + // Create a Handlers instance with the mock database + h := &Handlers{ + userdataStore: mockDb, + } -// for _, tt := range tests { -// t.Run(tt.name, func(t *testing.T) { -// // Set up the mock expectations -// mockFileHandler.On("ReadAccountData").Return(tt.existingData, tt.expectedError) -// if tt.expectedError == nil && len(tt.input) > 0 { -// mockFileHandler.On("WriteAccountData", mock.MatchedBy(func(data map[string]string) bool { -// return data["FamilyName"] == string(tt.input) -// })).Return(tt.writeError) -// } else if len(tt.input) == 0 { -// // For empty input, no WriteAccountData call should be made -// mockFileHandler.On("WriteAccountData", mock.Anything).Maybe().Return(tt.writeError) -// return -// } + // Create a context with a session ID + ctx := context.WithValue(context.Background(), "SessionId", "test-session") -// // Create the Handlers instance with the mock file handler -// h := &Handlers{ -// accountFileHandler: mockFileHandler, -// } + tests := []struct { + name string + input []byte + expectError bool + setupMock func(*MockDb) + }{ + { + name: "Valid family name", + input: []byte("Smith"), + expectError: false, + setupMock: func(m *MockDb) { + m.On("SetPrefix", uint8(0x20)).Return(nil) + m.On("SetSession", "test-session").Return(nil) + m.On("Put", mock.Anything, mock.Anything, []byte("Smith")).Return(nil) + }, + }, + { + name: "Empty family name", + input: []byte{}, + expectError: true, + setupMock: func(m *MockDb) {}, + }, + } -// // Call save familyname -// result, err := h.SaveFamilyname(context.Background(), "save_familyname", tt.input) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Setup mock expectations + tt.setupMock(mockDb) -// if err != nil { -// t.Fatalf("Failed to save family name with error: %v", err) -// } -// savedData, err := h.accountFileHandler.ReadAccountData() -// if err == nil { -// //Assert that the input provided is what was saved into the file -// assert.Equal(t, string(tt.input), savedData["FamilyName"]) -// } + // Call the function + _, err := h.SaveFamilyname(ctx, "", tt.input) -// // Assert the results -// assert.Equal(t, tt.expectedResult, result) -// assert.Equal(t, tt.expectedError, err) + if tt.expectError { + assert.Error(t, err) + } else { + assert.NoError(t, err) + mockDb.AssertExpectations(t) + } -// // Assert all expectations were met -// mockFileHandler.AssertExpectations(t) -// }) -// } -// } + // Clear mock for the next test + mockDb.ExpectedCalls = nil + mockDb.Calls = nil + }) + } +} // func TestSaveYOB(t *testing.T) { // // Create a new instance of MockAccountFileHandler @@ -986,60 +1003,3 @@ func (m *MockAccountService) CheckAccountStatus(trackingId string) (string, erro // }) // } // } - -// Test SaveFirstname -func TestSaveFirstName(t *testing.T) { - // Create a new instance of MockDb - mockDb := new(mocks.MockDb) - k := utils.PackKey(utils.DATA_FAMILY_NAME, []byte("session123")) - // Define test cases - tests := []struct { - name string - ctxValue string - input []byte - mockPutError error - expectedError error - expectedCalls []mock.Call - }{ - { - name: "Successful save", - ctxValue: "session123", - input: []byte("John"), - mockPutError: nil, - expectedError: nil, - expectedCalls: []mock.Call{ - // Expect the SetPrefix and SetSession calls - *mockDb.On("SetPrefix", utils.DATA_FAMILY_NAME).Return(), - *mockDb.On("SetSession", "session123").Return(), - // Expect the Put call - *mockDb.On("Put", context.WithValue(context.Background(), "SessionId", "session123"), k, []byte("John")).Return(nil), - }, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - // Set up the mock expectations - for _, call := range tt.expectedCalls { - call.Run(func(args mock.Arguments) {}) - } - - // Create the Handlers instance with the mock db - h := &Handlers{ - userdataStore: mockDb, - } - - // Create the context with the session ID - ctx := context.WithValue(context.Background(), "SessionId", tt.ctxValue) - - // Call the method - _, err := h.SaveFamilyname(ctx, "save_familyname", []byte("John")) - - // Assert the results - assert.Equal(t, tt.expectedError, err) - - // Assert all expectations were met - mockDb.AssertExpectations(t) - }) - } -} From 421fbe5543b44faee9ec14b7672144e581c26490 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Sat, 7 Sep 2024 09:55:00 +0300 Subject: [PATCH 190/201] setup mock for the acccount service --- internal/handlers/ussd/mocks/servicemock.go | 26 +++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 internal/handlers/ussd/mocks/servicemock.go diff --git a/internal/handlers/ussd/mocks/servicemock.go b/internal/handlers/ussd/mocks/servicemock.go new file mode 100644 index 0000000..9fb6d3e --- /dev/null +++ b/internal/handlers/ussd/mocks/servicemock.go @@ -0,0 +1,26 @@ +package mocks + +import ( + "git.grassecon.net/urdt/ussd/internal/models" + "github.com/stretchr/testify/mock" +) + +// MockAccountService implements AccountServiceInterface for testing +type MockAccountService struct { + mock.Mock +} + +func (m *MockAccountService) CreateAccount() (*models.AccountResponse, error) { + args := m.Called() + return args.Get(0).(*models.AccountResponse), args.Error(1) +} + +func (m *MockAccountService) CheckBalance(publicKey string) (string, error) { + args := m.Called(publicKey) + return args.String(0), args.Error(1) +} + +func (m *MockAccountService) CheckAccountStatus(trackingId string) (string, error) { + args := m.Called(trackingId) + return args.String(0), args.Error(1) +} \ No newline at end of file From 57225523954e8028a8e7de1190548d65929ec04b Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Sat, 7 Sep 2024 09:55:13 +0300 Subject: [PATCH 191/201] remove old mocks --- internal/handlers/ussd/mocks/mocks.go | 44 --------------------------- 1 file changed, 44 deletions(-) delete mode 100644 internal/handlers/ussd/mocks/mocks.go diff --git a/internal/handlers/ussd/mocks/mocks.go b/internal/handlers/ussd/mocks/mocks.go deleted file mode 100644 index 3c7eb1e..0000000 --- a/internal/handlers/ussd/mocks/mocks.go +++ /dev/null @@ -1,44 +0,0 @@ -package mocks - -import ( - "git.grassecon.net/urdt/ussd/internal/models" - "github.com/stretchr/testify/mock" -) - -type MockAccountFileHandler struct { - mock.Mock -} - -func (m *MockAccountFileHandler) EnsureFileExists() error { - args := m.Called() - return args.Error(0) -} - -func (m *MockAccountFileHandler) ReadAccountData() (map[string]string, error) { - args := m.Called() - return args.Get(0).(map[string]string), args.Error(1) -} - -func (m *MockAccountFileHandler) WriteAccountData(data map[string]string) error { - args := m.Called(data) - return args.Error(0) -} - -type MockAccountService struct { - mock.Mock -} - -func (m *MockAccountService) CreateAccount() (*models.AccountResponse, error) { - args := m.Called() - return args.Get(0).(*models.AccountResponse), args.Error(1) -} - -func (m *MockAccountService) CheckAccountStatus(TrackingId string) (string, error) { - args := m.Called() - return args.Get(0).(string), args.Error(1) -} - -func (m *MockAccountService) CheckBalance(PublicKey string) (string, error) { - args := m.Called() - return args.Get(0).(string), args.Error(1) -} From 04ea11dd6d3c3d9af6d65a9e95924c4bd976587c Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Sat, 7 Sep 2024 09:55:47 +0300 Subject: [PATCH 192/201] setup db mock --- internal/handlers/ussd/mocks/dbmock.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/internal/handlers/ussd/mocks/dbmock.go b/internal/handlers/ussd/mocks/dbmock.go index 71f7eca..0b40eab 100644 --- a/internal/handlers/ussd/mocks/dbmock.go +++ b/internal/handlers/ussd/mocks/dbmock.go @@ -4,7 +4,6 @@ import ( "context" "git.defalsify.org/vise.git/lang" - "git.grassecon.net/urdt/ussd/internal/utils" "github.com/stretchr/testify/mock" ) @@ -13,7 +12,7 @@ type MockDb struct { } func (m *MockDb) SetPrefix(prefix uint8) { - m.Called(utils.DATA_FAMILY_NAME) + m.Called(prefix) } func (m *MockDb) Prefix() uint8 { From d1d5c897d1e0ad724a303c8517ca6f6fdb0430fe Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Sat, 7 Sep 2024 09:55:59 +0300 Subject: [PATCH 193/201] refactor --- internal/handlers/ussd/menuhandler_test.go | 120 +++++++++------------ 1 file changed, 49 insertions(+), 71 deletions(-) diff --git a/internal/handlers/ussd/menuhandler_test.go b/internal/handlers/ussd/menuhandler_test.go index b13da16..e496773 100644 --- a/internal/handlers/ussd/menuhandler_test.go +++ b/internal/handlers/ussd/menuhandler_test.go @@ -4,84 +4,62 @@ import ( "context" "testing" - "git.defalsify.org/vise.git/lang" - "git.grassecon.net/urdt/ussd/internal/models" - + "git.grassecon.net/urdt/ussd/internal/handlers/ussd/mocks" "github.com/alecthomas/assert/v2" "github.com/stretchr/testify/mock" ) -// MockAccountService implements AccountServiceInterface for testing -type MockAccountService struct { - mock.Mock -} - -func (m *MockAccountService) CreateAccount() (*models.AccountResponse, error) { - args := m.Called() - return args.Get(0).(*models.AccountResponse), args.Error(1) -} - -func (m *MockAccountService) CheckBalance(publicKey string) (string, error) { - args := m.Called(publicKey) - return args.String(0), args.Error(1) -} - -func (m *MockAccountService) CheckAccountStatus(trackingId string) (string, error) { - args := m.Called(trackingId) - return args.String(0), args.Error(1) -} - // MockDb is a mock implementation of the db.Db interface -type MockDb struct { - mock.Mock -} +//type MockDb struct { +// mock.Mock +// } -func (m *MockDb) SetPrefix(prefix uint8) { - m.Called(prefix) -} +// func (m *MockDb) SetPrefix(prefix uint8) { +// m.Called(prefix) +// } -func (m *MockDb) Prefix() uint8 { - args := m.Called() - return args.Get(0).(uint8) -} +// func (m *MockDb) Prefix() uint8 { +// args := m.Called() +// return args.Get(0).(uint8) +// } -func (m *MockDb) Safe() bool { - args := m.Called() - return args.Get(0).(bool) -} +// func (m *MockDb) Safe() bool { +// args := m.Called() +// return args.Get(0).(bool) +// } -func (m *MockDb) SetLanguage(language *lang.Language) { - m.Called(language) -} +// func (m *MockDb) SetLanguage(language *lang.Language) { +// m.Called(language) +// } -func (m *MockDb) SetLock(uint8, bool) error { - args := m.Called() - return args.Error(0) -} +// func (m *MockDb) SetLock(uint8, bool) error { +// args := m.Called() +// return args.Error(0) +// } -func (m *MockDb) Connect(ctx context.Context, connectionStr string) error { - args := m.Called(ctx, connectionStr) - return args.Error(0) -} +// func (m *MockDb) Connect(ctx context.Context, connectionStr string) error { +// args := m.Called(ctx, connectionStr) +// return args.Error(0) +// } -func (m *MockDb) SetSession(sessionId string) { - m.Called(sessionId) -} +// func (m *MockDb) SetSession(sessionId string) { +// m.Called(sessionId) +// } -func (m *MockDb) Put(ctx context.Context, key, value []byte) error { - args := m.Called(ctx, key, value) - return args.Error(0) -} +// func (m *MockDb) Put(ctx context.Context, key, value []byte) error { +// args := m.Called(ctx, key, value) +// return args.Error(0) +// } -func (m *MockDb) Get(ctx context.Context, key []byte) ([]byte, error) { - args := m.Called(ctx, key) - return nil, args.Error(0) -} +// func (m *MockDb) Get(ctx context.Context, key []byte) ([]byte, error) { +// args := m.Called(ctx, key) +// return nil, args.Error(0) +// } -func (m *MockDb) Close() error { - args := m.Called(nil) - return args.Error(0) -} +// func (m *MockDb) Close() error { +// args := m.Called(nil) +// return args.Error(0) +// } // func TestCreateAccount(t *testing.T) { // // Setup @@ -470,7 +448,7 @@ func (m *MockDb) Close() error { func TestSaveFirstname(t *testing.T) { // Create a mock database - mockDb := new(MockDb) + mockDb := new(mocks.MockDb) // Create a Handlers instance with the mock database h := &Handlers{ @@ -484,13 +462,13 @@ func TestSaveFirstname(t *testing.T) { name string input []byte expectError bool - setupMock func(*MockDb) + setupMock func(*mocks.MockDb) }{ { name: "Valid first name", input: []byte("John"), expectError: false, - setupMock: func(m *MockDb) { + setupMock: func(m *mocks.MockDb) { m.On("SetPrefix", uint8(0x20)).Return(nil) m.On("SetSession", "test-session").Return(nil) m.On("Put", mock.Anything, mock.Anything, []byte("John")).Return(nil) @@ -500,7 +478,7 @@ func TestSaveFirstname(t *testing.T) { name: "Empty first name", input: []byte{}, expectError: false, // Note: The function doesn't return an error for empty input - setupMock: func(m *MockDb) {}, + setupMock: func(m *mocks.MockDb) {}, }, } @@ -528,7 +506,7 @@ func TestSaveFirstname(t *testing.T) { func TestSaveFamilyname(t *testing.T) { // Create a mock database - mockDb := new(MockDb) + mockDb := new(mocks.MockDb) // Create a Handlers instance with the mock database h := &Handlers{ @@ -542,13 +520,13 @@ func TestSaveFamilyname(t *testing.T) { name string input []byte expectError bool - setupMock func(*MockDb) + setupMock func(*mocks.MockDb) }{ { name: "Valid family name", input: []byte("Smith"), expectError: false, - setupMock: func(m *MockDb) { + setupMock: func(m *mocks.MockDb) { m.On("SetPrefix", uint8(0x20)).Return(nil) m.On("SetSession", "test-session").Return(nil) m.On("Put", mock.Anything, mock.Anything, []byte("Smith")).Return(nil) @@ -558,7 +536,7 @@ func TestSaveFamilyname(t *testing.T) { name: "Empty family name", input: []byte{}, expectError: true, - setupMock: func(m *MockDb) {}, + setupMock: func(m *mocks.MockDb) {}, }, } From 4c3f63a48fb733c2b479668888754638976cd10f Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Sat, 7 Sep 2024 10:36:00 +0300 Subject: [PATCH 194/201] create an account only if not found in gdbm --- internal/handlers/ussd/menuhandler.go | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index c94a57c..89fc6c6 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -177,12 +177,7 @@ func (h *Handlers) CreateAccount(ctx context.Context, sym string, input []byte) if err != nil { return res, err } - } else { - err = h.createAccountNoExist(ctx, sessionId, &res) - if err != nil { - return res, err - } - } + } } return res, nil } From be33b7458fbe0bfae2ca5d15b12e6b67a5596094 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Sat, 7 Sep 2024 16:22:08 +0300 Subject: [PATCH 195/201] cleanup code --- internal/handlers/ussd/menuhandler.go | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 89fc6c6..27af8f4 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -145,7 +145,6 @@ func (h *Handlers) createAccountNoExist(ctx context.Context, sessionId string, r utils.DATA_PUBLIC_KEY: accountResp.Result.PublicKey, utils.DATA_CUSTODIAL_ID: accountResp.Result.CustodialId.String(), } - for key, value := range data { err := utils.WriteEntry(ctx, h.userdataStore, sessionId, key, []byte(value)) if err != nil { @@ -164,7 +163,6 @@ func (h *Handlers) createAccountNoExist(ctx context.Context, sessionId string, r func (h *Handlers) CreateAccount(ctx context.Context, sym string, input []byte) (resource.Result, error) { var res resource.Result var err error - sessionId, ok := ctx.Value("SessionId").(string) if !ok { return res, fmt.Errorf("missing session") @@ -177,7 +175,7 @@ func (h *Handlers) CreateAccount(ctx context.Context, sym string, input []byte) if err != nil { return res, err } - } + } } return res, nil } From dd975318613034ef6acf70ceba6a1b4e2e65ee99 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Sat, 7 Sep 2024 16:24:37 +0300 Subject: [PATCH 196/201] remove uimplemented tests --- internal/handlers/ussd/menuhandler_test.go | 888 +-------------------- 1 file changed, 36 insertions(+), 852 deletions(-) diff --git a/internal/handlers/ussd/menuhandler_test.go b/internal/handlers/ussd/menuhandler_test.go index e496773..4ab3046 100644 --- a/internal/handlers/ussd/menuhandler_test.go +++ b/internal/handlers/ussd/menuhandler_test.go @@ -2,449 +2,53 @@ package ussd import ( "context" + "encoding/json" "testing" + "git.defalsify.org/vise.git/db" "git.grassecon.net/urdt/ussd/internal/handlers/ussd/mocks" + "git.grassecon.net/urdt/ussd/internal/models" + "git.grassecon.net/urdt/ussd/internal/utils" "github.com/alecthomas/assert/v2" "github.com/stretchr/testify/mock" ) -// MockDb is a mock implementation of the db.Db interface -//type MockDb struct { -// mock.Mock -// } +func TestCreateAccount_Success(t *testing.T) { + mockCreateAccountService := new(mocks.MockAccountService) + mockUserDataStore := new(mocks.MockDb) -// func (m *MockDb) SetPrefix(prefix uint8) { -// m.Called(prefix) -// } + h := &Handlers{ + userdataStore: mockUserDataStore, + accountService: mockCreateAccountService, + } + ctx := context.WithValue(context.Background(), "SessionId", "test-session-12345") + k := utils.PackKey(utils.DATA_ACCOUNT_CREATED, []byte("test-session-12345")) + mockUserDataStore.On("SetPrefix", uint8(0x20)).Return(nil) + mockUserDataStore.On("SetSession", "test-session-12345").Return(nil) + mockUserDataStore.On("Get", ctx, k). + Return(nil, db.ErrNotFound{}) -// func (m *MockDb) Prefix() uint8 { -// args := m.Called() -// return args.Get(0).(uint8) -// } + // Define expected account response after api call + expectedAccountResp := &models.AccountResponse{ + Ok: true, + Result: struct { + CustodialId json.Number `json:"custodialId"` + PublicKey string `json:"publicKey"` + TrackingId string `json:"trackingId"` + }{ + CustodialId: "12", + PublicKey: "0x8E0XSCSVA", + TrackingId: "d95a7e83-196c-4fd0-866fSGAGA", + }, + } + mockCreateAccountService.On("CreateAccount").Return(expectedAccountResp, nil) -// func (m *MockDb) Safe() bool { -// args := m.Called() -// return args.Get(0).(bool) -// } + _, err := h.CreateAccount(ctx, "create_account", []byte("create_account")) -// func (m *MockDb) SetLanguage(language *lang.Language) { -// m.Called(language) -// } - -// func (m *MockDb) SetLock(uint8, bool) error { -// args := m.Called() -// return args.Error(0) -// } - -// func (m *MockDb) Connect(ctx context.Context, connectionStr string) error { -// args := m.Called(ctx, connectionStr) -// return args.Error(0) -// } - -// func (m *MockDb) SetSession(sessionId string) { -// m.Called(sessionId) -// } - -// func (m *MockDb) Put(ctx context.Context, key, value []byte) error { -// args := m.Called(ctx, key, value) -// return args.Error(0) -// } - -// func (m *MockDb) Get(ctx context.Context, key []byte) ([]byte, error) { -// args := m.Called(ctx, key) -// return nil, args.Error(0) -// } - -// func (m *MockDb) Close() error { -// args := m.Called(nil) -// return args.Error(0) -// } - -// func TestCreateAccount(t *testing.T) { -// // Setup -// tempDir, err := os.MkdirTemp("", "test_create_account") -// if err != nil { -// t.Fatalf("Failed to create temp directory: %v", err) -// } -// defer os.RemoveAll(tempDir) // Clean up after the test run - -// sessionID := "07xxxxxxxx" - -// // Set up the data file path using the session ID -// accountFilePath := filepath.Join(tempDir, sessionID+"_data") - -// // Initialize account file handler -// accountFileHandler := utils.NewAccountFileHandler(accountFilePath) - -// // Create a mock account service -// mockAccountService := &MockAccountService{} -// mockAccountResponse := &models.AccountResponse{ -// Ok: true, -// Result: struct { -// CustodialId json.Number `json:"custodialId"` -// PublicKey string `json:"publicKey"` -// TrackingId string `json:"trackingId"` -// }{ -// CustodialId: "test-custodial-id", -// PublicKey: "test-public-key", -// TrackingId: "test-tracking-id", -// }, -// } - -// // Set up expectations for the mock account service -// mockAccountService.On("CreateAccount").Return(mockAccountResponse, nil) - -// mockParser := new(MockFlagParser) - -// flag_account_created := uint32(1) -// flag_account_creation_failed := uint32(2) - -// mockParser.On("GetFlag", "flag_account_created").Return(flag_account_created, nil) -// mockParser.On("GetFlag", "flag_account_creation_failed").Return(flag_account_creation_failed, nil) - -// // Initialize Handlers with mock account service -// h := &Handlers{ -// fs: &FSData{Path: accountFilePath}, -// accountFileHandler: accountFileHandler, -// accountService: mockAccountService, -// parser: mockParser, -// } - -// tests := []struct { -// name string -// existingData map[string]string -// expectedResult resource.Result -// expectedData map[string]string -// }{ -// { -// name: "New account creation", -// existingData: nil, -// expectedResult: resource.Result{ -// FlagSet: []uint32{flag_account_created}, -// }, -// expectedData: map[string]string{ -// "TrackingId": "test-tracking-id", -// "PublicKey": "test-public-key", -// "CustodialId": "test-custodial-id", -// "Status": "PENDING", -// "Gender": "Not provided", -// "YOB": "Not provided", -// "Location": "Not provided", -// "Offerings": "Not provided", -// "FirstName": "Not provided", -// "FamilyName": "Not provided", -// }, -// }, -// { -// name: "Existing account", -// existingData: map[string]string{ -// "TrackingId": "test-tracking-id", -// "PublicKey": "test-public-key", -// "CustodialId": "test-custodial-id", -// "Status": "PENDING", -// "Gender": "Not provided", -// "YOB": "Not provided", -// "Location": "Not provided", -// "Offerings": "Not provided", -// "FirstName": "Not provided", -// "FamilyName": "Not provided", -// }, -// expectedResult: resource.Result{}, -// expectedData: map[string]string{ -// "TrackingId": "test-tracking-id", -// "PublicKey": "test-public-key", -// "CustodialId": "test-custodial-id", -// "Status": "PENDING", -// "Gender": "Not provided", -// "YOB": "Not provided", -// "Location": "Not provided", -// "Offerings": "Not provided", -// "FirstName": "Not provided", -// "FamilyName": "Not provided", -// }, -// }, -// } - -// for _, tt := range tests { -// t.Run(tt.name, func(t *testing.T) { -// // Set up the data file path using the session ID -// accountFilePath := filepath.Join(tempDir, sessionID+"_data") - -// // Setup existing data if any -// if tt.existingData != nil { -// data, _ := json.Marshal(tt.existingData) -// err := os.WriteFile(accountFilePath, data, 0644) -// if err != nil { -// t.Fatalf("Failed to write existing data: %v", err) -// } -// } - -// // Call the function -// result, err := h.CreateAccount(context.Background(), "", nil) - -// // Check for errors -// if err != nil { -// t.Fatalf("CreateAccount returned an error: %v", err) -// } - -// // Check the result -// if len(result.FlagSet) != len(tt.expectedResult.FlagSet) { -// t.Errorf("Expected %d flags, got %d", len(tt.expectedResult.FlagSet), len(result.FlagSet)) -// } -// for i, flag := range tt.expectedResult.FlagSet { -// if result.FlagSet[i] != flag { -// t.Errorf("Expected flag %d, got %d", flag, result.FlagSet[i]) -// } -// } - -// // Check the stored data -// data, err := os.ReadFile(accountFilePath) -// if err != nil { -// t.Fatalf("Failed to read account data file: %v", err) -// } - -// var storedData map[string]string -// err = json.Unmarshal(data, &storedData) -// if err != nil { -// t.Fatalf("Failed to unmarshal stored data: %v", err) -// } - -// for key, expectedValue := range tt.expectedData { -// if storedValue, ok := storedData[key]; !ok || storedValue != expectedValue { -// t.Errorf("Expected %s to be %s, got %s", key, expectedValue, storedValue) -// } -// } -// }) -// } -// } - -// func TestCreateAccount_Success(t *testing.T) { -// mockAccountFileHandler := new(mocks.MockAccountFileHandler) -// mockCreateAccountService := new(mocks.MockAccountService) - -// mockAccountFileHandler.On("EnsureFileExists").Return(nil) - -// // Mock that no account data exists -// mockAccountFileHandler.On("ReadAccountData").Return(nil, nil) - -// // Define expected account response after api call -// expectedAccountResp := &models.AccountResponse{ -// Ok: true, -// Result: struct { -// CustodialId json.Number `json:"custodialId"` -// PublicKey string `json:"publicKey"` -// TrackingId string `json:"trackingId"` -// }{ -// CustodialId: "12", -// PublicKey: "0x8E0XSCSVA", -// TrackingId: "d95a7e83-196c-4fd0-866fSGAGA", -// }, -// } -// mockCreateAccountService.On("CreateAccount").Return(expectedAccountResp, nil) - -// // Mock WriteAccountData to not error -// mockAccountFileHandler.On("WriteAccountData", mock.Anything).Return(nil) - -// handlers := &Handlers{ -// accountService: mockCreateAccountService, -// } - -// actualResponse, err := handlers.accountService.CreateAccount() - -// // Assert results -// assert.NoError(t, err) -// assert.Equal(t, expectedAccountResp.Ok, true) -// assert.Equal(t, expectedAccountResp, actualResponse) -// } - -// func TestSavePin(t *testing.T) { -// // Setup -// tempDir, err := os.MkdirTemp("", "test_save_pin") -// if err != nil { -// t.Fatalf("Failed to create temp directory: %v", err) -// } -// defer os.RemoveAll(tempDir) - -// sessionID := "07xxxxxxxx" - -// // Set up the data file path using the session ID -// accountFilePath := filepath.Join(tempDir, sessionID+"_data") -// initialAccountData := map[string]string{ -// "TrackingId": "test-tracking-id", -// "PublicKey": "test-public-key", -// } -// data, _ := json.Marshal(initialAccountData) -// err = os.WriteFile(accountFilePath, data, 0644) -// if err != nil { -// t.Fatalf("Failed to write initial account data: %v", err) -// } - -// // Create a new AccountFileHandler and set it in the Handlers struct -// accountFileHandler := utils.NewAccountFileHandler(accountFilePath) -// mockParser := new(MockFlagParser) - -// h := &Handlers{ -// accountFileHandler: accountFileHandler, -// parser: mockParser, -// } - -// flag_incorrect_pin := uint32(1) -// mockParser.On("GetFlag", "flag_incorrect_pin").Return(flag_incorrect_pin, nil) - -// tests := []struct { -// name string -// input []byte -// expectedFlags []uint32 -// expectedData map[string]string -// expectedErrors bool -// }{ -// { -// name: "Valid PIN", -// input: []byte("1234"), -// expectedFlags: []uint32{}, -// expectedData: map[string]string{ -// "TrackingId": "test-tracking-id", -// "PublicKey": "test-public-key", -// "AccountPIN": "1234", -// }, -// }, -// { -// name: "Invalid PIN - non-numeric", -// input: []byte("12ab"), -// expectedFlags: []uint32{flag_incorrect_pin}, -// expectedData: initialAccountData, // No changes expected -// expectedErrors: false, -// }, -// { -// name: "Invalid PIN - less than 4 digits", -// input: []byte("123"), -// expectedFlags: []uint32{flag_incorrect_pin}, -// expectedData: initialAccountData, // No changes expected -// expectedErrors: false, -// }, -// { -// name: "Invalid PIN - more than 4 digits", -// input: []byte("12345"), -// expectedFlags: []uint32{flag_incorrect_pin}, -// expectedData: initialAccountData, // No changes expected -// expectedErrors: false, -// }, -// } - -// for _, tt := range tests { -// t.Run(tt.name, func(t *testing.T) { -// err := accountFileHandler.EnsureFileExists() -// if err != nil { -// t.Fatalf("Failed to ensure account file exists: %v", err) -// } - -// result, err := h.SavePin(context.Background(), "", tt.input) -// if err != nil && !tt.expectedErrors { -// t.Fatalf("SavePin returned an unexpected error: %v", err) -// } - -// if len(result.FlagSet) != len(tt.expectedFlags) { -// t.Errorf("Expected %d flags, got %d", len(tt.expectedFlags), len(result.FlagSet)) -// } -// for i, flag := range tt.expectedFlags { -// if result.FlagSet[i] != flag { -// t.Errorf("Expected flag %d, got %d", flag, result.FlagSet[i]) -// } -// } - -// data, err := os.ReadFile(accountFilePath) -// if err != nil { -// t.Fatalf("Failed to read account data file: %v", err) -// } - -// var storedData map[string]string -// err = json.Unmarshal(data, &storedData) -// if err != nil { -// t.Fatalf("Failed to unmarshal stored data: %v", err) -// } - -// for key, expectedValue := range tt.expectedData { -// if storedValue, ok := storedData[key]; !ok || storedValue != expectedValue { -// t.Errorf("Expected %s to be %s, got %s", key, expectedValue, storedValue) -// } -// } -// }) -// } -// } - -// func TestSaveLocation(t *testing.T) { -// // Create a new instance of MockAccountFileHandler -// mockFileHandler := new(mocks.MockAccountFileHandler) - -// // Define test cases -// tests := []struct { -// name string -// input []byte -// existingData map[string]string -// writeError error -// expectedResult resource.Result -// expectedError error -// }{ -// { -// name: "Successful Save", -// input: []byte("Mombasa"), -// existingData: map[string]string{"Location": "Mombasa"}, -// writeError: nil, -// expectedResult: resource.Result{}, -// expectedError: nil, -// }, -// { -// name: "Empty location input", -// input: []byte{}, -// existingData: map[string]string{"OtherKey": "OtherValue"}, -// writeError: nil, -// expectedResult: resource.Result{}, -// expectedError: nil, -// }, -// } - -// for _, tt := range tests { -// t.Run(tt.name, func(t *testing.T) { -// // Set up the mock expectations -// mockFileHandler.On("ReadAccountData").Return(tt.existingData, tt.expectedError) -// if tt.expectedError == nil && len(tt.input) > 0 { -// mockFileHandler.On("WriteAccountData", mock.MatchedBy(func(data map[string]string) bool { -// return data["Location"] == string(tt.input) -// })).Return(tt.writeError) -// } else if len(tt.input) == 0 { -// // For empty input, no WriteAccountData call should be made -// mockFileHandler.On("WriteAccountData", mock.Anything).Maybe().Return(tt.writeError) -// return -// } - -// // Create the Handlers instance with the mock file handler -// h := &Handlers{ -// accountFileHandler: mockFileHandler, -// } - -// // Call Save Location -// result, err := h.SaveLocation(context.Background(), "save_location", tt.input) - -// if err != nil { -// t.Fatalf("Failed to save location with error: %v", err) -// } - -// savedData, err := h.accountFileHandler.ReadAccountData() -// if err == nil { -// //Assert that the input provided is what was saved into the file -// assert.Equal(t, string(tt.input), savedData["Location"]) -// } - -// // Assert the results -// assert.Equal(t, tt.expectedResult, result) -// assert.Equal(t, tt.expectedError, err) - -// // Assert all expectations were met -// mockFileHandler.AssertExpectations(t) -// }) -// } -// } + // Assert results + assert.NoError(t, err) + assert.Equal(t, expectedAccountResp.Ok, true) +} func TestSaveFirstname(t *testing.T) { // Create a mock database @@ -561,423 +165,3 @@ func TestSaveFamilyname(t *testing.T) { }) } } - -// func TestSaveYOB(t *testing.T) { -// // Create a new instance of MockAccountFileHandler -// mockFileHandler := new(mocks.MockAccountFileHandler) - -// // Define test cases -// tests := []struct { -// name string -// input []byte -// existingData map[string]string -// writeError error -// expectedResult resource.Result -// expectedError error -// }{ -// { -// name: "Successful Save", -// input: []byte("2006"), -// existingData: map[string]string{"": ""}, -// writeError: nil, -// expectedResult: resource.Result{}, -// expectedError: nil, -// }, -// { -// name: "YOB less than 4 digits(invalid date entry)", -// input: []byte{}, -// existingData: map[string]string{"": ""}, -// writeError: nil, -// expectedError: nil, -// }, -// } - -// for _, tt := range tests { -// t.Run(tt.name, func(t *testing.T) { -// // Set up the mock expectations -// mockFileHandler.On("ReadAccountData").Return(tt.existingData, tt.expectedError) -// if tt.expectedError == nil && len(tt.input) > 0 { -// mockFileHandler.On("WriteAccountData", mock.MatchedBy(func(data map[string]string) bool { -// return data["YOB"] == string(tt.input) -// })).Return(tt.writeError) -// } else if len(tt.input) != 4 { -// // For input whose input is not a valid yob, no WriteAccountData call should be made -// mockFileHandler.On("WriteAccountData", mock.Anything).Maybe().Return(tt.writeError) -// return -// } - -// // Create the Handlers instance with the mock file handler -// h := &Handlers{ -// accountFileHandler: mockFileHandler, -// } - -// // Call save yob -// result, err := h.SaveYob(context.Background(), "save_yob", tt.input) - -// if err != nil { -// t.Fatalf("Failed to save family name with error: %v", err) -// } -// savedData, err := h.accountFileHandler.ReadAccountData() -// if err == nil { -// //Assert that the input provided is what was saved into the file -// assert.Equal(t, string(tt.input), savedData["YOB"]) -// } - -// // Assert the results -// assert.Equal(t, tt.expectedResult, result) -// assert.Equal(t, tt.expectedError, err) - -// // Assert all expectations were met -// mockFileHandler.AssertExpectations(t) -// }) -// } -// } - -// func TestSaveOfferings(t *testing.T) { -// // Create a new instance of MockAccountFileHandler -// mockFileHandler := new(mocks.MockAccountFileHandler) - -// // Define test cases -// tests := []struct { -// name string -// input []byte -// existingData map[string]string -// writeError error -// expectedResult resource.Result -// expectedError error -// }{ -// { -// name: "Successful Save", -// input: []byte("Bananas"), -// existingData: map[string]string{"": ""}, -// writeError: nil, -// expectedResult: resource.Result{}, -// expectedError: nil, -// }, -// { -// name: "Empty input", -// input: []byte{}, -// existingData: map[string]string{"": ""}, -// writeError: nil, -// expectedError: nil, -// }, -// } - -// for _, tt := range tests { -// t.Run(tt.name, func(t *testing.T) { -// // Set up the mock expectations -// mockFileHandler.On("ReadAccountData").Return(tt.existingData, tt.expectedError) -// if tt.expectedError == nil && len(tt.input) > 0 { -// mockFileHandler.On("WriteAccountData", mock.MatchedBy(func(data map[string]string) bool { -// return data["Offerings"] == string(tt.input) -// })).Return(tt.writeError) -// } else if len(tt.input) != 4 { -// // For input whose input is not a valid yob, no WriteAccountData call should be made -// mockFileHandler.On("WriteAccountData", mock.Anything).Maybe().Return(tt.writeError) -// return -// } - -// // Create the Handlers instance with the mock file handler -// h := &Handlers{ -// accountFileHandler: mockFileHandler, -// } - -// // Call save yob -// result, err := h.SaveOfferings(context.Background(), "save_offerings", tt.input) - -// if err != nil { -// t.Fatalf("Failed to save offerings with error: %v", err) -// } -// savedData, err := h.accountFileHandler.ReadAccountData() -// if err == nil { -// //Assert that the input provided is what was saved into the file -// assert.Equal(t, string(tt.input), savedData["Offerings"]) -// } - -// // Assert the results -// assert.Equal(t, tt.expectedResult, result) -// assert.Equal(t, tt.expectedError, err) - -// // Assert all expectations were met -// mockFileHandler.AssertExpectations(t) -// }) -// } -// } - -// func TestSaveGender(t *testing.T) { -// // Create a new instance of MockAccountFileHandler -// mockFileHandler := new(mocks.MockAccountFileHandler) - -// // Define test cases -// tests := []struct { -// name string -// input []byte -// existingData map[string]string -// writeError error -// expectedResult resource.Result -// expectedError error -// expectedGender string -// }{ -// { -// name: "Successful Save - Male", -// input: []byte("1"), -// existingData: map[string]string{"OtherKey": "OtherValue"}, -// writeError: nil, -// expectedResult: resource.Result{}, -// expectedError: nil, -// expectedGender: "Male", -// }, -// { -// name: "Successful Save - Female", -// input: []byte("2"), -// existingData: map[string]string{"OtherKey": "OtherValue"}, -// writeError: nil, -// expectedResult: resource.Result{}, -// expectedError: nil, -// expectedGender: "Female", -// }, -// { -// name: "Successful Save - Unspecified", -// input: []byte("3"), -// existingData: map[string]string{"OtherKey": "OtherValue"}, -// writeError: nil, -// expectedResult: resource.Result{}, -// expectedError: nil, -// expectedGender: "Unspecified", -// }, - -// { -// name: "Empty Input", -// input: []byte{}, -// existingData: map[string]string{"OtherKey": "OtherValue"}, -// writeError: nil, -// expectedResult: resource.Result{}, -// expectedError: nil, -// expectedGender: "", -// }, -// } - -// for _, tt := range tests { -// t.Run(tt.name, func(t *testing.T) { -// // Set up the mock expectations -// mockFileHandler.On("ReadAccountData").Return(tt.existingData, tt.expectedError) -// if tt.expectedError == nil && len(tt.input) > 0 { -// mockFileHandler.On("WriteAccountData", mock.MatchedBy(func(data map[string]string) bool { -// return data["Gender"] == tt.expectedGender -// })).Return(tt.writeError) -// } else if len(tt.input) == 0 { -// // For empty input, no WriteAccountData call should be made -// mockFileHandler.On("WriteAccountData", mock.Anything).Maybe().Return(tt.writeError) -// } - -// // Create the Handlers instance with the mock file handler -// h := &Handlers{ -// accountFileHandler: mockFileHandler, -// } - -// // Call the method -// result, err := h.SaveGender(context.Background(), "save_gender", tt.input) - -// // Assert the results -// assert.Equal(t, tt.expectedResult, result) -// assert.Equal(t, tt.expectedError, err) - -// // Verify WriteAccountData was called with the expected data -// if len(tt.input) > 0 && tt.expectedError == nil { -// mockFileHandler.AssertCalled(t, "WriteAccountData", mock.MatchedBy(func(data map[string]string) bool { -// return data["Gender"] == tt.expectedGender -// })) -// } - -// // Assert all expectations were met -// mockFileHandler.AssertExpectations(t) -// }) -// } -// } - -// func TestGetSender(t *testing.T) { -// mockAccountFileHandler := new(mocks.MockAccountFileHandler) -// h := &Handlers{ -// accountFileHandler: mockAccountFileHandler, -// } - -// tests := []struct { -// name string -// expectedResult resource.Result -// accountData map[string]string -// }{ -// { -// name: "Valid public key", -// expectedResult: resource.Result{ -// Content: "test-public-key", -// }, -// accountData: map[string]string{ -// "PublicKey": "test-public-key", -// }, -// }, -// { -// name: "Missing public key", -// expectedResult: resource.Result{ -// Content: "", -// }, -// accountData: map[string]string{}, -// }, -// } - -// for _, tt := range tests { -// t.Run(tt.name, func(t *testing.T) { -// // Reset the mock state -// mockAccountFileHandler.Mock = mock.Mock{} - -// mockAccountFileHandler.On("ReadAccountData").Return(tt.accountData, nil) - -// result, err := h.GetSender(context.Background(), "", nil) - -// if err != nil { -// t.Fatalf("Error occurred: %v", err) -// } - -// assert.Equal(t, tt.expectedResult.Content, result.Content) -// mockAccountFileHandler.AssertCalled(t, "ReadAccountData") -// }) -// } -// } - -// func TestGetAmount(t *testing.T) { -// mockAccountFileHandler := new(mocks.MockAccountFileHandler) -// h := &Handlers{ -// accountFileHandler: mockAccountFileHandler, -// } - -// tests := []struct { -// name string -// expectedResult resource.Result -// accountData map[string]string -// }{ -// { -// name: "Valid amount", -// expectedResult: resource.Result{ -// Content: "0.003", -// }, -// accountData: map[string]string{ -// "Amount": "0.003", -// }, -// }, -// { -// name: "Missing amount", -// expectedResult: resource.Result{}, -// accountData: map[string]string{ -// "Amount": "", -// }, -// }, -// } - -// for _, tt := range tests { -// t.Run(tt.name, func(t *testing.T) { -// // Reset the mock state -// mockAccountFileHandler.Mock = mock.Mock{} - -// mockAccountFileHandler.On("ReadAccountData").Return(tt.accountData, nil) - -// result, err := h.GetAmount(context.Background(), "", nil) - -// assert.NoError(t, err) -// assert.Equal(t, tt.expectedResult.Content, result.Content) - -// mockAccountFileHandler.AssertCalled(t, "ReadAccountData") -// }) -// } -// } - -// func TestGetProfileInfo(t *testing.T) { -// tests := []struct { -// name string -// accountData map[string]string -// readError error -// expectedResult resource.Result -// expectedError error -// }{ -// { -// name: "Complete Profile", -// accountData: map[string]string{ -// "FirstName": "John", -// "FamilyName": "Doe", -// "Gender": "Male", -// "YOB": "1980", -// "Location": "Mombasa", -// "Offerings": "Product A", -// }, -// readError: nil, -// expectedResult: resource.Result{ -// Content: fmt.Sprintf( -// "Name: %s %s\nGender: %s\nAge: %d\nLocation: %s\nYou provide: %s\n", -// "John", "Doe", "Male", 44, "Mombasa", "Product A", -// ), -// }, -// expectedError: nil, -// }, -// { -// name: "Profile with Not Provided Fields", -// accountData: map[string]string{ -// "FirstName": "Not provided", -// "FamilyName": "Doe", -// "Gender": "Female", -// "YOB": "1995", -// "Location": "Not provided", -// "Offerings": "Service B", -// }, -// readError: nil, -// expectedResult: resource.Result{ -// Content: fmt.Sprintf( -// "Name: %s\nGender: %s\nAge: %d\nLocation: %s\nYou provide: %s\n", -// "Not provided", "Female", 29, "Not provided", "Service B", -// ), -// }, -// expectedError: nil, -// }, -// { -// name: "Profile with YOB as Not provided", -// accountData: map[string]string{ -// "FirstName": "Not provided", -// "FamilyName": "Doe", -// "Gender": "Female", -// "YOB": "Not provided", -// "Location": "Not provided", -// "Offerings": "Service B", -// }, -// readError: nil, -// expectedResult: resource.Result{ -// Content: fmt.Sprintf( -// "Name: %s\nGender: %s\nAge: %s\nLocation: %s\nYou provide: %s\n", -// "Not provided", "Female", "Not provided", "Not provided", "Service B", -// ), -// }, -// expectedError: nil, -// }, -// } - -// for _, tt := range tests { -// t.Run(tt.name, func(t *testing.T) { -// // Create a new instance of MockAccountFileHandler -// mockFileHandler := new(mocks.MockAccountFileHandler) - -// // Set up the mock expectations -// mockFileHandler.On("ReadAccountData").Return(tt.accountData, tt.readError) - -// // Create the Handlers instance with the mock file handler -// h := &Handlers{ -// accountFileHandler: mockFileHandler, -// } - -// // Call the method -// result, err := h.GetProfileInfo(context.Background(), "get_profile_info", nil) - -// // Assert the results -// assert.Equal(t, tt.expectedResult, result) -// assert.Equal(t, tt.expectedError, err) - -// // Assert all expectations were met -// mockFileHandler.AssertExpectations(t) -// }) -// } -// } From 01c13ec581b029add5bcb6eb432d84f9e4897a55 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Sat, 7 Sep 2024 16:25:29 +0300 Subject: [PATCH 197/201] make packKey accessible from tests --- internal/utils/db.go | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/internal/utils/db.go b/internal/utils/db.go index 32fb804..5b128f6 100644 --- a/internal/utils/db.go +++ b/internal/utils/db.go @@ -33,15 +33,16 @@ func typToBytes(typ DataTyp) []byte { return b[:] } -func packKey(typ DataTyp, data []byte) []byte { +func PackKey(typ DataTyp, data []byte) []byte { v := typToBytes(typ) return append(v, data...) } func ReadEntry(ctx context.Context, store db.Db, sessionId string, typ DataTyp) ([]byte, error) { + store.SetPrefix(db.DATATYPE_USERDATA) store.SetSession(sessionId) - k := packKey(typ, []byte(sessionId)) + k := PackKey(typ, []byte(sessionId)) b, err := store.Get(ctx, k) if err != nil { return nil, err @@ -52,6 +53,6 @@ func ReadEntry(ctx context.Context, store db.Db, sessionId string, typ DataTyp) func WriteEntry(ctx context.Context, store db.Db, sessionId string, typ DataTyp, value []byte) error { store.SetPrefix(db.DATATYPE_USERDATA) store.SetSession(sessionId) - k := packKey(typ, []byte(sessionId)) + k := PackKey(typ, []byte(sessionId)) return store.Put(ctx, k, value) } From e14fd5e496d7efe1660994bbe6e0dd260a146d51 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Sat, 7 Sep 2024 17:41:05 +0300 Subject: [PATCH 198/201] Return the response and the error --- internal/handlers/ussd/menuhandler.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 27af8f4..066eef2 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -203,7 +203,7 @@ func (h *Handlers) SavePin(ctx context.Context, sym string, input []byte) (resou err = utils.WriteEntry(ctx, h.userdataStore, sessionId, utils.DATA_ACCOUNT_PIN, []byte(accountPIN)) if err != nil { - return res, nil + return res, err } return res, nil From deb4706b1d05f3670172ba64992696565c042eb4 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Sat, 7 Sep 2024 17:51:30 +0300 Subject: [PATCH 199/201] Test commit --- internal/handlers/ussd/menuhandler_test.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/internal/handlers/ussd/menuhandler_test.go b/internal/handlers/ussd/menuhandler_test.go index 4ab3046..4f26e12 100644 --- a/internal/handlers/ussd/menuhandler_test.go +++ b/internal/handlers/ussd/menuhandler_test.go @@ -165,3 +165,7 @@ func TestSaveFamilyname(t *testing.T) { }) } } + +func testSavePin () { + +} \ No newline at end of file From 6d02ea79ecdf25d277f5b930577bf3fdb3d519f7 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Sat, 7 Sep 2024 18:09:13 +0300 Subject: [PATCH 200/201] add go-vise --- go.sum | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/go.sum b/go.sum index f203383..2624d07 100644 --- a/go.sum +++ b/go.sum @@ -1,2 +1,36 @@ +git.defalsify.org/vise.git v0.1.0-rc.1.0.20240906020635-400f69d01a89 h1:YyQODhMwSM5YD9yKHM5jCF0HC0RQtE3MkVXcTnOhXJo= +git.defalsify.org/vise.git v0.1.0-rc.1.0.20240906020635-400f69d01a89/go.mod h1:JDguWmcoWBdsnpw7PUjVZAEpdC/ubBmjdUBy3tjP63M= +github.com/alecthomas/assert/v2 v2.2.2 h1:Z/iVC0xZfWTaFNE6bA3z07T86hd45Xe2eLt6WVy2bbk= +github.com/alecthomas/assert/v2 v2.2.2/go.mod h1:pXcQ2Asjp247dahGEmsZ6ru0UVwnkhktn7S0bBDLxvQ= +github.com/alecthomas/participle/v2 v2.0.0 h1:Fgrq+MbuSsJwIkw3fEj9h75vDP0Er5JzepJ0/HNHv0g= +github.com/alecthomas/participle/v2 v2.0.0/go.mod h1:rAKZdJldHu8084ojcWevWAL8KmEU+AT+Olodb+WoN2Y= +github.com/alecthomas/repr v0.2.0 h1:HAzS41CIzNW5syS8Mf9UwXhNH1J9aix/BvDRf1Ml2Yk= +github.com/alecthomas/repr v0.2.0/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4= +github.com/barbashov/iso639-3 v0.0.0-20211020172741-1f4ffb2d8d1c h1:H9Nm+I7Cg/YVPpEV1RzU3Wq2pjamPc/UtHDgItcb7lE= +github.com/barbashov/iso639-3 v0.0.0-20211020172741-1f4ffb2d8d1c/go.mod h1:rGod7o6KPeJ+hyBpHfhi4v7blx9sf+QsHsA7KAsdN6U= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/fxamacker/cbor/v2 v2.4.0 h1:ri0ArlOR+5XunOP8CRUowT0pSJOwhW098ZCUyskZD88= +github.com/fxamacker/cbor/v2 v2.4.0/go.mod h1:TA1xS00nchWmaBnEIxPSE5oHLuJBAVvqrtAnWBwBCVo= +github.com/graygnuorg/go-gdbm v0.0.0-20220711140707-71387d66dce4 h1:U4kkNYryi/qfbBF8gh7Vsbuz+cVmhf5kt6pE9bYYyLo= +github.com/graygnuorg/go-gdbm v0.0.0-20220711140707-71387d66dce4/go.mod h1:zpZDgZFzeq9s0MIeB1P50NIEWDFFHSFBohI/NbaTD/Y= +github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM= +github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg= +github.com/mattn/kinako v0.0.0-20170717041458-332c0a7e205a h1:0Q3H0YXzMHiciXtRcM+j0jiCe8WKPQHoRgQiRTnfcLY= +github.com/mattn/kinako v0.0.0-20170717041458-332c0a7e205a/go.mod h1:CdTTBOYzS5E4mWS1N8NWP6AHI19MP0A2B18n3hLzRMk= +github.com/peteole/testdata-loader v0.3.0 h1:8jckE9KcyNHgyv/VPoaljvKZE0Rqr8+dPVYH6rfNr9I= +github.com/peteole/testdata-loader v0.3.0/go.mod h1:Mt0ZbRtb56u8SLJpNP+BnQbENljMorYBpqlvt3cS83U= +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.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= +github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/leonelquinteros/gotext.v1 v1.3.1 h1:8d9/fdTG0kn/B7NNGV1BsEyvektXFAbkMsTZS2sFSCc= +gopkg.in/leonelquinteros/gotext.v1 v1.3.1/go.mod h1:X1WlGDeAFIYsW6GjgMm4VwUwZ2XjI7Zan2InxSUQWrU= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= From 16a56ef29d1a5db62e4c0980a517d04e1292fdc2 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Sat, 7 Sep 2024 18:09:55 +0300 Subject: [PATCH 201/201] add go-vise --- go.mod | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/go.mod b/go.mod index de33912..e2aff05 100644 --- a/go.mod +++ b/go.mod @@ -2,4 +2,24 @@ module git.grassecon.net/urdt/ussd go 1.22.6 -require github.com/stretchr/testify v1.9.0 // indirect +require ( + github.com/alecthomas/participle/v2 v2.0.0 // indirect + github.com/alecthomas/repr v0.2.0 // indirect + github.com/barbashov/iso639-3 v0.0.0-20211020172741-1f4ffb2d8d1c // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/fxamacker/cbor/v2 v2.4.0 // indirect + github.com/graygnuorg/go-gdbm v0.0.0-20220711140707-71387d66dce4 // indirect + github.com/hexops/gotextdiff v1.0.3 // indirect + github.com/mattn/kinako v0.0.0-20170717041458-332c0a7e205a // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/stretchr/objx v0.5.2 // indirect + github.com/stretchr/testify v1.9.0 + github.com/x448/float16 v0.8.4 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) + +require ( + git.defalsify.org/vise.git v0.1.0-rc.1.0.20240906020635-400f69d01a89 + github.com/alecthomas/assert/v2 v2.2.2 + gopkg.in/leonelquinteros/gotext.v1 v1.3.1 +)