support importing transaction by csv/tsv file via command line

This commit is contained in:
MaysWind
2024-09-02 00:40:00 +08:00
parent 366311edbb
commit 7c59e8386e
27 changed files with 1496 additions and 208 deletions
+74
View File
@@ -244,6 +244,31 @@ var UserData = &cli.Command{
},
},
},
{
Name: "transaction-import",
Usage: "Import transactions to specified user",
Action: bindAction(importUserTransaction),
Flags: []cli.Flag{
&cli.StringFlag{
Name: "username",
Aliases: []string{"n"},
Required: true,
Usage: "Specific user name",
},
&cli.StringFlag{
Name: "file",
Aliases: []string{"f"},
Required: true,
Usage: "Specific import file path (e.g. transaction.csv)",
},
&cli.StringFlag{
Name: "type",
Aliases: []string{"t"},
Required: true,
Usage: "Import file type (supports \"ezbookkeeping_csv\", \"ezbookkeeping_tsv\")",
},
},
},
{
Name: "transaction-export",
Usage: "Export user all transactions to file",
@@ -639,6 +664,55 @@ func exportUserTransaction(c *core.CliContext) error {
return nil
}
func importUserTransaction(c *core.CliContext) error {
_, err := initializeSystem(c)
if err != nil {
return err
}
username := c.String("username")
filePath := c.String("file")
filetype := c.String("type")
if filePath == "" {
log.BootErrorf(c, "[user_data.importUserTransaction] import file path is not specified")
return os.ErrNotExist
}
fileExists, err := utils.IsExists(filePath)
if !fileExists {
log.BootErrorf(c, "[user_data.importUserTransaction] import file does not exist")
return os.ErrExist
}
if filetype != "ezbookkeeping_csv" && filetype != "ezbookkeeping_tsv" {
log.BootErrorf(c, "[user_data.importUserTransaction] unknown file type \"%s\"", filetype)
return errs.ErrImportFileTypeNotSupported
}
data, err := os.ReadFile(filePath)
if err != nil {
log.BootErrorf(c, "[user_data.importUserTransaction] failed to load import file")
return err
}
log.BootInfof(c, "[user_data.importUserTransaction] start importing transactions to user \"%s\"", username)
err = clis.UserData.ImportTransaction(c, username, filetype, data)
if err != nil {
log.BootErrorf(c, "[user_data.importUserTransaction] error occurs when importing user data")
return err
}
log.BootInfof(c, "[user_data.importUserTransaction] transactions have been imported to user \"%s\"", username)
return nil
}
func printUserInfo(user *models.User) {
fmt.Printf("[Uid] %d\n", user.Uid)
fmt.Printf("[Username] %s\n", user.Username)