iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🐥

Exporting Zaim Data to CSV Using the Zaim API and Go

に公開

This is the Go version of my previously posted article, "Outputting Zaim Data to CSV Using Zaim API and Python".

https://zenn.dev/hidaka/articles/zaim-backup-python

Purpose

  • Create a system to export Zaim data to CSV.
  • Ensure the backup data contains the same content as the file exported by Zaim's own export function (aligning the column names).

Procedure

API Registration and Token Acquisition

For API registration and token acquisition, please refer to the previous article.

Implementing the Code

Add a package to fetch and manipulate Zaim data

Terminal
go get github.com/s-sasaki-0529/go-zaim

https://github.com/s-sasaki-0529/go-zaim

Add Code to Fetch Data

Add the Acquired Token Information to the .env File

Create a .env file and enter the acquired tokens.

.env
CONSUMER_KEY=
CONSUMER_SECRET=
ACCESS_TOKEN=
ACCESS_SECRET=

Add Code to Fetch Data

Implement config.go to load token information, zaim.go to fetch data, and main.go to call each process.

config.go
package main

import (
	"fmt"
	"os"

	gozaim "github.com/s-sasaki-0529/go-zaim"

	"github.com/joho/godotenv"
)

func GetClient() *gozaim.Client {
	err := godotenv.Load(".env")

	if err != nil {
		fmt.Printf("Could not load: %v", err)
	}

	c := gozaim.NewClient(
		os.Getenv("CONSUMER_KEY"),
		os.Getenv("CONSUMER_SECRET"),
		os.Getenv("ACCESS_TOKEN"),
		os.Getenv("ACCESS_SECRET"),
	)

	return c
}
zaim.go
package main

import (
	"fmt"
	"net/url"

	gozaim "github.com/s-sasaki-0529/go-zaim"
)

type ZaimData struct {
	money      []gozaim.Money
	categories []gozaim.Category
	genres     []gozaim.Genre
	accounts   []gozaim.Account
}

// Fetch Zaim data
func GetZaimData(c *gozaim.Client) ZaimData {

	// Fetch data list
	m, err := c.FetchMoney(url.Values{})
	if err != nil {
		fmt.Println("Failed to get money", err)
	}

	msg := fmt.Sprintf("Fetched %d records.\n", len(m))
	fmt.Println(msg)

	// Fetch category list
	ca, err := c.FetchCategories()
	if err != nil {
		fmt.Println("Failed to get categories", err)
	}

	// Fetch genre list
	g, err := c.FetchGenres()
	if err != nil {
		fmt.Println("Failed to get genres", err)
	}

	// Fetch account list
	a, err := c.FetchAccounts()
	if err != nil {
		fmt.Println("Failed to get accounts", err)
	}

	result := ZaimData{
		m,
		ca,
		g,
		a,
	}

	return result
}
main.go
package main

import "fmt"

func main() {

	// Client settings
	c := GetClient()

	// Fetch data
	d := GetZaimData(c)
	fmt.Println(d)

}

Data has been fetched, but items like categories and accounts only contain IDs. Therefore, we will implement a process to assign various names based on the IDs.

Assign Names Based on IDs

Add the process for assigning names.

zaim.go
type MoneyJP struct {
	Date         string `csv:"日付"`
	Mode         string `csv:"方法"`
	Category     string `csv:"カテゴリ"`
	Genre        string `csv:"カテゴリの内訳"`
	From         string `csv:"支払元"`
	To           string `csv:"入金先"`
	Name         string `csv:"品目"`
	Comment      string `csv:"メモ"`
	Place        string `csv:"お店"`
	CurrencyCode string `csv:"通貨"`
	Income       int    `csv:"収入"`
	Payment      int    `csv:"支出"`
	Transfer     int    `csv:"振替"`
}

// Assign type names based on type IDs
func ConvertData(datas ZaimData) []MoneyJP {
	var money []MoneyJP

	for _, v := range datas.money {
		p, i, t := GetAmount(v.Mode, v.Amount)
		cm := MoneyJP{
			v.Date,
			v.Mode,
			GetCategoryName(v.CategoryID, datas.categories),
			GetGenreName(v.GenreID, datas.genres),
			GetAccountName(v.FromAccountID, datas.accounts),
			GetAccountName(v.ToAccountID, datas.accounts),
			v.Name,
			v.Comment,
			v.Place,
			v.CurrencyCode,
			p,
			i,
			t,
		}

		money = append(money, cm)

	}
	return money
}

// Returns the category name associated with the ID
func GetCategoryName(id int, categories []gozaim.Category) string {
	for _, v := range categories {
		if v.ID == id {
			return v.Name
		}
	}
	return ""
}

// Returns the genre name associated with the ID
func GetGenreName(id int, genres []gozaim.Genre) string {
	for _, v := range genres {
		if v.ID == id {
			return v.Name
		}
	}
	return ""
}

// Returns the account name associated with the ID
func GetAccountName(id int, accounts []gozaim.Account) string {
	for _, v := range accounts {
		if v.ID == id {
			return v.Name
		}
	}
	return "-"
}

// Returns the amount according to the mode
func GetAmount(mode string, amount int) (int, int, int) {
	var p, i, t int

	switch mode {
	case "payment":
		p = amount
	case "income":
		i = amount
	case "transfer":
		t = amount
	default:
	}

	return p, i, t

}
main.go
// Assign type names
cd := ConvertData(d)
fmt.Println(cd)

Next, we will implement the process of changing the column names to Japanese and outputting to CSV.

Add Code to Output Data

We will change the column names to Japanese and remove unnecessary data such as user IDs. Then, we will export the organized data to CSV.

zaim.go
// CSV output
func OutputCSV(money []MoneyJP) {
	file, _ := os.OpenFile("zaim-backup.csv", os.O_RDWR|os.O_CREATE, os.ModePerm)
	defer file.Close()

	// Write the CSV file
	gocsv.MarshalFile(&money, file)

}
main.go
// Output to CSV
OutputCSV(cd)

With this, the code implementation is complete.

Execute the Implemented Code

Run the following command in an application that can execute shell scripts, such as a terminal.

Terminal
% go run *.go

The number of fetched records will be displayed in the console, and a file named zaim-backup.csv will be generated.

Summary

The code implemented this time is available in the following repository.

https://github.com/ryohidaka/zaim-backup-go

References

https://zenn.dev/a_ichi1/articles/c9f3870350c5e2

https://qiita.com/nkumag/items/ef372ea35dcfbfa19310

https://itsakura.com/go-switch

GitHubで編集を提案

Discussion