prolog-point-of-sale/views/products.pl

116 lines
3.2 KiB
Prolog

:- http_handler(root(.), products_view(Method), [method(Method), methods([get, post])]).
:- http_handler(root('style.css'), http_reply_file('style.css', []), []).
price_str(Price, PriceStr) :-
Euro is Price / 100,
format(atom(PriceStr), '€ ~2f', Euro).
products_add -->
{http_session_data(user(_))}, !, % Check if we're logged in
html(
div([
h2('Add product'),
form([method=post], [
div([
label(for=name, 'Name'),
input([
type=text,
placeholder='Name',
name=name,
id=name,
required
])
]),
div([
label(for=price, 'Price'),
input([
type=text,
placeholder='Price',
name=price,
id=price,
required
])
]),
div(input(type=submit))
])
])
).
products_add --> []. % If not, do not show
products_list([]) --> [].
products_list([product(Name, Price)|Products]) -->
{price_str(Price, PriceStr)},
html([
a([
class(product),
'data-name'(Name),
href('/cart/add/'+Name)
], [
div(class(product__name), [Name]),
div(class(product__price), [PriceStr])
])
]),
products_list(Products).
cart([]) --> [].
cart([Name|Items]) -->
{
product(Name, Cents),
price_str(Cents, Price)
},
html([
div(class(cart__entry), [
div(class(cart__name), Name),
div(class(cart__price), Price)
])
]),
cart(Items).
account -->
{http_session_data(user(Username))}, !,
html([
div(['Hello ', Username, '!']),
a(href('/logout'), 'Log out')
]).
account -->
html(a(href('/login'), 'Log in')).
products_view(get, _Request) :-
(bagof(product(X, Y), product(X, Y), Products); Products = []),
(bagof(Name, http_session_data(cart_entry(Name)), CartEntries); CartEntries = []),
reply_html_page(
[
title('point of shit'),
link([
type('text/css'),
rel('stylesheet'),
href('style.css')
])
],
[
h1('Products'),
main([
div(class(products), \products_list(Products)),
div(class(cart), \cart(CartEntries))
]),
\products_add,
h2('Account'),
\account
]
).
products_view(post, Request) :-
% Check if we're logged in
\+ http_session_data(user(_)), !,
http_session_assert(reason('You need to be logged in to do this.')),
http_redirect(see_other, root(login), Request).
products_view(post, Request) :-
http_read_data(Request, [name=Name, price=Price], []),
atom_number(Price, PriceNumber),
Cents is round(PriceNumber * 100),
retractall_product(Name, _),
assert_product(Name, Cents),
http_redirect(see_other, root(.), Request).