| 1 | package App::Web::Oof; |
| 2 | |
| 3 | use 5.014000; |
| 4 | use strict; |
| 5 | use warnings; |
| 6 | use utf8; |
| 7 | use parent qw/Plack::Component/; |
| 8 | |
| 9 | our $VERSION = '0.000_005'; |
| 10 | |
| 11 | use DBIx::Simple; |
| 12 | use Email::Sender::Simple 'sendmail'; |
| 13 | use Email::Simple; |
| 14 | use File::Slurp; |
| 15 | use HTML::TreeBuilder; |
| 16 | use HTML::Element::Library; |
| 17 | use JSON::MaybeXS qw/encode_json decode_json/; |
| 18 | use Plack::Builder; |
| 19 | use Plack::Request; |
| 20 | use Try::Tiny; |
| 21 | |
| 22 | sub 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 | |
| 35 | sub HTML::Element::fid { shift->look_down(id => shift) } |
| 36 | sub HTML::Element::fclass { shift->look_down(class => qr/\b$_[0]\b/) } |
| 37 | |
| 38 | ################################################## |
| 39 | |
| 40 | my %db; |
| 41 | my ($form, $continue, $order, $details, $pay); |
| 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'; |
| 54 | $details = parse_html 'details'; |
| 55 | $pay = parse_html 'pay'; |
| 56 | } |
| 57 | |
| 58 | sub stringify_money { sprintf "£%.2f", $_[0] / 100 } |
| 59 | |
| 60 | sub make_slug { |
| 61 | my $slug = $_[0]; |
| 62 | $slug =~ y/ /-/; |
| 63 | $slug =~ y/a-zA-Z0-9-//cd; |
| 64 | $slug |
| 65 | } |
| 66 | |
| 67 | sub 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 | |
| 86 | our %highlight; |
| 87 | sub form_table_row { |
| 88 | my ($data, $tr) = @_; |
| 89 | $tr->attr(class => 'highlight') if $highlight{$data->{product}}; |
| 90 | $tr->fclass($_)->replace_content($data->{$_}) for qw/title subtitle stock/; |
| 91 | $tr->fclass('price')->replace_content(stringify_money $data->{price}); |
| 92 | $tr->fclass('freepost')->detach unless $data->{freepost}; |
| 93 | $tr->fclass('title')->attr('data-product', $data->{product}); |
| 94 | $tr->fclass('title')->attr('href', '/details/'.$data->{product}.'/'.make_slug $data->{title}); |
| 95 | # $tr->fclass('title')->attr('data-summary', $data->{summary}); |
| 96 | $tr->look_down(_tag => 'input')->attr(max => $data->{stock}); |
| 97 | $tr->look_down(_tag => 'input')->attr(name => 'quant'.$data->{product}); |
| 98 | } |
| 99 | |
| 100 | sub form_app { |
| 101 | my ($env) = @_; |
| 102 | $db{$$} //= DBIx::Simple->connect($ENV{OOF_DSN} // 'dbi:Pg:'); |
| 103 | my $req = Plack::Request->new($env); |
| 104 | |
| 105 | local %highlight = map { $_ => 1 } $req->param('highlight'); |
| 106 | my $data = $db{$$}->select(products => '*', {}, 'product')->hashes; |
| 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 | |
| 113 | sub continue_table_row { |
| 114 | my ($data, $tr) = @_; |
| 115 | $tr->fclass($_)->replace_content($data->{$_}) for qw/title subtitle quantity/; |
| 116 | $tr->fclass('freepost')->detach unless $data->{freepost}; |
| 117 | $tr->fclass('price')->replace_content(stringify_money $data->{subtotal}); |
| 118 | $tr->fclass('title')->attr('data-product', $data->{product}); |
| 119 | } |
| 120 | |
| 121 | sub continue_app { |
| 122 | my ($env) = @_; |
| 123 | $db{$$} //= DBIx::Simple->connect($ENV{OOF_DSN} // 'dbi:Pg:'); |
| 124 | my $tree = $continue->clone; |
| 125 | my $req = Plack::Request->new($env); |
| 126 | my $params = $req->body_parameters; |
| 127 | |
| 128 | my ($quant, $quant_freepost, $total, @data, @notes) = (0) x 3; |
| 129 | for (sort keys %$params) { |
| 130 | next unless /^quant/; |
| 131 | next unless $params->{$_}; |
| 132 | my $data = $db{$$}->select(products => '*', {product => substr $_, 5})->hash; |
| 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}; |
| 144 | $quant_freepost += $data->{quantity} if $data->{freepost}; |
| 145 | $total += $data->{subtotal}; |
| 146 | push @data, $data |
| 147 | } |
| 148 | |
| 149 | return [500, ['Content-type' => 'text/plain'], ['Error: no items in order.']] unless $quant; |
| 150 | |
| 151 | $tree->fid('subtotal')->replace_content(stringify_money $total); |
| 152 | my $dvalue; |
| 153 | if ($params->{discount}) { |
| 154 | my $discount = $db{$$}->select(discounts => '*', {discount => $params->{discount}})->hash; |
| 155 | if (!defined $discount) { |
| 156 | push @notes, 'Discount code incorrect. No discount applied.' |
| 157 | } elsif ($db{$$}->select(orders => 'COUNT(*)', {discount => $params->{discount}})->list) { |
| 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; |
| 170 | my $postage = 220 + 50 * ($quant - $quant_freepost); |
| 171 | $postage = 0 if $quant == $quant_freepost; |
| 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 | |
| 185 | sub order_app { |
| 186 | my ($env) = @_; |
| 187 | $db{$$} //= DBIx::Simple->connect($ENV{OOF_DSN} // 'dbi:Pg:'); |
| 188 | my $tree = $order->clone; |
| 189 | my $req = Plack::Request->new($env); |
| 190 | my ($id) = $env->{PATH_INFO} =~ m,^/([0-9A-F]+),; |
| 191 | if ($id) { |
| 192 | my $total = $db{$$}->select(orders => 'total', {id => $id})->list or |
| 193 | return [500, ['Content-type', 'text/plain'], ['Order not found']]; |
| 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; |
| 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}; |
| 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"], []] |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | sub 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 | |
| 249 | sub 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 | |
| 257 | sub 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+),; |
| 262 | my %data = %{$db{$$}->select(products => '*', {product => $id})->hash}; |
| 263 | my @pics = <static/fullpics/$id-*>; |
| 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}); |
| 268 | $tree->look_down(rel => 'canonical')->attr(href => "/details/$id/$slug"); |
| 269 | $tree->fid('pictures')->find('li')->iter3(\@pics, \&details_list_element); |
| 270 | $tree->fid('jsonld')->replace_content(encode_json product_to_schemaorg '', %data); |
| 271 | |
| 272 | for my $ahref ($tree->find('a')) { |
| 273 | $ahref->attr(href => "/form?highlight=$id") if $ahref->attr('href') eq '/'; |
| 274 | } |
| 275 | |
| 276 | [200, ['Content-type' => 'text/html; charset=utf-8'], [$tree->as_HTML]] |
| 277 | } |
| 278 | |
| 279 | sub 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 | |
| 290 | sub app { |
| 291 | my $footer = read_file 'tmpl/footer.html'; |
| 292 | builder { |
| 293 | enable sub { |
| 294 | my $app = shift; |
| 295 | sub { |
| 296 | my $res = $app->(@_); |
| 297 | $res->[2][0] =~ s,</body>,$footer</body>, if $res->[0] == 200; |
| 298 | $res; |
| 299 | } |
| 300 | }; |
| 301 | mount '/' => sub { [301, [Location => '/form'], []] }; |
| 302 | mount '/form' => \&form_app; |
| 303 | mount '/continue' => \&continue_app; |
| 304 | mount '/order' => \&order_app; |
| 305 | mount '/details' => \&details_app; |
| 306 | mount '/pay' => \&pay_app; |
| 307 | } |
| 308 | } |
| 309 | |
| 310 | 1; |
| 311 | __END__ |
| 312 | |
| 313 | =head1 NAME |
| 314 | |
| 315 | App::Web::Oof - Oversimplified order form / ecommerce website |
| 316 | |
| 317 | =head1 SYNOPSIS |
| 318 | |
| 319 | use App::Web::Oof; |
| 320 | |
| 321 | =head1 DESCRIPTION |
| 322 | |
| 323 | Oof (Oversimplified order form) is a very simple ecommerce website. |
| 324 | It is the code behind L<https://ledparts4you.uk.to>. |
| 325 | |
| 326 | This version is reasonably functional, yet not very reusable, hence |
| 327 | the version number. |
| 328 | |
| 329 | =head1 AUTHOR |
| 330 | |
| 331 | Marius Gavrilescu, E<lt>marius@ieval.roE<gt> |
| 332 | |
| 333 | =head1 COPYRIGHT AND LICENSE |
| 334 | |
| 335 | Copyright (C) 2016 by Marius Gavrilescu |
| 336 | |
| 337 | This library is free software; you can redistribute it and/or modify |
| 338 | it under the same terms as Perl itself, either Perl version 5.22.1 or, |
| 339 | at your option, any later version of Perl 5 you may have available. |
| 340 | |
| 341 | |
| 342 | =cut |