Bump version and update Changes
[app-web-oof.git] / lib / App / Web / Oof.pm
CommitLineData
6e33dd68
MG
1package App::Web::Oof;
2
3use 5.014000;
4use strict;
5use warnings;
6use utf8;
7use parent qw/Plack::Component/;
8
6348c409 9our $VERSION = '0.000_006';
6e33dd68
MG
10
11use DBIx::Simple;
8526cf2b
MG
12use Email::Sender::Simple 'sendmail';
13use Email::Simple;
1576fc41 14use File::Slurp;
6e33dd68
MG
15use HTML::TreeBuilder;
16use HTML::Element::Library;
17use JSON::MaybeXS qw/encode_json decode_json/;
18use Plack::Builder;
19use Plack::Request;
1576fc41 20use Try::Tiny;
6e33dd68
MG
21
22sub HTML::Element::iter3 {
23 my ($self, $data, $code) = @_;
24 my $orig = $self;
25 my $prev = $orig;
26 for my $el (@$data) {
27 my $current = $orig->clone;
28 $code->($el, $current);
29 $prev->postinsert($current);
30 $prev = $current;
31 }
32 $orig->detach;
33}
34
35sub HTML::Element::fid { shift->look_down(id => shift) }
36sub HTML::Element::fclass { shift->look_down(class => qr/\b$_[0]\b/) }
37
38##################################################
39
1576fc41
MG
40my %db;
41my ($form, $continue, $order, $details, $pay);
6e33dd68
MG
42
43{
44 sub parse_html {
45 my $builder = HTML::TreeBuilder->new;
46 $builder->ignore_unknown(0);
47 $builder->parse_file("tmpl/$_[0].html");
48 $builder
49 }
50
51 $form = parse_html 'form';
52 $continue = parse_html 'continue';
53 $order = parse_html 'order';
1576fc41
MG
54 $details = parse_html 'details';
55 $pay = parse_html 'pay';
6e33dd68
MG
56}
57
58sub stringify_money { sprintf "£%.2f", $_[0] / 100 }
59
1576fc41
MG
60sub make_slug {
61 my $slug = $_[0];
62 $slug =~ y/ /-/;
63 $slug =~ y/a-zA-Z0-9-//cd;
64 $slug
65}
66
8bb7ab90
MG
67sub product_to_schemaorg {
68 my ($include_url, %data) = @_;
69 my $stock = $data{stock} > 0 ? 'InStock' : 'OutOfStock';
70 +{
71 '@context' => 'http://schema.org/',
72 '@type' => 'Product',
73 name => $data{title},
74 image => "/static/fullpics/$data{product}-1.jpg",
75 description => $data{summary},
76 offers => {
77 '@type' => 'Offer',
78 price => ($data{price} =~ s/(..)$/\.$1/r),
79 priceCurrency => 'GBP',
80 availability => "http://schema.org/$stock",
81 ($include_url ? (url => "/details/$data{product}/" . make_slug $data{title}) : ())
82 }
83 }
84}
85
fc536c37 86our %highlight;
6e33dd68
MG
87sub form_table_row {
88 my ($data, $tr) = @_;
fc536c37 89 $tr->attr(class => 'highlight') if $highlight{$data->{product}};
6e33dd68
MG
90 $tr->fclass($_)->replace_content($data->{$_}) for qw/title subtitle stock/;
91 $tr->fclass('price')->replace_content(stringify_money $data->{price});
8bbff1bc 92 $tr->fclass('freepost')->detach unless $data->{freepost};
6e33dd68 93 $tr->fclass('title')->attr('data-product', $data->{product});
1576fc41
MG
94 $tr->fclass('title')->attr('href', '/details/'.$data->{product}.'/'.make_slug $data->{title});
95# $tr->fclass('title')->attr('data-summary', $data->{summary});
6e33dd68
MG
96 $tr->look_down(_tag => 'input')->attr(max => $data->{stock});
97 $tr->look_down(_tag => 'input')->attr(name => 'quant'.$data->{product});
98}
99
100sub form_app {
101 my ($env) = @_;
1576fc41 102 $db{$$} //= DBIx::Simple->connect($ENV{OOF_DSN} // 'dbi:Pg:');
fc536c37 103 my $req = Plack::Request->new($env);
6e33dd68 104
fc536c37 105 local %highlight = map { $_ => 1 } $req->param('highlight');
1576fc41 106 my $data = $db{$$}->select(products => '*', {}, 'product')->hashes;
6e33dd68
MG
107 my $tree = $form->clone;
108 $tree->find('tbody')->find('tr')->iter3($data, \&form_table_row);
109
110 [200, ['Content-type' => 'text/html; charset=utf-8'], [$tree->as_HTML]]
111}
112
113sub continue_table_row {
114 my ($data, $tr) = @_;
115 $tr->fclass($_)->replace_content($data->{$_}) for qw/title subtitle quantity/;
8bbff1bc 116 $tr->fclass('freepost')->detach unless $data->{freepost};
6e33dd68
MG
117 $tr->fclass('price')->replace_content(stringify_money $data->{subtotal});
118 $tr->fclass('title')->attr('data-product', $data->{product});
119}
120
121sub continue_app {
122 my ($env) = @_;
1576fc41 123 $db{$$} //= DBIx::Simple->connect($ENV{OOF_DSN} // 'dbi:Pg:');
6e33dd68
MG
124 my $tree = $continue->clone;
125 my $req = Plack::Request->new($env);
126 my $params = $req->body_parameters;
127
8bbff1bc 128 my ($quant, $quant_freepost, $total, @data, @notes) = (0) x 3;
6e33dd68
MG
129 for (sort keys %$params) {
130 next unless /^quant/;
131 next unless $params->{$_};
1576fc41 132 my $data = $db{$$}->select(products => '*', {product => substr $_, 5})->hash;
6e33dd68
MG
133 $data->{quantity} = $params->{$_};
134 if ($data->{stock} == 0) {
135 push @notes, 'Item is out of stock and was removed from order: '.$data->{title};
136 next
137 }
138 if ($data->{quantity} > $data->{stock}) {
139 $data->{quantity} = $data->{stock};
140 push @notes, 'Not enough units of "'.$data->{title}.'" available. Quantity reduced to '.$data->{quantity}
141 }
142 $data->{subtotal} = $data->{price} * $data->{quantity};
143 $quant += $data->{quantity};
8bbff1bc 144 $quant_freepost += $data->{quantity} if $data->{freepost};
6e33dd68
MG
145 $total += $data->{subtotal};
146 push @data, $data
147 }
148
1576fc41
MG
149 return [500, ['Content-type' => 'text/plain'], ['Error: no items in order.']] unless $quant;
150
6e33dd68
MG
151 $tree->fid('subtotal')->replace_content(stringify_money $total);
152 my $dvalue;
153 if ($params->{discount}) {
1576fc41 154 my $discount = $db{$$}->select(discounts => '*', {discount => $params->{discount}})->hash;
6e33dd68
MG
155 if (!defined $discount) {
156 push @notes, 'Discount code incorrect. No discount applied.'
1576fc41 157 } elsif ($db{$$}->select(orders => 'COUNT(*)', {discount => $params->{discount}})->list) {
6e33dd68
MG
158 push @notes, 'Discount code already used once. No discount applied.'
159 } else {
160 $dvalue = int (0.5 + $discount->{fraction} * $total) if $discount->{fraction};
161 $dvalue = $discount->{flat} if $discount->{flat};
162 $tree->fid('discount')->replace_content('-'.stringify_money $dvalue);
163 $total -= $dvalue;
164 $tree->look_down(name => 'discount')->attr(value => $params->{discount});
165 push @notes, 'Discount applied.'
166 }
167 }
168 $tree->look_down(name => 'discount')->detach unless $dvalue;
169 $tree->fid('discount_tr')->detach unless $dvalue;
8bbff1bc
MG
170 my $postage = 220 + 50 * ($quant - $quant_freepost);
171 $postage = 0 if $quant == $quant_freepost;
6e33dd68
MG
172 $tree->fid('postage')->replace_content(stringify_money $postage);
173 $total += $postage;
174 $tree->fid('total')->replace_content(stringify_money $total);
175
176 $tree->fid('order')->find('tbody')->find('tr')->iter3(\@data, \&continue_table_row);
177 $tree->iter($tree->fid('notes')->find('li') => @notes);
178
179 $tree->look_down(name => 'products')->attr(value => encode_json \@data);
180 $tree->look_down(name => 'total')->attr(value => $total);
181
182 [200, ['Content-type' => 'text/html; charset=utf-8'], [$tree->as_HTML]]
183}
184
185sub order_app {
186 my ($env) = @_;
1576fc41 187 $db{$$} //= DBIx::Simple->connect($ENV{OOF_DSN} // 'dbi:Pg:');
6e33dd68
MG
188 my $tree = $order->clone;
189 my $req = Plack::Request->new($env);
1576fc41
MG
190 my ($id) = $env->{PATH_INFO} =~ m,^/([0-9A-F]+),;
191 if ($id) {
85e0d9a2
MG
192 my $total = $db{$$}->select(orders => 'total', {id => $id})->list or
193 return [500, ['Content-type', 'text/plain'], ['Order not found']];
1576fc41
MG
194 $tree->fid('orderid')->replace_content($id);
195 $tree->look_down(name => 'order')->attr(value => $id);
196 $tree->fid('total')->replace_content(stringify_money $total);
197 $tree->find('script')->attr('data-amount', $total);
198 return [200, ['Content-type' => 'text/html; charset=utf-8'], [$tree->as_HTML]]
199 } else {
200 my %parms = %{$req->body_parameters};
201 my $id = sprintf "%X%04X", time, $$;
202 my $err;
203 try {
204 $db{$$}->begin_work;
205 my $products = decode_json $req->body_parameters->{products};
206 for my $prod (@$products) {
207 my $stock = $db{$$}->select(products => 'stock', {product => $prod->{product}})->list;
208 die "Not enough of " .$prod->{title}."\n" if $prod->{quantity} > $stock;
209 $db{$$}->update(products => {stock => $stock - $prod->{quantity}}, {product => $prod->{product}});
210 }
211 $db{$$}->insert(orders => {id => $id, %parms});
212 $db{$$}->commit;
8526cf2b
MG
213 sendmail (Email::Simple->create(
214 header => [
215 From => $ENV{OOF_EMAIL_FROM},
216 To => $ENV{OOF_EMAIL_TO},
217 Subject => "Order $id placed",
218 ],
219 body => 'A new order was placed.',
220 )) if $ENV{OOF_EMAIL_TO};
1576fc41
MG
221 } catch {
222 $db{$$}->rollback;
223 $err = [500, ['Content-type', 'text/plain'], ["Error: $_"]]
224 };
225 return $err if $err;
226 return [303, [Location => "/order/$id"], []]
6e33dd68 227 }
1576fc41
MG
228}
229
5eeddbd0
MG
230sub cancel {
231 my ($order) = @_;
232 $db{$$} //= DBIx::Simple->connect($ENV{OOF_DSN} // 'dbi:Pg:');
233 $order = $db{$$}->select(orders => '*', {id => $order})->hash;
234 my $products = decode_json $order->{products};
235 $db{$$}->begin_work;
236 try {
237 for my $prod (@$products) {
238 my $stock = $db{$$}->select(products => 'stock', {product => $prod->{product}})->list;
239 $db{$$}->update(products => {stock => $stock + $prod->{quantity}}, {product => $prod->{product}});
240 }
241 $db{$$}->delete(orders => {id => $order->{id}});
242 $db{$$}->commit;
243 } catch {
244 $db{$$}->rollback;
245 die $_
246 }
247}
248
1576fc41
MG
249sub details_list_element {
250 my ($data, $li) = @_;
251 $li->find('a')->attr(href => "/$data");
252 my $thumb = $data =~ s/fullpics/thumbs/r;
253 $thumb = $data unless -f $thumb;
254 $li->find('img')->attr(src => "/$thumb");
255}
256
257sub details_app {
258 my ($env) = @_;
259 $db{$$} //= DBIx::Simple->connect($ENV{OOF_DSN} // 'dbi:Pg:');
260 my $tree = $details->clone;
261 my ($id) = $env->{PATH_INFO} =~ m,^/(\d+),;
8bb7ab90 262 my %data = %{$db{$$}->select(products => '*', {product => $id})->hash};
1576fc41 263 my @pics = <static/fullpics/$id-*>;
8bb7ab90
MG
264 my $slug = make_slug $data{title};
265 $tree->find('title')->replace_content("$data{title} | ledparts4you");
266 $tree->find('h2')->replace_content($data{title});
267 $tree->fid('summary')->replace_content($data{summary});
1576fc41 268 $tree->look_down(rel => 'canonical')->attr(href => "/details/$id/$slug");
b66954a0 269 $tree->fid('pictures')->find('li')->iter3(\@pics, \&details_list_element);
8bb7ab90 270 $tree->fid('jsonld')->replace_content(encode_json product_to_schemaorg '', %data);
6e33dd68 271
fc536c37
MG
272 for my $ahref ($tree->find('a')) {
273 $ahref->attr(href => "/form?highlight=$id") if $ahref->attr('href') eq '/';
274 }
275
6e33dd68
MG
276 [200, ['Content-type' => 'text/html; charset=utf-8'], [$tree->as_HTML]]
277}
278
1576fc41
MG
279sub pay_app {
280 my ($env) = @_;
281 my $req = Plack::Request->new($env);
282 $db{$$} //= DBIx::Simple->connect($ENV{OOF_DSN} // 'dbi:Pg:');
283 my $order = $req->body_parameters->{order};
284 my $token = $req->body_parameters->{stripeToken};
285 return [500, ['Content-type' => 'text/html; charset=utf-8'], ['No token received, payment did not succeed.']] unless $token;
286 $db{$$}->update(orders => {stripe_token => $token}, {id => $order});
287 [200, ['Content-type' => 'text/html; charset=utf-8'], [$pay->as_HTML]];
288}
289
6e33dd68 290sub app {
1576fc41 291 my $footer = read_file 'tmpl/footer.html';
6e33dd68 292 builder {
1576fc41
MG
293 enable sub {
294 my $app = shift;
295 sub {
296 my $res = $app->(@_);
0c3c4e70 297 $res->[2][0] =~ s,</body>,$footer</body>, if $res->[0] == 200;
1576fc41
MG
298 $res;
299 }
300 };
6e33dd68
MG
301 mount '/' => sub { [301, [Location => '/form'], []] };
302 mount '/form' => \&form_app;
303 mount '/continue' => \&continue_app;
304 mount '/order' => \&order_app;
1576fc41
MG
305 mount '/details' => \&details_app;
306 mount '/pay' => \&pay_app;
6e33dd68
MG
307 }
308}
309
3101;
311__END__
312
313=head1 NAME
314
315App::Web::Oof - Oversimplified order form / ecommerce website
316
317=head1 SYNOPSIS
318
319 use App::Web::Oof;
320
321=head1 DESCRIPTION
322
323Oof (Oversimplified order form) is a very simple ecommerce website.
39be4169
MG
324It is the code behind L<https://ledparts4you.uk.to>.
325
326This version is reasonably functional, yet not very reusable, hence
327the version number.
6e33dd68
MG
328
329=head1 AUTHOR
330
331Marius Gavrilescu, E<lt>marius@ieval.roE<gt>
332
333=head1 COPYRIGHT AND LICENSE
334
335Copyright (C) 2016 by Marius Gavrilescu
336
337This library is free software; you can redistribute it and/or modify
338it under the same terms as Perl itself, either Perl version 5.22.1 or,
339at your option, any later version of Perl 5 you may have available.
340
341
342=cut
This page took 0.032992 seconds and 4 git commands to generate.