Compare commits
88 Commits
go-vise-0.
...
menu-api-e
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0be570ae2d
|
||
|
|
6a36bc43b5
|
||
|
|
1d27a88908
|
||
|
|
4889e6d18b
|
||
|
|
368c25125a
|
||
|
|
283793a2ae
|
||
|
|
bec7e5c69f
|
||
|
|
d638aba85e
|
||
|
|
df7788dd0b
|
||
|
|
4a62773098
|
||
|
|
26d315b032
|
||
|
|
1927544533
|
||
|
|
c641a0c669
|
||
|
|
952da86931
|
||
|
|
be6391686f
|
||
|
|
65794c1b20
|
||
| b058f9d770 | |||
|
|
2a93ea7a0c
|
||
|
|
f89b1acc6c | ||
| ddeafe015b | |||
|
|
1dc8b054eb
|
||
|
|
a3ff3be5b1
|
||
|
|
ea52a7cf0a
|
||
|
|
a993026380
|
||
|
|
4ee241714b
|
||
|
|
d7dc743fa2 | ||
|
|
c220cbb767
|
||
| 0dc322729f | |||
| 726d6dd338 | |||
| a8b202bd79 | |||
|
|
6dbd250694
|
||
|
|
cc760e7698
|
||
|
|
8648ea599c
|
||
|
|
77e4c5d43a
|
||
|
|
b15ba367c4
|
||
|
|
4db862bc97
|
||
|
|
6ad67f6adc
|
||
| 0caf82a27e | |||
| a430857309 | |||
|
|
2643c0c9ff
|
||
|
|
b8852e1ab3
|
||
|
|
0dea34daab
|
||
|
|
8057313c78
|
||
|
|
1bd96d0689
|
||
|
|
bbfe46f162
|
||
|
|
eff2cbde8b
|
||
|
|
5c85ecffd1
|
||
|
|
ad1f9233ca | ||
| e9fdd1ddbe | |||
|
|
8a03b05c90
|
||
|
|
c18c40b1b8 | ||
|
|
5a38b40eaf | ||
|
|
6112ca175f | ||
|
|
c7ebca4729
|
||
|
|
fa0070b9a8
|
||
|
|
4a447fbb45
|
||
|
|
cb32cfe9d8
|
||
|
|
cf4e80dcb8
|
||
|
|
c02d70eaa4
|
||
|
|
909d1f3409
|
||
|
|
66cf90f044
|
||
|
|
74d5da3987 | ||
|
|
f215159725
|
||
|
|
a6301163eb
|
||
|
|
a07fce527f | ||
|
|
8a5209584d
|
||
|
|
ddc8f6dad1
|
||
|
|
c2b68231f5
|
||
|
|
3f3dbf414c
|
||
|
|
e4c3e9f015
|
||
|
|
9b71244391 | ||
|
|
ada1f26b68
|
||
|
|
935b777e57
|
||
|
|
7d3ff690f0
|
||
|
|
a455cfb854
|
||
|
|
19372c17f4
|
||
|
|
1cc2f58ab3
|
||
|
|
3756bdc98a | ||
|
|
e07f88b368
|
||
| 472624a831 | |||
|
|
84422684c5
|
||
|
|
28fc7a0462
|
||
|
|
78d349ccc7
|
||
|
|
0813a619b4
|
||
|
|
5ed9d2643b
|
||
|
|
8dcba67fe9
|
||
|
|
5cac17676a
|
||
| 4439cc249a |
2
.gitignore
vendored
2
.gitignore
vendored
@@ -4,3 +4,5 @@ go.work*
|
||||
**/*/*.bin
|
||||
**/*/.state/
|
||||
cmd/.state/
|
||||
id_*
|
||||
*.gdbm
|
||||
|
||||
@@ -69,13 +69,11 @@ func main() {
|
||||
var resourceDir string
|
||||
var size uint
|
||||
var engineDebug bool
|
||||
var stateDebug bool
|
||||
var host string
|
||||
var port uint
|
||||
flag.StringVar(&dbDir, "dbdir", ".state", "database dir to read from")
|
||||
flag.StringVar(&resourceDir, "resourcedir", path.Join("services", "registration"), "resource dir")
|
||||
flag.BoolVar(&engineDebug, "engine-debug", false, "use engine debug output")
|
||||
flag.BoolVar(&stateDebug, "state-debug", false, "use engine debug output")
|
||||
flag.BoolVar(&engineDebug, "d", false, "use engine debug output")
|
||||
flag.UintVar(&size, "s", 160, "max size of output")
|
||||
flag.StringVar(&host, "h", "127.0.0.1", "http host")
|
||||
flag.UintVar(&port, "p", 7123, "http port")
|
||||
@@ -89,30 +87,27 @@ func main() {
|
||||
cfg := engine.Config{
|
||||
Root: "root",
|
||||
OutputSize: uint32(size),
|
||||
FlagCount: uint32(16),
|
||||
}
|
||||
if stateDebug {
|
||||
cfg.StateDebug = true
|
||||
FlagCount: uint32(128),
|
||||
}
|
||||
|
||||
if engineDebug {
|
||||
cfg.EngineDebug = true
|
||||
}
|
||||
|
||||
menuStorageService := storage.MenuStorageService{}
|
||||
|
||||
rs, err := menuStorageService.GetResource(scriptDir, ctx)
|
||||
menuStorageService := storage.NewMenuStorageService(dbDir, resourceDir)
|
||||
rs, err := menuStorageService.GetResource(ctx)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, err.Error())
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
err = menuStorageService.EnsureDbDir(dbDir)
|
||||
err = menuStorageService.EnsureDbDir()
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, err.Error())
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
userdataStore := menuStorageService.GetUserdataDb(dbDir, ctx)
|
||||
userdataStore, err := menuStorageService.GetUserdataDb(ctx)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, err.Error())
|
||||
os.Exit(1)
|
||||
@@ -125,7 +120,7 @@ func main() {
|
||||
}
|
||||
|
||||
lhs, err := handlers.NewLocalHandlerService(pfp, true, dbResource, cfg, rs)
|
||||
lhs.WithDataStore(&userdataStore)
|
||||
lhs.SetDataStore(&userdataStore)
|
||||
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, err.Error())
|
||||
@@ -138,7 +133,7 @@ func main() {
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
stateStore, err := menuStorageService.GetStateStore(dbDir, ctx)
|
||||
stateStore, err := menuStorageService.GetStateStore(ctx)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, err.Error())
|
||||
os.Exit(1)
|
||||
|
||||
@@ -41,14 +41,12 @@ func main() {
|
||||
var resourceDir string
|
||||
var size uint
|
||||
var engineDebug bool
|
||||
var stateDebug bool
|
||||
var host string
|
||||
var port uint
|
||||
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(&engineDebug, "engine-debug", false, "use engine debug output")
|
||||
flag.BoolVar(&stateDebug, "state-debug", false, "use engine debug output")
|
||||
flag.BoolVar(&engineDebug, "d", false, "use engine debug output")
|
||||
flag.UintVar(&size, "s", 160, "max size of output")
|
||||
flag.StringVar(&host, "h", "127.0.0.1", "http host")
|
||||
flag.UintVar(&port, "p", 7123, "http port")
|
||||
@@ -62,29 +60,27 @@ func main() {
|
||||
cfg := engine.Config{
|
||||
Root: "root",
|
||||
OutputSize: uint32(size),
|
||||
FlagCount: uint32(16),
|
||||
}
|
||||
if stateDebug {
|
||||
cfg.StateDebug = true
|
||||
FlagCount: uint32(128),
|
||||
}
|
||||
|
||||
if engineDebug {
|
||||
cfg.EngineDebug = true
|
||||
}
|
||||
|
||||
menuStorageService := storage.MenuStorageService{}
|
||||
rs, err := menuStorageService.GetResource(scriptDir, ctx)
|
||||
menuStorageService := storage.NewMenuStorageService(dbDir, resourceDir)
|
||||
rs, err := menuStorageService.GetResource(ctx)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, err.Error())
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
err = menuStorageService.EnsureDbDir(dbDir)
|
||||
err = menuStorageService.EnsureDbDir()
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, err.Error())
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
userdataStore := menuStorageService.GetUserdataDb(dbDir, ctx)
|
||||
userdataStore, err := menuStorageService.GetUserdataDb(ctx)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, err.Error())
|
||||
os.Exit(1)
|
||||
@@ -97,7 +93,7 @@ func main() {
|
||||
}
|
||||
|
||||
lhs, err := handlers.NewLocalHandlerService(pfp, true, dbResource, cfg, rs)
|
||||
lhs.WithDataStore(&userdataStore)
|
||||
lhs.SetDataStore(&userdataStore)
|
||||
|
||||
hl, err := lhs.GetHandler()
|
||||
if err != nil {
|
||||
@@ -105,7 +101,7 @@ func main() {
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
stateStore, err := menuStorageService.GetStateStore(dbDir, ctx)
|
||||
stateStore, err := menuStorageService.GetStateStore(ctx)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, err.Error())
|
||||
os.Exit(1)
|
||||
@@ -138,22 +134,26 @@ func main() {
|
||||
for true {
|
||||
rqs, err = sh.Process(rqs)
|
||||
if err != nil {
|
||||
logg.ErrorCtxf(ctx, "error in process: %v", "err", err)
|
||||
fmt.Errorf("error in process: %v", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
rqs, err = sh.Output(rqs)
|
||||
if err != nil {
|
||||
logg.ErrorCtxf(ctx, "error in output: %v", "err", err)
|
||||
fmt.Errorf("error in output: %v", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
rqs, err = sh.Reset(rqs)
|
||||
if err != nil {
|
||||
logg.ErrorCtxf(ctx, "error in reset: %v", "err", err)
|
||||
fmt.Errorf("error in reset: %v", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
fmt.Println("")
|
||||
_, err = fmt.Scanln(&rqs.Input)
|
||||
if err != nil {
|
||||
logg.ErrorCtxf(ctx, "error in input", "err", err)
|
||||
fmt.Errorf("error in input: %v", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
@@ -30,13 +30,11 @@ func main() {
|
||||
var resourceDir string
|
||||
var size uint
|
||||
var engineDebug bool
|
||||
var stateDebug bool
|
||||
var host string
|
||||
var port uint
|
||||
flag.StringVar(&dbDir, "dbdir", ".state", "database dir to read from")
|
||||
flag.StringVar(&resourceDir, "resourcedir", path.Join("services", "registration"), "resource dir")
|
||||
flag.BoolVar(&engineDebug, "engine-debug", false, "use engine debug output")
|
||||
flag.BoolVar(&stateDebug, "state-debug", false, "use engine debug output")
|
||||
flag.BoolVar(&engineDebug, "d", false, "use engine debug output")
|
||||
flag.UintVar(&size, "s", 160, "max size of output")
|
||||
flag.StringVar(&host, "h", "127.0.0.1", "http host")
|
||||
flag.UintVar(&port, "p", 7123, "http port")
|
||||
@@ -50,29 +48,27 @@ func main() {
|
||||
cfg := engine.Config{
|
||||
Root: "root",
|
||||
OutputSize: uint32(size),
|
||||
FlagCount: uint32(16),
|
||||
}
|
||||
if stateDebug {
|
||||
cfg.StateDebug = true
|
||||
FlagCount: uint32(128),
|
||||
}
|
||||
|
||||
if engineDebug {
|
||||
cfg.EngineDebug = true
|
||||
}
|
||||
|
||||
menuStorageService := storage.MenuStorageService{}
|
||||
rs, err := menuStorageService.GetResource(scriptDir, ctx)
|
||||
menuStorageService := storage.NewMenuStorageService(dbDir, resourceDir)
|
||||
rs, err := menuStorageService.GetResource(ctx)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, err.Error())
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
err = menuStorageService.EnsureDbDir(dbDir)
|
||||
err = menuStorageService.EnsureDbDir()
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, err.Error())
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
userdataStore := menuStorageService.GetUserdataDb(dbDir, ctx)
|
||||
userdataStore, err := menuStorageService.GetUserdataDb(ctx)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, err.Error())
|
||||
os.Exit(1)
|
||||
@@ -85,7 +81,7 @@ func main() {
|
||||
}
|
||||
|
||||
lhs, err := handlers.NewLocalHandlerService(pfp, true, dbResource, cfg, rs)
|
||||
lhs.WithDataStore(&userdataStore)
|
||||
lhs.SetDataStore(&userdataStore)
|
||||
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, err.Error())
|
||||
@@ -98,7 +94,7 @@ func main() {
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
stateStore, err := menuStorageService.GetStateStore(dbDir, ctx)
|
||||
stateStore, err := menuStorageService.GetStateStore(ctx)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, err.Error())
|
||||
os.Exit(1)
|
||||
|
||||
23
cmd/main.go
23
cmd/main.go
@@ -23,10 +23,10 @@ func main() {
|
||||
var dbDir string
|
||||
var size uint
|
||||
var sessionId string
|
||||
var debug bool
|
||||
var engineDebug bool
|
||||
flag.StringVar(&sessionId, "session-id", "075xx2123", "session id")
|
||||
flag.StringVar(&dbDir, "dbdir", ".state", "database dir to read from")
|
||||
flag.BoolVar(&debug, "d", false, "use engine debug output")
|
||||
flag.BoolVar(&engineDebug, "d", false, "use engine debug output")
|
||||
flag.UintVar(&size, "s", 160, "max size of output")
|
||||
flag.Parse()
|
||||
|
||||
@@ -40,30 +40,31 @@ func main() {
|
||||
Root: "root",
|
||||
SessionId: sessionId,
|
||||
OutputSize: uint32(size),
|
||||
FlagCount: uint32(16),
|
||||
FlagCount: uint32(128),
|
||||
}
|
||||
|
||||
menuStorageService := storage.MenuStorageService{}
|
||||
resourceDir := scriptDir
|
||||
menuStorageService := storage.NewMenuStorageService(dbDir, resourceDir)
|
||||
|
||||
err := menuStorageService.EnsureDbDir(dbDir)
|
||||
err := menuStorageService.EnsureDbDir()
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, err.Error())
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
rs, err := menuStorageService.GetResource(scriptDir, ctx)
|
||||
rs, err := menuStorageService.GetResource(ctx)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, err.Error())
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
pe, err := menuStorageService.GetPersister(dbDir, ctx)
|
||||
pe, err := menuStorageService.GetPersister(ctx)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, err.Error())
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
userdatastore := menuStorageService.GetUserdataDb(dbDir, ctx)
|
||||
userdatastore, err := menuStorageService.GetUserdataDb(ctx)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, err.Error())
|
||||
os.Exit(1)
|
||||
@@ -76,8 +77,8 @@ func main() {
|
||||
}
|
||||
|
||||
lhs, err := handlers.NewLocalHandlerService(pfp, true, dbResource, cfg, rs)
|
||||
lhs.WithDataStore(&userdatastore)
|
||||
lhs.WithPersister(pe)
|
||||
lhs.SetDataStore(&userdatastore)
|
||||
lhs.SetPersister(pe)
|
||||
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, err.Error())
|
||||
@@ -92,7 +93,7 @@ func main() {
|
||||
|
||||
en := lhs.GetEngine()
|
||||
en = en.WithFirst(hl.Init)
|
||||
if debug {
|
||||
if engineDebug {
|
||||
en = en.WithDebug(nil)
|
||||
}
|
||||
|
||||
|
||||
2
go.mod
2
go.mod
@@ -3,7 +3,7 @@ module git.grassecon.net/urdt/ussd
|
||||
go 1.22.6
|
||||
|
||||
require (
|
||||
git.defalsify.org/vise.git v0.1.0-rc.3.0.20240920144308-b2d2c5f18f38
|
||||
git.defalsify.org/vise.git v0.1.0-rc.3.0.20240923162317-c20d557a3dbb
|
||||
github.com/alecthomas/assert/v2 v2.2.2
|
||||
github.com/peteole/testdata-loader v0.3.0
|
||||
gopkg.in/leonelquinteros/gotext.v1 v1.3.1
|
||||
|
||||
8
go.sum
8
go.sum
@@ -1,9 +1,5 @@
|
||||
git.defalsify.org/vise.git v0.1.0-rc.3.0.20240911231817-0d23e0dbb57f h1:CuJvG3NyMoRtHUim4aZdrfjjJBg2AId7z0yp7Q97bRM=
|
||||
git.defalsify.org/vise.git v0.1.0-rc.3.0.20240911231817-0d23e0dbb57f/go.mod h1:JDguWmcoWBdsnpw7PUjVZAEpdC/ubBmjdUBy3tjP63M=
|
||||
git.defalsify.org/vise.git v0.1.0-rc.3.0.20240914163514-577f56f43bea h1:6ZYT+dIjd/f5vn9y5AJDZ7SQQckA6w5ZfUoKygyI11o=
|
||||
git.defalsify.org/vise.git v0.1.0-rc.3.0.20240914163514-577f56f43bea/go.mod h1:JDguWmcoWBdsnpw7PUjVZAEpdC/ubBmjdUBy3tjP63M=
|
||||
git.defalsify.org/vise.git v0.1.0-rc.3.0.20240920144308-b2d2c5f18f38 h1:4aAZijIcq33ixnZ+U48ckDIkwSfZL3St/CqoXZcC5K8=
|
||||
git.defalsify.org/vise.git v0.1.0-rc.3.0.20240920144308-b2d2c5f18f38/go.mod h1:JDguWmcoWBdsnpw7PUjVZAEpdC/ubBmjdUBy3tjP63M=
|
||||
git.defalsify.org/vise.git v0.1.0-rc.3.0.20240923162317-c20d557a3dbb h1:6P4kxihcwMjDKzvUFC6t2zGNb7MDW+l/ACGlSAN1N8Y=
|
||||
git.defalsify.org/vise.git v0.1.0-rc.3.0.20240923162317-c20d557a3dbb/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=
|
||||
|
||||
@@ -46,7 +46,7 @@ func(f *BaseSessionHandler) Process(rqs RequestSession) (RequestSession, error)
|
||||
var err error
|
||||
var ok bool
|
||||
|
||||
logg.InfoCtxf(rqs.Ctx, "new request", rqs)
|
||||
logg.InfoCtxf(rqs.Ctx, "new request", "data", rqs)
|
||||
|
||||
rqs.Storage, err = f.provider.Get(rqs.Config.SessionId)
|
||||
if err != nil {
|
||||
|
||||
@@ -44,62 +44,62 @@ func NewLocalHandlerService(fp string, debug bool, dbResource *resource.DbResour
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (localHandlerService *LocalHandlerService) WithPersister(Pe *persist.Persister) {
|
||||
localHandlerService.Pe = Pe
|
||||
func (ls *LocalHandlerService) SetPersister(Pe *persist.Persister) {
|
||||
ls.Pe = Pe
|
||||
}
|
||||
|
||||
func (localHandlerService *LocalHandlerService) WithDataStore(db *db.Db) {
|
||||
localHandlerService.UserdataStore = db
|
||||
func (ls *LocalHandlerService) SetDataStore(db *db.Db) {
|
||||
ls.UserdataStore = db
|
||||
}
|
||||
|
||||
func (localHandlerService *LocalHandlerService) GetHandler() (*ussd.Handlers, error) {
|
||||
ussdHandlers, err := ussd.NewHandlers(localHandlerService.Parser, *localHandlerService.UserdataStore)
|
||||
func (ls *LocalHandlerService) GetHandler() (*ussd.Handlers, error) {
|
||||
ussdHandlers, err := ussd.NewHandlers(ls.Parser, *ls.UserdataStore)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ussdHandlers = ussdHandlers.WithPersister(localHandlerService.Pe)
|
||||
localHandlerService.DbRs.AddLocalFunc("set_language", ussdHandlers.SetLanguage)
|
||||
localHandlerService.DbRs.AddLocalFunc("create_account", ussdHandlers.CreateAccount)
|
||||
localHandlerService.DbRs.AddLocalFunc("save_pin", ussdHandlers.SavePin)
|
||||
localHandlerService.DbRs.AddLocalFunc("verify_pin", ussdHandlers.VerifyPin)
|
||||
localHandlerService.DbRs.AddLocalFunc("check_identifier", ussdHandlers.CheckIdentifier)
|
||||
localHandlerService.DbRs.AddLocalFunc("check_account_status", ussdHandlers.CheckAccountStatus)
|
||||
localHandlerService.DbRs.AddLocalFunc("authorize_account", ussdHandlers.Authorize)
|
||||
localHandlerService.DbRs.AddLocalFunc("quit", ussdHandlers.Quit)
|
||||
localHandlerService.DbRs.AddLocalFunc("check_balance", ussdHandlers.CheckBalance)
|
||||
localHandlerService.DbRs.AddLocalFunc("validate_recipient", ussdHandlers.ValidateRecipient)
|
||||
localHandlerService.DbRs.AddLocalFunc("transaction_reset", ussdHandlers.TransactionReset)
|
||||
localHandlerService.DbRs.AddLocalFunc("max_amount", ussdHandlers.MaxAmount)
|
||||
localHandlerService.DbRs.AddLocalFunc("validate_amount", ussdHandlers.ValidateAmount)
|
||||
localHandlerService.DbRs.AddLocalFunc("reset_transaction_amount", ussdHandlers.ResetTransactionAmount)
|
||||
localHandlerService.DbRs.AddLocalFunc("get_recipient", ussdHandlers.GetRecipient)
|
||||
localHandlerService.DbRs.AddLocalFunc("get_sender", ussdHandlers.GetSender)
|
||||
localHandlerService.DbRs.AddLocalFunc("get_amount", ussdHandlers.GetAmount)
|
||||
localHandlerService.DbRs.AddLocalFunc("reset_incorrect", ussdHandlers.ResetIncorrectPin)
|
||||
localHandlerService.DbRs.AddLocalFunc("save_firstname", ussdHandlers.SaveFirstname)
|
||||
localHandlerService.DbRs.AddLocalFunc("save_familyname", ussdHandlers.SaveFamilyname)
|
||||
localHandlerService.DbRs.AddLocalFunc("save_gender", ussdHandlers.SaveGender)
|
||||
localHandlerService.DbRs.AddLocalFunc("save_location", ussdHandlers.SaveLocation)
|
||||
localHandlerService.DbRs.AddLocalFunc("save_yob", ussdHandlers.SaveYob)
|
||||
localHandlerService.DbRs.AddLocalFunc("save_offerings", ussdHandlers.SaveOfferings)
|
||||
localHandlerService.DbRs.AddLocalFunc("quit_with_balance", ussdHandlers.QuitWithBalance)
|
||||
localHandlerService.DbRs.AddLocalFunc("reset_account_authorized", ussdHandlers.ResetAccountAuthorized)
|
||||
localHandlerService.DbRs.AddLocalFunc("reset_allow_update", ussdHandlers.ResetAllowUpdate)
|
||||
localHandlerService.DbRs.AddLocalFunc("get_profile_info", ussdHandlers.GetProfileInfo)
|
||||
localHandlerService.DbRs.AddLocalFunc("verify_yob", ussdHandlers.VerifyYob)
|
||||
localHandlerService.DbRs.AddLocalFunc("reset_incorrect_date_format", ussdHandlers.ResetIncorrectYob)
|
||||
localHandlerService.DbRs.AddLocalFunc("set_reset_single_edit", ussdHandlers.SetResetSingleEdit)
|
||||
localHandlerService.DbRs.AddLocalFunc("initiate_transaction", ussdHandlers.InitiateTransaction)
|
||||
localHandlerService.DbRs.AddLocalFunc("save_temporary_pin", ussdHandlers.SaveTemporaryPin)
|
||||
localHandlerService.DbRs.AddLocalFunc("verify_new_pin", ussdHandlers.VerifyNewPin)
|
||||
localHandlerService.DbRs.AddLocalFunc("confirm_pin_change", ussdHandlers.ConfirmPinChange)
|
||||
localHandlerService.DbRs.AddLocalFunc("quit_with_help", ussdHandlers.QuitWithHelp)
|
||||
ussdHandlers = ussdHandlers.WithPersister(ls.Pe)
|
||||
ls.DbRs.AddLocalFunc("set_language", ussdHandlers.SetLanguage)
|
||||
ls.DbRs.AddLocalFunc("create_account", ussdHandlers.CreateAccount)
|
||||
ls.DbRs.AddLocalFunc("save_pin", ussdHandlers.SavePin)
|
||||
ls.DbRs.AddLocalFunc("verify_pin", ussdHandlers.VerifyPin)
|
||||
ls.DbRs.AddLocalFunc("check_identifier", ussdHandlers.CheckIdentifier)
|
||||
ls.DbRs.AddLocalFunc("check_account_status", ussdHandlers.CheckAccountStatus)
|
||||
ls.DbRs.AddLocalFunc("authorize_account", ussdHandlers.Authorize)
|
||||
ls.DbRs.AddLocalFunc("quit", ussdHandlers.Quit)
|
||||
ls.DbRs.AddLocalFunc("check_balance", ussdHandlers.CheckBalance)
|
||||
ls.DbRs.AddLocalFunc("validate_recipient", ussdHandlers.ValidateRecipient)
|
||||
ls.DbRs.AddLocalFunc("transaction_reset", ussdHandlers.TransactionReset)
|
||||
ls.DbRs.AddLocalFunc("max_amount", ussdHandlers.MaxAmount)
|
||||
ls.DbRs.AddLocalFunc("validate_amount", ussdHandlers.ValidateAmount)
|
||||
ls.DbRs.AddLocalFunc("reset_transaction_amount", ussdHandlers.ResetTransactionAmount)
|
||||
ls.DbRs.AddLocalFunc("get_recipient", ussdHandlers.GetRecipient)
|
||||
ls.DbRs.AddLocalFunc("get_sender", ussdHandlers.GetSender)
|
||||
ls.DbRs.AddLocalFunc("get_amount", ussdHandlers.GetAmount)
|
||||
ls.DbRs.AddLocalFunc("reset_incorrect", ussdHandlers.ResetIncorrectPin)
|
||||
ls.DbRs.AddLocalFunc("save_firstname", ussdHandlers.SaveFirstname)
|
||||
ls.DbRs.AddLocalFunc("save_familyname", ussdHandlers.SaveFamilyname)
|
||||
ls.DbRs.AddLocalFunc("save_gender", ussdHandlers.SaveGender)
|
||||
ls.DbRs.AddLocalFunc("save_location", ussdHandlers.SaveLocation)
|
||||
ls.DbRs.AddLocalFunc("save_yob", ussdHandlers.SaveYob)
|
||||
ls.DbRs.AddLocalFunc("save_offerings", ussdHandlers.SaveOfferings)
|
||||
ls.DbRs.AddLocalFunc("reset_account_authorized", ussdHandlers.ResetAccountAuthorized)
|
||||
ls.DbRs.AddLocalFunc("reset_allow_update", ussdHandlers.ResetAllowUpdate)
|
||||
ls.DbRs.AddLocalFunc("get_profile_info", ussdHandlers.GetProfileInfo)
|
||||
ls.DbRs.AddLocalFunc("verify_yob", ussdHandlers.VerifyYob)
|
||||
ls.DbRs.AddLocalFunc("reset_incorrect_date_format", ussdHandlers.ResetIncorrectYob)
|
||||
ls.DbRs.AddLocalFunc("initiate_transaction", ussdHandlers.InitiateTransaction)
|
||||
ls.DbRs.AddLocalFunc("save_temporary_pin", ussdHandlers.SaveTemporaryPin)
|
||||
ls.DbRs.AddLocalFunc("verify_new_pin", ussdHandlers.VerifyNewPin)
|
||||
ls.DbRs.AddLocalFunc("confirm_pin_change", ussdHandlers.ConfirmPinChange)
|
||||
ls.DbRs.AddLocalFunc("quit_with_help", ussdHandlers.QuitWithHelp)
|
||||
ls.DbRs.AddLocalFunc("fetch_custodial_balances", ussdHandlers.FetchCustodialBalances)
|
||||
|
||||
return ussdHandlers, nil
|
||||
}
|
||||
|
||||
func (localHandlerService *LocalHandlerService) GetEngine() *engine.DefaultEngine {
|
||||
en := engine.NewEngine(localHandlerService.Cfg, localHandlerService.Rs)
|
||||
en = en.WithPersister(localHandlerService.Pe)
|
||||
// TODO: enable setting of sessionId on engine init time
|
||||
func (ls *LocalHandlerService) GetEngine() *engine.DefaultEngine {
|
||||
en := engine.NewEngine(ls.Cfg, ls.Rs)
|
||||
en = en.WithPersister(ls.Pe)
|
||||
return en
|
||||
}
|
||||
|
||||
@@ -10,16 +10,14 @@ import (
|
||||
)
|
||||
|
||||
type AccountServiceInterface interface {
|
||||
CheckBalance(publicKey string) (string, error)
|
||||
CheckBalance(publicKey string) (*models.BalanceResponse, error)
|
||||
CreateAccount() (*models.AccountResponse, error)
|
||||
CheckAccountStatus(trackingId string) (string, error)
|
||||
CheckAccountStatus(trackingId string) (*models.TrackStatusResponse, error)
|
||||
}
|
||||
|
||||
type AccountService struct {
|
||||
}
|
||||
|
||||
|
||||
|
||||
// CheckAccountStatus retrieves the status of an account transaction based on the provided tracking ID.
|
||||
//
|
||||
// Parameters:
|
||||
@@ -27,64 +25,51 @@ type AccountService struct {
|
||||
// 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) {
|
||||
func (as *AccountService) CheckAccountStatus(trackingId string) (*models.TrackStatusResponse, error) {
|
||||
resp, err := http.Get(config.TrackStatusURL + trackingId)
|
||||
if err != nil {
|
||||
return "", err
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return "", err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var trackResp models.TrackStatusResponse
|
||||
err = json.Unmarshal(body, &trackResp)
|
||||
if err != nil {
|
||||
return "", err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
status := trackResp.Result.Transaction.Status
|
||||
|
||||
return status, nil
|
||||
return &trackResp, 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) {
|
||||
|
||||
func (as *AccountService) CheckBalance(publicKey string) (*models.BalanceResponse, error) {
|
||||
resp, err := http.Get(config.BalanceURL + publicKey)
|
||||
if err != nil {
|
||||
return "0.0", err
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return "0.0", err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var balanceResp models.BalanceResponse
|
||||
err = json.Unmarshal(body, &balanceResp)
|
||||
if err != nil {
|
||||
return "0.0", err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
balance := balanceResp.Result.Balance
|
||||
return balance, nil
|
||||
return &balanceResp, nil
|
||||
}
|
||||
|
||||
|
||||
//CreateAccount creates a new account in the custodial system.
|
||||
// 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.
|
||||
@@ -96,17 +81,14 @@ func (as *AccountService) CreateAccount() (*models.AccountResponse, error) {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -117,17 +117,14 @@ func (h *Handlers) Init(ctx context.Context, sym string, input []byte) (resource
|
||||
func (h *Handlers) SetLanguage(ctx context.Context, sym string, input []byte) (resource.Result, error) {
|
||||
var res resource.Result
|
||||
|
||||
sym, _ = h.st.Where()
|
||||
symbol, _ := h.st.Where()
|
||||
code := strings.Split(symbol, "_")[1]
|
||||
|
||||
switch sym {
|
||||
case "set_default":
|
||||
res.FlagSet = append(res.FlagSet, state.FLAG_LANG)
|
||||
res.Content = "eng"
|
||||
case "set_swa":
|
||||
res.FlagSet = append(res.FlagSet, state.FLAG_LANG)
|
||||
res.Content = "swa"
|
||||
default:
|
||||
if !utils.IsValidISO639(code) {
|
||||
return res, nil
|
||||
}
|
||||
res.FlagSet = append(res.FlagSet, state.FLAG_LANG)
|
||||
res.Content = code
|
||||
|
||||
languageSetFlag, err := h.flagManager.GetFlag("flag_language_set")
|
||||
if err != nil {
|
||||
@@ -279,32 +276,6 @@ func (h *Handlers) ConfirmPinChange(ctx context.Context, sym string, input []byt
|
||||
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) {
|
||||
var res resource.Result
|
||||
|
||||
menuOption := string(input)
|
||||
|
||||
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, flag_allow_update)
|
||||
res.FlagSet = append(res.FlagSet, flag_single_edit)
|
||||
case "3":
|
||||
res.FlagReset = append(res.FlagReset, flag_allow_update)
|
||||
res.FlagSet = append(res.FlagSet, flag_single_edit)
|
||||
case "4":
|
||||
res.FlagReset = append(res.FlagReset, flag_allow_update)
|
||||
res.FlagSet = append(res.FlagSet, flag_single_edit)
|
||||
default:
|
||||
res.FlagReset = append(res.FlagReset, flag_single_edit)
|
||||
}
|
||||
|
||||
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
|
||||
@@ -319,8 +290,6 @@ func (h *Handlers) VerifyPin(ctx context.Context, sym string, input []byte) (res
|
||||
if !ok {
|
||||
return res, fmt.Errorf("missing session")
|
||||
}
|
||||
|
||||
//AccountPin, _ := utils.ReadEntry(ctx, h.userdataStore, sessionId, utils.DATA_ACCOUNT_PIN)
|
||||
store := h.userdataStore
|
||||
AccountPin, err := store.ReadEntry(ctx, sessionId, utils.DATA_ACCOUNT_PIN)
|
||||
if err != nil {
|
||||
@@ -356,7 +325,6 @@ func (h *Handlers) SaveFirstname(ctx context.Context, sym string, input []byte)
|
||||
if !ok {
|
||||
return res, fmt.Errorf("missing session")
|
||||
}
|
||||
|
||||
if len(input) > 0 {
|
||||
firstName := string(input)
|
||||
store := h.userdataStore
|
||||
@@ -436,6 +404,7 @@ func (h *Handlers) SaveLocation(ctx context.Context, sym string, input []byte) (
|
||||
|
||||
// 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) {
|
||||
symbol, _ := h.st.Where()
|
||||
var res resource.Result
|
||||
var err error
|
||||
sessionId, ok := ctx.Value("SessionId").(string)
|
||||
@@ -443,21 +412,11 @@ func (h *Handlers) SaveGender(ctx context.Context, sym string, input []byte) (re
|
||||
return res, fmt.Errorf("missing session")
|
||||
}
|
||||
|
||||
if len(input) > 0 {
|
||||
gender := string(input)
|
||||
switch gender {
|
||||
case "1":
|
||||
gender = "Male"
|
||||
case "2":
|
||||
gender = "Female"
|
||||
case "3":
|
||||
gender = "Unspecified"
|
||||
}
|
||||
store := h.userdataStore
|
||||
err = store.WriteEntry(ctx, sessionId, utils.DATA_GENDER, []byte(gender))
|
||||
if err != nil {
|
||||
return res, nil
|
||||
}
|
||||
gender := strings.Split(symbol, "_")[1]
|
||||
store := h.userdataStore
|
||||
err = store.WriteEntry(ctx, sessionId, utils.DATA_GENDER, []byte(gender))
|
||||
if err != nil {
|
||||
return res, nil
|
||||
}
|
||||
|
||||
return res, nil
|
||||
@@ -564,9 +523,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) {
|
||||
var res resource.Result
|
||||
|
||||
flag_incorrect_pin, _ := h.flagManager.GetFlag("flag_incorrect_pin")
|
||||
|
||||
res.FlagReset = append(res.FlagReset, flag_incorrect_pin)
|
||||
return res, nil
|
||||
}
|
||||
@@ -578,6 +535,7 @@ 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")
|
||||
flag_api_error, _ := h.flagManager.GetFlag("flag_api_call_error")
|
||||
|
||||
sessionId, ok := ctx.Value("SessionId").(string)
|
||||
if !ok {
|
||||
@@ -589,18 +547,23 @@ func (h *Handlers) CheckAccountStatus(ctx context.Context, sym string, input []b
|
||||
return res, err
|
||||
}
|
||||
|
||||
status, err := h.accountService.CheckAccountStatus(string(trackingId))
|
||||
accountStatus, err := h.accountService.CheckAccountStatus(string(trackingId))
|
||||
if err != nil {
|
||||
fmt.Println("Error checking account status:", err)
|
||||
return res, err
|
||||
}
|
||||
if !accountStatus.Ok {
|
||||
res.FlagSet = append(res.FlagSet, flag_api_error)
|
||||
return res, err
|
||||
}
|
||||
res.FlagReset = append(res.FlagReset, flag_api_error)
|
||||
status := accountStatus.Result.Transaction.Status
|
||||
|
||||
err = store.WriteEntry(ctx, sessionId, utils.DATA_ACCOUNT_STATUS, []byte(status))
|
||||
if err != nil {
|
||||
return res, nil
|
||||
}
|
||||
|
||||
if status == "SUCCESS" {
|
||||
if accountStatus.Result.Transaction.Status == "SUCCESS" {
|
||||
res.FlagSet = append(res.FlagSet, flag_account_success)
|
||||
res.FlagReset = append(res.FlagReset, flag_account_pending)
|
||||
} else {
|
||||
@@ -640,7 +603,6 @@ func (h *Handlers) QuitWithHelp(ctx context.Context, sym string, input []byte) (
|
||||
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) {
|
||||
var res resource.Result
|
||||
@@ -681,6 +643,8 @@ func (h *Handlers) CheckBalance(ctx context.Context, sym string, input []byte) (
|
||||
var res resource.Result
|
||||
var err error
|
||||
|
||||
flag_api_error, _ := h.flagManager.GetFlag("flag_api_call_error")
|
||||
|
||||
sessionId, ok := ctx.Value("SessionId").(string)
|
||||
if !ok {
|
||||
return res, fmt.Errorf("missing session")
|
||||
@@ -692,15 +656,60 @@ func (h *Handlers) CheckBalance(ctx context.Context, sym string, input []byte) (
|
||||
return res, err
|
||||
}
|
||||
|
||||
balance, err := h.accountService.CheckBalance(string(publicKey))
|
||||
balanceResponse, err := h.accountService.CheckBalance(string(publicKey))
|
||||
if err != nil {
|
||||
return res, nil
|
||||
}
|
||||
if !balanceResponse.Ok {
|
||||
res.FlagSet = append(res.FlagSet, flag_api_error)
|
||||
return res, nil
|
||||
}
|
||||
res.FlagReset = append(res.FlagReset, flag_api_error)
|
||||
balance := balanceResponse.Result.Balance
|
||||
res.Content = balance
|
||||
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func (h *Handlers) FetchCustodialBalances(ctx context.Context, sym string, input []byte) (resource.Result, error) {
|
||||
var res resource.Result
|
||||
flag_api_error, _ := h.flagManager.GetFlag("flag_api_call_error")
|
||||
|
||||
sessionId, ok := ctx.Value("SessionId").(string)
|
||||
if !ok {
|
||||
return res, fmt.Errorf("missing session")
|
||||
}
|
||||
symbol, _ := h.st.Where()
|
||||
balanceType := strings.Split(symbol, "_")[0]
|
||||
|
||||
store := h.userdataStore
|
||||
publicKey, err := store.ReadEntry(ctx, sessionId, utils.DATA_PUBLIC_KEY)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
balanceResponse, err := h.accountService.CheckBalance(string(publicKey))
|
||||
if err != nil {
|
||||
return res, nil
|
||||
}
|
||||
if !balanceResponse.Ok {
|
||||
res.FlagSet = append(res.FlagSet, flag_api_error)
|
||||
return res, nil
|
||||
}
|
||||
res.FlagReset = append(res.FlagReset, flag_api_error)
|
||||
balance := balanceResponse.Result.Balance
|
||||
|
||||
switch balanceType {
|
||||
case "my":
|
||||
res.Content = fmt.Sprintf("Your balance is %s", balance)
|
||||
case "community":
|
||||
res.Content = fmt.Sprintf("Your community balance is %s", balance)
|
||||
default:
|
||||
break
|
||||
}
|
||||
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) {
|
||||
var res resource.Result
|
||||
@@ -797,10 +806,11 @@ func (h *Handlers) MaxAmount(ctx context.Context, sym string, input []byte) (res
|
||||
store := h.userdataStore
|
||||
publicKey, _ := store.ReadEntry(ctx, sessionId, utils.DATA_PUBLIC_KEY)
|
||||
|
||||
balance, err := h.accountService.CheckBalance(string(publicKey))
|
||||
balanceResp, err := h.accountService.CheckBalance(string(publicKey))
|
||||
if err != nil {
|
||||
return res, nil
|
||||
}
|
||||
balance := balanceResp.Result.Balance
|
||||
|
||||
res.Content = balance
|
||||
|
||||
@@ -819,18 +829,25 @@ func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte)
|
||||
}
|
||||
|
||||
flag_invalid_amount, _ := h.flagManager.GetFlag("flag_invalid_amount")
|
||||
flag_api_error, _ := h.flagManager.GetFlag("flag_api_call_error")
|
||||
|
||||
store := h.userdataStore
|
||||
publicKey, _ := store.ReadEntry(ctx, sessionId, utils.DATA_PUBLIC_KEY)
|
||||
|
||||
amountStr := string(input)
|
||||
|
||||
balanceStr, err := h.accountService.CheckBalance(string(publicKey))
|
||||
balanceRes, err := h.accountService.CheckBalance(string(publicKey))
|
||||
balanceStr := balanceRes.Result.Balance
|
||||
|
||||
if !balanceRes.Ok {
|
||||
res.FlagSet = append(res.FlagSet, flag_api_error)
|
||||
return res, nil
|
||||
}
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
res.Content = balanceStr
|
||||
res.FlagReset = append(res.FlagReset, flag_api_error)
|
||||
|
||||
// Parse the balance
|
||||
balanceParts := strings.Split(balanceStr, " ")
|
||||
@@ -922,36 +939,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) {
|
||||
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")
|
||||
|
||||
store := h.userdataStore
|
||||
publicKey, err := store.ReadEntry(ctx, sessionId, utils.DATA_PUBLIC_KEY)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
balance, err := h.accountService.CheckBalance(string(publicKey))
|
||||
if err != nil {
|
||||
return res, nil
|
||||
}
|
||||
res.Content = l.Get("Your account balance is %s", balance)
|
||||
res.FlagReset = append(res.FlagReset, flag_account_authorized)
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// InitiateTransaction returns a confirmation and resets the transaction data
|
||||
// on the gdbm store.
|
||||
func (h *Handlers) InitiateTransaction(ctx context.Context, sym string, input []byte) (resource.Result, error) {
|
||||
@@ -985,16 +972,23 @@ 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 Gdbm backed storage.
|
||||
func (h *Handlers) GetProfileInfo(ctx context.Context, sym string, input []byte) (resource.Result, error) {
|
||||
var res resource.Result
|
||||
var defaultValue string
|
||||
sessionId, ok := ctx.Value("SessionId").(string)
|
||||
if !ok {
|
||||
return res, fmt.Errorf("missing session")
|
||||
}
|
||||
|
||||
// Default value when an entry is not found
|
||||
defaultValue := "Not Provided"
|
||||
language, ok := ctx.Value("Language").(lang.Language)
|
||||
if !ok {
|
||||
return res, fmt.Errorf("value for 'Language' is not of type lang.Language")
|
||||
}
|
||||
code := language.Code
|
||||
if code == "swa" {
|
||||
defaultValue = "Haipo"
|
||||
} else {
|
||||
defaultValue = "Not Provided"
|
||||
}
|
||||
|
||||
// Helper function to handle nil byte slices and convert them to string
|
||||
getEntryOrDefault := func(entry []byte, err error) string {
|
||||
@@ -1031,12 +1025,23 @@ func (h *Handlers) GetProfileInfo(ctx context.Context, sym string, input []byte)
|
||||
return res, fmt.Errorf("invalid year of birth: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Format the result
|
||||
res.Content = fmt.Sprintf(
|
||||
"Name: %s\nGender: %s\nAge: %s\nLocation: %s\nYou provide: %s\n",
|
||||
name, gender, age, location, offerings,
|
||||
)
|
||||
switch language.Code {
|
||||
case "eng":
|
||||
res.Content = fmt.Sprintf(
|
||||
"Name: %s\nGender: %s\nAge: %s\nLocation: %s\nYou provide: %s\n",
|
||||
name, gender, age, location, offerings,
|
||||
)
|
||||
case "swa":
|
||||
res.Content = fmt.Sprintf(
|
||||
"Jina: %s\nJinsia: %s\nUmri: %s\nEneo: %s\nUnauza: %s\n",
|
||||
name, gender, age, location, offerings,
|
||||
)
|
||||
default:
|
||||
res.Content = fmt.Sprintf(
|
||||
"Name: %s\nGender: %s\nAge: %s\nLocation: %s\nYou provide: %s\n",
|
||||
name, gender, age, location, offerings,
|
||||
)
|
||||
}
|
||||
|
||||
return res, nil
|
||||
}
|
||||
|
||||
@@ -7,8 +7,12 @@ import (
|
||||
"log"
|
||||
"path"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.defalsify.org/vise.git/asm"
|
||||
"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/mocks"
|
||||
@@ -16,6 +20,7 @@ import (
|
||||
"git.grassecon.net/urdt/ussd/internal/utils"
|
||||
"github.com/alecthomas/assert/v2"
|
||||
testdataloader "github.com/peteole/testdata-loader"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -23,10 +28,53 @@ var (
|
||||
flagsPath = path.Join(baseDir, "services", "registration", "pp.csv")
|
||||
)
|
||||
|
||||
func TestCreateAccount(t *testing.T) {
|
||||
type Transaction struct {
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
Status string `json:"status"`
|
||||
TransferValue json.Number `json:"transferValue"`
|
||||
TxHash string `json:"txHash"`
|
||||
TxType string `json:"txType"`
|
||||
}
|
||||
|
||||
func TestNewHandlers(t *testing.T) {
|
||||
fm, err := NewFlagManager(flagsPath)
|
||||
if err != nil {
|
||||
t.Logf(err.Error())
|
||||
}
|
||||
t.Run("Valid UserDataStore", func(t *testing.T) {
|
||||
mockStore := &mocks.MockUserDataStore{}
|
||||
handlers, err := NewHandlers(fm.parser, mockStore)
|
||||
if err != nil {
|
||||
t.Fatalf("expected no error, got %v", err)
|
||||
}
|
||||
if handlers == nil {
|
||||
t.Fatal("expected handlers to be non-nil")
|
||||
}
|
||||
if handlers.userdataStore == nil {
|
||||
t.Fatal("expected userdataStore to be set in handlers")
|
||||
}
|
||||
})
|
||||
|
||||
// Test case for nil userdataStore
|
||||
t.Run("Nil UserDataStore", func(t *testing.T) {
|
||||
appFlags := &asm.FlagParser{}
|
||||
|
||||
handlers, err := NewHandlers(appFlags, nil)
|
||||
|
||||
if err == nil {
|
||||
t.Fatal("expected an error, got none")
|
||||
}
|
||||
if handlers != nil {
|
||||
t.Fatal("expected handlers to be nil")
|
||||
}
|
||||
if err.Error() != "cannot create handler with nil userdata store" {
|
||||
t.Fatalf("expected specific error, got %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestCreateAccount(t *testing.T) {
|
||||
fm, err := NewFlagManager(flagsPath)
|
||||
if err != nil {
|
||||
t.Logf(err.Error())
|
||||
}
|
||||
@@ -94,6 +142,25 @@ func TestCreateAccount(t *testing.T) {
|
||||
mockDataStore.AssertExpectations(t)
|
||||
}
|
||||
|
||||
func TestWithPersister(t *testing.T) {
|
||||
// Test case: Setting a persister
|
||||
h := &Handlers{}
|
||||
p := &persist.Persister{}
|
||||
|
||||
result := h.WithPersister(p)
|
||||
|
||||
assert.Equal(t, p, h.pe, "The persister should be set correctly.")
|
||||
assert.Equal(t, h, result, "The returned handler should be the same instance.")
|
||||
}
|
||||
|
||||
func TestWithPersister_PanicWhenAlreadySet(t *testing.T) {
|
||||
// Test case: Panic on multiple calls
|
||||
h := &Handlers{pe: &persist.Persister{}}
|
||||
require.Panics(t, func() {
|
||||
h.WithPersister(&persist.Persister{})
|
||||
}, "Should panic when trying to set a persister again.")
|
||||
}
|
||||
|
||||
func TestSaveFirstname(t *testing.T) {
|
||||
// Create a new instance of MockMyDataStore
|
||||
mockStore := new(mocks.MockUserDataStore)
|
||||
@@ -295,6 +362,7 @@ func TestSaveOfferings(t *testing.T) {
|
||||
func TestSaveGender(t *testing.T) {
|
||||
// Create a new instance of MockMyDataStore
|
||||
mockStore := new(mocks.MockUserDataStore)
|
||||
mockState := state.NewState(16)
|
||||
|
||||
// Define the session ID and context
|
||||
sessionId := "session123"
|
||||
@@ -302,34 +370,32 @@ func TestSaveGender(t *testing.T) {
|
||||
|
||||
// Define test cases
|
||||
tests := []struct {
|
||||
name string
|
||||
input []byte
|
||||
expectedGender string
|
||||
expectCall bool
|
||||
name string
|
||||
input []byte
|
||||
expectedGender string
|
||||
expectCall bool
|
||||
executingSymbol string
|
||||
}{
|
||||
{
|
||||
name: "Valid Male Input",
|
||||
input: []byte("1"),
|
||||
expectedGender: "Male",
|
||||
expectCall: true,
|
||||
name: "Valid Male Input",
|
||||
input: []byte("1"),
|
||||
expectedGender: "male",
|
||||
executingSymbol: "set_male",
|
||||
expectCall: true,
|
||||
},
|
||||
{
|
||||
name: "Valid Female Input",
|
||||
input: []byte("2"),
|
||||
expectedGender: "Female",
|
||||
expectCall: true,
|
||||
name: "Valid Female Input",
|
||||
input: []byte("2"),
|
||||
expectedGender: "female",
|
||||
executingSymbol: "set_female",
|
||||
expectCall: true,
|
||||
},
|
||||
{
|
||||
name: "Valid Unspecified Input",
|
||||
input: []byte("3"),
|
||||
expectedGender: "Unspecified",
|
||||
expectCall: true,
|
||||
},
|
||||
{
|
||||
name: "Empty Input",
|
||||
input: []byte(""),
|
||||
expectedGender: "",
|
||||
expectCall: false,
|
||||
name: "Valid Unspecified Input",
|
||||
input: []byte("3"),
|
||||
executingSymbol: "set_unspecified",
|
||||
expectedGender: "unspecified",
|
||||
expectCall: true,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -342,14 +408,15 @@ func TestSaveGender(t *testing.T) {
|
||||
} else {
|
||||
mockStore.On("WriteEntry", ctx, sessionId, utils.DATA_GENDER, []byte(tt.expectedGender)).Return(nil)
|
||||
}
|
||||
|
||||
mockState.ExecPath = append(mockState.ExecPath, tt.executingSymbol)
|
||||
// Create the Handlers instance with the mock store
|
||||
h := &Handlers{
|
||||
userdataStore: mockStore,
|
||||
st: mockState,
|
||||
}
|
||||
|
||||
// Call the method
|
||||
_, err := h.SaveGender(ctx, "someSym", tt.input)
|
||||
_, err := h.SaveGender(ctx, "save_gender", tt.input)
|
||||
|
||||
// Assert no error
|
||||
assert.NoError(t, err)
|
||||
@@ -421,7 +488,10 @@ func TestMaxAmount(t *testing.T) {
|
||||
sessionId := "session123"
|
||||
ctx := context.WithValue(context.Background(), "SessionId", sessionId)
|
||||
publicKey := "0xcasgatweksalw1018221"
|
||||
expectedBalance := "0.003CELO"
|
||||
|
||||
expectedBalance := &models.BalanceResponse{
|
||||
Ok: true,
|
||||
}
|
||||
|
||||
// Set up the expected behavior of the mock
|
||||
mockStore.On("ReadEntry", ctx, sessionId, utils.DATA_PUBLIC_KEY).Return([]byte(publicKey), nil)
|
||||
@@ -437,7 +507,7 @@ func TestMaxAmount(t *testing.T) {
|
||||
res, _ := h.MaxAmount(ctx, "max_amount", []byte("check_balance"))
|
||||
|
||||
//Assert that the balance that was set as the result content is what was returned by Check Balance
|
||||
assert.Equal(t, expectedBalance, res.Content)
|
||||
assert.Equal(t, expectedBalance.Result.Balance, res.Content)
|
||||
|
||||
}
|
||||
|
||||
@@ -516,12 +586,10 @@ func TestGetRecipient(t *testing.T) {
|
||||
func TestGetFlag(t *testing.T) {
|
||||
fm, err := NewFlagManager(flagsPath)
|
||||
expectedFlag := uint32(9)
|
||||
|
||||
if err != nil {
|
||||
t.Logf(err.Error())
|
||||
}
|
||||
flag, err := fm.GetFlag("flag_account_created")
|
||||
|
||||
if err != nil {
|
||||
t.Logf(err.Error())
|
||||
}
|
||||
@@ -538,13 +606,13 @@ func TestSetLanguage(t *testing.T) {
|
||||
}
|
||||
// Define test cases
|
||||
tests := []struct {
|
||||
name string
|
||||
execPath []string
|
||||
expectedResult resource.Result
|
||||
name string
|
||||
execPath []string
|
||||
expectedResult resource.Result
|
||||
}{
|
||||
{
|
||||
name: "Set Default Language (English)",
|
||||
execPath: []string{"set_default"},
|
||||
execPath: []string{"set_eng"},
|
||||
expectedResult: resource.Result{
|
||||
FlagSet: []uint32{state.FLAG_LANG, 8},
|
||||
Content: "eng",
|
||||
@@ -558,13 +626,6 @@ func TestSetLanguage(t *testing.T) {
|
||||
Content: "swa",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Unhandled path",
|
||||
execPath: []string{""},
|
||||
expectedResult: resource.Result{
|
||||
FlagSet: []uint32{8},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
@@ -592,76 +653,6 @@ func TestSetLanguage(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetResetSingleEdit(t *testing.T) {
|
||||
fm, err := NewFlagManager(flagsPath)
|
||||
|
||||
flag_allow_update, _ := fm.parser.GetFlag("flag_allow_update")
|
||||
flag_single_edit, _ := fm.parser.GetFlag("flag_single_edit")
|
||||
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
// Define test cases
|
||||
tests := []struct {
|
||||
name string
|
||||
input []byte
|
||||
expectedResult resource.Result
|
||||
}{
|
||||
{
|
||||
name: "Set single Edit",
|
||||
input: []byte("2"),
|
||||
expectedResult: resource.Result{
|
||||
FlagSet: []uint32{flag_single_edit},
|
||||
FlagReset: []uint32{flag_allow_update},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Set single Edit",
|
||||
input: []byte("3"),
|
||||
expectedResult: resource.Result{
|
||||
FlagSet: []uint32{flag_single_edit},
|
||||
FlagReset: []uint32{flag_allow_update},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Set single edit",
|
||||
input: []byte("4"),
|
||||
expectedResult: resource.Result{
|
||||
FlagReset: []uint32{flag_allow_update},
|
||||
FlagSet: []uint32{flag_single_edit},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "No single edit set",
|
||||
input: []byte("1"),
|
||||
expectedResult: resource.Result{
|
||||
FlagReset: []uint32{flag_single_edit},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
|
||||
// Create the Handlers instance with the mock flag manager
|
||||
h := &Handlers{
|
||||
flagManager: fm.parser,
|
||||
}
|
||||
|
||||
// Call the method
|
||||
res, err := h.SetResetSingleEdit(context.Background(), "set_reset_single_edit", tt.input)
|
||||
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
// Assert that the Result FlagSet has the required flags after language switch
|
||||
assert.Equal(t, res, tt.expectedResult, "Flags should match reset edit")
|
||||
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestResetAllowUpdate(t *testing.T) {
|
||||
fm, err := NewFlagManager(flagsPath)
|
||||
|
||||
@@ -1068,53 +1059,109 @@ func TestVerifyPin(t *testing.T) {
|
||||
|
||||
func TestCheckAccountStatus(t *testing.T) {
|
||||
fm, err := NewFlagManager(flagsPath)
|
||||
|
||||
if err != nil {
|
||||
t.Logf(err.Error())
|
||||
}
|
||||
mockDataStore := new(mocks.MockUserDataStore)
|
||||
mockCreateAccountService := new(mocks.MockAccountService)
|
||||
|
||||
sessionId := "session123"
|
||||
flag_account_success, _ := fm.GetFlag("flag_account_success")
|
||||
flag_account_pending, _ := fm.GetFlag("flag_account_pending")
|
||||
flag_api_error, _ := fm.GetFlag("flag_api_call_error")
|
||||
|
||||
ctx := context.WithValue(context.Background(), "SessionId", sessionId)
|
||||
|
||||
h := &Handlers{
|
||||
userdataStore: mockDataStore,
|
||||
accountService: mockCreateAccountService,
|
||||
flagManager: fm.parser,
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
input []byte
|
||||
status string
|
||||
response *models.TrackStatusResponse
|
||||
expectedResult resource.Result
|
||||
}{
|
||||
{
|
||||
name: "Test when account status is Success",
|
||||
input: []byte("TrackingId1234"),
|
||||
status: "SUCCESS",
|
||||
name: "Test when account status is Success",
|
||||
input: []byte("TrackingId1234"),
|
||||
response: &models.TrackStatusResponse{
|
||||
Ok: true,
|
||||
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\""
|
||||
}
|
||||
}{
|
||||
Transaction: Transaction{
|
||||
CreatedAt: time.Now(),
|
||||
Status: "SUCCESS",
|
||||
TransferValue: json.Number("0.5"),
|
||||
TxHash: "0x123abc456def",
|
||||
TxType: "transfer",
|
||||
},
|
||||
},
|
||||
},
|
||||
expectedResult: resource.Result{
|
||||
FlagSet: []uint32{flag_account_success},
|
||||
FlagReset: []uint32{flag_account_pending},
|
||||
FlagReset: []uint32{flag_api_error, flag_account_pending},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Test when fetching account status is not Success",
|
||||
input: []byte("TrackingId1234"),
|
||||
response: &models.TrackStatusResponse{
|
||||
Ok: false,
|
||||
},
|
||||
expectedResult: resource.Result{
|
||||
FlagSet: []uint32{flag_api_error},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Test when checking account status api call is a SUCCESS but an account is not yet ready",
|
||||
input: []byte("TrackingId1234"),
|
||||
response: &models.TrackStatusResponse{
|
||||
Ok: true,
|
||||
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\""
|
||||
}
|
||||
}{
|
||||
Transaction: Transaction{
|
||||
CreatedAt: time.Now(),
|
||||
Status: "IN_NETWORK",
|
||||
TransferValue: json.Number("0.5"),
|
||||
TxHash: "0x123abc456def",
|
||||
TxType: "transfer",
|
||||
},
|
||||
},
|
||||
},
|
||||
expectedResult: resource.Result{
|
||||
FlagSet: []uint32{flag_account_pending},
|
||||
FlagReset: []uint32{flag_api_error, flag_account_success},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
typ := utils.DATA_TRACKING_ID
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
mockDataStore := new(mocks.MockUserDataStore)
|
||||
mockCreateAccountService := new(mocks.MockAccountService)
|
||||
|
||||
h := &Handlers{
|
||||
userdataStore: mockDataStore,
|
||||
accountService: mockCreateAccountService,
|
||||
flagManager: fm.parser,
|
||||
}
|
||||
|
||||
status := tt.response.Result.Transaction.Status
|
||||
// Define expected interactions with the mock
|
||||
mockDataStore.On("ReadEntry", ctx, sessionId, typ).Return(tt.input, nil)
|
||||
mockDataStore.On("ReadEntry", ctx, sessionId, utils.DATA_TRACKING_ID).Return(tt.input, nil)
|
||||
|
||||
mockCreateAccountService.On("CheckAccountStatus", string(tt.input)).Return(tt.status, nil)
|
||||
mockDataStore.On("WriteEntry", ctx, sessionId, utils.DATA_ACCOUNT_STATUS, []byte(tt.status)).Return(nil)
|
||||
mockCreateAccountService.On("CheckAccountStatus", string(tt.input)).Return(tt.response, nil)
|
||||
mockDataStore.On("WriteEntry", ctx, sessionId, utils.DATA_ACCOUNT_STATUS, []byte(status)).Return(nil).Maybe()
|
||||
|
||||
// Call the method under test
|
||||
res, _ := h.CheckAccountStatus(ctx, "check_status", tt.input)
|
||||
res, _ := h.CheckAccountStatus(ctx, "check_account_status", tt.input)
|
||||
|
||||
// Assert that no errors occurred
|
||||
assert.NoError(t, err)
|
||||
@@ -1414,73 +1461,14 @@ func TestIsValidPIN(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuitWithBalance(t *testing.T) {
|
||||
fm, err := NewFlagManager(flagsPath)
|
||||
|
||||
if err != nil {
|
||||
t.Logf(err.Error())
|
||||
}
|
||||
flag_account_authorized, _ := fm.parser.GetFlag("flag_account_authorized")
|
||||
|
||||
mockDataStore := new(mocks.MockUserDataStore)
|
||||
mockCreateAccountService := new(mocks.MockAccountService)
|
||||
|
||||
sessionId := "session123"
|
||||
|
||||
ctx := context.WithValue(context.Background(), "SessionId", sessionId)
|
||||
|
||||
h := &Handlers{
|
||||
userdataStore: mockDataStore,
|
||||
accountService: mockCreateAccountService,
|
||||
flagManager: fm.parser,
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
input []byte
|
||||
publicKey []byte
|
||||
balance string
|
||||
expectedResult resource.Result
|
||||
}{
|
||||
{
|
||||
name: "Test quit with balance",
|
||||
balance: "0.02CELO",
|
||||
publicKey: []byte("0xrqeqrequuq"),
|
||||
expectedResult: resource.Result{
|
||||
FlagReset: []uint32{flag_account_authorized},
|
||||
Content: fmt.Sprintf("Your account balance is %s", "0.02CELO"),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
|
||||
mockDataStore.On("ReadEntry", ctx, sessionId, utils.DATA_PUBLIC_KEY).Return(tt.publicKey, nil)
|
||||
mockCreateAccountService.On("CheckBalance", string(tt.publicKey)).Return(tt.balance, nil)
|
||||
|
||||
// Call the method under test
|
||||
res, _ := h.QuitWithBalance(ctx, "test_quit_with_balance", tt.input)
|
||||
|
||||
// Assert that no errors occurred
|
||||
assert.NoError(t, err)
|
||||
|
||||
//Assert that the account created flag has been set to the result
|
||||
assert.Equal(t, res, tt.expectedResult, "Expected result should be equal to the actual result")
|
||||
|
||||
// Assert that expectations were met
|
||||
mockDataStore.AssertExpectations(t)
|
||||
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateAmount(t *testing.T) {
|
||||
fm, err := NewFlagManager(flagsPath)
|
||||
|
||||
if err != nil {
|
||||
t.Logf(err.Error())
|
||||
}
|
||||
//flag_invalid_amount, _ := fm.parser.GetFlag("flag_invalid_amount")
|
||||
flag_invalid_amount, _ := fm.parser.GetFlag("flag_invalid_amount")
|
||||
flag_api_error, _ := fm.GetFlag("flag_api_call_error")
|
||||
mockDataStore := new(mocks.MockUserDataStore)
|
||||
mockCreateAccountService := new(mocks.MockAccountService)
|
||||
|
||||
@@ -1494,49 +1482,79 @@ func TestValidateAmount(t *testing.T) {
|
||||
flagManager: fm.parser,
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
input []byte
|
||||
publicKey []byte
|
||||
balance string
|
||||
expectedResult resource.Result
|
||||
name string
|
||||
input []byte
|
||||
publicKey []byte
|
||||
balanceResponse *models.BalanceResponse
|
||||
expectedResult resource.Result
|
||||
}{
|
||||
{
|
||||
name: "Test with valid amount",
|
||||
input: []byte("0.001"),
|
||||
balance: "0.003 CELO",
|
||||
name: "Test with valid amount",
|
||||
input: []byte("0.001"),
|
||||
balanceResponse: &models.BalanceResponse{
|
||||
Ok: true,
|
||||
Result: struct {
|
||||
Balance string `json:"balance"`
|
||||
Nonce json.Number `json:"nonce"`
|
||||
}{
|
||||
Balance: "0.003 CELO",
|
||||
Nonce: json.Number("0"),
|
||||
},
|
||||
},
|
||||
publicKey: []byte("0xrqeqrequuq"),
|
||||
expectedResult: resource.Result{
|
||||
Content: "0.001",
|
||||
Content: "0.001",
|
||||
FlagReset: []uint32{flag_api_error},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Test with amount larger than balance",
|
||||
input: []byte("0.02"),
|
||||
balanceResponse: &models.BalanceResponse{
|
||||
Ok: true,
|
||||
Result: struct {
|
||||
Balance string `json:"balance"`
|
||||
Nonce json.Number `json:"nonce"`
|
||||
}{
|
||||
Balance: "0.003 CELO",
|
||||
Nonce: json.Number("0"),
|
||||
},
|
||||
},
|
||||
publicKey: []byte("0xrqeqrequuq"),
|
||||
expectedResult: resource.Result{
|
||||
FlagSet: []uint32{flag_invalid_amount},
|
||||
FlagReset: []uint32{flag_api_error},
|
||||
Content: "0.02",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Test with invalid amount",
|
||||
input: []byte("0.02ms"),
|
||||
balanceResponse: &models.BalanceResponse{
|
||||
Ok: true,
|
||||
Result: struct {
|
||||
Balance string `json:"balance"`
|
||||
Nonce json.Number `json:"nonce"`
|
||||
}{
|
||||
Balance: "0.003 CELO",
|
||||
Nonce: json.Number("0"),
|
||||
},
|
||||
},
|
||||
publicKey: []byte("0xrqeqrequuq"),
|
||||
expectedResult: resource.Result{
|
||||
FlagSet: []uint32{flag_invalid_amount},
|
||||
FlagReset: []uint32{flag_api_error},
|
||||
Content: "0.02ms",
|
||||
},
|
||||
},
|
||||
// {
|
||||
// name: "Test with amount larger than balance",
|
||||
// input: []byte("0.02"),
|
||||
// balance: "0.003 CELO",
|
||||
// publicKey: []byte("0xrqeqrequuq"),
|
||||
// expectedResult: resource.Result{
|
||||
// FlagSet: []uint32{flag_invalid_amount},
|
||||
// Content: "0.02",
|
||||
// },
|
||||
// },
|
||||
// {
|
||||
// name: "Test with invalid amount",
|
||||
// input: []byte("0.02ms"),
|
||||
// balance: "0.003 CELO",
|
||||
// publicKey: []byte("0xrqeqrequuq"),
|
||||
// expectedResult: resource.Result{
|
||||
// FlagSet: []uint32{flag_invalid_amount},
|
||||
// Content: "0.02ms",
|
||||
// },
|
||||
// },
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
|
||||
mockDataStore.On("ReadEntry", ctx, sessionId, utils.DATA_PUBLIC_KEY).Return(tt.publicKey, nil)
|
||||
mockCreateAccountService.On("CheckBalance", string(tt.publicKey)).Return(tt.balance, nil)
|
||||
mockDataStore.On("WriteEntry", ctx, sessionId, utils.DATA_AMOUNT, tt.input).Return(nil)
|
||||
mockCreateAccountService.On("CheckBalance", string(tt.publicKey)).Return(tt.balanceResponse, nil)
|
||||
mockDataStore.On("WriteEntry", ctx, sessionId, utils.DATA_AMOUNT, tt.input).Return(nil).Maybe()
|
||||
|
||||
// Call the method under test
|
||||
res, _ := h.ValidateAmount(ctx, "test_validate_amount", tt.input)
|
||||
@@ -1614,31 +1632,83 @@ func TestValidateRecipient(t *testing.T) {
|
||||
|
||||
func TestCheckBalance(t *testing.T) {
|
||||
|
||||
mockDataStore := new(mocks.MockUserDataStore)
|
||||
sessionId := "session123"
|
||||
publicKey := "0X13242618721"
|
||||
balance := "0.003 CELO"
|
||||
|
||||
expectedResult := resource.Result{
|
||||
Content: "0.003 CELO",
|
||||
}
|
||||
|
||||
mockCreateAccountService := new(mocks.MockAccountService)
|
||||
fm, _ := NewFlagManager(flagsPath)
|
||||
flag_api_error, _ := fm.GetFlag("flag_api_call_error")
|
||||
|
||||
ctx := context.WithValue(context.Background(), "SessionId", sessionId)
|
||||
|
||||
h := &Handlers{
|
||||
userdataStore: mockDataStore,
|
||||
accountService: mockCreateAccountService,
|
||||
//flagManager: fm.parser,
|
||||
tests := []struct {
|
||||
name string
|
||||
balanceResonse *models.BalanceResponse
|
||||
expectedResult resource.Result
|
||||
}{
|
||||
{
|
||||
name: "Test when checking a balance is not a success",
|
||||
balanceResonse: &models.BalanceResponse{
|
||||
Ok: false,
|
||||
Result: struct {
|
||||
Balance string `json:"balance"`
|
||||
Nonce json.Number `json:"nonce"`
|
||||
}{
|
||||
Balance: "0.003 CELO",
|
||||
Nonce: json.Number("0"),
|
||||
},
|
||||
},
|
||||
expectedResult: resource.Result{
|
||||
FlagSet: []uint32{flag_api_error},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Test when checking a balance is a success",
|
||||
balanceResonse: &models.BalanceResponse{
|
||||
Ok: true,
|
||||
Result: struct {
|
||||
Balance string `json:"balance"`
|
||||
Nonce json.Number `json:"nonce"`
|
||||
}{
|
||||
Balance: "0.003 CELO",
|
||||
Nonce: json.Number("0"),
|
||||
},
|
||||
},
|
||||
expectedResult: resource.Result{
|
||||
Content: "0.003 CELO",
|
||||
FlagReset: []uint32{flag_api_error},
|
||||
},
|
||||
},
|
||||
}
|
||||
//mock call operations
|
||||
mockDataStore.On("ReadEntry", ctx, sessionId, utils.DATA_PUBLIC_KEY).Return([]byte(publicKey), nil)
|
||||
mockCreateAccountService.On("CheckBalance", string(publicKey)).Return(balance, nil)
|
||||
|
||||
res, _ := h.CheckBalance(ctx, "check_balance", []byte("123456"))
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
|
||||
assert.Equal(t, res, expectedResult, "Result should contain flag(s) that have been reset")
|
||||
mockDataStore := new(mocks.MockUserDataStore)
|
||||
mockCreateAccountService := new(mocks.MockAccountService)
|
||||
mockState := state.NewState(16)
|
||||
|
||||
// Create the Handlers instance with the mock store
|
||||
h := &Handlers{
|
||||
userdataStore: mockDataStore,
|
||||
flagManager: fm.parser,
|
||||
st: mockState,
|
||||
accountService: mockCreateAccountService,
|
||||
}
|
||||
|
||||
// Set up the expected behavior of the mock
|
||||
mockDataStore.On("ReadEntry", ctx, sessionId, utils.DATA_PUBLIC_KEY).Return([]byte(publicKey), nil)
|
||||
mockCreateAccountService.On("CheckBalance", string(publicKey)).Return(tt.balanceResonse, nil)
|
||||
|
||||
// Call the method
|
||||
res, _ := h.CheckBalance(ctx, "check_balance", []byte(""))
|
||||
|
||||
// Assert that expectations were met
|
||||
mockDataStore.AssertExpectations(t)
|
||||
|
||||
//Assert that the result set to content is what was expected
|
||||
assert.Equal(t, res, tt.expectedResult, "Result should contain flags set according to user input")
|
||||
|
||||
})
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1648,22 +1718,50 @@ func TestGetProfile(t *testing.T) {
|
||||
|
||||
mockDataStore := new(mocks.MockUserDataStore)
|
||||
mockCreateAccountService := new(mocks.MockAccountService)
|
||||
mockState := state.NewState(16)
|
||||
|
||||
h := &Handlers{
|
||||
userdataStore: mockDataStore,
|
||||
accountService: mockCreateAccountService,
|
||||
st: mockState,
|
||||
}
|
||||
ctx := context.WithValue(context.Background(), "SessionId", sessionId)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
keys []utils.DataTyp
|
||||
profileInfo []string
|
||||
result resource.Result
|
||||
name string
|
||||
languageCode string
|
||||
keys []utils.DataTyp
|
||||
profileInfo []string
|
||||
result resource.Result
|
||||
}{
|
||||
{
|
||||
name: "Test with full profile information",
|
||||
keys: []utils.DataTyp{utils.DATA_FAMILY_NAME, utils.DATA_FIRST_NAME, utils.DATA_GENDER, utils.DATA_OFFERINGS, utils.DATA_LOCATION, utils.DATA_YOB},
|
||||
profileInfo: []string{"Doee", "John", "Male", "Bananas", "Kilifi", "1976"},
|
||||
name: "Test with full profile information in eng",
|
||||
keys: []utils.DataTyp{utils.DATA_FAMILY_NAME, utils.DATA_FIRST_NAME, utils.DATA_GENDER, utils.DATA_OFFERINGS, utils.DATA_LOCATION, utils.DATA_YOB},
|
||||
profileInfo: []string{"Doee", "John", "Male", "Bananas", "Kilifi", "1976"},
|
||||
languageCode: "eng",
|
||||
result: resource.Result{
|
||||
Content: fmt.Sprintf(
|
||||
"Name: %s\nGender: %s\nAge: %s\nLocation: %s\nYou provide: %s\n",
|
||||
"John Doee", "Male", "48", "Kilifi", "Bananas",
|
||||
),
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Test with with profile information in swa ",
|
||||
keys: []utils.DataTyp{utils.DATA_FAMILY_NAME, utils.DATA_FIRST_NAME, utils.DATA_GENDER, utils.DATA_OFFERINGS, utils.DATA_LOCATION, utils.DATA_YOB},
|
||||
profileInfo: []string{"Doee", "John", "Male", "Bananas", "Kilifi", "1976"},
|
||||
languageCode: "swa",
|
||||
result: resource.Result{
|
||||
Content: fmt.Sprintf(
|
||||
"Jina: %s\nJinsia: %s\nUmri: %s\nEneo: %s\nUnauza: %s\n",
|
||||
"John Doee", "Male", "48", "Kilifi", "Bananas",
|
||||
),
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Test with with profile information with language that is not yet supported",
|
||||
keys: []utils.DataTyp{utils.DATA_FAMILY_NAME, utils.DATA_FIRST_NAME, utils.DATA_GENDER, utils.DATA_OFFERINGS, utils.DATA_LOCATION, utils.DATA_YOB},
|
||||
profileInfo: []string{"Doee", "John", "Male", "Bananas", "Kilifi", "1976"},
|
||||
languageCode: "nor",
|
||||
result: resource.Result{
|
||||
Content: fmt.Sprintf(
|
||||
"Name: %s\nGender: %s\nAge: %s\nLocation: %s\nYou provide: %s\n",
|
||||
@@ -1674,9 +1772,14 @@ func TestGetProfile(t *testing.T) {
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ctx := context.WithValue(context.Background(), "SessionId", sessionId)
|
||||
ctx = context.WithValue(ctx, "Language", lang.Language{
|
||||
Code: tt.languageCode,
|
||||
})
|
||||
for index, key := range tt.keys {
|
||||
mockDataStore.On("ReadEntry", ctx, sessionId, key).Return([]byte(tt.profileInfo[index]), nil)
|
||||
mockDataStore.On("ReadEntry", ctx, sessionId, key).Return([]byte(tt.profileInfo[index]), nil).Maybe()
|
||||
}
|
||||
|
||||
res, _ := h.GetProfileInfo(ctx, "get_profile_info", []byte(""))
|
||||
|
||||
// Assert that expectations were met
|
||||
@@ -1833,3 +1936,85 @@ func TestConfirmPin(t *testing.T) {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestFetchCustodialBalances(t *testing.T) {
|
||||
fm, err := NewFlagManager(flagsPath)
|
||||
if err != nil {
|
||||
t.Logf(err.Error())
|
||||
}
|
||||
flag_api_error, _ := fm.GetFlag("flag_api_call_error")
|
||||
|
||||
// Define test data
|
||||
sessionId := "session123"
|
||||
publicKey := "0X13242618721"
|
||||
ctx := context.WithValue(context.Background(), "SessionId", sessionId)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
balanceResonse *models.BalanceResponse
|
||||
expectedResult resource.Result
|
||||
}{
|
||||
{
|
||||
name: "Test when fetch custodial balances is not a success",
|
||||
balanceResonse: &models.BalanceResponse{
|
||||
Ok: false,
|
||||
Result: struct {
|
||||
Balance string `json:"balance"`
|
||||
Nonce json.Number `json:"nonce"`
|
||||
}{
|
||||
Balance: "0.003 CELO",
|
||||
Nonce: json.Number("0"),
|
||||
},
|
||||
},
|
||||
expectedResult: resource.Result{
|
||||
FlagSet: []uint32{flag_api_error},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Test when fetch custodial balances is a success",
|
||||
balanceResonse: &models.BalanceResponse{
|
||||
Ok: true,
|
||||
Result: struct {
|
||||
Balance string `json:"balance"`
|
||||
Nonce json.Number `json:"nonce"`
|
||||
}{
|
||||
Balance: "0.003 CELO",
|
||||
Nonce: json.Number("0"),
|
||||
},
|
||||
},
|
||||
expectedResult: resource.Result{
|
||||
FlagReset: []uint32{flag_api_error},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
|
||||
mockDataStore := new(mocks.MockUserDataStore)
|
||||
mockCreateAccountService := new(mocks.MockAccountService)
|
||||
mockState := state.NewState(16)
|
||||
|
||||
// Create the Handlers instance with the mock store
|
||||
h := &Handlers{
|
||||
userdataStore: mockDataStore,
|
||||
flagManager: fm.parser,
|
||||
st: mockState,
|
||||
accountService: mockCreateAccountService,
|
||||
}
|
||||
|
||||
// Set up the expected behavior of the mock
|
||||
mockDataStore.On("ReadEntry", ctx, sessionId, utils.DATA_PUBLIC_KEY).Return([]byte(publicKey), nil)
|
||||
mockCreateAccountService.On("CheckBalance", string(publicKey)).Return(tt.balanceResonse, nil)
|
||||
|
||||
// Call the method
|
||||
res, _ := h.FetchCustodialBalances(ctx, "fetch_custodial_balances", []byte(""))
|
||||
|
||||
// Assert that expectations were met
|
||||
mockDataStore.AssertExpectations(t)
|
||||
|
||||
//Assert that the result set to content is what was expected
|
||||
assert.Equal(t, res, tt.expectedResult, "Result should contain flags set according to user input")
|
||||
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,12 +15,12 @@ func (m *MockAccountService) CreateAccount() (*models.AccountResponse, error) {
|
||||
return args.Get(0).(*models.AccountResponse), args.Error(1)
|
||||
}
|
||||
|
||||
func (m *MockAccountService) CheckBalance(publicKey string) (string, error) {
|
||||
func (m *MockAccountService) CheckBalance(publicKey string) (*models.BalanceResponse, error) {
|
||||
args := m.Called(publicKey)
|
||||
return args.String(0), args.Error(1)
|
||||
return args.Get(0).(*models.BalanceResponse), args.Error(1)
|
||||
}
|
||||
|
||||
func (m *MockAccountService) CheckAccountStatus(trackingId string) (string, error) {
|
||||
func (m *MockAccountService) CheckAccountStatus(trackingId string) (*models.TrackStatusResponse, error) {
|
||||
args := m.Called(trackingId)
|
||||
return args.String(0), args.Error(1)
|
||||
return args.Get(0).(*models.TrackStatusResponse), args.Error(1)
|
||||
}
|
||||
43
internal/storage/db.go
Normal file
43
internal/storage/db.go
Normal file
@@ -0,0 +1,43 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"git.defalsify.org/vise.git/db"
|
||||
)
|
||||
|
||||
const (
|
||||
DATATYPE_USERSUB = 64
|
||||
)
|
||||
|
||||
type SubPrefixDb struct {
|
||||
store db.Db
|
||||
pfx []byte
|
||||
}
|
||||
|
||||
func NewSubPrefixDb(store db.Db, pfx []byte) *SubPrefixDb {
|
||||
return &SubPrefixDb{
|
||||
store: store,
|
||||
pfx: pfx,
|
||||
}
|
||||
}
|
||||
|
||||
func(s *SubPrefixDb) toKey(k []byte) []byte {
|
||||
return append(s.pfx, k...)
|
||||
}
|
||||
|
||||
func(s *SubPrefixDb) Get(ctx context.Context, key []byte) ([]byte, error) {
|
||||
s.store.SetPrefix(DATATYPE_USERSUB)
|
||||
key = s.toKey(key)
|
||||
v, err := s.store.Get(ctx, key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
func(s *SubPrefixDb) Put(ctx context.Context, key []byte, val []byte) error {
|
||||
s.store.SetPrefix(DATATYPE_USERSUB)
|
||||
key = s.toKey(key)
|
||||
return s.store.Put(ctx, key, val)
|
||||
}
|
||||
54
internal/storage/db_test.go
Normal file
54
internal/storage/db_test.go
Normal file
@@ -0,0 +1,54 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
memdb "git.defalsify.org/vise.git/db/mem"
|
||||
)
|
||||
|
||||
func TestSubPrefix(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db := memdb.NewMemDb()
|
||||
err := db.Connect(ctx, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sdba := NewSubPrefixDb(db, []byte("tinkywinky"))
|
||||
err = sdba.Put(ctx, []byte("foo"), []byte("dipsy"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
r, err := sdba.Get(ctx, []byte("foo"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(r, []byte("dipsy")) {
|
||||
t.Fatalf("expected 'dipsy', got %s", r)
|
||||
}
|
||||
|
||||
sdbb := NewSubPrefixDb(db, []byte("lala"))
|
||||
r, err = sdbb.Get(ctx, []byte("foo"))
|
||||
if err == nil {
|
||||
t.Fatal("expected not found")
|
||||
}
|
||||
|
||||
err = sdbb.Put(ctx, []byte("foo"), []byte("pu"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r, err = sdbb.Get(ctx, []byte("foo"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(r, []byte("pu")) {
|
||||
t.Fatalf("expected 'pu', got %s", r)
|
||||
}
|
||||
|
||||
r, err = sdba.Get(ctx, []byte("foo"))
|
||||
if !bytes.Equal(r, []byte("dipsy")) {
|
||||
t.Fatalf("expected 'dipsy', got %s", r)
|
||||
}
|
||||
}
|
||||
115
internal/storage/gdbm.go
Normal file
115
internal/storage/gdbm.go
Normal file
@@ -0,0 +1,115 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"git.defalsify.org/vise.git/db"
|
||||
"git.defalsify.org/vise.git/lang"
|
||||
gdbmdb "git.defalsify.org/vise.git/db/gdbm"
|
||||
)
|
||||
|
||||
var (
|
||||
dbC map[string]chan db.Db
|
||||
)
|
||||
|
||||
type ThreadGdbmDb struct {
|
||||
db db.Db
|
||||
connStr string
|
||||
}
|
||||
|
||||
func NewThreadGdbmDb() *ThreadGdbmDb {
|
||||
if dbC == nil {
|
||||
dbC = make(map[string]chan db.Db)
|
||||
}
|
||||
return &ThreadGdbmDb{}
|
||||
}
|
||||
|
||||
func(tdb *ThreadGdbmDb) Connect(ctx context.Context, connStr string) error {
|
||||
var ok bool
|
||||
_, ok = dbC[connStr]
|
||||
if ok {
|
||||
logg.WarnCtxf(ctx, "already registered thread gdbm, skipping", "connStr", connStr)
|
||||
return nil
|
||||
}
|
||||
gdb := gdbmdb.NewGdbmDb()
|
||||
err := gdb.Connect(ctx, connStr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
dbC[connStr] = make(chan db.Db, 1)
|
||||
dbC[connStr]<- gdb
|
||||
tdb.connStr = connStr
|
||||
return nil
|
||||
}
|
||||
|
||||
func(tdb *ThreadGdbmDb) reserve() {
|
||||
if tdb.db == nil {
|
||||
tdb.db = <-dbC[tdb.connStr]
|
||||
}
|
||||
}
|
||||
|
||||
func(tdb *ThreadGdbmDb) release() {
|
||||
if tdb.db == nil {
|
||||
return
|
||||
}
|
||||
dbC[tdb.connStr] <- tdb.db
|
||||
tdb.db = nil
|
||||
}
|
||||
|
||||
func(tdb *ThreadGdbmDb) SetPrefix(pfx uint8) {
|
||||
tdb.reserve()
|
||||
tdb.db.SetPrefix(pfx)
|
||||
}
|
||||
|
||||
func(tdb *ThreadGdbmDb) SetSession(sessionId string) {
|
||||
tdb.reserve()
|
||||
tdb.db.SetSession(sessionId)
|
||||
}
|
||||
|
||||
func(tdb *ThreadGdbmDb) SetLanguage(lng *lang.Language) {
|
||||
tdb.reserve()
|
||||
tdb.db.SetLanguage(lng)
|
||||
}
|
||||
|
||||
func(tdb *ThreadGdbmDb) Safe() bool {
|
||||
tdb.reserve()
|
||||
v := tdb.db.Safe()
|
||||
tdb.release()
|
||||
return v
|
||||
}
|
||||
|
||||
func(tdb *ThreadGdbmDb) Prefix() uint8 {
|
||||
tdb.reserve()
|
||||
v := tdb.db.Prefix()
|
||||
tdb.release()
|
||||
return v
|
||||
}
|
||||
|
||||
func(tdb *ThreadGdbmDb) SetLock(typ uint8, locked bool) error {
|
||||
tdb.reserve()
|
||||
err := tdb.db.SetLock(typ, locked)
|
||||
tdb.release()
|
||||
return err
|
||||
}
|
||||
|
||||
func(tdb *ThreadGdbmDb) Put(ctx context.Context, key []byte, val []byte) error {
|
||||
tdb.reserve()
|
||||
err := tdb.db.Put(ctx, key, val)
|
||||
tdb.release()
|
||||
return err
|
||||
}
|
||||
|
||||
func(tdb *ThreadGdbmDb) Get(ctx context.Context, key []byte) ([]byte, error) {
|
||||
tdb.reserve()
|
||||
v, err := tdb.db.Get(ctx, key)
|
||||
tdb.release()
|
||||
return v, err
|
||||
}
|
||||
|
||||
func(tdb *ThreadGdbmDb) Close() error {
|
||||
tdb.reserve()
|
||||
close(dbC[tdb.connStr])
|
||||
err := tdb.db.Close()
|
||||
tdb.db = nil
|
||||
return err
|
||||
}
|
||||
@@ -8,57 +8,96 @@ import (
|
||||
|
||||
"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/persist"
|
||||
"git.defalsify.org/vise.git/resource"
|
||||
"git.defalsify.org/vise.git/logging"
|
||||
)
|
||||
|
||||
var (
|
||||
logg = logging.NewVanilla().WithDomain("storage")
|
||||
)
|
||||
|
||||
type StorageService interface {
|
||||
GetPersister(dbDir string, ctx context.Context) (*persist.Persister, error)
|
||||
GetUserdataDb(dbDir string, ctx context.Context) db.Db
|
||||
GetResource(resourceDir string, ctx context.Context) (resource.Resource, error)
|
||||
EnsureDbDir(dbDir string) error
|
||||
GetPersister(ctx context.Context) (*persist.Persister, error)
|
||||
GetUserdataDb(ctx context.Context) db.Db
|
||||
GetResource(ctx context.Context) (resource.Resource, error)
|
||||
EnsureDbDir() error
|
||||
}
|
||||
|
||||
type MenuStorageService struct{}
|
||||
|
||||
func (menuStorageService *MenuStorageService) GetPersister(dbDir string, ctx context.Context) (*persist.Persister, error) {
|
||||
store := gdbmdb.NewGdbmDb()
|
||||
storeFile := path.Join(dbDir, "state.gdbm")
|
||||
store.Connect(ctx, storeFile)
|
||||
pr := persist.NewPersister(store)
|
||||
return pr, nil
|
||||
type MenuStorageService struct{
|
||||
dbDir string
|
||||
resourceDir string
|
||||
resourceStore db.Db
|
||||
stateStore db.Db
|
||||
userDataStore db.Db
|
||||
}
|
||||
|
||||
func (menuStorageService *MenuStorageService) GetUserdataDb(dbDir string, ctx context.Context) db.Db {
|
||||
store := gdbmdb.NewGdbmDb()
|
||||
storeFile := path.Join(dbDir, "userdata.gdbm")
|
||||
store.Connect(ctx, storeFile)
|
||||
|
||||
return store
|
||||
func NewMenuStorageService(dbDir string, resourceDir string) *MenuStorageService {
|
||||
return &MenuStorageService{
|
||||
dbDir: dbDir,
|
||||
resourceDir: resourceDir,
|
||||
}
|
||||
}
|
||||
|
||||
func (menuStorageService *MenuStorageService) GetResource(resourceDir string, ctx context.Context) (resource.Resource, error) {
|
||||
store := fsdb.NewFsDb()
|
||||
err := store.Connect(ctx, resourceDir)
|
||||
func (ms *MenuStorageService) GetPersister(ctx context.Context) (*persist.Persister, error) {
|
||||
ms.stateStore = NewThreadGdbmDb()
|
||||
storeFile := path.Join(ms.dbDir, "state.gdbm")
|
||||
err := ms.stateStore.Connect(ctx, storeFile)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rfs := resource.NewDbResource(store)
|
||||
pr := persist.NewPersister(ms.stateStore)
|
||||
logg.TraceCtxf(ctx, "menu storage service", "persist", pr, "store", ms.stateStore)
|
||||
return pr, nil
|
||||
}
|
||||
|
||||
func (ms *MenuStorageService) GetUserdataDb(ctx context.Context) (db.Db, error) {
|
||||
ms.userDataStore = NewThreadGdbmDb()
|
||||
storeFile := path.Join(ms.dbDir, "userdata.gdbm")
|
||||
err := ms.userDataStore.Connect(ctx, storeFile)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ms.userDataStore, nil
|
||||
}
|
||||
|
||||
func (ms *MenuStorageService) GetResource(ctx context.Context) (resource.Resource, error) {
|
||||
ms.resourceStore = fsdb.NewFsDb()
|
||||
err := ms.resourceStore.Connect(ctx, ms.resourceDir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rfs := resource.NewDbResource(ms.resourceStore)
|
||||
return rfs, nil
|
||||
}
|
||||
|
||||
func (menuStorageService *MenuStorageService) GetStateStore(dbDir string, ctx context.Context) (db.Db, error) {
|
||||
store := gdbmdb.NewGdbmDb()
|
||||
storeFile := path.Join(dbDir, "state.gdbm")
|
||||
store.Connect(ctx, storeFile)
|
||||
return store, nil
|
||||
func (ms *MenuStorageService) GetStateStore(ctx context.Context) (db.Db, error) {
|
||||
if ms.stateStore != nil {
|
||||
panic("set up store when already exists")
|
||||
}
|
||||
ms.stateStore = NewThreadGdbmDb()
|
||||
storeFile := path.Join(ms.dbDir, "state.gdbm")
|
||||
err := ms.stateStore.Connect(ctx, storeFile)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ms.stateStore, nil
|
||||
}
|
||||
|
||||
func (menuStorageService *MenuStorageService) EnsureDbDir(dbDir string) error {
|
||||
err := os.MkdirAll(dbDir, 0700)
|
||||
func (ms *MenuStorageService) EnsureDbDir() error {
|
||||
err := os.MkdirAll(ms.dbDir, 0700)
|
||||
if err != nil {
|
||||
return fmt.Errorf("state dir create exited with error: %v\n", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ms *MenuStorageService) Close() error {
|
||||
errA := ms.stateStore.Close()
|
||||
errB := ms.userDataStore.Close()
|
||||
errC := ms.resourceStore.Close()
|
||||
if errA != nil || errB != nil || errC != nil {
|
||||
return fmt.Errorf("%v %v %v", errA, errB, errC)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
11
internal/utils/isocode.go
Normal file
11
internal/utils/isocode.go
Normal file
@@ -0,0 +1,11 @@
|
||||
package utils
|
||||
|
||||
var isoCodes = map[string]bool{
|
||||
"eng": true, // English
|
||||
"swa": true, // Swahili
|
||||
|
||||
}
|
||||
|
||||
func IsValidISO639(code string) bool {
|
||||
return isoCodes[code]
|
||||
}
|
||||
1
services/registration/_catch
Normal file
1
services/registration/_catch
Normal file
@@ -0,0 +1 @@
|
||||
Something went wrong.Please try again
|
||||
1
services/registration/_catch.vis
Normal file
1
services/registration/_catch.vis
Normal file
@@ -0,0 +1 @@
|
||||
HALT
|
||||
@@ -5,8 +5,10 @@ MOUT back 0
|
||||
HALT
|
||||
LOAD validate_amount 64
|
||||
RELOAD validate_amount
|
||||
CATCH api_failure flag_api_call_error 1
|
||||
CATCH invalid_amount flag_invalid_amount 1
|
||||
INCMP _ 0
|
||||
LOAD get_recipient 12
|
||||
LOAD get_sender 64
|
||||
LOAD get_amount 12
|
||||
INCMP transaction_pin *
|
||||
|
||||
1
services/registration/api_failure
Normal file
1
services/registration/api_failure
Normal file
@@ -0,0 +1 @@
|
||||
Failed to connect to the custodial service.Please try again.
|
||||
5
services/registration/api_failure.vis
Normal file
5
services/registration/api_failure.vis
Normal file
@@ -0,0 +1,5 @@
|
||||
MOUT retry 0
|
||||
MOUT quit 9
|
||||
HALT
|
||||
INCMP _ 0
|
||||
INCMP quit 9
|
||||
@@ -1,4 +1,5 @@
|
||||
LOAD reset_account_authorized 0
|
||||
RELOAD reset_account_authorized
|
||||
MOUT my_balance 1
|
||||
MOUT community_balance 2
|
||||
MOUT back 0
|
||||
|
||||
@@ -1 +1 @@
|
||||
Your community balance is: 0.00SRF
|
||||
{{.fetch_custodial_balances}}
|
||||
@@ -1,5 +1,11 @@
|
||||
LOAD reset_incorrect 0
|
||||
LOAD reset_incorrect 6
|
||||
LOAD fetch_custodial_balances 0
|
||||
CATCH api_failure flag_api_call_error 1
|
||||
MAP fetch_custodial_balances
|
||||
CATCH incorrect_pin flag_incorrect_pin 1
|
||||
CATCH pin_entry flag_account_authorized 0
|
||||
LOAD quit_with_balance 0
|
||||
MOUT back 0
|
||||
MOUT quit 9
|
||||
HALT
|
||||
INCMP _ 0
|
||||
INCMP quit 9
|
||||
|
||||
1
services/registration/edit_familyname_menu
Normal file
1
services/registration/edit_familyname_menu
Normal file
@@ -0,0 +1 @@
|
||||
Edit family name
|
||||
1
services/registration/edit_familyname_menu_swa
Normal file
1
services/registration/edit_familyname_menu_swa
Normal file
@@ -0,0 +1 @@
|
||||
Weka jina la familia
|
||||
@@ -2,19 +2,19 @@ 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
|
||||
MOUT edit_location 4
|
||||
MOUT edit_offerings 5
|
||||
MOUT view 6
|
||||
MOUT edit_familyname 2
|
||||
MOUT edit_gender 3
|
||||
MOUT edit_yob 4
|
||||
MOUT edit_location 5
|
||||
MOUT edit_offerings 6
|
||||
MOUT view 7
|
||||
MOUT back 0
|
||||
HALT
|
||||
INCMP _ 0
|
||||
LOAD set_reset_single_edit 0
|
||||
RELOAD set_reset_single_edit
|
||||
INCMP my_account 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
|
||||
INCMP enter_familyname 2
|
||||
INCMP select_gender 3
|
||||
INCMP enter_yob 4
|
||||
INCMP enter_location 5
|
||||
INCMP enter_offerings 6
|
||||
INCMP view_profile 7
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
LOAD save_firstname 0
|
||||
CATCH incorrect_pin flag_incorrect_pin 1
|
||||
CATCH profile_update_success flag_allow_update 1
|
||||
LOAD save_familyname 0
|
||||
RELOAD save_familyname
|
||||
MOUT back 0
|
||||
HALT
|
||||
RELOAD save_familyname
|
||||
INCMP _ 0
|
||||
INCMP select_gender *
|
||||
INCMP pin_entry *
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
Weka jina la familia
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
CATCH incorrect_date_format flag_incorrect_date_format 1
|
||||
LOAD save_yob 0
|
||||
CATCH update_success flag_allow_update 1
|
||||
CATCH incorrect_pin flag_incorrect_pin 1
|
||||
CATCH profile_update_success flag_allow_update 1
|
||||
LOAD save_location 0
|
||||
MOUT back 0
|
||||
HALT
|
||||
RELOAD save_location
|
||||
INCMP _ 0
|
||||
LOAD save_location 0
|
||||
CATCH pin_entry flag_single_edit 1
|
||||
INCMP enter_offerings *
|
||||
INCMP pin_entry *
|
||||
|
||||
@@ -1,4 +1,12 @@
|
||||
CATCH incorrect_pin flag_incorrect_pin 1
|
||||
CATCH profile_update_success flag_allow_update 1
|
||||
LOAD save_firstname 0
|
||||
RELOAD save_firstname
|
||||
MOUT back 0
|
||||
HALT
|
||||
RELOAD save_firstname
|
||||
INCMP _ 0
|
||||
INCMP enter_familyname *
|
||||
INCMP pin_entry *
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
LOAD save_location 0
|
||||
CATCH incorrect_pin flag_incorrect_pin 1
|
||||
CATCH update_success flag_allow_update 1
|
||||
CATCH profile_update_success flag_allow_update 1
|
||||
LOAD save_offerings 0
|
||||
MOUT back 0
|
||||
HALT
|
||||
LOAD save_offerings 0
|
||||
RELOAD save_offerings
|
||||
INCMP _ 0
|
||||
INCMP pin_entry *
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
LOAD save_gender 0
|
||||
CATCH update_success flag_allow_update 1
|
||||
CATCH incorrect_pin flag_incorrect_pin 1
|
||||
CATCH profile_update_success flag_allow_update 1
|
||||
LOAD save_yob 0
|
||||
MOUT back 0
|
||||
HALT
|
||||
LOAD verify_yob 0
|
||||
CATCH incorrect_date_format flag_incorrect_date_format 1
|
||||
RELOAD save_yob
|
||||
INCMP _ 0
|
||||
LOAD verify_yob 8
|
||||
LOAD save_yob 0
|
||||
CATCH pin_entry flag_single_edit 1
|
||||
INCMP enter_location *
|
||||
INCMP pin_entry *
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
LOAD check_balance 64
|
||||
RELOAD check_balance
|
||||
CATCH api_failure flag_api_call_error 1
|
||||
MAP check_balance
|
||||
MOUT send 1
|
||||
MOUT vouchers 2
|
||||
|
||||
@@ -7,7 +7,7 @@ MOUT pin_options 5
|
||||
MOUT my_address 6
|
||||
MOUT back 0
|
||||
HALT
|
||||
INCMP _ 0
|
||||
INCMP main 0
|
||||
INCMP edit_profile 1
|
||||
INCMP change_language 2
|
||||
INCMP balances 3
|
||||
|
||||
@@ -1 +1 @@
|
||||
Your balance is: 0.00 SRF
|
||||
{{.fetch_custodial_balances}}
|
||||
@@ -1,5 +1,11 @@
|
||||
LOAD reset_incorrect 0
|
||||
LOAD reset_incorrect 6
|
||||
LOAD fetch_custodial_balances 0
|
||||
CATCH api_failure flag_api_call_error 1
|
||||
MAP fetch_custodial_balances
|
||||
CATCH incorrect_pin flag_incorrect_pin 1
|
||||
CATCH pin_entry flag_account_authorized 0
|
||||
LOAD quit_with_balance 0
|
||||
MOUT back 0
|
||||
MOUT quit 9
|
||||
HALT
|
||||
INCMP _ 0
|
||||
INCMP quit 9
|
||||
|
||||
@@ -14,3 +14,4 @@ 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
|
||||
flag,flag_api_call_error,25,this is set when communication to an external service fails
|
||||
|
||||
|
1
services/registration/profile_update_success
Normal file
1
services/registration/profile_update_success
Normal file
@@ -0,0 +1 @@
|
||||
Profile updated successfully
|
||||
5
services/registration/profile_update_success.vis
Normal file
5
services/registration/profile_update_success.vis
Normal file
@@ -0,0 +1,5 @@
|
||||
MOUT back 0
|
||||
MOUT quit 9
|
||||
HALT
|
||||
INCMP edit_profile 0
|
||||
INCMP quit 9
|
||||
1
services/registration/profile_update_success_swa
Normal file
1
services/registration/profile_update_success_swa
Normal file
@@ -0,0 +1 @@
|
||||
Ombi la Kuweka wasifu limefanikiwa
|
||||
@@ -1,6 +1,8 @@
|
||||
CATCH select_language flag_language_set 0
|
||||
CATCH terms flag_account_created 0
|
||||
LOAD check_account_status 0
|
||||
RELOAD check_account_status
|
||||
CATCH api_failure flag_api_call_error 1
|
||||
CATCH account_pending flag_account_pending 1
|
||||
CATCH create_pin flag_pin_set 0
|
||||
CATCH main flag_account_success 1
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
LOAD save_familyname 0
|
||||
CATCH update_success flag_allow_update 1
|
||||
CATCH incorrect_pin flag_incorrect_pin 1
|
||||
CATCH profile_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 flag_single_edit 1
|
||||
INCMP _ 0
|
||||
INCMP enter_yob 1
|
||||
INCMP enter_yob 2
|
||||
INCMP enter_yob 3
|
||||
INCMP set_male 1
|
||||
INCMP set_female 2
|
||||
INCMP set_unspecified 3
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
MOUT english 0
|
||||
MOUT kiswahili 1
|
||||
HALT
|
||||
INCMP set_default 0
|
||||
INCMP set_eng 0
|
||||
INCMP set_swa 1
|
||||
INCMP . *
|
||||
|
||||
4
services/registration/set_female.vis
Normal file
4
services/registration/set_female.vis
Normal file
@@ -0,0 +1,4 @@
|
||||
LOAD save_gender 0
|
||||
CATCH incorrect_pin flag_incorrect_pin 1
|
||||
CATCH profile_update_success flag_allow_update 1
|
||||
MOVE pin_entry
|
||||
4
services/registration/set_male.vis
Normal file
4
services/registration/set_male.vis
Normal file
@@ -0,0 +1,4 @@
|
||||
LOAD save_gender 0
|
||||
CATCH incorrect_pin flag_incorrect_pin 1
|
||||
CATCH profile_update_success flag_allow_update 1
|
||||
MOVE pin_entry
|
||||
4
services/registration/set_unspecified.vis
Normal file
4
services/registration/set_unspecified.vis
Normal file
@@ -0,0 +1,4 @@
|
||||
LOAD save_gender 0
|
||||
CATCH incorrect_pin flag_incorrect_pin 1
|
||||
CATCH profile_update_success flag_allow_update 1
|
||||
MOVE pin_entry
|
||||
@@ -1,7 +1,7 @@
|
||||
LOAD reset_incorrect 6
|
||||
CATCH incorrect_pin flag_incorrect_pin 1
|
||||
CATCH _ flag_account_authorized 0
|
||||
LOAD get_amount 10
|
||||
RELOAD get_amount
|
||||
MAP get_amount
|
||||
RELOAD get_recipient
|
||||
MAP get_recipient
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
{{.get_recipient}} will receive {{.validate_amount}} from {{.get_sender}}
|
||||
{{.get_recipient}} will receive {{.get_amount}} from {{.get_sender}}
|
||||
Please enter your PIN to confirm:
|
||||
@@ -1,12 +1,13 @@
|
||||
MAP validate_amount
|
||||
RELOAD get_amount
|
||||
MAP get_amount
|
||||
RELOAD get_recipient
|
||||
MAP get_recipient
|
||||
RELOAD get_sender
|
||||
MAP get_sender
|
||||
MOUT back 0
|
||||
MOUT quit 9
|
||||
HALT
|
||||
LOAD authorize_account 6
|
||||
HALT
|
||||
RELOAD authorize_account
|
||||
CATCH incorrect_pin flag_incorrect_pin 1
|
||||
INCMP _ 0
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
{{.get_recipient}} atapokea {{.validate_amount}} kutoka kwa {{.get_sender}}
|
||||
{{.get_recipient}} atapokea {{.get_amount}} kutoka kwa {{.get_sender}}
|
||||
Tafadhali weka PIN yako kudhibitisha:
|
||||
1
services/registration/view_menu_swa
Normal file
1
services/registration/view_menu_swa
Normal file
@@ -0,0 +1 @@
|
||||
Angalia Wasifu
|
||||
Reference in New Issue
Block a user