Commit | Line | Data |
---|---|---|
6e33dd68 MG |
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 | ||
06dc23e9 | 9 | our $VERSION = '0.000_007'; |
6e33dd68 MG |
10 | |
11 | use DBIx::Simple; | |
8526cf2b MG |
12 | use Email::Sender::Simple 'sendmail'; |
13 | use Email::Simple; | |
1576fc41 | 14 | use File::Slurp; |
6e33dd68 MG |
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; | |
18be372d | 20 | use Text::CSV; |
1576fc41 | 21 | use Try::Tiny; |
6e33dd68 MG |
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 | ||
c51bcbe6 MG |
41 | my $postage_base = $ENV{OOF_POSTAGE_BASE} // 225; |
42 | my $postage_per_item = $ENV{OOF_POSTAGE_PER_ITEM} // 50; | |
43 | ||
44 | ################################################## | |
45 | ||
1576fc41 | 46 | my %db; |
80e9b2b1 | 47 | my ($form, $continue, $order, $details, $pay, $display, $down); |
6e33dd68 MG |
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'; | |
1576fc41 MG |
60 | $details = parse_html 'details'; |
61 | $pay = parse_html 'pay'; | |
69d4d80d | 62 | $display = parse_html 'display'; |
80e9b2b1 | 63 | $down = parse_html 'down'; |
6e33dd68 MG |
64 | } |
65 | ||
66 | sub stringify_money { sprintf "£%.2f", $_[0] / 100 } | |
67 | ||
1576fc41 MG |
68 | sub make_slug { |
69 | my $slug = $_[0]; | |
70 | $slug =~ y/ /-/; | |
71 | $slug =~ y/a-zA-Z0-9-//cd; | |
72 | $slug | |
73 | } | |
74 | ||
8bb7ab90 MG |
75 | sub product_to_schemaorg { |
76 | my ($include_url, %data) = @_; | |
77 | my $stock = $data{stock} > 0 ? 'InStock' : 'OutOfStock'; | |
a9e59992 MG |
78 | my @extra; |
79 | push @extra, (brand => {'@type' => 'Brand', name => $data{brand}}) if $data{brand}; | |
80 | push @extra, (model => $data{model}) if $data{model}; | |
8bb7ab90 MG |
81 | +{ |
82 | '@context' => 'http://schema.org/', | |
83 | '@type' => 'Product', | |
84 | name => $data{title}, | |
85 | image => "/static/fullpics/$data{product}-1.jpg", | |
506d6d02 | 86 | description => $data{subtitle}, |
a9e59992 | 87 | @extra, |
8bb7ab90 MG |
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 | ||
fc536c37 | 98 | our %highlight; |
6e33dd68 MG |
99 | sub form_table_row { |
100 | my ($data, $tr) = @_; | |
fc536c37 | 101 | $tr->attr(class => 'highlight') if $highlight{$data->{product}}; |
6e33dd68 MG |
102 | $tr->fclass($_)->replace_content($data->{$_}) for qw/title subtitle stock/; |
103 | $tr->fclass('price')->replace_content(stringify_money $data->{price}); | |
8bbff1bc | 104 | $tr->fclass('freepost')->detach unless $data->{freepost}; |
6e33dd68 | 105 | $tr->fclass('title')->attr('data-product', $data->{product}); |
1576fc41 MG |
106 | $tr->fclass('title')->attr('href', '/details/'.$data->{product}.'/'.make_slug $data->{title}); |
107 | # $tr->fclass('title')->attr('data-summary', $data->{summary}); | |
6e33dd68 MG |
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) = @_; | |
1576fc41 | 114 | $db{$$} //= DBIx::Simple->connect($ENV{OOF_DSN} // 'dbi:Pg:'); |
fc536c37 | 115 | my $req = Plack::Request->new($env); |
6e33dd68 | 116 | |
fc536c37 | 117 | local %highlight = map { $_ => 1 } $req->param('highlight'); |
c7ed4de4 | 118 | my $data = $db{$$}->select(products => '*', {stock => {'>', 0}}, 'product')->hashes; |
6e33dd68 MG |
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/; | |
8bbff1bc | 128 | $tr->fclass('freepost')->detach unless $data->{freepost}; |
6e33dd68 MG |
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) = @_; | |
1576fc41 | 135 | $db{$$} //= DBIx::Simple->connect($ENV{OOF_DSN} // 'dbi:Pg:'); |
6e33dd68 MG |
136 | my $tree = $continue->clone; |
137 | my $req = Plack::Request->new($env); | |
138 | my $params = $req->body_parameters; | |
139 | ||
8bbff1bc | 140 | my ($quant, $quant_freepost, $total, @data, @notes) = (0) x 3; |
6e33dd68 MG |
141 | for (sort keys %$params) { |
142 | next unless /^quant/; | |
143 | next unless $params->{$_}; | |
1576fc41 | 144 | my $data = $db{$$}->select(products => '*', {product => substr $_, 5})->hash; |
6e33dd68 MG |
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}; | |
8bbff1bc | 156 | $quant_freepost += $data->{quantity} if $data->{freepost}; |
6e33dd68 MG |
157 | $total += $data->{subtotal}; |
158 | push @data, $data | |
159 | } | |
160 | ||
1576fc41 MG |
161 | return [500, ['Content-type' => 'text/plain'], ['Error: no items in order.']] unless $quant; |
162 | ||
6e33dd68 MG |
163 | $tree->fid('subtotal')->replace_content(stringify_money $total); |
164 | my $dvalue; | |
165 | if ($params->{discount}) { | |
1576fc41 | 166 | my $discount = $db{$$}->select(discounts => '*', {discount => $params->{discount}})->hash; |
6e33dd68 MG |
167 | if (!defined $discount) { |
168 | push @notes, 'Discount code incorrect. No discount applied.' | |
1576fc41 | 169 | } elsif ($db{$$}->select(orders => 'COUNT(*)', {discount => $params->{discount}})->list) { |
6e33dd68 MG |
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; | |
c51bcbe6 | 182 | my $postage = $postage_base + $postage_per_item * ($quant - $quant_freepost); |
8bbff1bc | 183 | $postage = 0 if $quant == $quant_freepost; |
6e33dd68 MG |
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) = @_; | |
1576fc41 | 199 | $db{$$} //= DBIx::Simple->connect($ENV{OOF_DSN} // 'dbi:Pg:'); |
6e33dd68 MG |
200 | my $tree = $order->clone; |
201 | my $req = Plack::Request->new($env); | |
1576fc41 MG |
202 | my ($id) = $env->{PATH_INFO} =~ m,^/([0-9A-F]+),; |
203 | if ($id) { | |
85e0d9a2 MG |
204 | my $total = $db{$$}->select(orders => 'total', {id => $id})->list or |
205 | return [500, ['Content-type', 'text/plain'], ['Order not found']]; | |
1576fc41 MG |
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 | } | |
defe4693 | 223 | $db{$$}->insert(orders => {id => $id, date => time, %parms}); |
1576fc41 | 224 | $db{$$}->commit; |
8526cf2b MG |
225 | sendmail (Email::Simple->create( |
226 | header => [ | |
227 | From => $ENV{OOF_EMAIL_FROM}, | |
228 | To => $ENV{OOF_EMAIL_TO}, | |
dbb58773 | 229 | Subject => "Order $id placed for ".stringify_money($parms{total}), |
8526cf2b MG |
230 | ], |
231 | body => 'A new order was placed.', | |
232 | )) if $ENV{OOF_EMAIL_TO}; | |
1576fc41 MG |
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"], []] | |
6e33dd68 | 239 | } |
1576fc41 MG |
240 | } |
241 | ||
5eeddbd0 MG |
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 | ||
1576fc41 MG |
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+),; | |
8bb7ab90 | 274 | my %data = %{$db{$$}->select(products => '*', {product => $id})->hash}; |
1576fc41 | 275 | my @pics = <static/fullpics/$id-*>; |
8bb7ab90 MG |
276 | my $slug = make_slug $data{title}; |
277 | $tree->find('title')->replace_content("$data{title} | ledparts4you"); | |
278 | $tree->find('h2')->replace_content($data{title}); | |
889f48be MG |
279 | my $summary_literal = HTML::Element::Library::super_literal $data{summary}; |
280 | $tree->fid('summary')->replace_content($summary_literal); | |
1576fc41 | 281 | $tree->look_down(rel => 'canonical')->attr(href => "/details/$id/$slug"); |
b66954a0 | 282 | $tree->fid('pictures')->find('li')->iter3(\@pics, \&details_list_element); |
8bb7ab90 | 283 | $tree->fid('jsonld')->replace_content(encode_json product_to_schemaorg '', %data); |
6e33dd68 | 284 | |
2f1de030 MG |
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 | ||
fc536c37 MG |
296 | for my $ahref ($tree->find('a')) { |
297 | $ahref->attr(href => "/form?highlight=$id") if $ahref->attr('href') eq '/'; | |
298 | } | |
299 | ||
6e33dd68 MG |
300 | [200, ['Content-type' => 'text/html; charset=utf-8'], [$tree->as_HTML]] |
301 | } | |
302 | ||
1576fc41 MG |
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 | ||
69d4d80d MG |
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 | ||
18be372d MG |
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 | ||
69d4d80d MG |
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); | |
18be372d MG |
348 | my $csv = join "\n", map { make_hermes_csv $_ } @orders; |
349 | $tree->fid('hermes_csv')->replace_content($csv_header . $csv); | |
69d4d80d MG |
350 | [200, ['Content-type' => 'text/html; charset=utf-8'], [$tree->as_HTML]]; |
351 | } | |
352 | ||
6e33dd68 | 353 | sub app { |
1576fc41 | 354 | my $footer = read_file 'tmpl/footer.html'; |
6e33dd68 | 355 | builder { |
1576fc41 MG |
356 | enable sub { |
357 | my $app = shift; | |
358 | sub { | |
359 | my $res = $app->(@_); | |
0c3c4e70 | 360 | $res->[2][0] =~ s,</body>,$footer</body>, if $res->[0] == 200; |
1576fc41 MG |
361 | $res; |
362 | } | |
363 | }; | |
80e9b2b1 MG |
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 | }; | |
6e33dd68 MG |
376 | mount '/' => sub { [301, [Location => '/form'], []] }; |
377 | mount '/form' => \&form_app; | |
378 | mount '/continue' => \&continue_app; | |
379 | mount '/order' => \&order_app; | |
1576fc41 MG |
380 | mount '/details' => \&details_app; |
381 | mount '/pay' => \&pay_app; | |
69d4d80d | 382 | mount '/display' => \&display_app; |
6e33dd68 MG |
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. | |
39be4169 MG |
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. | |
6e33dd68 MG |
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 |