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