package pkg import ( "context" "fmt" "github.com/julienschmidt/httprouter" "html/template" "math" "net/http" "strconv" "time" ) type InvoiceEntry struct { Slug string Date time.Time Number string Total string CustomerName string CustomerSlug string Status string StatusLabel string } type InvoicesIndexPage struct { Invoices []*InvoiceEntry } func IndexInvoices(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { page := &InvoicesIndexPage{ Invoices: mustCollectInvoiceEntries(r.Context(), getConn(r), mustGetCompany(r), getLocale(r)), } mustRenderAppTemplate(w, r, "invoices/index.gohtml", page) } func mustCollectInvoiceEntries(ctx context.Context, conn *Conn, company *Company, locale *Locale) []*InvoiceEntry { rows := conn.MustQuery(ctx, "select invoice.slug, invoice_date, invoice_number, contact.business_name, contact.slug, invoice.invoice_status, isi18n.name, to_price(total, decimal_digits) from invoice join contact using (contact_id) join invoice_status_i18n isi18n on invoice.invoice_status = isi18n.invoice_status and isi18n.lang_tag = $2 join invoice_amount using (invoice_id) join currency using (currency_code) where invoice.company_id = $1 order by invoice_date, invoice_number", company.Id, locale.Language.String()) defer rows.Close() var entries []*InvoiceEntry for rows.Next() { entry := &InvoiceEntry{} if err := rows.Scan(&entry.Slug, &entry.Date, &entry.Number, &entry.CustomerName, &entry.CustomerSlug, &entry.Status, &entry.StatusLabel, &entry.Total); err != nil { panic(err) } entries = append(entries, entry) } if rows.Err() != nil { panic(rows.Err()) } return entries } func GetInvoiceForm(w http.ResponseWriter, r *http.Request, params httprouter.Params) { locale := getLocale(r) conn := getConn(r) company := mustGetCompany(r) form := newInvoiceForm(r.Context(), conn, locale, company) slug := params[0].Value if slug == "new" { form.Date.Val = time.Now().Format("2006-01-02") w.WriteHeader(http.StatusOK) mustRenderNewInvoiceForm(w, r, form) return } invoice := mustGetInvoice(r.Context(), conn, company, slug) if invoice == nil { http.NotFound(w, r) return } mustRenderAppTemplate(w, r, "invoices/view.gohtml", invoice) } type invoice struct { Number string Date time.Time Invoicer taxDetails Invoicee taxDetails Notes string Products []*invoiceProduct Subtotal string Taxes [][]string Total string } type taxDetails struct { Name string VATIN string Address string City string PostalCode string Province string Email string Phone string } type invoiceProduct struct { Name string Description string Price string Quantity int Total string } func mustGetInvoice(ctx context.Context, conn *Conn, company *Company, slug string) *invoice { inv := &invoice{} var invoiceId int var decimalDigits int if notFoundErrorOrPanic(conn.QueryRow(ctx, "select invoice_id, decimal_digits, invoice_number, invoice_date, notes, business_name, vatin, phone, email, address, city, province, postal_code, to_price(subtotal, decimal_digits), to_price(total, decimal_digits) from invoice join contact using (contact_id) join invoice_amount using (invoice_id) join currency using (currency_code) where invoice.slug = $1", slug).Scan(&invoiceId, &decimalDigits, &inv.Number, &inv.Date, &inv.Notes, &inv.Invoicee.Name, &inv.Invoicee.VATIN, &inv.Invoicee.Phone, &inv.Invoicee.Email, &inv.Invoicee.Address, &inv.Invoicee.City, &inv.Invoicee.Province, &inv.Invoicee.PostalCode, &inv.Subtotal, &inv.Total)) { return nil } if err := conn.QueryRow(ctx, "select business_name, vatin, phone, email, address, city, province, postal_code from company where company_id = $1", company.Id).Scan(&inv.Invoicer.Name, &inv.Invoicer.VATIN, &inv.Invoicer.Phone, &inv.Invoicer.Email, &inv.Invoicer.Address, &inv.Invoicer.City, &inv.Invoicer.Province, &inv.Invoicer.PostalCode); err != nil { panic(err) } if err := conn.QueryRow(ctx, "select array_agg(array[name, to_price(amount, $2)]) from invoice_tax_amount join tax using (tax_id) where invoice_id = $1", invoiceId, decimalDigits).Scan(&inv.Taxes); err != nil { panic(err) } rows := conn.MustQuery(ctx, "select name, description, to_price(price, $2), quantity, to_price(round(price * quantity * (1 - discount_rate))::integer, 2) from invoice_product where invoice_id = $1", invoiceId, decimalDigits) defer rows.Close() for rows.Next() { product := &invoiceProduct{} if err := rows.Scan(&product.Name, &product.Description, &product.Price, &product.Quantity, &product.Total); err != nil { panic(err) } inv.Products = append(inv.Products, product) } if rows.Err() != nil { panic(rows.Err()) } return inv } type newInvoicePage struct { Form *invoiceForm Subtotal string Taxes [][]string Total string } func newNewInvoicePage(form *invoiceForm, r *http.Request) *newInvoicePage { page := &newInvoicePage{ Form: form, } conn := getConn(r) company := mustGetCompany(r) err := conn.QueryRow(r.Context(), "select subtotal, taxes, total from compute_new_invoice_amount($1, $2)", company.Id, NewInvoiceProductArray(form.Products)).Scan(&page.Subtotal, &page.Taxes, &page.Total) if err != nil { panic(err) } return page } func mustRenderNewInvoiceForm(w http.ResponseWriter, r *http.Request, form *invoiceForm) { locale := getLocale(r) form.Customer.EmptyLabel = gettext("Select a customer to bill.", locale) page := newNewInvoicePage(form, r) mustRenderAppTemplate(w, r, "invoices/new.gohtml", page) } func mustRenderNewInvoiceProductsForm(w http.ResponseWriter, r *http.Request, form *invoiceForm) { conn := getConn(r) company := mustGetCompany(r) page := newInvoiceProductsPage{ Form: form, Products: mustGetProductChoices(r.Context(), conn, company), } mustRenderAppTemplate(w, r, "invoices/products.gohtml", page) } func mustGetProductChoices(ctx context.Context, conn *Conn, company *Company) []*productChoice { rows := conn.MustQuery(ctx, "select product.product_id, product.name, to_price(price, decimal_digits) from product join company using (company_id) join currency using (currency_code) where company_id = $1 order by name", company.Id) defer rows.Close() var choices []*productChoice for rows.Next() { entry := &productChoice{} if err := rows.Scan(&entry.Id, &entry.Name, &entry.Price); err != nil { panic(err) } choices = append(choices, entry) } if rows.Err() != nil { panic(rows.Err()) } return choices } type newInvoiceProductsPage struct { Form *invoiceForm Products []*productChoice } type productChoice struct { Id int Name string Price string } func HandleAddInvoice(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { locale := getLocale(r) conn := getConn(r) company := mustGetCompany(r) form := newInvoiceForm(r.Context(), conn, locale, company) if err := form.Parse(r); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } if err := verifyCsrfTokenValid(r); err != nil { http.Error(w, err.Error(), http.StatusForbidden) return } switch r.Form.Get("action") { case "update": form.Update() w.WriteHeader(http.StatusOK) mustRenderNewInvoiceForm(w, r, form) case "products": w.WriteHeader(http.StatusOK) mustRenderNewInvoiceProductsForm(w, r, form) case "add": if !form.Validate() { w.WriteHeader(http.StatusUnprocessableEntity) mustRenderNewInvoiceForm(w, r, form) return } conn.MustExec(r.Context(), "select add_invoice($1, $2, $3, $4, $5, $6)", company.Id, form.Number, form.Date, form.Customer, form.Notes, NewInvoiceProductArray(form.Products)) http.Redirect(w, r, companyURI(company, "/invoices"), http.StatusSeeOther) default: http.Error(w, gettext("Invalid action", locale), http.StatusBadRequest) } } func HandleAddProductsToInvoice(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { locale := getLocale(r) conn := getConn(r) company := mustGetCompany(r) form := newInvoiceForm(r.Context(), conn, locale, company) if err := form.Parse(r); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } index := len(form.Products) productsId := r.Form["id"] rows := conn.MustQuery(r.Context(), "select product_id, name, description, to_price(price, decimal_digits), 1 as quantity, 0 as discount, array_remove(array_agg(tax_id), null) from product join company using (company_id) join currency using (currency_code) left join product_tax using (product_id) where product_id = any ($1) group by product_id, name, description, price, decimal_digits", productsId) defer rows.Close() for rows.Next() { product := newInvoiceProductForm(index, company, locale, form.Tax.Options) if err := rows.Scan(product.ProductId, product.Name, product.Description, product.Price, product.Quantity, product.Discount, product.Tax); err != nil { panic(err) } form.Products = append(form.Products, product) index++ } if rows.Err() != nil { panic(rows.Err()) } w.WriteHeader(http.StatusOK) mustRenderNewInvoiceForm(w, r, form) } type invoiceForm struct { locale *Locale company *Company Customer *SelectField Number *InputField Date *InputField Notes *InputField Tax *SelectField Products []*invoiceProductForm } func newInvoiceForm(ctx context.Context, conn *Conn, locale *Locale, company *Company) *invoiceForm { return &invoiceForm{ locale: locale, company: company, Customer: &SelectField{ Name: "customer", Label: pgettext("input", "Customer", locale), Required: true, Options: MustGetOptions(ctx, conn, "select contact_id::text, business_name from contact where company_id = $1 order by business_name", company.Id), }, Number: &InputField{ Name: "number", Label: pgettext("input", "Number", locale), Type: "text", Required: false, }, Date: &InputField{ Name: "date", Label: pgettext("input", "Invoice Date", locale), Type: "date", Required: true, }, Notes: &InputField{ Name: "description", Label: pgettext("input", "Notes", locale), Type: "textarea", }, Tax: &SelectField{ Name: "text", Label: pgettext("input", "Taxes", locale), Multiple: true, Options: mustGetTaxOptions(ctx, conn, company), }, } } func (form *invoiceForm) Parse(r *http.Request) error { if err := r.ParseForm(); err != nil { return err } form.Customer.FillValue(r) form.Number.FillValue(r) form.Date.FillValue(r) form.Notes.FillValue(r) if _, ok := r.Form["product.id.0"]; ok { for index := 0; true; index++ { if _, ok := r.Form["product.id."+strconv.Itoa(index)]; !ok { break } productForm := newInvoiceProductForm(index, form.company, form.locale, form.Tax.Options) if err := productForm.Parse(r); err != nil { return err } form.Products = append(form.Products, productForm) } } return nil } func (form *invoiceForm) Validate() bool { validator := newFormValidator() validator.CheckValidSelectOption(form.Customer, gettext("Name can not be empty.", form.locale)) if validator.CheckRequiredInput(form.Date, gettext("Invoice date can not be empty.", form.locale)) { validator.CheckValidDate(form.Date, gettext("Invoice date must be a valid date.", form.locale)) } validator.CheckValidSelectOption(form.Tax, gettext("Selected tax is not valid.", form.locale)) allOK := validator.AllOK() for _, product := range form.Products { allOK = product.Validate() && allOK } return allOK } func (form *invoiceForm) Update() { products := form.Products form.Products = nil for n, product := range products { if product.Quantity.Val != "0" { if n != len(form.Products) { product.Reindex(len(form.Products)) } form.Products = append(form.Products, product) } } } func mustGetTaxOptions(ctx context.Context, conn *Conn, company *Company) []*SelectOption { return MustGetOptions(ctx, conn, "select tax_id::text, name from tax where company_id = $1 order by name", company.Id) } type invoiceProductForm struct { locale *Locale company *Company ProductId *InputField Name *InputField Description *InputField Price *InputField Quantity *InputField Discount *InputField Tax *SelectField } func newInvoiceProductForm(index int, company *Company, locale *Locale, taxOptions []*SelectOption) *invoiceProductForm { form := &invoiceProductForm{ locale: locale, company: company, ProductId: &InputField{ Label: pgettext("input", "Id", locale), Type: "hidden", Required: true, }, Name: &InputField{ Label: pgettext("input", "Name", locale), Type: "text", Required: true, }, Description: &InputField{ Label: pgettext("input", "Description", locale), Type: "textarea", }, Price: &InputField{ Label: pgettext("input", "Price", locale), Type: "number", Required: true, Attributes: []template.HTMLAttr{ `min="0"`, template.HTMLAttr(fmt.Sprintf(`step="%v"`, company.MinCents())), }, }, Quantity: &InputField{ Label: pgettext("input", "Quantity", locale), Type: "number", Required: true, Attributes: []template.HTMLAttr{ `min="0"`, }, }, Discount: &InputField{ Label: pgettext("input", "Discount (%)", locale), Type: "number", Required: true, Attributes: []template.HTMLAttr{ `min="0"`, `max="100"`, }, }, Tax: &SelectField{ Label: pgettext("input", "Taxes", locale), Multiple: true, Options: taxOptions, }, } form.Reindex(index) return form } func (form *invoiceProductForm) Reindex(index int) { suffix := "." + strconv.Itoa(index) form.ProductId.Name = "product.id" + suffix form.Name.Name = "product.name" + suffix form.Description.Name = "product.description" + suffix form.Price.Name = "product.price" + suffix form.Quantity.Name = "product.quantity" + suffix form.Discount.Name = "product.discount" + suffix form.Tax.Name = "product.tax" + suffix } func (form *invoiceProductForm) Parse(r *http.Request) error { if err := r.ParseForm(); err != nil { return err } form.ProductId.FillValue(r) form.Name.FillValue(r) form.Description.FillValue(r) form.Price.FillValue(r) form.Quantity.FillValue(r) form.Discount.FillValue(r) form.Tax.FillValue(r) return nil } func (form *invoiceProductForm) Validate() bool { validator := newFormValidator() validator.CheckRequiredInput(form.Name, gettext("Name can not be empty.", form.locale)) if validator.CheckRequiredInput(form.Price, gettext("Price can not be empty.", form.locale)) { validator.CheckValidDecimal(form.Price, form.company.MinCents(), math.MaxFloat64, gettext("Price must be a number greater than zero.", form.locale)) } if validator.CheckRequiredInput(form.Quantity, gettext("Quantity can not be empty.", form.locale)) { validator.CheckValidInteger(form.Quantity, 1, math.MaxInt32, gettext("Quantity must be a number greater than zero.", form.locale)) } if validator.CheckRequiredInput(form.Discount, gettext("Discount can not be empty.", form.locale)) { validator.CheckValidInteger(form.Discount, 0, 100, gettext("Discount must be a percentage between 0 and 100.", form.locale)) } validator.CheckValidSelectOption(form.Tax, gettext("Selected tax is not valid.", form.locale)) return validator.AllOK() }