visedriver/internal/handlers/ussd/menuhandler.go

852 lines
24 KiB
Go
Raw Normal View History

package ussd
import (
"bytes"
"context"
2024-09-02 15:04:53 +02:00
"errors"
"fmt"
"path"
"regexp"
2024-08-27 13:57:26 +02:00
"strconv"
"strings"
2024-08-31 09:21:20 +02:00
"git.defalsify.org/vise.git/asm"
"git.defalsify.org/vise.git/engine"
"git.defalsify.org/vise.git/lang"
"git.defalsify.org/vise.git/resource"
"git.defalsify.org/vise.git/state"
"git.grassecon.net/urdt/ussd/internal/handlers/server"
2024-08-27 09:16:25 +02:00
"git.grassecon.net/urdt/ussd/internal/models"
"git.grassecon.net/urdt/ussd/internal/utils"
2024-09-02 15:04:53 +02:00
"github.com/graygnuorg/go-gdbm"
"gopkg.in/leonelquinteros/gotext.v1"
)
var (
2024-08-29 22:15:58 +02:00
scriptDir = path.Join("services", "registration")
translationDir = path.Join(scriptDir, "locale")
2024-09-02 15:04:53 +02:00
dbFile = path.Join(scriptDir, "vise.gdbm")
)
2024-09-02 15:04:53 +02:00
const (
TrackingIdKey = "TRACKINGID"
PublicKeyKey = "PUBLICKEY"
CustodialIdKey = "CUSTODIALID"
AccountPin = "ACCOUNTPIN"
AccountStatus = "ACCOUNTSTATUS"
FirstName = "FIRSTNAME"
FamilyName = "FAMILYNAME"
YearOfBirth = "YOB"
Location = "LOCATION"
Gender = "GENDER"
Offerings = "OFFERINGS"
Recipient = "RECIPIENT"
Amount = "AMOUNT"
)
func toBytes(s string) []byte {
return []byte(s)
}
type FSData struct {
Path string
St *state.State
}
type Handlers struct {
fs *FSData
2024-09-02 15:04:53 +02:00
db *gdbm.Database
2024-08-31 09:21:20 +02:00
parser *asm.FlagParser
2024-08-29 18:56:25 +02:00
accountFileHandler utils.AccountFileHandlerInterface
2024-08-29 22:15:58 +02:00
accountService server.AccountServiceInterface
}
2024-08-31 09:21:20 +02:00
func NewHandlers(dir string, st *state.State) (*Handlers, error) {
2024-09-02 15:04:53 +02:00
db, err := gdbm.Open(dbFile, gdbm.ModeWrcreat)
if err != nil {
panic(err)
}
2024-08-31 09:26:49 +02:00
pfp := path.Join(scriptDir, "pp.csv")
2024-08-31 09:21:20 +02:00
parser := asm.NewFlagParser()
2024-09-02 15:04:53 +02:00
_, err = parser.Load(pfp)
2024-08-31 09:21:20 +02:00
if err != nil {
return nil, err
}
return &Handlers{
2024-09-02 15:04:53 +02:00
db: db,
fs: &FSData{
2024-08-31 09:21:20 +02:00
Path: dir,
St: st,
},
2024-08-31 09:21:20 +02:00
parser: parser,
accountFileHandler: utils.NewAccountFileHandler(dir + "_data"),
2024-08-29 22:15:58 +02:00
accountService: &server.AccountService{},
2024-08-31 09:21:20 +02:00
}, nil
}
// Define the regex pattern as a constant
const pinPattern = `^\d{4}$`
// isValidPIN checks whether the given input is a 4 digit number
func isValidPIN(pin string) bool {
match, _ := regexp.MatchString(pinPattern, pin)
return match
}
func (h *Handlers) PreloadFlags(flagKeys []string) (map[string]uint32, error) {
flags := make(map[string]uint32)
for _, key := range flagKeys {
flag, err := h.parser.GetFlag(key)
if err != nil {
return nil, err
}
flags[key] = flag
}
return flags, nil
}
2024-08-28 15:23:52 +02:00
// SetLanguage sets the language across the menu
func (h *Handlers) SetLanguage(ctx context.Context, sym string, input []byte) (resource.Result, error) {
inputStr := string(input)
res := resource.Result{}
switch inputStr {
case "0":
res.FlagSet = []uint32{state.FLAG_LANG}
res.Content = "eng"
case "1":
res.FlagSet = []uint32{state.FLAG_LANG}
res.Content = "swa"
default:
}
res.FlagSet = append(res.FlagSet, models.USERFLAG_LANGUAGE_SET)
return res, nil
}
2024-08-28 15:23:52 +02:00
// CreateAccount checks if any account exists on the JSON data file, and if not
// creates an account on the API,
// sets the default values and flags
func (h *Handlers) CreateAccount(ctx context.Context, sym string, input []byte) (resource.Result, error) {
res := resource.Result{}
err := h.accountFileHandler.EnsureFileExists()
if err != nil {
return res, err
}
// if an account exists, return to prevent duplicate account creation
existingAccountData, err := h.accountFileHandler.ReadAccountData()
if existingAccountData != nil {
return res, err
}
2024-08-29 18:56:25 +02:00
accountResp, err := h.accountService.CreateAccount()
if err != nil {
res.FlagSet = append(res.FlagSet, models.USERFLAG_ACCOUNT_CREATION_FAILED)
return res, err
}
2024-09-02 15:04:53 +02:00
data := map[string]string{
TrackingIdKey: accountResp.Result.TrackingId,
PublicKeyKey: accountResp.Result.PublicKey,
CustodialIdKey: accountResp.Result.CustodialId.String(),
}
2024-09-02 15:04:53 +02:00
for key, value := range data {
err := h.db.Store(toBytes(key), toBytes(value), true)
if err != nil {
return res, err
}
}
res.FlagSet = append(res.FlagSet, models.USERFLAG_ACCOUNT_CREATED)
return res, err
}
2024-08-27 12:30:00 +02:00
// SavePin persists the user's PIN choice into the filesystem
func (h *Handlers) SavePin(ctx context.Context, sym string, input []byte) (resource.Result, error) {
res := resource.Result{}
accountPIN := string(input)
2024-09-02 15:04:53 +02:00
// accountData, err := h.accountFileHandler.ReadAccountData()
// if err != nil {
// return res, err
// }
2024-08-27 23:17:45 +02:00
// Validate that the PIN is a 4-digit number
if !isValidPIN(accountPIN) {
res.FlagSet = append(res.FlagSet, models.USERFLAG_INCORRECTPIN)
return res, nil
}
2024-08-27 23:17:45 +02:00
res.FlagReset = append(res.FlagReset, models.USERFLAG_INCORRECTPIN)
2024-09-02 15:04:53 +02:00
//accountData["AccountPIN"] = accountPIN
2024-09-02 15:04:53 +02:00
key := []byte(AccountPin)
value := []byte(accountPIN)
h.db.Store(key, value, true)
// err = h.accountFileHandler.WriteAccountData(accountData)
// if err != nil {
// return res, err
// }
return res, nil
}
2024-08-29 22:15:58 +02:00
// SetResetSingleEdit sets and resets flags to allow gradual editing of profile information.
func (h *Handlers) SetResetSingleEdit(ctx context.Context, sym string, input []byte) (resource.Result, error) {
res := resource.Result{}
menuOption := string(input)
switch menuOption {
case "2":
2024-08-29 22:15:58 +02:00
res.FlagReset = append(res.FlagSet, models.USERFLAG_ALLOW_UPDATE)
res.FlagSet = append(res.FlagSet, models.USERFLAG_SINGLE_EDIT)
case "3":
2024-08-29 22:15:58 +02:00
res.FlagReset = append(res.FlagSet, models.USERFLAG_ALLOW_UPDATE)
res.FlagSet = append(res.FlagSet, models.USERFLAG_SINGLE_EDIT)
case "4":
2024-08-29 22:15:58 +02:00
res.FlagReset = append(res.FlagSet, models.USERFLAG_ALLOW_UPDATE)
res.FlagSet = append(res.FlagSet, models.USERFLAG_SINGLE_EDIT)
default:
res.FlagReset = append(res.FlagReset, models.USERFLAG_SINGLE_EDIT)
}
return res, nil
}
2024-08-28 15:23:52 +02:00
// VerifyPin checks whether the confirmation PIN is similar to the account PIN
2024-08-29 22:15:58 +02:00
// If similar, it sets the USERFLAG_PIN_SET flag allowing the user
2024-08-28 15:23:52 +02:00
// to access the main menu
func (h *Handlers) VerifyPin(ctx context.Context, sym string, input []byte) (resource.Result, error) {
res := resource.Result{}
2024-09-02 15:04:53 +02:00
pin, err := h.db.Fetch([]byte(AccountPin))
if err == nil {
if bytes.Equal(input, pin) {
res.FlagSet = []uint32{models.USERFLAG_VALIDPIN}
res.FlagReset = []uint32{models.USERFLAG_PINMISMATCH}
res.FlagSet = append(res.FlagSet, models.USERFLAG_PIN_SET)
} else {
res.FlagSet = []uint32{models.USERFLAG_PINMISMATCH}
}
} else if errors.Is(err, gdbm.ErrItemNotFound) {
//PIN not set yet
} else {
2024-09-02 15:04:53 +02:00
return res, err
}
return res, nil
}
2024-08-31 09:21:20 +02:00
// codeFromCtx retrieves language codes from the context that can be used for handling translations
func codeFromCtx(ctx context.Context) string {
var code string
engine.Logg.DebugCtxf(ctx, "in msg", "ctx", ctx, "val", code)
if ctx.Value("Language") != nil {
lang := ctx.Value("Language").(lang.Language)
code = lang.Code
}
return code
}
2024-08-27 12:30:00 +02:00
// SaveFirstname updates the first name in a JSON data file with the provided input.
func (h *Handlers) SaveFirstname(cxt context.Context, sym string, input []byte) (resource.Result, error) {
res := resource.Result{}
2024-09-02 15:04:53 +02:00
// accountData, err := h.accountFileHandler.ReadAccountData()
// if err != nil {
// return res, err
// }
if len(input) > 0 {
name := string(input)
2024-09-02 15:04:53 +02:00
//accountData["FirstName"] = name
2024-09-02 15:04:53 +02:00
key := []byte(FirstName)
value := []byte(name)
h.db.Store(key, value, true)
// err = h.accountFileHandler.WriteAccountData(accountData)
// if err != nil {
// return res, err
// }
}
return res, nil
}
2024-08-27 12:30:00 +02:00
// SaveFamilyname updates the family name in a JSON data file with the provided input.
func (h *Handlers) SaveFamilyname(cxt context.Context, sym string, input []byte) (resource.Result, error) {
res := resource.Result{}
if len(input) > 0 {
secondname := string(input)
2024-09-02 15:04:53 +02:00
key := []byte(FamilyName)
value := []byte(secondname)
2024-09-02 15:04:53 +02:00
h.db.Store(key, value, true)
}
return res, nil
}
2024-08-27 12:30:00 +02:00
// SaveYOB updates the Year of Birth(YOB) in a JSON data file with the provided input.
func (h *Handlers) SaveYob(cxt context.Context, sym string, input []byte) (resource.Result, error) {
res := resource.Result{}
2024-08-26 20:58:21 +02:00
yob := string(input)
2024-08-27 13:57:26 +02:00
if len(yob) == 4 {
yob := string(input)
2024-09-02 15:04:53 +02:00
//accountData["YOB"] = yob
key := []byte(YearOfBirth)
value := []byte(yob)
2024-09-02 15:04:53 +02:00
h.db.Store(key, value, true)
// err = h.accountFileHandler.WriteAccountData(accountData)
// if err != nil {
// return res, err
// }
}
return res, nil
}
2024-08-27 12:30:00 +02:00
// SaveLocation updates the location in a JSON data file with the provided input.
func (h *Handlers) SaveLocation(cxt context.Context, sym string, input []byte) (resource.Result, error) {
res := resource.Result{}
2024-09-02 15:04:53 +02:00
// accountData, err := h.accountFileHandler.ReadAccountData()
// if err != nil {
// return res, err
// }
if len(input) > 0 {
location := string(input)
2024-09-02 15:04:53 +02:00
key := []byte(Location)
value := []byte(location)
2024-09-02 15:04:53 +02:00
h.db.Store(key, value, true)
}
return res, nil
}
2024-08-27 12:30:00 +02:00
// SaveGender updates the gender in a JSON data file with the provided input.
func (h *Handlers) SaveGender(ctx context.Context, sym string, input []byte) (resource.Result, error) {
res := resource.Result{}
if len(input) > 0 {
gender := string(input)
switch gender {
case "1":
gender = "Male"
case "2":
gender = "Female"
case "3":
2024-08-29 22:15:58 +02:00
gender = "Unspecified"
}
2024-09-02 15:04:53 +02:00
//accountData["Gender"] = gender
key := []byte(Gender)
value := []byte(gender)
2024-09-02 15:04:53 +02:00
h.db.Store(key, value, true)
// err = h.accountFileHandler.WriteAccountData(accountData)
// if err != nil {
// return res, err
// }
}
return res, nil
}
2024-08-27 12:30:00 +02:00
// SaveOfferings updates the offerings(goods and services provided by the user) in a JSON data file with the provided input.
func (h *Handlers) SaveOfferings(ctx context.Context, sym string, input []byte) (resource.Result, error) {
res := resource.Result{}
2024-09-02 15:04:53 +02:00
// accountData, err := h.accountFileHandler.ReadAccountData()
// if err != nil {
// return res, err
// }
if len(input) > 0 {
offerings := string(input)
2024-09-02 15:04:53 +02:00
//accountData["Offerings"] = offerings
key := []byte(Offerings)
value := []byte(offerings)
2024-09-02 15:04:53 +02:00
h.db.Store(key, value, true)
// err = h.accountFileHandler.WriteAccountData(accountData)
// if err != nil {
// return res, err
// }
}
return res, nil
}
2024-08-29 22:15:58 +02:00
// ResetAllowUpdate resets the allowupdate flag that allows a user to update profile data.
func (h *Handlers) ResetAllowUpdate(ctx context.Context, sym string, input []byte) (resource.Result, error) {
res := resource.Result{}
2024-08-29 22:15:58 +02:00
res.FlagReset = append(res.FlagReset, models.USERFLAG_ALLOW_UPDATE)
return res, nil
}
2024-08-29 22:15:58 +02:00
// ResetAccountAuthorized resets the account authorization flag after a successful PIN entry.
func (h *Handlers) ResetAccountAuthorized(ctx context.Context, sym string, input []byte) (resource.Result, error) {
res := resource.Result{}
2024-08-29 22:15:58 +02:00
res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_AUTHORIZED)
return res, nil
}
2024-08-28 15:23:52 +02:00
// CheckIdentifier retrieves the PublicKey from the JSON data file.
func (h *Handlers) CheckIdentifier(ctx context.Context, sym string, input []byte) (resource.Result, error) {
res := resource.Result{}
2024-09-02 15:04:53 +02:00
// accountData, err := h.accountFileHandler.ReadAccountData()
// if err != nil {
// return res, err
// }
publicKey, err := h.db.Fetch([]byte(PublicKeyKey))
if err != nil {
return res, err
}
2024-09-02 15:04:53 +02:00
res.Content = string(publicKey)
return res, nil
}
2024-08-29 22:15:58 +02:00
// Authorize attempts to unlock the next sequential nodes by verifying the provided PIN against the already set PIN.
2024-08-28 11:19:38 +02:00
// It sets the required flags that control the flow.
2024-08-29 22:15:58 +02:00
func (h *Handlers) Authorize(ctx context.Context, sym string, input []byte) (resource.Result, error) {
res := resource.Result{}
2024-09-02 15:04:53 +02:00
//pin := string(input)
2024-09-02 15:04:53 +02:00
// accountData, err := h.accountFileHandler.ReadAccountData()
// if err != nil {
// return res, err
// }
// Preload the required flags
flagKeys := []string{"flag_incorrect_pin", "flag_account_authorized", "flag_allow_update"}
flags, err := h.PreloadFlags(flagKeys)
if err != nil {
return res, err
}
2024-09-02 15:04:53 +02:00
storedpin, err := h.db.Fetch([]byte(AccountPin))
if err == nil {
if len(input) == 4 {
if bytes.Equal(input, storedpin) {
if h.fs.St.MatchFlag(flags["flag_account_authorized"], false) {
res.FlagReset = append(res.FlagReset, flags["flag_incorrect_pin"])
res.FlagSet = append(res.FlagSet, flags["flag_allow_update"], flags["flag_account_authorized"])
} else {
res.FlagSet = append(res.FlagSet, flags["flag_allow_update"])
res.FlagReset = append(res.FlagReset, flags["flag_account_authorized"])
}
} else {
res.FlagSet = append(res.FlagSet, flags["flag_incorrect_pin"])
res.FlagReset = append(res.FlagReset, flags["flag_account_authorized"])
return res, nil
}
}
2024-09-02 15:04:53 +02:00
} else if errors.Is(err, gdbm.ErrItemNotFound) {
//PIN not set yet
} else {
return res, err
}
2024-09-02 15:04:53 +02:00
// if len(input) == 4 {
// if pin != accountData["AccountPIN"] {
// res.FlagSet = append(res.FlagSet, flags["flag_incorrect_pin"])
// res.FlagReset = append(res.FlagReset, flags["flag_account_authorized"])
// return res, nil
// }
// if h.fs.St.MatchFlag(flags["flag_account_authorized"], false) {
// res.FlagReset = append(res.FlagReset, flags["flag_incorrect_pin"])
// res.FlagSet = append(res.FlagSet, flags["flag_allow_update"], flags["flag_account_authorized"])
// } else {
// res.FlagSet = append(res.FlagSet, flags["flag_allow_update"])
// res.FlagReset = append(res.FlagReset, flags["flag_account_authorized"])
// }
// }
return res, nil
}
2024-08-29 22:15:58 +02:00
// ResetIncorrectPin resets the incorrect pin flag after a new PIN attempt.
func (h *Handlers) ResetIncorrectPin(ctx context.Context, sym string, input []byte) (resource.Result, error) {
res := resource.Result{}
res.FlagReset = append(res.FlagReset, models.USERFLAG_INCORRECTPIN)
return res, nil
}
2024-08-28 15:23:52 +02:00
// CheckAccountStatus queries the API using the TrackingId and sets flags
// based on the account status
func (h *Handlers) CheckAccountStatus(ctx context.Context, sym string, input []byte) (resource.Result, error) {
res := resource.Result{}
2024-09-02 15:04:53 +02:00
// accountData, err := h.accountFileHandler.ReadAccountData()
// if err != nil {
// return res, err
// }
trackingId, err := h.db.Fetch([]byte(TrackingIdKey))
if err != nil {
return res, err
}
2024-09-02 15:04:53 +02:00
status, err := h.accountService.CheckAccountStatus(string(trackingId))
if err != nil {
fmt.Println("Error checking account status:", err)
2024-09-02 15:04:53 +02:00
return res, err
}
2024-09-02 15:04:53 +02:00
//accountData["Status"] = status
err = h.db.Store(toBytes(TrackingIdKey), toBytes(status), true)
if err != nil {
return res, nil
}
if status == "SUCCESS" {
res.FlagSet = append(res.FlagSet, models.USERFLAG_ACCOUNT_SUCCESS)
res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_PENDING)
} else {
res.FlagReset = append(res.FlagSet, models.USERFLAG_ACCOUNT_SUCCESS)
res.FlagSet = append(res.FlagReset, models.USERFLAG_ACCOUNT_PENDING)
}
2024-09-02 15:04:53 +02:00
// err = h.accountFileHandler.WriteAccountData(accountData)
// if err != nil {
// return res, err
// }
return res, nil
}
2024-08-28 15:23:52 +02:00
// Quit displays the Thank you message and exits the menu
func (h *Handlers) Quit(ctx context.Context, sym string, input []byte) (resource.Result, error) {
res := resource.Result{}
2024-08-29 22:05:41 +02:00
code := codeFromCtx(ctx)
l := gotext.NewLocale(translationDir, code)
l.AddDomain("default")
2024-08-31 09:21:20 +02:00
2024-08-29 22:05:41 +02:00
res.Content = l.Get("Thank you for using Sarafu. Goodbye!")
2024-08-29 22:22:27 +02:00
res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_AUTHORIZED)
return res, nil
}
2024-08-28 15:23:52 +02:00
// VerifyYob verifies the length of the given input
func (h *Handlers) VerifyYob(ctx context.Context, sym string, input []byte) (resource.Result, error) {
res := resource.Result{}
date := string(input)
2024-08-27 13:57:26 +02:00
_, err := strconv.Atoi(date)
if err != nil {
// If conversion fails, input is not numeric
res.FlagSet = append(res.FlagSet, models.USERFLAG_INCORRECTDATEFORMAT)
return res, nil
}
2024-08-27 13:57:26 +02:00
if len(date) == 4 {
res.FlagReset = append(res.FlagReset, models.USERFLAG_INCORRECTDATEFORMAT)
2024-08-27 13:57:26 +02:00
} else {
res.FlagSet = append(res.FlagSet, models.USERFLAG_INCORRECTDATEFORMAT)
}
return res, nil
}
2024-09-02 09:03:57 +02:00
// ResetIncorrectYob resets the incorrect date format flag after a new attempt
func (h *Handlers) ResetIncorrectYob(ctx context.Context, sym string, input []byte) (resource.Result, error) {
res := resource.Result{}
res.FlagReset = append(res.FlagReset, models.USERFLAG_INCORRECTDATEFORMAT)
return res, nil
}
2024-08-29 22:15:58 +02:00
// CheckBalance retrieves the balance from the API using the "PublicKey" and sets
2024-08-28 15:23:52 +02:00
// the balance as the result content
func (h *Handlers) CheckBalance(ctx context.Context, sym string, input []byte) (resource.Result, error) {
res := resource.Result{}
2024-09-02 15:04:53 +02:00
publicKey, err := h.db.Fetch([]byte(PublicKeyKey))
if err != nil {
return res, err
}
2024-09-02 15:04:53 +02:00
balance, err := h.accountService.CheckBalance(string(publicKey))
if err != nil {
return res, nil
}
res.Content = balance
return res, nil
}
2024-08-28 15:23:52 +02:00
// ValidateRecipient validates that the given input is a valid phone number.
func (h *Handlers) ValidateRecipient(ctx context.Context, sym string, input []byte) (resource.Result, error) {
res := resource.Result{}
recipient := string(input)
if recipient != "0" {
// mimic invalid number check
if recipient == "000" {
res.FlagSet = append(res.FlagSet, models.USERFLAG_INVALID_RECIPIENT)
res.Content = recipient
return res, nil
}
2024-09-02 15:04:53 +02:00
// accountData["Recipient"] = recipient
key := []byte(Recipient)
value := []byte(recipient)
2024-09-02 15:04:53 +02:00
h.db.Store(key, value, true)
}
return res, nil
}
2024-08-28 15:23:52 +02:00
// TransactionReset resets the previous transaction data (Recipient and Amount)
// as well as the invalid flags
func (h *Handlers) TransactionReset(ctx context.Context, sym string, input []byte) (resource.Result, error) {
res := resource.Result{}
2024-09-02 15:04:53 +02:00
err := h.db.Delete([]byte(Amount))
if err != nil && !errors.Is(err, gdbm.ErrItemNotFound) {
panic(err)
}
2024-09-02 15:04:53 +02:00
err = h.db.Delete([]byte(Recipient))
if err != nil && !errors.Is(err, gdbm.ErrItemNotFound) {
panic(err)
}
res.FlagReset = append(res.FlagReset, models.USERFLAG_INVALID_RECIPIENT, models.USERFLAG_INVALID_RECIPIENT_WITH_INVITE)
return res, nil
}
2024-08-28 15:23:52 +02:00
// ResetTransactionAmount resets the transaction amount and invalid flag
func (h *Handlers) ResetTransactionAmount(ctx context.Context, sym string, input []byte) (resource.Result, error) {
res := resource.Result{}
2024-09-02 15:04:53 +02:00
err := h.db.Delete([]byte(Amount))
if err != nil && !errors.Is(err, gdbm.ErrItemNotFound) {
panic(err)
}
res.FlagReset = append(res.FlagReset, models.USERFLAG_INVALID_AMOUNT)
return res, nil
}
2024-08-29 22:15:58 +02:00
// MaxAmount gets the current balance from the API and sets it as
2024-08-28 15:23:52 +02:00
// the result content.
func (h *Handlers) MaxAmount(ctx context.Context, sym string, input []byte) (resource.Result, error) {
res := resource.Result{}
2024-09-02 15:04:53 +02:00
publicKey, err := h.db.Fetch([]byte(PublicKeyKey))
2024-08-27 15:10:43 +02:00
if err != nil {
return res, err
}
2024-09-02 15:04:53 +02:00
balance, err := h.accountService.CheckBalance(string(publicKey))
2024-08-27 15:10:43 +02:00
if err != nil {
return res, nil
}
res.Content = balance
return res, nil
}
2024-08-28 15:23:52 +02:00
// ValidateAmount ensures that the given input is a valid amount and that
// it is not more than the current balance.
func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte) (resource.Result, error) {
res := resource.Result{}
amountStr := string(input)
2024-09-02 15:04:53 +02:00
publicKey, err := h.db.Fetch([]byte(PublicKeyKey))
if err != nil {
return res, err
}
2024-09-02 15:04:53 +02:00
balanceStr, err := h.accountService.CheckBalance(string(publicKey))
if err != nil {
return res, err
}
res.Content = balanceStr
// Parse the balance
balanceParts := strings.Split(balanceStr, " ")
if len(balanceParts) != 2 {
return res, fmt.Errorf("unexpected balance format: %s", balanceStr)
}
balanceValue, err := strconv.ParseFloat(balanceParts[0], 64)
if err != nil {
return res, fmt.Errorf("failed to parse balance: %v", err)
}
// Extract numeric part from input
re := regexp.MustCompile(`^(\d+(\.\d+)?)\s*(?:CELO)?$`)
matches := re.FindStringSubmatch(strings.TrimSpace(amountStr))
if len(matches) < 2 {
res.FlagSet = append(res.FlagSet, models.USERFLAG_INVALID_AMOUNT)
res.Content = amountStr
return res, nil
}
inputAmount, err := strconv.ParseFloat(matches[1], 64)
if err != nil {
res.FlagSet = append(res.FlagSet, models.USERFLAG_INVALID_AMOUNT)
res.Content = amountStr
return res, nil
}
if inputAmount > balanceValue {
res.FlagSet = append(res.FlagSet, models.USERFLAG_INVALID_AMOUNT)
res.Content = amountStr
return res, nil
}
res.Content = fmt.Sprintf("%.3f", inputAmount) // Format to 3 decimal places
2024-09-02 15:04:53 +02:00
key := []byte(Amount)
value := []byte(res.Content)
h.db.Store(key, value, true)
if err != nil {
return res, err
}
return res, nil
}
2024-08-28 15:23:52 +02:00
// GetRecipient returns the transaction recipient from a JSON data file.
func (h *Handlers) GetRecipient(ctx context.Context, sym string, input []byte) (resource.Result, error) {
res := resource.Result{}
2024-09-02 15:04:53 +02:00
recipient, err := h.db.Fetch([]byte(Recipient))
if err != nil {
return res, err
}
2024-09-02 15:04:53 +02:00
res.Content = string(recipient)
return res, nil
}
2024-08-27 10:22:37 +02:00
// GetProfileInfo retrieves and formats the profile information of a user from a JSON data file.
func (h *Handlers) GetProfileInfo(ctx context.Context, sym string, input []byte) (resource.Result, error) {
res := resource.Result{}
2024-08-27 12:30:00 +02:00
var age string
accountData, err := h.accountFileHandler.ReadAccountData()
if err != nil {
return res, err
}
2024-08-27 12:30:00 +02:00
var name string
if accountData["FirstName"] == "Not provided" || accountData["FamilyName"] == "Not provided" {
name = "Not provided"
} else {
name = accountData["FirstName"] + " " + accountData["FamilyName"]
}
gender := accountData["Gender"]
yob := accountData["YOB"]
location := accountData["Location"]
offerings := accountData["Offerings"]
2024-08-27 12:30:00 +02:00
if yob == "Not provided" {
age = "Not provided"
} else {
2024-08-27 13:57:26 +02:00
ageInt, err := strconv.Atoi(yob)
2024-08-27 12:30:00 +02:00
if err != nil {
return res, nil
}
2024-08-27 13:57:26 +02:00
age = strconv.Itoa(utils.CalculateAgeWithYOB(ageInt))
}
2024-08-27 12:30:00 +02:00
formattedData := fmt.Sprintf("Name: %s\nGender: %s\nAge: %s\nLocation: %s\nYou provide: %s\n", name, gender, age, location, offerings)
res.Content = formattedData
return res, nil
}
2024-08-27 10:22:37 +02:00
// GetSender retrieves the public key from a JSON data file.
func (h *Handlers) GetSender(ctx context.Context, sym string, input []byte) (resource.Result, error) {
res := resource.Result{}
2024-09-02 15:04:53 +02:00
//accountData, err := h.accountFileHandler.ReadAccountData()
publicKey, err := h.db.Fetch([]byte(PublicKeyKey))
if err != nil {
return res, err
}
2024-09-02 15:04:53 +02:00
res.Content = string(publicKey)
return res, nil
}
// GetAmount retrieves the amount from a JSON data file.
func (h *Handlers) GetAmount(ctx context.Context, sym string, input []byte) (resource.Result, error) {
res := resource.Result{}
2024-09-02 15:04:53 +02:00
//accountData, err := h.accountFileHandler.ReadAccountData()
amount, err := h.db.Fetch([]byte(Amount))
if err != nil {
return res, err
}
2024-09-02 15:04:53 +02:00
res.Content = string(amount)
return res, nil
}
2024-08-28 11:19:38 +02:00
// QuickWithBalance retrieves the balance for a given public key from the custodial balance API endpoint before
// gracefully exiting the session.
func (h *Handlers) QuitWithBalance(ctx context.Context, sym string, input []byte) (resource.Result, error) {
res := resource.Result{}
code := codeFromCtx(ctx)
l := gotext.NewLocale(translationDir, code)
l.AddDomain("default")
2024-09-02 15:04:53 +02:00
// accountData, err := h.accountFileHandler.ReadAccountData()
// if err != nil {
// return res, err
// }
publicKey, err := h.db.Fetch([]byte(PublicKeyKey))
if err != nil {
return res, err
}
2024-09-02 15:04:53 +02:00
balance, err := h.accountService.CheckBalance(string(publicKey))
if err != nil {
return res, nil
}
res.Content = l.Get("Your account balance is %s", balance)
2024-08-29 22:15:58 +02:00
res.FlagReset = append(res.FlagReset, models.USERFLAG_ACCOUNT_AUTHORIZED)
return res, nil
}
2024-08-28 15:23:52 +02:00
// InitiateTransaction returns a confirmation and resets the transaction data
// on the JSON file.
func (h *Handlers) InitiateTransaction(ctx context.Context, sym string, input []byte) (resource.Result, error) {
res := resource.Result{}
2024-08-28 17:26:41 +02:00
code := codeFromCtx(ctx)
l := gotext.NewLocale(translationDir, code)
l.AddDomain("default")
// TODO
// Use the amount, recipient and sender to call the API and initialize the transaction
2024-09-02 15:04:53 +02:00
publicKey, err := h.db.Fetch([]byte(PublicKeyKey))
if err != nil {
return res, err
}
amount, err := h.db.Fetch([]byte(Amount))
2024-08-28 13:54:39 +02:00
if err != nil {
return res, err
}
2024-09-02 15:04:53 +02:00
recipient, err := h.db.Fetch([]byte(Recipient))
if err != nil {
return res, err
}
res.Content = l.Get("Your request has been sent. %s will receive %s from %s.", string(recipient), string(amount), string(publicKey))
2024-08-28 13:54:39 +02:00
account_authorized_flag, err := h.parser.GetFlag("flag_account_authorized")
if err != nil {
res.FlagReset = append(res.FlagReset, account_authorized_flag)
}
return res, nil
}