~mendelmaleh/pfin

d457b7332e7162a8508e9ba3b9b0e303a5ffd044 — Mendel Elmaleh 9 months ago da1cda1
Switch to csvutil, output all transactions if no -unpaid flag, make it work without csv header
1 files changed, 21 insertions(+), 5 deletions(-)

M cmd/sum/main.go
M cmd/sum/main.go => cmd/sum/main.go +21 -5
@@ 1,12 1,13 @@
package main

import (
	"encoding/csv"
	"flag"
	"fmt"
	"log"
	"os"

	"github.com/trimmer-io/go-csv"
	"github.com/jszwec/csvutil"
)

func main() {


@@ 20,7 21,16 @@ func main() {

	var rows []Row

	dec := csv.NewDecoder(os.Stdin)
	header, err := csvutil.Header(Row{}, "")
	if err != nil {
		log.Fatal(err)
	}

	dec, err := csvutil.NewDecoder(csv.NewReader(os.Stdin), header...)
	if err != nil {
		log.Fatal(err)
	}

	if err := dec.Decode(&rows); err != nil {
		log.Fatal(err)
	}


@@ 61,23 71,29 @@ func main() {
	// summary
	fmt.Fprintf(os.Stderr, "total %.2f, debits %.2f, credits %.2f", debits+credits, debits, credits)

	writer := csv.NewWriter(os.Stdout)
	enc := csvutil.NewEncoder(writer)

	// unpaid
	if *opts.unpaid {
		var unpaid float64
		var i int

		enc := csv.NewEncoder(os.Stdout)

		// TODO: improve float comparison hack
		for i = len(rows) - 1; int(((debits+credits)-unpaid)*100) > 0; i-- {
			if a := rows[i].Amount(); a > 0 {
				unpaid += a
				enc.EncodeRecord(rows[i])
				enc.Encode(rows[i])
			}
		}

		fmt.Fprintf(os.Stderr, ", unpaid %.2f", unpaid)
	} else {
		for i := len(rows) - 1; i >= 0; i-- {
			enc.Encode(rows[i])
		}
	}

	writer.Flush()
	fmt.Fprintf(os.Stderr, "\n")
}