Compare commits

..

No commits in common. "045bf7ff6ab16c42282d7084abf55c6a1510f128" and "e94e3f6ebc44931fdad50744e3108570377c993a" have entirely different histories.

15 changed files with 86 additions and 359 deletions

View File

@ -1,39 +0,0 @@
-- Deploy numerus:add_product to pg
-- requires: schema_numerus
-- requires: product
-- requires: product_tax
-- requires: parse_price
-- requires: company
-- requires: currency
begin;
set search_path to numerus, public;
create or replace function add_product(company_id integer, name text, description text, price text, taxes integer[]) returns uuid
as $$
declare
pid integer;
pslug uuid;
begin
insert into product (company_id, name, description, price)
select add_product.company_id, add_product.name, add_product.description, parse_price(add_product.price, decimal_digits)
from company
join currency using (currency_code)
where company.company_id = add_product.company_id
returning product_id, slug
into pid, pslug;
insert into product_tax (product_id, tax_id)
select pid, tax_id
from unnest(taxes) as tax(tax_id);
return pslug;
end;
$$ language plpgsql;
revoke execute on function add_product(integer, text, text, text, integer[]) from public;
grant execute on function add_product(integer, text, text, text, integer[]) to invoicer;
grant execute on function add_product(integer, text, text, text, integer[]) to admin;
commit;

View File

@ -1,47 +0,0 @@
-- Deploy numerus:edit_product to pg
-- requires: schema_numerus
-- requires: product
-- requires: product_tax
-- requires: parse_price
-- requires: company
-- requires: currency
begin;
set search_path to numerus, public;
create or replace function edit_product(slug uuid, name text, description text, price text, taxes integer[]) returns boolean
as $$
declare
pid integer;
begin
update product
set name = edit_product.name
, description = edit_product.description
, price = parse_price(edit_product.price, decimal_digits)
from company
join currency using (currency_code)
where product.company_id = company.company_id
and product.slug = edit_product.slug
returning product_id
into pid;
if pid is null then
return false;
end if;
delete from product_tax where product_id = pid;
insert into product_tax(product_id, tax_id)
select pid, tax_id
from unnest(taxes) as tax(tax_id);
return true;
end;
$$ language plpgsql;
revoke execute on function edit_product(uuid, text, text, text, integer[]) from public;
grant execute on function edit_product(uuid, text, text, text, integer[]) to invoicer;
grant execute on function edit_product(uuid, text, text, text, integer[]) to admin;
commit;

View File

