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