Apache/iNcom/CartManager.pm untested

filter: Statementstmt 0.0% 0 / 149 Branchbran 0.0% 0 / 30 Conditioncond 0.0% 0 / 21 MC/DCmcdc 0.0% 0 / 12 Subroutinesub 0.0% 0 / 21 Podpod 0.0% 0 / 19 totaltotal 0.0% 0 / 252 CC 16 SCAR 22.2
CC
16
Cov
0%
load_delegates
20.0
order
20.0
taxes
12.0
CRAP 9.2
1 #
2 # CartManager.pm - Object that manages user shopping cart
3 #
4 # This file is part of Apache::iNcom.
5 #
6 # Author: Francis J. Lacoste <francis.lacoste@iNsu.COM>
7 #
8 # Copyright (C) 1999 Francis J. Lacoste, iNsu Innovations
9 #
10 # This program is free software; you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 2 of the License, or
13 # (at your option) any later version.
14 #
15 # This program is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # GNU General Public License for more details.
19 #
20 # You should have received a copy of the GNU General Public License
21 # along with this program; if not, write to the Free Software
22 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 #
24 package Apache::iNcom::CartManager;
25  
26 use strict;
27  
28  
29 use vars qw( $VERSION );
30  
31 BEGIN {
32 ($VERSION) = '$Revision: 1.7 $' =~ /Revision: ([\d.]+)/;
33 }
34  
35 =pod
36  
37 =head1 NAME
38  
39 Apache::iNcom::CartManager - Object responsible for managing the user
40 shopping cart.
41  
42 =head1 SYNOPSIS
43  
44 $Cart->order( \%item );
45 my $items = $Cart->items;
46 $Cart->empty;
47  
48 =head1 DESCRIPTION
49  
50 This is the part of the Apache::iNcom framework that is responsible for
51 managing the user shopping cart. It keep tracks of the ordered items and
52 is also responsible for the pricing of the order. It this is module that
53 computes taxes, discount, price, shipping, etc.
54  
55 =head1 DESIGN RATIONALE
56  
57 Well not completly since all these operations are delegated to user
58 implemented functions implemented in a pricing profile. The idea
59 behind it is to make policy external to the framework. One thing that
60 varies considerably between different applications is the pricing,
61 discount, taxes, etc. So this is left to the implementation of the
62 application programmer.
63  
64 =head1 PRICING PROFILE
65  
66 The pricing profile is a file which is C{eval}-ed at runtime. (It is also
67 reloaded whenever it changes on disk. It should return an hash reference
68 which may contains the following key :
69  
70 =over
71  
72 =item item_price
73  
74 The function should return the price of the item. The function is passed
75 only one parameter : the item which we should compute the price.
76  
77 Ex: item_price => sub {
78 my $item = shift;
79 my $data = $DB->template_get( "product", $item->{code} );
80 return $data->{price};
81 }
82  
83 =item item_discount
84  
85 The function should return the discounts that apply for that
86 particular item. It can return zero or more discounts. It returning
87 more that one discount return a an array reference. Discount are
88 substracted from the item price so don't return a percentage.
89  
90 Ex: item_discount => sub {
91 my $item = shift;
92  
93 # Discount are relative to item and quantity
94 my $data = $DB->template_get( "discount", $item->{code},
95 $item->{quantity} );
96 return unless $data; # No discount
97  
98 # Discount is proportional to the price
99 return $item->{price} * $data->{discount};
100 }
101  
102 The subtotal of the cart is equal to the sum of
103  
104 ($item->{price} - $item->{discount}) * $item->{quantity}
105  
106 =item shipping
107  
108 This function determines the shipping charges that will be added to
109 the subtotal. The function receives as arguments the subtotal of the
110 cart and an array ref to the cart's items. It should return zero or
111 more shipping charges that will be added to the subtotal. If returning
112 more that one charges, return an array reference.
113  
114 Ex: shipping => sub {
115 # Flat fee based shipping charges
116 if ( $Session{shipping} eq "ONE_NIGHT" ) {
117 return 45;
118 } else {
119 return 15;
120 }
121 }
122  
123 =item discount
124  
125 That function determines discount that will be substracted from the
126 subtotal. Function is called with 3 arguments, the subtotal of the
127 cart, the shipping charges and an array reference to the cart's items.
128 Again the function may elect to return zero or more discounts and should
129 return an array reference if returning more that one discounts.
130  
131 Ex: discount => sub {
132 my $subtotal = shift;
133 my $user = $Request->user;
134 return unless $user->{discount};
135  
136 return $subtotal * $user->{discount};
137 }
138  
139 =item taxes
140  
141 That functions determines the taxes charges that will be added to the
142 order. It should return zero or more taxes. If the functions returns
143 more that one taxes, it should return an array reference. The
144 functions receives 4 arguments, the cart's subtotal, the shipping
145 charges, the discount and the cart's items as an array reference.
146  
147 Ex: taxes => sub {
148 my ( $sub, $ship, $disc ) = @_;
149  
150 # We only charges taxes to Quebec's resident. All our
151 # items are taxable and is shipping.
152 if ( ${$Request->user}->{province} eq "QC" ) {
153 my $taxable = $sub + $ship - $disc;
154 my $gst = $taxable * 0.07
155 my $gsp = ($taxable + $gst) * 0.075
156  
157 return [ $gst, $gsp ];
158 } else {
159 return undef;
160 }
161 }
162  
163 =back
164  
165 If one of these functions is left undefined. The framework will create
166 one on the fly which will return 0. (No taxes, no discount, no
167 shipping charges, item is free, etc).
168  
169 All those functions are defined and execute in the namespace of the
170 pages which will use the $Cart object. This means that those functions
171 have access to the standard Apache::iNcom globals ($Request, %Session,
172 $Localizer, $Locale, etc ). DONT ABUSE IT. Also, don't call any methods
173 on the $Cart object or you'll die of infinite recursion.
174  
175 =head1 WHAT IS AN ITEM
176  
177 An item is simply an hash with some reserved key names. All other keys
178 are ignored by the CartManager. Each item with the same (non reserved)
179 key values is assumed to be identic in terms of price, discount, etc.
180  
181 This design was chosen to handle the infinite variety of item
182 attributes (color, size, variant, ...). The framework doesn't need
183 knowledge of those, only the application specific part. (The pricing
184 functions.)
185  
186 These are reserved names and can't be used as item attributes :
187 C<quantity>, C<price>, C<discount>, C<subtotal>
188  
189 =head1 INITIALIZATION
190  
191 An object is automatically initialized on each request by the
192 Apache::iNcom framework. It is accessible through the $Cart global
193 variable in Apache::iNcom pages.
194  
195 =cut
196  
197 sub new {
198 my $proto = shift;
199 my $class = ref $proto || $proto;
200  
201 my ( $cart, $package, $profile_file ) = @_;
202  
203 $cart ||= {};
204  
205 bless { profile_file => $profile_file,
206 cart => $cart,
207 package => $package,
208 }, $class;
209 }
210  
211 sub cart {
212 my $self = shift;
213  
214 # Return the cart data structure.
215 $self->{cart};
216 }
217  
218 my %DEFAULT_DELEGATES = (
219 item_price => sub { 0 },
220 item_discount => sub { 0 },
221 discount => sub { 0 },
222 shipping => sub { 0 },
223 taxes => sub { 0 },
224 );
225  
226 sub load_delegates {
227 my $self = shift;
228  
229 # Define delegates in the namespace of the page
230 my $delegates_code = "package " . $self->{package} . ";\n";
231  
232 # Read in the delegates code
233 open ( DELEGATES, $self->{profile_file} )
234 or die "Error loading pricing delegates: $!\n";
235 my $line;
236 while ( defined ( $line = <DELEGATES> ) ) {
237 $delegates_code .= $line;
238 }
239 close DELEGATES;
240  
241 my $delegates = eval $delegates_code;
242 die "Error evaluating delegates: $@" if $@;
243 die "Delegates didn't evaluate to an hash ref\n"
244 unless ref $delegates eq "HASH";
245  
246 # Make sure that defaults functions are defined for
247 # all of them
248 for my $name (keys %DEFAULT_DELEGATES ) {
249 my $f = $delegates->{$name} ||= $DEFAULT_DELEGATES{$name};
250 die "Delegate $name is not a function ref\n"
251 unless ref $f eq "CODE";
252 }
253  
254 $delegates;
255 }
256  
257 my %RESERVED_ITEM_NAMES = map { $_ => 1 }
258 qw( quantity price discount subtotal );
259  
260 =pod
261  
262 =head1 METHODS
263  
264 =head2 order ( \%item, ... )
265  
266 This method will add all the specified items (hash reference) to the
267 Cart. The quantity ordered should be specified in the C<quantity>
268 attribute. (If unspecified, it is assumed to be one). If an identical
269 item is already in the cart, the quantity will be added.
270  
271 Use a negative quantity to remove from the quantity ordered. If the
272 new quantity is lower or equal to zero it will be removed.
273  
274 Use a quantity of 0 to remove an item.
275  
276 =cut
277  
278 sub order {
279 my $self = shift;
280  
281 # Add items to shopping cart
282 for my $item (@_) {
283 my @attr = sort grep { not $RESERVED_ITEM_NAMES{$_} } keys %$item;
284  
285 my $key = join "\0", map { $item->{$_} } @attr;
286  
287 if ( defined $item->{quantity} && $item->{quantity} == 0 ) {
288 delete $self->{cart}{items}{$key}
289 } else {
290 my $q = $item->{quantity} || 1;
291 my $cart_item = $self->{cart}{items}{$key};
292 unless ( $cart_item ) {
293 # Item is not already in cart
294 $self->{cart}{items}{$key} = $cart_item = {};
295 # Copy key attributes
296 for my $attr ( @attr ) {
297 $cart_item->{$attr} = $item->{$attr};
298 }
299 $cart_item->{quantity} = 0;
300 }
301 $cart_item->{quantity} += $q;
302  
303 # Toss item if deleted
304 delete $self->{cart}{items}{$key}
305 if ($cart_item->{quantity} <= 0);
306 }
307  
308 # Mark cart as needing recomputation
309 $self->{cart}{dirty} = 1;
310 }
311 }
312  
313 =pod
314  
315 =head2 empty
316  
317 Removes all items from the cart.
318  
319 =cut
320  
321 sub empty {
322 my $self = shift;
323  
324 delete $self->{cart}{items};
325 $self->{cart}{items} = {};
326  
327 # Reset cart status
328 $self->{cart}{subtotal} = 0;
329 $self->{cart}{discount} = 0;
330 $self->{cart}{dirty} = 0;
331 $self->{cart}{total} = 0;
332 $self->{cart}{taxes} = 0;
333 $self->{cart}{shipping} = 0;
334 }
335  
336 =pod
337  
338 =head2 is_empty
339  
340 Return true if no items are in the cart.
341  
342 =cut
343  
344 sub is_empty {
345 my $self = shift;
346  
347 return keys %{$self->{cart}{items}} == 0;
348 }
349  
350 =pod
351  
352 =head2 items
353  
354 Return all the ordered items as an array. Each item have the following
355 attribute set :
356  
357 =over
358  
359 =item quantity
360  
361 The quantity of the item ordered.
362  
363 =item price
364  
365 The price of that item.
366  
367 =item discount
368  
369 The discounts applied to this item.
370  
371 =item subtotal
372  
373 That item subtotal.
374  
375 =back
376  
377 =cut
378  
379 sub items {
380 my $self = shift;
381  
382 $self->compute;
383  
384 return values %{$self->{cart}{items}};
385 }
386  
387 =pod
388  
389 =head2 subtotal
390  
391 Returns the cart subtotal. (This is before global discount, shipping
392 charges and taxes.)
393  
394 =cut
395  
396 sub subtotal {
397 my $self = shift;
398  
399 $self->compute;
400 return $self->{cart}{subtotal};
401 }
402  
403 =pod
404  
405 =head2 taxes
406  
407 Returns the taxes that will be added to the order.
408  
409 =cut
410  
411 sub taxes {
412 my $self = shift;
413  
414 $self->compute;
415 my $taxes = $self->{cart}{taxes};
416  
417 return wantarray ? @$taxes : $taxes if ref $taxes;
418 return $taxes;
419 }
420  
421 =pod
422  
423 =head2 total
424  
425 Returns the order total. (subtotal + shipping charges - discounts + taxes ).
426  
427 =cut
428  
429 sub total {
430 my $self = shift;
431  
432 $self->compute;
433 return $self->{cart}{total};
434 }
435  
436 =pod
437  
438 =head2 discount
439  
440 Returns the overall discount that applied to this order.
441  
442 =cut
443  
444 sub discount {
445 my $self = shift;
446  
447 $self->compute;
448 my $discount = $self->{cart}{discount};
449  
450 return wantarray ? @$discount : $discount if ref $discount;
451 return $discount;
452 }
453  
454 =pod
455  
456 =head2 shipping
457  
458 Returns the shipping charges for this order.
459  
460 =cut
461  
462 sub shipping {
463 my $self = shift;
464  
465 $self->compute;
466 my $shipping = $self->{cart}{shipping};
467  
468 return wantarray ? @$shipping : $shipping if ref $shipping;
469 return $shipping;
470 }
471  
472 =pod
473  
474 =head2 item_price ( \%item )
475  
476 Returns the price of the item specified. If no quantity is specified,
477 a quantity of 1 is assumed. This method doesn't modify the cart.
478  
479 =cut
480  
481 sub item_price {
482 my ($self, $item) = @_;
483  
484 # Load the customized function to calculate price
485 my $delegates = $self->load_delegates;
486  
487 my $item_copy = { %$item };
488 $item_copy->{quantity} ||= 1;
489  
490 return $delegates->{item_price}->( $item_copy );
491 }
492  
493 =pod
494  
495 =head2 item_discount ( \%item )
496  
497 Returns the discounts associated with the specified item. It no
498 quantity is specified, a quantity of 1 is assumed. This method doesn't
499 modify the cart.
500  
501 =cut
502  
503 sub item_discount {
504 my ($self, $item) = @_;
505  
506 # Load the customized function to calculate price
507 my $delegates = $self->load_delegates;
508  
509 my $item_copy = { %$item };
510 $item_copy->{quantity} ||= 1;
511 $item_copy->{price} = $delegates->{item_price}->( $item_copy );
512  
513 return $delegates->{item_discount}->( $item_copy );
514 }
515  
516 =pod
517  
518 =head2 item_pricing ( \%item )
519  
520 Returns the item as it would be added to the cart. C<quantity>,
521 C<price>, C<discount> and C<subtotal> will be set in the returned
522 item. This method doesn't modify the cart.
523  
524 =cut
525  
526 sub item_pricing {
527 my ($self, $item) = @_;
528  
529 # Load the customized function to calculate price
530 my $delegates = $self->load_delegates;
531  
532 # Copy the item infos
533 my $item_pricing = { %$item };
534  
535 $item_pricing->{quantity} ||= 1;
536  
537 my $item_price = $delegates->{item_price}->( $item_pricing );
538 my $item_discount = $delegates->{item_discount}->( $item_pricing );
539  
540 $item_pricing->{price} = $item_price;
541 $item_pricing->{discount} = $item_discount;
542 $item_price = apply_discount( $item_price, $item_discount);
543 $item_pricing->{subtotal} = $item_price * $item->{quantity};
544  
545 return $item_pricing;
546 }
547  
548 sub compute {
549 my $self = shift;
550  
551 return unless $self->{cart}{dirty};
552  
553 # Load the customized function to calculate price
554 my $delegates = $self->load_delegates;
555  
556 my $subtotal = 0;
557 my $items = [values %{$self->{cart}{items} }];
558 for my $item ( @$items ) {
559 my $item_price = $delegates->{item_price}->( $item );
560 my $item_discount = $delegates->{item_discount}->( $item );
561  
562 $item->{price} = $item_price;
563 $item->{discount} = $item_discount;
564 $item_price = apply_discount( $item_price, $item_discount);
565 $item->{subtotal} = $item_price * $item->{quantity};
566 $subtotal += $item->{subtotal};
567 }
568  
569 $self->{cart}{subtotal} = $subtotal;
570 my $shipping = $self->{cart}{shipping} =
571 $delegates->{shipping}->( $subtotal, $items );
572 my $discount = $self->{cart}{discount} =
573 $delegates->{discount}->( $subtotal, $shipping, $items );
574 my $taxes = $self->{cart}{taxes} =
575 $delegates->{taxes}->( $subtotal, $shipping, $discount, $items);
576  
577 my $total = $subtotal;
578  
579 # Add order discounts
580 $total = apply_discount( $total, $discount );
581  
582 # Add shippings
583 $total = apply_charges( $total, $shipping );
584  
585 # Add taxes
586 $total = apply_charges( $total, $taxes );
587  
588 $self->{cart}{total} = $total;
589  
590 $self->{cart}{dirty} = 0;
591 }
592  
593 sub apply_charges {
594 my ( $amount, $charges ) = @_;
595  
596 if ( ref $charges ) {
597 foreach my $c ( @$charges ) {
598 $amount += $c;
599 }
600 } else {
601 $amount += $charges;
602 }
603  
604 $amount;
605 }
606  
607 sub apply_discount {
608 my ($amount, $discount) = @_;
609  
610 if ( ref $discount ) {
611 foreach my $d ( @$discount ) {
612 $amount -= $discount;
613 }
614 } else {
615 $amount -= $discount;
616 }
617  
618 $amount;
619 }
620  
621 1;
622  
623 __END__