@ -2,6 +2,7 @@ package pkg
import (
"context"
"github.com/jackc/pgx/v4"
"github.com/julienschmidt/httprouter"
"html/template"
"net/http"
@ -37,9 +38,14 @@ func GetContactForm(w http.ResponseWriter, r *http.Request, params httprouter.Pa
mustRenderNewContactForm(w, r, form)
return
}
if notFoundErrorOrPanic(conn.QueryRow(r.Context(), "select business_name, substr(vatin::text, 3), trade_name, phone, email, web, address, city, province, postal_code, country_code from contact where slug = $1", slug).Scan(form.BusinessName, form.VATIN, form.TradeName, form.Phone, form.Email, form.Web, form.Address, form.City, form.Province, form.PostalCode, form.Country)) {
err := conn.QueryRow(r.Context(), "select business_name, substr(vatin::text, 3), trade_name, phone, email, web, address, city, province, postal_code, country_code from contact where slug = $1", slug).Scan(form.BusinessName, form.VATIN, form.TradeName, form.Phone, form.Email, form.Web, form.Address, form.City, form.Province, form.PostalCode, form.Country)
if err != nil {
if err == pgx.ErrNoRows {
http.NotFound(w, r)
return
} else {
panic(err)
}
}
w.WriteHeader(http.StatusOK)
mustRenderEditContactForm(w, r, form)

View File

@ -50,16 +50,6 @@ func NewDatabase(ctx context.Context, connString string) (*Db, error) {
return &Db{pool}, nil
}
func notFoundErrorOrPanic(err error) bool {
if err == pgx.ErrNoRows {
return true
}
if err != nil {
panic(err)
}
return false
}
func (db *Db) Acquire(ctx context.Context) (*Conn, error) {
conn, err := db.Pool.Acquire(ctx)
if err != nil {
@ -90,18 +80,13 @@ func (c *Conn) MustBegin(ctx context.Context) *Tx {
func (c *Conn) MustGetText(ctx context.Context, def string, sql string, args ...interface{}) string {
var result string
if notFoundErrorOrPanic(c.Conn.QueryRow(ctx, sql, args...).Scan(&result)) {
if err := c.Conn.QueryRow(ctx, sql, args...).Scan(&result); err != nil {
if err == pgx.ErrNoRows {
return def
}
return result
}
func (c *Conn) MustGetBool(ctx context.Context, sql string, args ...interface{}) bool {
var result bool
if err := c.Conn.QueryRow(ctx, sql, args...).Scan(&result); err != nil {
panic(err)
}
return result
}
@ -145,9 +130,12 @@ func (tx *Tx) MustGetInteger(ctx context.Context, sql string, args ...interface{
func (tx *Tx) MustGetIntegerOrDefault(ctx context.Context, def int, sql string, args ...interface{}) int {
var result int
if notFoundErrorOrPanic(tx.QueryRow(ctx, sql, args...).Scan(&result)) {
if err := tx.QueryRow(ctx, sql, args...).Scan(&result); err != nil {
if err == pgx.ErrNoRows {
return def
}
panic(err)
}
return result
}

View File

@ -28,19 +28,23 @@ type InvoicesIndexPage struct {
func IndexInvoices(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
page := &InvoicesIndexPage{
Invoices: mustCollectInvoiceEntries(r.Context(), getConn(r), mustGetCompany(r), getLocale(r)),
Invoices: mustGetInvoiceEntries(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 from invoice join contact using (contact_id) join invoice_status_i18n isi18n on invoice.invoice_status = isi18n.invoice_status and isi18n.lang_tag = $2 where invoice.company_id = $1 order by invoice_date, invoice_number", company.Id, locale.Language.String())
func mustGetInvoiceEntries(ctx context.Context, conn *Conn, company *Company, locale *Locale) []*InvoiceEntry {
rows, err := conn.Query(ctx, "select invoice.slug, invoice_date, invoice_number, contact.business_name, contact.slug, invoice.invoice_status, isi18n.name from invoice join contact using (contact_id) join invoice_status_i18n isi18n on invoice.invoice_status = isi18n.invoice_status and isi18n.lang_tag = $2 where invoice.company_id = $1 order by invoice_date, invoice_number", company.Id, locale.Language.String())
if err != nil {
panic(err)
}
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); err != nil {
err = rows.Scan(&entry.Slug, &entry.Date, &entry.Number, &entry.CustomerName, &entry.CustomerSlug, &entry.Status, &entry.StatusLabel)
if err != nil {
panic(err)
}
entries = append(entries, entry)
@ -59,6 +63,7 @@ func GetInvoiceForm(w http.ResponseWriter, r *http.Request, params httprouter.Pa
form := newInvoiceForm(r.Context(), conn, locale, company)
slug := params[0].Value
if slug == "new" {
form.Customer.EmptyLabel = gettext("Select a customer to bill.", locale)
form.Date.Val = time.Now().Format("2006-01-02")
w.WriteHeader(http.StatusOK)
mustRenderNewInvoiceForm(w, r, form)
@ -67,8 +72,6 @@ func GetInvoiceForm(w http.ResponseWriter, r *http.Request, params httprouter.Pa
}
func mustRenderNewInvoiceForm(w http.ResponseWriter, r *http.Request, form *invoiceForm) {
locale := getLocale(r)
form.Customer.EmptyLabel = gettext("Select a customer to bill.", locale)
mustRenderAppTemplate(w, r, "invoices/new.gohtml", form)
}

View File

@ -3,11 +3,11 @@ package pkg
import (
"context"
"fmt"
"github.com/jackc/pgx/v4"
"github.com/julienschmidt/httprouter"
"html/template"
"math"
"net/http"
"strconv"
)
type ProductEntry struct {
@ -40,9 +40,25 @@ func GetProductForm(w http.ResponseWriter, r *http.Request, params httprouter.Pa
mustRenderNewProductForm(w, r, form)
return
}
if notFoundErrorOrPanic(conn.QueryRow(r.Context(), "select product.name, product.description, to_price(price, decimal_digits), array_agg(tax_id) from product join product_tax using (product_id) join company using (company_id) join currency using (currency_code) where product.slug = $1 group by product_id, product.name, product.description, price, decimal_digits", slug).Scan(form.Name, form.Description, form.Price, form.Tax)) {
var productId int
err := conn.QueryRow(r.Context(), "select product_id, product.name, product.description, to_price(price, decimal_digits) from product join company using (company_id) join currency using (currency_code) where product.slug = $1", slug).Scan(&productId, form.Name, form.Description, form.Price)
if err != nil {
if err == pgx.ErrNoRows {
http.NotFound(w, r)
return
} else {
panic(err)
}
}
rows, err := conn.Query(r.Context(), "select tax_id from product_tax where product_id = $1", productId)
if err != nil {
panic(err)
}
defer rows.Close()
for rows.Next() {
if err := rows.Scan(form.Tax); err != nil {
panic(err)
}
}
w.WriteHeader(http.StatusOK)
mustRenderEditProductForm(w, r, form)
@ -73,29 +89,25 @@ func HandleAddProduct(w http.ResponseWriter, r *http.Request, _ httprouter.Param
mustRenderNewProductForm(w, r, form)
return
}
taxes := mustSliceAtoi(form.Tax.Selected)
conn.MustExec(r.Context(), "select add_product($1, $2, $3, $4, $5)", company.Id, form.Name, form.Description, form.Price, taxes)
http.Redirect(w, r, companyURI(company, "/products"), http.StatusSeeOther)
tx := conn.MustBegin(r.Context())
productId := tx.MustGetInteger(r.Context(), "insert into product (company_id, name, description, price) select company_id, $2, $3, parse_price($4, decimal_digits) from company join currency using (currency_code) where company_id = $1 returning product_id", company.Id, form.Name, form.Description, form.Price)
if len(form.Tax.Selected) > 0 {
batch := &pgx.Batch{}
for _, tax := range form.Tax.Selected {
batch.Queue("insert into product_tax(product_id, tax_id) values ($1, $2)", productId, tax)
}
func sliceAtoi(s []string) ([]int, error) {
i := []int{}
for _, vs := range s {
vi, err := strconv.Atoi(vs)
if err != nil {
return i, err
}
i = append(i, vi)
}
return i, nil
}
func mustSliceAtoi(s []string) []int {
i, err := sliceAtoi(s)
if err != nil {
br := tx.SendBatch(r.Context(), batch)
for range form.Tax.Selected {
if _, err := br.Exec(); err != nil {
panic(err)
}
return i
}
if err := br.Close(); err != nil {
panic(err)
}
}
tx.MustCommit(r.Context())
http.Redirect(w, r, companyURI(company, "/products"), http.StatusSeeOther)
}
func HandleUpdateProduct(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
@ -116,11 +128,28 @@ func HandleUpdateProduct(w http.ResponseWriter, r *http.Request, params httprout
mustRenderEditProductForm(w, r, form)
return
}
tx := conn.MustBegin(r.Context())
slug := params[0].Value
taxes := mustSliceAtoi(form.Tax.Selected)
if ok := conn.MustGetBool(r.Context(), "select edit_product($1, $2, $3, $4, $5)", slug, form.Name, form.Description, form.Price, taxes); !ok {
productId := tx.MustGetIntegerOrDefault(r.Context(), 0, "update product set name = $1, description = $2, price = parse_price($3, decimal_digits) from company join currency using (currency_code) where product.company_id = company.company_id and product.slug = $4 returning product_id", form.Name, form.Description, form.Price, slug)
if productId == 0 {
tx.MustRollback(r.Context())
http.NotFound(w, r)
}
batch := &pgx.Batch{}
batch.Queue("delete from product_tax where product_id = $1", productId)
for _, tax := range form.Tax.Selected {
batch.Queue("insert into product_tax(product_id, tax_id) values ($1, $2)", productId, tax)
}
br := tx.SendBatch(r.Context(), batch)
for i := 0; i < batch.Len(); i++ {
if _, err := br.Exec(); err != nil {
panic(err)
}
}
if err := br.Close(); err != nil {
panic(err)
}
tx.MustCommit(r.Context())
http.Redirect(w, r, companyURI(company, "/products/"+slug), http.StatusSeeOther)
}

View File

@ -1,7 +0,0 @@
-- Revert numerus:add_product from pg
begin;
drop function if exists numerus.add_product(integer, text, text, text, integer[]);
commit;

View File

@ -1,7 +0,0 @@
-- Revert numerus:edit_product from pg
begin;
drop function if exists numerus.edit_product(uuid, text, text, text, integer[]);
commit;

View File

@ -49,5 +49,3 @@ product_tax [schema_numerus product tax] 2023-02-08T11:36:49Z jordi fita mas <jo
invoice [schema_numerus company contact invoice_status currency] 2023-02-09T09:52:21Z jordi fita mas <jordi@tandem.blog> # Add relation for invoice
discount_rate [schema_numerus] 2023-02-10T17:22:40Z jordi fita mas <jordi@tandem.blog> # Add domain for discount rates
invoice_product [schema_numerus invoice discount_rate] 2023-02-10T17:07:08Z jordi fita mas <jordi@tandem.blog> # Add relation for invoice product
add_product [schema_numerus product product_tax parse_price company currency] 2023-02-14T10:32:18Z jordi fita mas <jordi@tandem.blog> # Add function to add new products
edit_product [schema_numerus product product_tax parse_price company currency] 2023-02-14T11:06:03Z jordi fita mas <jordi@tandem.blog> # Add function to edit products

View File

@ -1,80 +0,0 @@
-- Test add_product
set client_min_messages to warning;
create extension if not exists pgtap;
reset client_min_messages;
begin;
select plan(14);
set search_path to auth, numerus, public;
select has_function('numerus', 'add_product', array ['integer', 'text', 'text', 'text', 'integer[]']);
select function_lang_is('numerus', 'add_product', array ['integer', 'text', 'text', 'text', 'integer[]'], 'plpgsql');
select function_returns('numerus', 'add_product', array ['integer', 'text', 'text', 'text', 'integer[]'], 'uuid');
select isnt_definer('numerus', 'add_product', array ['integer', 'text', 'text', 'text', 'integer[]']);
select volatility_is('numerus', 'add_product', array ['integer', 'text', 'text', 'text', 'integer[]'], 'volatile');
select function_privs_are('numerus', 'add_product', array ['integer', 'text', 'text', 'text', 'integer[]'], 'guest', array []::text[]);
select function_privs_are('numerus', 'add_product', array ['integer', 'text', 'text', 'text', 'integer[]'], 'invoicer', array ['EXECUTE']);
select function_privs_are('numerus', 'add_product', array ['integer', 'text', 'text', 'text', 'integer[]'], 'admin', array ['EXECUTE']);
select function_privs_are('numerus', 'add_product', array ['integer', 'text', 'text', 'text', 'integer[]'], 'authenticator', array []::text[]);
set client_min_messages to warning;
truncate product_tax cascade;
truncate product cascade;
truncate tax cascade;
truncate company cascade;
reset client_min_messages;
insert into company (company_id, business_name, vatin, trade_name, phone, email, web, address, city, province, postal_code, country_code, currency_code)
values (1, 'Company 2', 'XX123', '', '555-555-555', 'a@a', '', '', '', '', '', 'ES', 'EUR')
, (2, 'Company 4', 'XX234', '', '666-666-666', 'b@b', '', '', '', '', '', 'FR', 'USD')
;
insert into tax (tax_id, company_id, name, rate)
values (3, 1, 'IRPF -15 %', -0.15)
, (4, 1, 'IVA 21 %', 0.21)
, (5, 2, 'IRPF -7 %', -0.07)
, (6, 2, 'IVA 10 %', 0.10)
;
select lives_ok(
$$ select add_product(1, 'Product 1', 'Description 1', '12.12', array[3, 4]) $$,
'Should be able to add product to first company'
);
select lives_ok(
$$ select add_product(2, 'Product 2', 'Description 2', '24.24', array[6]) $$,
'Should be able to add product to second company'
);
select lives_ok(
$$ select add_product(2, 'Product 3', 'Description 3', '36.36', array[]::integer[]) $$,
'Should be able to add product without taxes'
);
select bag_eq(
$$ select company_id, name, description, price, created_at from product $$,
$$ values (1, 'Product 1', 'Description 1', 1212, current_timestamp)
, (2, 'Product 2', 'Description 2', 2424, current_timestamp)
, (2, 'Product 3', 'Description 3', 3636, current_timestamp)
$$,
'Should have added all three products'
);
select bag_eq(
$$ select tax_id, name from product_tax join product using (product_id) $$,
$$ values (3, 'Product 1')
, (4, 'Product 1')
, (6, 'Product 2')
$$,
'Should have added the taxes for the products we told to'
);
select *
from finish();
rollback;

View File

@ -1,101 +0,0 @@
-- Test edit_product
set client_min_messages to warning;
create extension if not exists pgtap;
reset client_min_messages;
begin;
select plan(15);
set search_path to auth, numerus, public;
select has_function('numerus', 'edit_product', array ['uuid', 'text', 'text', 'text', 'integer[]']);
select function_lang_is('numerus', 'edit_product', array ['uuid', 'text', 'text', 'text', 'integer[]'], 'plpgsql');
select function_returns('numerus', 'edit_product', array ['uuid', 'text', 'text', 'text', 'integer[]'], 'boolean');
select isnt_definer('numerus', 'edit_product', array ['uuid', 'text', 'text', 'text', 'integer[]']);
select volatility_is('numerus', 'edit_product', array ['uuid', 'text', 'text', 'text', 'integer[]'], 'volatile');
select function_privs_are('numerus', 'edit_product', array ['uuid', 'text', 'text', 'text', 'integer[]'], 'guest', array []::text[]);
select function_privs_are('numerus', 'edit_product', array ['uuid', 'text', 'text', 'text', 'integer[]'], 'invoicer', array ['EXECUTE']);
select function_privs_are('numerus', 'edit_product', array ['uuid', 'text', 'text', 'text', 'integer[]'], 'admin', array ['EXECUTE']);
select function_privs_are('numerus', 'edit_product', array ['uuid', 'text', 'text', 'text', 'integer[]'], 'authenticator', array []::text[]);
set client_min_messages to warning;
truncate product_tax cascade;
truncate product cascade;
truncate tax cascade;
truncate company cascade;
reset client_min_messages;
insert into company (company_id, business_name, vatin, trade_name, phone, email, web, address, city, province, postal_code, country_code, currency_code)
values (1, 'Company 2', 'XX123', '', '555-555-555', 'a@a', '', '', '', '', '', 'ES', 'EUR')
, (2, 'Company 4', 'XX234', '', '666-666-666', 'b@b', '', '', '', '', '', 'FR', 'USD')
;
insert into tax (tax_id, company_id, name, rate)
values (3, 1, 'IRPF -15 %', -0.15)
, (4, 1, 'IVA 21 %', 0.21)
, (5, 2, 'IRPF -7 %', -0.07)
, (6, 2, 'IVA 10 %', 0.10)
;
insert into product (product_id, company_id, slug, name, description, price)
values (7, 1, 'd2300404-bd23-48b3-8e2b-2bbf86dc7bd6', 'Product 01', 'Description01', 1200)
, (8, 2, '2f085b8b-da90-41fe-b8cf-6ba8d94cfa38', 'Product 02', 'Description02', 2400)
, (9, 2, '84044d0b-af33-442a-95a6-21efc77260d5', 'Product 03', 'Description03', 3600)
;
insert into product_tax (product_id, tax_id)
values (7, 3)
, (8, 5)
, (9, 5)
, (9, 6)
;
select is(
edit_product('d2300404-bd23-48b3-8e2b-2bbf86dc7bd6', 'Product 1', 'Description 1', '12.12', array[3, 4]),
true,
'Should be able to edit product from first company'
);
select is(
edit_product('2f085b8b-da90-41fe-b8cf-6ba8d94cfa38', 'Product 2', 'Description 2', '24.24', array[6]),
true,
'Should be able to edit product from second company'
);
select is(
edit_product('84044d0b-af33-442a-95a6-21efc77260d5', 'Product 3', 'Description 3', '36.36', array[]::integer[]),
true,
'Should be able to edit a product a remove all taxes'
);
select is(
edit_product('87e158d1-a0f5-48a7-854b-b86d7b4bb21c', 'Product 4', 'Description 4', '48.48', array[]::integer[]),
false,
'Should return false when the product does not exist'
);
select bag_eq(
$$ select product_id, company_id, name, description, price from product $$,
$$ values (7, 1, 'Product 1', 'Description 1', 1212)
, (8, 2, 'Product 2', 'Description 2', 2424)
, (9, 2, 'Product 3', 'Description 3', 3636)
$$,
'Should have edited all three products'
);
select bag_eq(
$$ select product_id, tax_id from product_tax $$,
$$ values (7, 3)
, (7, 4)
, (8, 6)
$$,
'Should have updated the taxes for the products we told to'
);
select *
from finish();
rollback;

View File

@ -33,8 +33,8 @@ select col_hasnt_default('product_tax', 'tax_id');
set client_min_messages to warning;
truncate product_tax cascade;
truncate product cascade;
truncate product_tax cascade;
truncate tax cascade;
truncate company_user cascade;
truncate company cascade;

View File

@ -1,7 +0,0 @@
-- Verify numerus:add_product on pg
begin;
select has_function_privilege('numerus.add_product(integer, text, text, text, integer[])', 'execute');
rollback;

View File

@ -1,7 +0,0 @@
-- Verify numerus:edit_product on pg
begin;
select has_function_privilege('numerus.edit_product(uuid, text, text, text, integer[])', 'execute');
rollback;

View File

@ -34,10 +34,8 @@
{{- end }}
<fieldset>
<button formnovalidate name="action" value="products"
type="submit">{{( pgettext "Add products" "action" )}}</button>
<button formnovalidate name="action" value="update"
type="submit">{{( pgettext "Update" "action" )}}</button>
<button name="action" value="products" type="submit">{{( pgettext "Add products" "action" )}}</button>
<button name="action" value="update" type="submit">{{( pgettext "Update" "action" )}}</button>
<button class="primary" name="action" value="add"
type="submit">{{( pgettext "New invoice" "action" )}}</button>
</fieldset>