Files
any2anexoj/internal/writing/csv/writer.go
natercio 47f38fce2b
Badges / coveralls (push) Successful in 1m1s
Implement HTML writer (#33)
Reviewed-on: #33
Co-authored-by: Natercio Moniz <[email protected]>
2026-10-05 16:25:21 +01:00

60 lines
1.5 KiB
Go

// Package csv renders an internal.AggregatorWriter as the CSV schema
// expected by Modelo 3 do Anexo J.
package csv
import (
"encoding/csv"
"fmt"
"io"
"github.com/nmoniz/any2anexoj/internal"
)
type Writer struct {
w *csv.Writer
}
func NewWriter(w io.Writer) *Writer {
return &Writer{w: csv.NewWriter(w)}
}
func (cw *Writer) Render(aw *internal.AggregatorWriter) error {
err := cw.w.Write([]string{
"source_country", "code",
"realization_year", "realization_month", "realization_day", "realization_value",
"acquisition_year", "acquisition_month", "acquisition_day", "acquisition_value",
"expenses", "foreign_tax_paid", "counter_country",
})
if err != nil {
return fmt.Errorf("write csv header: %w", err)
}
for ri := range aw.Iter() {
err := cw.w.Write(reportItemToRow(ri))
if err != nil {
return fmt.Errorf("write csv row: %w", err)
}
}
cw.w.Flush()
return cw.w.Error()
}
func reportItemToRow(ri internal.ReportItem) []string {
return []string{
fmt.Sprintf("%d", ri.AssetCountry),
string(ri.Nature),
fmt.Sprintf("%d", ri.SellTimestamp.Year()),
fmt.Sprintf("%d", int(ri.SellTimestamp.Month())),
fmt.Sprintf("%d", ri.SellTimestamp.Day()),
ri.SellValue.StringFixed(2),
fmt.Sprintf("%d", ri.BuyTimestamp.Year()),
fmt.Sprintf("%d", int(ri.BuyTimestamp.Month())),
fmt.Sprintf("%d", ri.BuyTimestamp.Day()),
ri.BuyValue.StringFixed(2),
ri.Fees.StringFixed(2),
ri.Taxes.StringFixed(2),
fmt.Sprintf("%d", ri.BrokerCountry),
}
}