Beispiel #1
0
Datei: bill.go Projekt: cjgk/bill
func (b *Bill) exportAction(c *cli.Context) {
	var tplTxt string
	invNos := c.IntSlice("invoices")

	// TODO: override from command line
	invYear := strconv.Itoa(time.Now().Year())
	invDir := filepath.Join(b.BillPath, InvDir, invYear)

	if len(invNos) == 0 {
		invNos = append(invNos, findLatestInvoice(invDir))
	}

	funcMap := template.FuncMap{
		"rowsum": func(unitprice float64, qty int) float64 {
			return unitprice * float64(qty)
		},
		"add": func(a float64, b float64) float64 {
			return a + b
		},
		"vat": func(price float64, vatrate float64) float64 {
			return price * vatrate / 100
		},
	}

	for _, i := range invNos {
		inv, invName := LoadInvoice(invDir, i)
		cust := loadCustomer(b.BillPath, inv.Customer)
		exp := Export{
			&inv,
			&cust,
		}

		if len(cust.Template) > 0 {
			custTplPath := filepath.Join(b.BillPath, TplDir, cust.Template) + ".html"
			tplByte, err := ioutil.ReadFile(custTplPath)
			if err != nil {
				log.Fatalln(err)
			}

			tplTxt = string(tplByte)
		} else {
			tplTxt = defaultTemplate
		}

		tpl, err := template.New("invoice").Funcs(funcMap).Parse(tplTxt)
		if err != nil {
			log.Fatalln(err)
		}

		outPath := filepath.Join(b.BillPath, ExpDir, invName) + ".html"
		f, err := os.Create(outPath)
		if err != nil {
			log.Fatalln(err)
		}
		defer f.Close()

		err = tpl.Execute(f, &exp)
		if err != nil {
			log.Fatalln(err)
		}
	}

}