package pkg import ( "github.com/julienschmidt/httprouter" "net/http" ) type DashboardPage struct { Sales string Income string Expenses string VAT string IRPF string NetIncome string } func ServeDashboard(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { company := mustGetCompany(r) conn := getConn(r) rows := conn.MustQuery(r.Context(), ` select to_price(0, decimal_digits) as sales , to_price(coalesce(invoice.total, 0), decimal_digits) as income , to_price(coalesce(expense.total, 0), decimal_digits) as expenses , to_price(coalesce(tax.vat, 0), decimal_digits) as vat , to_price(coalesce(tax.irpf, 0), decimal_digits) as irpf , to_price(coalesce(invoice.total - expense.total - tax.vat + tax.irpf, 0), decimal_digits) as net_income from company left join ( select company_id, sum(total)::integer as total from invoice join invoice_amount using (invoice_id) group by company_id ) as invoice using (company_id) left join ( select company_id, sum(amount)::integer as total from expense group by company_id ) as expense using (company_id) left join ( select invoice.company_id , sum(case when tax_class.name = 'IVA' then invoice_tax_amount.amount else 0 end)::integer as vat , sum(case when tax_class.name = 'IRPF' then invoice_tax_amount.amount else 0 end)::integer as irpf from invoice join invoice_tax_amount using (invoice_id) join tax using (tax_id) join tax_class using (tax_class_id) group by invoice.company_id ) as tax using (company_id) join currency using (currency_code) where company_id = $1 `, company.Id) defer rows.Close() dashboard := &DashboardPage{} for rows.Next() { if err := rows.Scan(&dashboard.Sales, &dashboard.Income, &dashboard.Expenses, &dashboard.VAT, &dashboard.IRPF, &dashboard.NetIncome); err != nil { panic(err) } } if rows.Err() != nil { panic(rows.Err()) } mustRenderMainTemplate(w, r, "dashboard.gohtml", dashboard) }