package pkg import ( "context" "fmt" "github.com/julienschmidt/httprouter" "html/template" "math" "net/http" "time" ) func servePaymentIndex(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { conn := getConn(r) company := mustGetCompany(r) locale := getLocale(r) page := NewPaymentIndexPage(r.Context(), conn, company, locale) page.MustRender(w, r) } func serveExpensePaymentIndex(w http.ResponseWriter, r *http.Request, params httprouter.Params) { expenseSlug := params[0].Value conn := getConn(r) company := mustGetCompany(r) locale := getLocale(r) expense := mustGetPaymentExpense(r.Context(), conn, expenseSlug) if expense == nil { http.NotFound(w, r) return } page := NewPaymentIndexPageForExpense(r.Context(), conn, company, locale, expense) page.MustRender(w, r) } type PaymentIndexPage struct { Payments []*PaymentEntry BaseURI string Expense *PaymentExpense } func NewPaymentIndexPage(ctx context.Context, conn *Conn, company *Company, locale *Locale) *PaymentIndexPage { return &PaymentIndexPage{ Payments: mustCollectPaymentEntries(ctx, conn, company, locale, 0), BaseURI: companyURI(company, "/payments"), } } func NewPaymentIndexPageForExpense(ctx context.Context, conn *Conn, company *Company, locale *Locale, expense *PaymentExpense) *PaymentIndexPage { return &PaymentIndexPage{ Payments: mustCollectPaymentEntries(ctx, conn, company, locale, expense.Id), BaseURI: companyURI(company, "/expenses/"+expense.Slug+"/payments"), Expense: expense, } } func (page *PaymentIndexPage) MustRender(w http.ResponseWriter, r *http.Request) { mustRenderMainTemplate(w, r, "payments/index.gohtml", page) } type PaymentExpense struct { Id int Slug string InvoiceNumber string } func mustGetPaymentExpense(ctx context.Context, conn *Conn, expenseSlug string) *PaymentExpense { if !ValidUuid(expenseSlug) { return nil } expense := &PaymentExpense{} if notFoundErrorOrPanic(conn.QueryRow(ctx, ` select expense_id , slug , coalesce(nullif(invoice_number, ''), slug::text) from expense where expense.slug = $1 `, expenseSlug).Scan( &expense.Id, &expense.Slug, &expense.InvoiceNumber)) { return nil } return expense } func (expense *PaymentExpense) calcRemainingPaymentAmount(ctx context.Context, conn *Conn) string { return conn.MustGetText(ctx, "", ` select to_price(greatest(0, expense.amount + tax_amount - paid_amount)::int, decimal_digits) from ( select coalesce (sum(payment.amount), 0) as paid_amount from expense_payment join payment using (payment_id) where expense_payment.expense_id = $1 ) as payment cross join ( select coalesce (sum(amount), 0) as tax_amount from expense_tax_amount where expense_id = $1 ) as tax cross join ( select amount, decimal_digits from expense join currency using (currency_code) where expense_id = $1 ) as expense `, expense.Id) } type PaymentEntry struct { ID int Slug string PaymentDate time.Time Description string ExpenseSlug string InvoiceNumber string Total string OriginalFileName string Tags []string Status string StatusLabel string } func mustCollectPaymentEntries(ctx context.Context, conn *Conn, company *Company, locale *Locale, expenseId int) []*PaymentEntry { rows := conn.MustQuery(ctx, ` select payment_id , payment.slug , payment_date , description , to_price(payment.amount, decimal_digits) as total , payment.tags , payment.payment_status , psi18n.name , coalesce(attachment.original_filename, '') , coalesce(expense.slug::text, '') , coalesce(expense.invoice_number, '') from payment join payment_status_i18n psi18n on payment.payment_status = psi18n.payment_status and psi18n.lang_tag = $1 join currency using (currency_code) left join payment_attachment as attachment using (payment_id) left join expense_payment using (payment_id) left join expense using (expense_id) where payment.company_id = $2 and ($3 = 0 or expense_id = $3) order by payment_date desc, total desc `, locale.Language, company.Id, expenseId) defer rows.Close() var entries []*PaymentEntry for rows.Next() { entry := &PaymentEntry{} if err := rows.Scan(&entry.ID, &entry.Slug, &entry.PaymentDate, &entry.Description, &entry.Total, &entry.Tags, &entry.Status, &entry.StatusLabel, &entry.OriginalFileName, &entry.ExpenseSlug, &entry.InvoiceNumber); err != nil { panic(err) } entries = append(entries, entry) } if rows.Err() != nil { panic(rows.Err()) } return entries } func servePaymentForm(w http.ResponseWriter, r *http.Request, params httprouter.Params) { locale := getLocale(r) conn := getConn(r) company := mustGetCompany(r) form := newPaymentForm(r.Context(), conn, locale, company) slug := params[0].Value if slug == "new" { form.PaymentDate.Val = time.Now().Format("2006-01-02") form.MustRender(w, r) return } if !ValidUuid(slug) { http.NotFound(w, r) return } if !form.MustFillFromDatabase(r.Context(), conn, slug) { http.NotFound(w, r) return } form.MustRender(w, r) } func serveExpensePaymentForm(w http.ResponseWriter, r *http.Request, params httprouter.Params) { locale := getLocale(r) conn := getConn(r) company := mustGetCompany(r) expenseSlug := params[0].Value expense := mustGetPaymentExpense(r.Context(), conn, expenseSlug) if expense == nil { http.NotFound(w, r) return } form := newPaymentFormForExpense(r.Context(), conn, locale, company, expense) paymentSlug := params[1].Value if paymentSlug == "new" { form.PaymentDate.Val = time.Now().Format("2006-01-02") form.Description.Val = fmt.Sprintf(gettext("Payment of %s", locale), form.Expense.InvoiceNumber) form.Amount.Val = form.Expense.calcRemainingPaymentAmount(r.Context(), conn) form.MustRender(w, r) return } if !ValidUuid(paymentSlug) { http.NotFound(w, r) return } if !form.MustFillFromDatabase(r.Context(), conn, paymentSlug) { http.NotFound(w, r) return } form.MustRender(w, r) } type PaymentForm struct { locale *Locale company *Company Slug string BaseURI string Expense *PaymentExpense Description *InputField PaymentDate *InputField PaymentAccount *SelectField Amount *InputField File *FileField Tags *TagsField } func newPaymentForm(ctx context.Context, conn *Conn, locale *Locale, company *Company) *PaymentForm { return &PaymentForm{ locale: locale, company: company, BaseURI: companyURI(company, "/payments"), Description: &InputField{ Name: "description", Label: pgettext("input", "Description", locale), Required: true, Type: "text", }, PaymentDate: &InputField{ Name: "payment_date", Label: pgettext("input", "Payment Date", locale), Required: true, Type: "date", }, PaymentAccount: &SelectField{ Name: "payment_account", Label: pgettext("input", "Account", locale), Required: true, Options: MustGetOptions(ctx, conn, "select payment_account_id::text, name from payment_account where company_id = $1 order by name", company.Id), }, Amount: &InputField{ Name: "amount", Label: pgettext("input", "Amount", locale), Type: "number", Required: true, Attributes: []template.HTMLAttr{ `min="0"`, template.HTMLAttr(fmt.Sprintf(`step="%v"`, company.MinCents())), }, }, File: &FileField{ Name: "file", Label: pgettext("input", "File", locale), MaxSize: 1 << 20, }, Tags: &TagsField{ Name: "tags", Label: pgettext("input", "Tags", locale), }, } } func newPaymentFormForExpense(ctx context.Context, conn *Conn, locale *Locale, company *Company, expense *PaymentExpense) *PaymentForm { form := newPaymentForm(ctx, conn, locale, company) form.BaseURI = companyURI(company, "/expenses/"+expense.Slug+"/payments") form.Expense = expense return form } func (f *PaymentForm) MustRender(w http.ResponseWriter, r *http.Request) { if f.Slug == "" { f.PaymentAccount.EmptyLabel = gettext("Select an account.", f.locale) mustRenderMainTemplate(w, r, "payments/new.gohtml", f) } else { mustRenderMainTemplate(w, r, "payments/edit.gohtml", f) } } func (f *PaymentForm) MustFillFromDatabase(ctx context.Context, conn *Conn, slug string) bool { selectedPaymentAccount := f.PaymentAccount.Selected f.PaymentAccount.Clear() if notFoundErrorOrPanic(conn.QueryRow(ctx, ` select description , payment_date , payment_account_id::text , to_price(amount, decimal_digits) , tags from payment join currency using (currency_code) where payment.slug = $1 `, slug).Scan( f.Description, f.PaymentDate, f.PaymentAccount, f.Amount, f.Tags)) { f.PaymentAccount.Selected = selectedPaymentAccount return false } f.Slug = slug return true } func (f *PaymentForm) Parse(r *http.Request) error { if err := r.ParseMultipartForm(f.File.MaxSize); err != nil { return err } f.Description.FillValue(r) f.PaymentDate.FillValue(r) f.PaymentAccount.FillValue(r) f.Amount.FillValue(r) if err := f.File.FillValue(r); err != nil { return err } f.Tags.FillValue(r) return nil } func (f *PaymentForm) Validate() bool { validator := newFormValidator() validator.CheckRequiredInput(f.Description, gettext("Description can not be empty.", f.locale)) validator.CheckValidSelectOption(f.PaymentAccount, gettext("Selected payment account is not valid.", f.locale)) validator.CheckValidDate(f.PaymentDate, gettext("Payment date must be a valid date.", f.locale)) if validator.CheckRequiredInput(f.Amount, gettext("Amount can not be empty.", f.locale)) { validator.CheckValidDecimal(f.Amount, f.company.MinCents(), math.MaxFloat64, gettext("Amount must be a number greater than zero.", f.locale)) } return validator.AllOK() } func handleAddPayment(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { locale := getLocale(r) conn := getConn(r) company := mustGetCompany(r) form := newPaymentForm(r.Context(), conn, locale, company) handleAddPaymentForm(w, r, conn, company, form) } func handleAddPaymentForm(w http.ResponseWriter, r *http.Request, conn *Conn, company *Company, form *PaymentForm) { 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 } if !form.Validate() { if !IsHTMxRequest(r) { w.WriteHeader(http.StatusUnprocessableEntity) } form.MustRender(w, r) return } var paymentSlug any if form.Expense != nil { paymentSlug = form.Expense.Id } slug := conn.MustGetText(r.Context(), "", "select add_payment($1, $2, $3, $4, $5, $6, $7)", company.Id, paymentSlug, form.PaymentDate, form.PaymentAccount, form.Description, form.Amount, form.Tags) if len(form.File.Content) > 0 { conn.MustQuery(r.Context(), "select attach_to_payment($1, $2, $3, $4)", slug, form.File.OriginalFileName, form.File.ContentType, form.File.Content) } htmxRedirect(w, r, form.BaseURI) } func handleAddExpensePayment(w http.ResponseWriter, r *http.Request, params httprouter.Params) { expenseSlug := params[0].Value locale := getLocale(r) conn := getConn(r) company := mustGetCompany(r) expense := mustGetPaymentExpense(r.Context(), conn, expenseSlug) if expense == nil { http.NotFound(w, r) return } form := newPaymentFormForExpense(r.Context(), conn, locale, company, expense) handleAddPaymentForm(w, r, conn, company, form) } func handleEditPayment(w http.ResponseWriter, r *http.Request, params httprouter.Params) { conn := getConn(r) locale := getLocale(r) company := mustGetCompany(r) form := newPaymentForm(r.Context(), conn, locale, company) form.Slug = params[0].Value handleEditPaymentForm(w, r, conn, form) } func handleEditPaymentForm(w http.ResponseWriter, r *http.Request, conn *Conn, form *PaymentForm) { if !ValidUuid(form.Slug) { http.NotFound(w, r) return } 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 } if !form.Validate() { if !IsHTMxRequest(r) { w.WriteHeader(http.StatusUnprocessableEntity) } form.MustRender(w, r) return } if found := conn.MustGetText(r.Context(), "", "select edit_payment($1, $2, $3, $4, $5, $6)", form.Slug, form.PaymentDate, form.PaymentAccount, form.Description, form.Amount, form.Tags); found == "" { http.NotFound(w, r) return } if len(form.File.Content) > 0 { conn.MustQuery(r.Context(), "select attach_to_payment($1, $2, $3, $4)", form.Slug, form.File.OriginalFileName, form.File.ContentType, form.File.Content) } htmxRedirect(w, r, form.BaseURI) } func handleEditExpensePayment(w http.ResponseWriter, r *http.Request, params httprouter.Params) { conn := getConn(r) locale := getLocale(r) company := mustGetCompany(r) expenseSlug := params[0].Value expense := mustGetPaymentExpense(r.Context(), conn, expenseSlug) if expense == nil { http.NotFound(w, r) return } form := newPaymentFormForExpense(r.Context(), conn, locale, company, expense) form.Slug = params[1].Value handleEditPaymentForm(w, r, conn, form) } func handleRemovePayment(w http.ResponseWriter, r *http.Request, params httprouter.Params) { company := mustGetCompany(r) removePayment(w, r, params[0].Value, companyURI(company, "/payments")) } func removePayment(w http.ResponseWriter, r *http.Request, slug string, backURI string) { if !ValidUuid(slug) { http.NotFound(w, r) return } if err := verifyCsrfTokenValid(r); err != nil { http.Error(w, err.Error(), http.StatusForbidden) return } conn := getConn(r) conn.MustExec(r.Context(), "select remove_payment($1)", slug) htmxRedirect(w, r, backURI) } func handleRemoveExpensePayment(w http.ResponseWriter, r *http.Request, params httprouter.Params) { conn := getConn(r) expenseSlug := params[0].Value expense := mustGetPaymentExpense(r.Context(), conn, expenseSlug) if expense == nil { http.NotFound(w, r) return } company := mustGetCompany(r) removePayment(w, r, params[1].Value, companyURI(company, "/expenses/"+expense.Slug+"/payments")) } func servePaymentAttachment(w http.ResponseWriter, r *http.Request, params httprouter.Params) { serveAttachment(w, r, params, ` select mime_type , content from payment join payment_attachment using (payment_id) where slug = $1 `) } func servePaymentTagsEditForm(w http.ResponseWriter, r *http.Request, params httprouter.Params) { serveTagsEditForm(w, r, params, "/payments/", "select tags from payment where slug = $1") } func handleUpdatePaymentTags(w http.ResponseWriter, r *http.Request, params httprouter.Params) { handleUpdateTags(w, r, params, "/payments/", "update payment set tags = $1 where slug = $2 returning slug") }