mirror of
https://github.com/wahyd4/cash-code-test.git
synced 2026-08-09 05:16:05 +10:00
81 lines
1.7 KiB
Go
81 lines
1.7 KiB
Go
package workflow
|
|
|
|
import (
|
|
"bufio"
|
|
"fmt"
|
|
"github.com/wahyd4/cash/commands"
|
|
"github.com/wahyd4/cash/domains"
|
|
"os"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
const commandSplitter = " "
|
|
|
|
// APP holds the bank app instance
|
|
type APP struct {
|
|
Bank *domains.Bank
|
|
}
|
|
|
|
// Run all the commands passed in
|
|
func (app *APP) Run(commands []commands.ICommand) error {
|
|
for _, command := range commands {
|
|
if err := command.Run(app.Bank); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Load loads inputs and generate commands
|
|
func (app *APP) Load(filePath string) ([]commands.ICommand, error) {
|
|
appCommands := make([]commands.ICommand, 0)
|
|
|
|
file, err := os.Open(filePath)
|
|
if err != nil {
|
|
return appCommands, err
|
|
}
|
|
defer file.Close()
|
|
|
|
scanner := bufio.NewScanner(file)
|
|
for scanner.Scan() {
|
|
commandString := scanner.Text()
|
|
appCommands = append(appCommands, buildCommand(commandString))
|
|
}
|
|
|
|
if err := scanner.Err(); err != nil {
|
|
return nil, fmt.Errorf("fail to read file %s with error: %v", filePath, err)
|
|
}
|
|
|
|
return appCommands, nil
|
|
}
|
|
|
|
func buildCommand(commandString string) commands.ICommand {
|
|
|
|
commandArgs := strings.Split(commandString, commandSplitter)
|
|
switch commandArgs[0] {
|
|
case "OPEN_ACCOUNT":
|
|
return &commands.OpenAccountCommand{Username: commandArgs[1]}
|
|
case "DEPOSIT":
|
|
money, _ := strconv.ParseFloat(commandArgs[2], 10)
|
|
return &commands.DepositCommand{
|
|
Account: commandArgs[1],
|
|
Money: money,
|
|
}
|
|
case "WITHDRAW":
|
|
money, _ := strconv.ParseFloat(commandArgs[2], 10)
|
|
return &commands.WithdrawCommand{
|
|
Account: commandArgs[1],
|
|
Money: money,
|
|
}
|
|
case "BALANCE":
|
|
return &commands.UserBalanceCommand{
|
|
Account: commandArgs[1],
|
|
}
|
|
case "TOTAL_BALANCE":
|
|
return &commands.TotalBalanceCommand{}
|
|
default:
|
|
return &commands.TotalBalanceCommand{}
|
|
}
|
|
}
|