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