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