Schema/Result/Product.pm

filter: Statementstmt 90.6% 263 / 290 Branchbran 79.6% 121 / 152 Conditioncond 64.1% 25 / 39 MC/DCmcdc 50.0% 12 / 24 Subroutinesub 90.0% 27 / 30 Podpod 100% 22 / 22 totaltotal 84.3% 470 / 557 CC 96 SCAR 30.7
CC
96
Cov
85%
tier_pricing
156.0
attribute_iterator
12.0
find_variant
12.0
CRAP 21.6
↑ Summary Test/Role/PostgreSQL.pm »
1 2 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
2  
3 package Interchange6::Schema::Result::Product;
4  
5 =head1 NAME
6  
7 Interchange6::Schema::Result::Product
8  
9 =cut
10  
11 2 ▶use base 'Interchange6::Schema::Base::Attribute';
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 2 ▶use DateTime;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 2 ▶use Encode;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 2 ▶use Try::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17 2 use Interchange6::Schema::Candy -components =>
18 [qw(Helper::Row::OnColumnChange Helper::Row::SelfResultSet
19 2 ▶ InflateColumn::DateTime TimeStamp)];
Subroutine BEGIN: called CC=1 SCAR=0.0
20  
21 =head1 DESCRIPTION
22  
23 The products table contains three product types parent, child and single.
24  
25 =over
26  
27 =item *
28  
29 B<Parent Product> A parent product is a container product in which variations of parent product or "child products" are linked.
30  
31 =item *
32  
33 B<Child Product> A child product for example "Acme Pro 10lb Dumbbell" would include the canonical_sku of the parent item whose description might be something like "Acme Pro Dumbbell". In general a child product would contain attributes while a parent product would not.
34  
35 =item *
36  
37 B<Single Product> A single product does not have child products and will become a parent product if a child product exists.
38  
39 =back
40  
41 =cut
42  
43 =head1 ACCESSORS
44  
45 =head2 sku
46  
47 Primary key.
48  
49 =cut
50  
51 2 primary_column sku => {
52 data_type => "varchar",
53 size => 64
54 };
55  
56 =head2 name
57  
58 The name used to identify the product.
59  
60 =cut
61  
62 2 column name => {
63 data_type => "varchar",
64 size => 255
65 };
66  
67 =head2 short_description
68  
69 A brief summary of the product.
70  
71 =cut
72  
73 2 column short_description => {
74 data_type => "varchar",
75 default_value => "",
76 size => 500
77 };
78  
79 =head2 description
80  
81 Full product description.
82  
83 =cut
84  
85 2 column description => {
86 data_type => "text"
87 };
88  
89 =head2 price
90  
91 Numeric value representing product cost. Default is 0.0.
92  
93 When C<price> is updated and product has related
94 L<Interchange6::Schema::Result::PriceModifier/discount> then also update
95 the related L<Interchange6::Schema::Result::PriceModifier/price>.
96 This is done using the method C<update_price_modifiers>.
97  
98 =cut
99  
100 2 column price => {
101 data_type => "numeric",
102 default_value => "0.0",
103 size => [ 10, 2 ],
104 keep_storage_value => 1,
105 };
106  
107 2 before_column_change price => {
108 method => 'update_price_modifiers',
109 txn_wrap => 1,
110 };
111  
112 =head2 uri
113  
114 Unique product uri. Example "acme-pro-dumbbells". Is nullable.
115  
116 =cut
117  
118 2 unique_column uri => {
119 data_type => "varchar",
120 is_nullable => 1,
121 size => 255
122 };
123  
124 =head2 weight
125  
126 Numeric weight of the product.
127  
128 Is nullable.
129  
130 =cut
131  
132 2 column weight => {
133 data_type => "numeric",
134 size => [ 10, 2 ],
135 is_nullable => 1,
136 };
137  
138 =head2 priority
139  
140 Display order priority.
141  
142 =cut
143  
144 2 column priority => {
145 data_type => "integer",
146 default_value => 0
147 };
148  
149 =head2 gtin
150  
151 Unique EAN or UPC type data. Is nullable.
152  
153 =cut
154  
155 2 unique_column gtin => {
156 data_type => "varchar",
157 is_nullable => 1,
158 size => 32
159 };
160  
161 =head2 canonical_sku
162  
163 The SKU of the main product if this product is a variant of a main product. Is nullable.
164  
165 =cut
166  
167 2 column canonical_sku => {
168 data_type => "varchar",
169 is_nullable => 1,
170 size => 64
171 };
172  
173 =head2 active
174  
175 Is this product active? Default is yes.
176  
177 =cut
178  
179 2 column active => {
180 data_type => "boolean",
181 default_value => 1
182 };
183  
184 =head2 inventory_exempt
185  
186 Is this producr exempt from inventory? Default is no.
187  
188 =cut
189  
190 2 column inventory_exempt => {
191 data_type => "boolean",
192 default_value => 0
193 };
194  
195 =head2 created
196  
197 Date and time when this record was created returned as L<DateTime> object.
198 Value is auto-set on insert.
199  
200 =cut
201  
202 2 column created => {
203 data_type => "datetime",
204 set_on_create => 1
205 };
206  
207 =head2 last_modified
208  
209 Date and time when this record was last modified returned as L<DateTime> object.
210 Value is auto-set on insert and update.
211  
212 =cut
213  
214 2 column last_modified => {
215 data_type => "datetime",
216 set_on_create => 1,
217 set_on_update => 1
218 };
219  
220 =head1 RELATIONS
221  
222 =head2 canonical
223  
224 Type: belongs_to
225  
226 Related object: L<Interchange6::Schema::Result::Product>
227  
228 =cut
229  
230 2 belongs_to
231 canonical => "Interchange6::Schema::Result::Product",
232 { 'foreign.sku' => 'self.canonical_sku' },
233 { join_type => 'left' };
234  
235 =head2 variants
236  
237 Type: has_many
238  
239 Related object: L<Interchange6::Schema::Result::Product>
240  
241 =cut
242  
243 2 has_many
244 variants => "Interchange6::Schema::Result::Product",
245 { "foreign.canonical_sku" => "self.sku" },
246 { cascade_copy => 0, cascade_delete => 0 };
247  
248 =head2 cart_products
249  
250 Type: has_many
251  
252 Related object: L<Interchange6::Schema::Result::CartProduct>
253  
254 =cut
255  
256 2 has_many
257 cart_products => "Interchange6::Schema::Result::CartProduct",
258 "sku",
259 { cascade_copy => 0, cascade_delete => 0 };
260  
261 =head2 price_modifiers
262  
263 Type: has_many
264  
265 Related object: L<Interchange6::Schema::Result::PriceModifier>
266  
267 =cut
268  
269 2 has_many
270 price_modifiers => "Interchange6::Schema::Result::PriceModifier",
271 "sku",
272 { cascade_copy => 0, cascade_delete => 0 };
273  
274 =head2 inventory
275  
276 Type: might_have
277  
278 Related object: L<Interchange6::Schema::Result::Inventory>
279  
280 =cut
281  
282 2 might_have
283 inventory => "Interchange6::Schema::Result::Inventory",
284 "sku",
285 { cascade_copy => 0, cascade_delete => 0 };
286  
287 =head2 media_products
288  
289 Type: has_many
290  
291 Related object: L<Interchange6::Schema::Result::MediaProduct>
292  
293 =cut
294  
295 2 has_many
296 media_products => "Interchange6::Schema::Result::MediaProduct",
297 "sku",
298 { cascade_copy => 0, cascade_delete => 0 };
299  
300 =head2 merchandising_products
301  
302 Type: has_many
303  
304 Related object: L<Interchange6::Schema::Result::MerchandisingProduct>
305  
306 =cut
307  
308 2 has_many
309 merchandising_products =>
310 "Interchange6::Schema::Result::MerchandisingProduct",
311 "sku",
312 { cascade_copy => 0, cascade_delete => 0 };
313  
314 =head2 merchandising_product_related
315  
316 Type: has_many
317  
318 Related object: L<Interchange6::Schema::Result::MerchandisingProduct>
319  
320 =cut
321  
322 2 has_many
323 merchandising_product_related =>
324 "Interchange6::Schema::Result::MerchandisingProduct",
325 { "foreign.sku_related" => "self.sku" },
326 { cascade_copy => 0, cascade_delete => 0 };
327  
328 =head2 navigation_products
329  
330 Type: has_many
331  
332 Related object: L<Interchange6::Schema::Result::NavigationProduct>
333  
334 =cut
335  
336 2 has_many
337 navigation_products => "Interchange6::Schema::Result::NavigationProduct",
338 "sku",
339 { cascade_copy => 0, cascade_delete => 0 };
340  
341 =head2 navigation
342  
343 Type: many_to_many with navigation
344  
345 =cut
346  
347 2 many_to_many navigations => "navigation_products", "navigation";
348  
349 =head2 orderlines
350  
351 Type: has_many
352  
353 Related object: L<Interchange6::Schema::Result::Orderline>
354  
355 =cut
356  
357 2 has_many
358 orderlines => "Interchange6::Schema::Result::Orderline",
359 "sku",
360 { cascade_copy => 0, cascade_delete => 0 };
361  
362 =head2 product_attributes
363  
364 Type: has_many
365  
366 Related object: L<Interchange6::Schema::Result::ProductAttribute>
367  
368 =cut
369  
370 2 has_many
371 product_attributes => "Interchange6::Schema::Result::ProductAttribute",
372 "sku",
373 { cascade_copy => 0, cascade_delete => 0 };
374  
375 =head2 media
376  
377 Type: many_to_many with media
378  
379 =cut
380  
381 2 many_to_many media => "media_products", "media";
382  
383 =head2 _product_reviews
384  
385 Type: has_many
386  
387 Related object: L<Interchange6::Schema::Result::ProductReview>
388  
389 This is considered a private method. Please see public L</product_reviews> method.
390  
391 =cut
392  
393 2 has_many
394 _product_reviews => "Interchange6::Schema::Result::ProductReview",
395 "sku", { cascade_copy => 0 };
396  
397 =head2 _reviews
398  
399 Type: many_to_many
400  
401 This is considered a private method. Accessor to related Message results. Please see public L</reviews> and L</add_to_reviews> methods.
402  
403 =cut
404  
405 2 many_to_many _reviews => "_product_reviews", "message";
406  
407 =head1 METHODS
408  
409 Attribute methods are provided by the L<Interchange6::Schema::Base::Attribute> class.
410  
411 =head2 insert
412  
413 Override inherited method to call L</generate_uri> method in case L</name>
414 and L</sku> have been supplied as arguments but L</uri> has not.
415  
416 =cut
417  
418 sub insert {
419 566 ▶ my ( $self, @args ) = @_;
Subroutine insert: called CC=4 SCAR=14.3
Pod documented
420 566 ▶ if ( $self->name && $self->sku && !$self->uri ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->name and $self->sku and not $self->uri) 12 554 566
Condition50%3/6
$self->name and $self->sku and not $self->uri
!ll&&!rl&&r
055412
$self->name and $self->sku
!ll&&!rl&&r
00566
MC/DC33%1/3
$self->name and $self->sku and not $self->uri
$self->name $self->sku not $self->uri
Truth table50%2/4
A and B and not(C)
A= $self->nameB= $self->skuC= not $self->uri
ABCresult
0XX0
10X0
1100
1111
421 12 $self->generate_uri;
422 }
423 565 $self->next::method(@args);
424 565 return $self;
425 }
426  
427 =head2 update_price_modifiers
428  
429 Called when L</price> is updated.
430  
431 =cut
432  
433 sub update_price_modifiers {
434 1 ▶ my ( $self, $old_value, $new_value ) = @_;
Subroutine update_price_modifiers: called CC=2 SCAR=6.9
Pod documented
435  
436 1 my $price_modifiers =
437 $self->price_modifiers->search( { discount => { '!=' => undef } } );
438  
439 1 ▶ while ( my $result = $price_modifiers->next ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $result = $price_modifiers->next) 1 1 2
440 1 $result->update(
441 {
442 price => sprintf( "%.2f",
443 $new_value - ( $new_value * $result->discount / 100 ) )
444 }
445 );
446 }
447 }
448  
449 =head2 generate_uri($attrs)
450  
451 Called by L</new> if no uri is given as an argument.
452  
453 The following steps are taken:
454  
455 =over
456  
457 1. Join C<< $self->name >> and C<< $self->uri >> with C<-> and stash
458 in C<$uri> to allow manipulation via filters
459  
460 2. Remove leading and trailing spaces and replace remaining spaces and
461 C</> with C<->
462  
463 3. Search for all rows in L<Interchange6::Schema::Result::Setting> where
464 C<scope> is C<Product> and C<name> is <generate_uri_filter>
465  
466 4. For each row found eval C<< $row->value >>
467  
468 5. Finally set the value of column L</uri> to C<$uri>
469  
470 =back
471  
472 Filters stored in L<Interchange6::Schema::Result::Setting> are executed via
473 eval and have access to C<$uri> and also the product result held in
474 C<$self>
475  
476 Examples of filters stored in Setting might be:
477  
478 {
479 scope => 'Product',
480 name => 'generate_uri_filter',
481 value => '$uri =~ s/badstuff/goodstuff/gi',
482 },
483 {
484 scope => 'Product',
485 name => 'generate_uri_filter',
486 value => '$uri = lc($uri)',
487 },
488  
489 =cut
490  
491 sub generate_uri {
492 12 ▶ my $self = shift;
Subroutine generate_uri: called CC=3 SCAR=11.0
Pod documented
493  
494 12 my $uri = join("-", $self->name, $self->sku);
495  
496 # make sure we have clean utf8
497 try {
498 12 ▶ $uri = Encode::decode( 'UTF-8', $uri, Encode::FB_CROAK )
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($uri) 8 4 12
499 unless utf8::is_utf8($uri);
500 }
501 catch {
502 0 ▶ $self->throw_exception(
Subroutine __ANON__: not called CC=1 SCAR=6.9
503 "Product->generate_uri failed to decode UTF-8 text: $_" );
504 12 };
505  
506 12 $uri =~ s/^\s+//; # remove leading space
507 12 $uri =~ s/\s+$//; # remove trailing space
508 12 $uri =~ s{[\s/]+}{-}g; # change space and / to -
509  
510 12 my $filters = $self->result_source->schema->resultset('Setting')->search(
511 {
512 scope => 'Product',
513 name => 'generate_uri_filter',
514 },
515 );
516  
517 12 ▶ while ( my $filter = $filters->next ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $filter = $filters->next) 3 11 14
518 3 eval $filter->value;
519 3 ▶ $self->throw_exception("Product->generate_uri filter croaked: $@")
Branch: 1 branch
BranchTrueFalseTotal
if $@ 1 2 3
520 if $@;
521 }
522  
523 11 $self->uri($uri);
524 }
525  
526 =head2 path
527  
528 Produces navigation path for this product.
529 Returns array reference in scalar context.
530  
531 Uses $type to select specific taxonomy from navigation if present.
532  
533 =cut
534  
535 sub path {
536 4 ▶ my ( $self, $type ) = @_;
Subroutine path: called CC=4 SCAR=13.9
Pod documented
537  
538 4 my $options = {};
539  
540 4 ▶ if ( defined $type ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $type) 1 3 4
541 1 $options = { "navigation.type" => $type };
542 }
543  
544 # search navigation entries for this product
545 4 my $navigation_product = $self->search_related(
546 'navigation_products',
547 $options,
548 {
549 prefetch => 'navigation',
550 order_by => {
551 -desc =>
552 [ 'me.priority', 'navigation.priority' ]
553 },
554 rows => 1,
555 }
556 )->single;
557  
558 4 my @path;
559  
560 4 ▶ if ( defined $navigation_product ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $navigation_product) 4 0 4
561 4 my $nav = $navigation_product->navigation;
562 4 my @anc = $nav->ancestors;
563  
564 4 @path = ( @anc, $nav );
565 }
566  
567 4 ▶ return wantarray ? @path : \@path;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 3 1 4
568 }
569  
570 =head2 tier_pricing
571  
572 Tier pricing can be calculated for a single role and also a combination of several roles.
573  
574 =over 4
575  
576 =item Arguments: array reference of L<Role names|Interchange6::Schema::Result::Role/name>
577  
578 =item Return Value: in scalar context an array reference ordered by quantity ascending of hash references of quantity and price, in list context returns an array instead of array reference
579  
580 =back
581  
582 The method always returns the best price for specific price points including
583 any PriceModifier rows where roles_id is undef.
584  
585 my $aref = $product->tier_pricing( 'trade' );
586  
587 # [
588 # { quantity => 1, price => 20 },
589 # { quantity => 10, price => 19 },
590 # { quantity => 100, price => 18 },
591 # ]
592  
593 =cut
594  
595 # TODO: SysPete is not happy with the initial version of this method.
596 # Patches always welcome.
597  
598 sub tier_pricing {
599 0 ▶ my ( $self, $args ) = @_;
Subroutine tier_pricing: not called CC=12 SCAR=50.5
Pod documented
600  
601 0 my $cond = { 'role.name' => undef };
602  
603 0 ▶ if ( $args ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args) 0 0 0
604 0 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
unless ref $args eq "ARRAY" 0 0 0
605 "Argument to tier_pricing must be an array reference")
606 unless ref($args) eq 'ARRAY';
607  
608 0 $cond = { 'role.name' => [ undef, { -in => $args } ] };
609 }
610  
611 0 my @result = $self->price_modifiers->search(
612 $cond,
613 {
614 join => 'role',
615 select => [ 'quantity', { min => 'price' } ],
616 as => [ 'quantity', 'price' ],
617 group_by => 'quantity',
618 order_by => { -asc => 'quantity' },
619 result_class => 'DBIx::Class::ResultClass::HashRefInflator',
620 },
621 )->all;
622  
623 0 ▶ if ( scalar @result && $result[0]->{quantity} < 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @result and $result[0]{"quantity"} < 1) 0 0 0
Condition0%0/3
scalar @result and $result[0]{"quantity"} < 1
!ll&&!rl&&r
000
MC/DC0%0/2
scalar @result and $result[0]{"quantity"} < 1
scalar @result $result[0]{"quantity"} < 1
Truth table0%0/3
A and B
A= scalar @resultB= $result[0]{"quantity"} < 1
ABresult
0X0
100
111
624  
625 # zero or minus qty should not be possible so we adjust to one if found
626  
627 0 $result[0]->{quantity} = 1;
628 }
629  
630 # maybe no qty 1 tier is defined so make sure we've got one
631  
632 0 ▶ if ( scalar @result && $result[0]->{quantity} == 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @result and $result[0]{'quantity'} == 1) { } 0 0 0
Condition0%0/3
scalar @result and $result[0]{"quantity"} == 1
!ll&&!rl&&r
000
MC/DC0%0/2
scalar @result and $result[0]{"quantity"} == 1
scalar @result $result[0]{"quantity"} == 1
Truth table0%0/3
A and B
A= scalar @resultB= $result[0]{"quantity"} == 1
ABresult
0X0
100
111
633 $result[0]->{price} = $self->price
634 0 ▶ if $self->price < $result[0]->{price};
Branch: 1 branch
BranchTrueFalseTotal
if $self->price < $result[0]{"price"} 0 0 0
635 }
636 else {
637 0 unshift @result, +{ quantity => 1, price => $self->price };
638 }
639  
640 # Remove quantities that are inappropriate due to price at higher
641 # quantity being higher (or same as) that a price at a lower quantity.
642 # Normally caused when there are different price breaks for different
643 # roles but we have been asked to combine multiple roles.
644  
645 0 my @return;
646 my $previous;
647 0 foreach my $i ( @result ) {
648 0 push @return, $i;
649 0 ▶ unless ( defined $previous ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $previous) 0 0 0
650 0 $previous = $i->{price};
651 0 next;
652 }
653 0 ▶ pop @return unless $i->{price} < $previous;
Branch: 1 branch
BranchTrueFalseTotal
unless $i->{"price"} < $previous 0 0 0
654 }
655  
656 0 ▶ return wantarray ? @return : \@return;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 0 0
657 }
658  
659 =head2 selling_price
660  
661 Arguments should be given as a hash reference with the following keys/values:
662  
663 =over 4
664  
665 =item * quantity => $quantity
666  
667 =item * roles => array reference of L<Role names|Interchange6::Schema::Result::Role/name>
668  
669 =back
670  
671 PriceModifier rows which have roles_is undefined are always included in the search in addition to any C<roles> that are provided as arguments. This enables promotional prices to be specified between fixed dates in L<Pricing price|Interchange6::Schema::Result::Pricing> to apply to all classes of user whether logged in or not.
672  
673 C<quantity> defaults to 1 if not supplied.
674  
675 Returns lowest price from L</price> and L<Pricing price|Interchange6::Schema::Result::Pricing/price>.
676  
677 Throws exception on bad arguments though unexpected keys in the hash reference will be silently discarded.
678  
679 If the query was constructed using
680 L<Interchange6::Schema::ResultSet::Product/with_lowest_selling_price> then
681 the cached value will be used rather than running a new query B<UNLESS>
682 arguments are supplied in which case a new query is performed.
683  
684 =cut
685  
686 sub selling_price {
687 113 ▶ my ( $self, $args ) = @_;
Subroutine selling_price: called CC=11 SCAR=24.2
Pod documented
688  
689 113 my $price = $self->price;
690  
691 113 ▶ if ( $self->has_column_loaded('selling_price') && !defined $args ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_column_loaded("selling_price") and not defined $args) 78 35 113
Condition66%2/3
$self->has_column_loaded("selling_price") and not defined $args
!ll&&!rl&&r
35078
MC/DC50%1/2
$self->has_column_loaded("selling_price") and not defined $args
$self->has_column_loaded("selling_price") not defined $args
Truth table66%2/3
A and not(B)
A= $self->has_column_loaded("selling_price")B= not defined $args
ABresult
0X0
100
111
692  
693 # initial query on Product already included selling_price so use it
694  
695 78 return $self->get_column('selling_price');
696 }
697  
698 35 ▶ if ($args) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args) { } 28 7 35
699 28 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
unless ref $args eq "HASH" 0 28 28
700 "Argument to selling_price must be a hash reference")
701 unless ref($args) eq 'HASH';
702 }
703 else {
704 7 $args = {};
705 }
706  
707 # quantity
708  
709 35 ▶ if ( defined $args->{quantity} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args->{'quantity'}) { } 28 7 35
710 $self->throw_exception(
711 sprintf( "Bad quantity: %s", $args->{quantity} ) )
712 28 ▶ unless $args->{quantity} =~ /^\d+$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $args->{"quantity"} =~ /^\d+$/ 0 28 28
713 }
714 else {
715 7 $args->{quantity} = 1;
716 }
717  
718 # roles
719  
720 35 my $role_cond = undef;
721  
722 35 ▶ if ( $args->{roles} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args->{"roles"}) 22 13 35
723 $self->throw_exception(
724 "Argument roles to selling price must be an array reference")
725 22 ▶ unless ref( $args->{roles} ) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $args->{"roles"} eq "ARRAY" 0 22 22
726  
727 22 $role_cond = [ undef, { -in => $args->{roles} } ];
728 }
729  
730 # now finally we can see if there is a better price for this customer
731  
732 35 my $today = $self->result_source->schema->format_datetime(DateTime->today);
733  
734 my $selling_price = $self->price_modifiers->search(
735 {
736 'role.name' => $role_cond,
737 quantity => { '<=', $args->{quantity} },
738 35 start_date => [ undef, { '<=', $today } ],
739 end_date => [ undef, { '>=', $today } ],
740 },
741 {
742 join => 'role',
743 },
744 )->get_column('price')->min;
745  
746 return
747 35 ▶ defined $selling_price
Branch: 1 branch
BranchTrueFalseTotal
defined $selling_price && $selling_price < $price ? : 30 5 35
Condition66%2/3
defined $selling_price and $selling_price < $price
!ll&&!rl&&r
5030
MC/DC50%1/2
defined $selling_price and $selling_price < $price
defined $selling_price $selling_price < $price
Truth table66%2/3
A and B
A= defined $selling_priceB= $selling_price < $price
ABresult
0X0
100
111
748 && $selling_price < $price ? $selling_price : $price;
749 }
750  
751 =head2 highest_price
752  
753 If this is a canonical product without variants or a variant product then
754 this method will return undef. If highest price is the same as L</selling_price>
755 then we again return undef.
756  
757 If the query was constructed using
758 L<Interchange6::Schema::ResultSet::Product/with_highest_price> then
759 the cached value will be used rather than running a new query.
760  
761 This method calls L</variant_count> and L</selling_price> so when constructing
762 a resultset query consider also chaining the associated ResultSet methods.
763  
764 =cut
765  
766 sub highest_price {
767 138 ▶ my $self = shift;
Subroutine highest_price: called CC=6 SCAR=17.9
Pod documented
768  
769 138 ▶ return undef unless $self->variant_count;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->variant_count 124 14 138
770  
771 14 my $highest_price;
772  
773 14 ▶ if ( $self->has_column_loaded('highest_price') ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_column_loaded('highest_price')) { } 7 7 14
774 7 $highest_price = $self->get_column('highest_price');
775 }
776 else {
777 7 $highest_price = $self->variants->get_column('price')->max;
778 }
779  
780 14 ▶ if ( $self->has_column_loaded('selling_price') ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_column_loaded("selling_price")) 7 7 14
781 7 ▶ return $highest_price if $highest_price > $self->selling_price;
Branch: 1 branch
BranchTrueFalseTotal
if $highest_price > $self->selling_price 6 1 7
782 1 return undef;
783 }
784  
785 7 ▶ if ( $highest_price >
Branch: 1 branch
BranchTrueFalseTotal
if ($highest_price > $self->self_rs->with_lowest_selling_price->single->selling_price) 6 1 7
786 $self->self_rs->with_lowest_selling_price->single->selling_price )
787 {
788 6 return $highest_price;
789 }
790  
791 1 return undef;
792 }
793  
794 =head2 find_variant \%input [\%match_info]
795  
796 Find product variant with the given attribute values
797 in $input.
798  
799 Returns variant in case of success.
800  
801 Returns undef in case of failure.
802  
803 You can pass an optional hash reference \%match_info
804 which is filled with attribute matches (only valid
805 in case of failure).
806  
807 =cut
808  
809 sub find_variant {
810 5 ▶ my ( $self, $input, $match_info ) = @_;
Subroutine find_variant: called CC=12 SCAR=24.8
Pod documented
811  
812 5 ▶ if ( my $canonical = $self->canonical ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $canonical = $self->canonical) 1 4 5
813 1 return $canonical->find_variant( $input, $match_info );
814 }
815  
816 4 my $gather_matches;
817  
818 4 ▶ if ( ref($match_info) eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $match_info eq "HASH") 2 2 4
819 2 $gather_matches = 1;
820 }
821  
822 # get all variants
823 4 my $all_variants = $self->search_related('variants');
824 4 my $variant;
825  
826 4 ▶ while ( $variant = $all_variants->next ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($variant = $all_variants->next) 18 2 20
827 18 my $sku;
828  
829 18 ▶ if ($gather_matches) {
Branch: 1 branch
BranchTrueFalseTotal
if ($gather_matches) 12 6 18
830 12 $sku = $variant->sku;
831 }
832  
833 18 my $variant_attributes = $variant->search_related(
834 'product_attributes',
835 {
836 'attribute.type' => 'variant',
837 },
838 {
839 join => 'attribute',
840 prefetch => 'attribute',
841 },
842 );
843  
844 18 my %match;
845  
846 18 ▶ while ( my $prod_att = $variant_attributes->next ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $prod_att = $variant_attributes->next) 33 14 47
847 33 my $name = $prod_att->attribute->name;
848  
849 33 my $pav_rs =
850 $prod_att->search_related( 'product_attribute_values', {},
851 { join => 'attribute_value', prefetch => 'attribute_value' } );
852  
853 33 ▶ if ( $pav_rs->count != 1
Branch: 1 branch
BranchTrueFalseTotal
if ($pav_rs->count != 1 or not defined $input->{$name} or $pav_rs->next->attribute_value->value ne $input->{$name}) 26 7 33
Condition83%5/6
$pav_rs->count != 1 or not defined $input->{$name} or $pav_rs->next->attribute_value->value ne $input->{$name}
l!l&&r!l&&!r
12147
$pav_rs->count != 1 or not defined $input->{$name}
l!l&&r!l&&!r
01221
MC/DC66%2/3
$pav_rs->count != 1 or not defined $input->{$name} or $pav_rs->next->attribute_value->value ne $input->{$name}
$pav_rs->count != 1 not defined $input->{$name} $pav_rs->next->attribute_value->value ne $input->{$name}
Truth table75%3/4
A or not(B) or C
A= $pav_rs->count != 1B= not defined $input->{$name}C= $pav_rs->next->attribute_value->value ne $input->{$name}
ABCresult
1XX1
01X1
0011
0000
854 || !defined $input->{$name}
855 || $pav_rs->next->attribute_value->value ne $input->{$name} )
856 {
857 26 ▶ if ($gather_matches) {
Branch: 1 branch
BranchTrueFalseTotal
if ($gather_matches) { } 22 4 26
858 22 $match_info->{$sku}->{$name} = 0;
859 22 next;
860 }
861 else {
862 4 last;
863 }
864 }
865  
866 7 ▶ if ($gather_matches) {
Branch: 1 branch
BranchTrueFalseTotal
if ($gather_matches) 2 5 7
867 2 $match_info->{$sku}->{$name} = 1;
868 }
869  
870 7 $match{$name} = 1;
871 }
872  
873 18 ▶ if ( scalar( keys %$input ) == scalar( keys %match ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %$input == scalar keys %match) 2 16 18
874 2 return $variant;
875 }
876 }
877  
878 2 return;
879 }
880  
881 =head2 attribute_iterator( %args )
882  
883 =over 4
884  
885 =item Arguments: C<< hashref => 1 >>
886  
887 =back
888  
889 Return a hashref of attributes keyed on attribute name instead of an arrayref.
890  
891 =over 4
892  
893 =item Arguments: C<< selected => $sku >>
894  
895 =back
896  
897 Set the 'selected' SKU. For a child product this is set automatically.
898  
899 =over 4
900  
901 =item Arguments: C<< cond => $cond >>
902  
903 =back
904  
905 Search condition to use. Default is:
906  
907 { 'attribute.type' => 'variant' }
908  
909 =over 4
910  
911 =item Arguments: C<< order_by => $order_by >>
912  
913 =back
914  
915 Ordering to use in query. Default is:
916  
917 [
918 { -desc => 'attribute.priority' },
919 { -asc => 'attribute.title' },
920 { -desc => 'attribute_value.priority' },
921 { -asc => 'attribute_value.title' },
922 ]
923  
924 Set the 'selected' SKU. For a child product this is set automatically.
925  
926 =over 4
927  
928 =item Returns: An arrayref of attributes complete with their respective attribute values.
929  
930 =back
931  
932 For canonical products, it shows all the attributes of the child products.
933  
934 For a child product, it shows all the attributes of the siblings.
935  
936 Example of returned arrayref:
937  
938 [
939 {
940 attribute_values => [
941 {
942 priority => 2,
943 selected => 0,
944 title => "Pink",
945 value => "pink"
946 },
947 {
948 priority => 1,
949 selected => 0,
950 title => "Yellow",
951 value => "yellow"
952 }
953 ],
954 name => "color",
955 priority => 2,
956 title => "Color"
957 },
958 {
959 attribute_values => [
960 {
961 priority => 2,
962 selected => 0,
963 title => "Small",
964 value => "small"
965 },
966 {
967 priority => 1,
968 selected => 0,
969 title => "Medium",
970 value => "medium"
971 },
972 ],
973 name => "size",
974 priority => 1,
975 title => "Size"
976 }
977 ]
978  
979 =cut
980  
981 sub attribute_iterator {
982 6 ▶ my ( $self, %args ) = @_;
Subroutine attribute_iterator: called CC=12 SCAR=24.9
Pod documented
983 6 my ($canonical);
984  
985 6 ▶ if ( $canonical = $self->canonical ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($canonical = $self->canonical) 1 5 6
986  
987 # get canonical object
988 1 $args{selected} = $self->sku;
989 1 return $canonical->attribute_iterator(%args);
990 }
991  
992 5 my $cond = {
993 'attribute.type' => 'variant',
994 };
995  
996 5 ▶ $cond = $args{cond} if defined $args{cond};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"cond"} 0 5 5
997  
998 5 my $order_by = [
999 { -desc => 'attribute.priority' },
1000 { -asc => 'attribute.title' },
1001 { -desc => 'attribute_value.priority' },
1002 { -asc => 'attribute_value.title' },
1003 ];
1004  
1005 5 ▶ $order_by = $args{order_by} if defined $args{order_by};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"order_by"} 0 5 5
1006  
1007 # search for variants
1008 5 my @prod_atts = $self->search_related('variants')->search_related(
1009 'product_attributes',
1010 $cond,
1011 {
1012 join => [
1013 'attribute', { product_attribute_values => 'attribute_value' },
1014 ],
1015 prefetch => [
1016 'attribute', { product_attribute_values => 'attribute_value' },
1017 ],
1018 order_by => $order_by,
1019 }
1020 )->hri->all;
1021  
1022 5 my %attributes;
1023 my @ordered_names;
1024 5 foreach my $prod_att ( @prod_atts ) {
1025 62 my $name = $prod_att->{attribute}->{name};
1026  
1027 62 ▶ unless ( exists $attributes{$name} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $attributes{$name}) 12 50 62
1028 12 push @ordered_names, $name;
1029 $attributes{$name} = {
1030 name => $name,
1031 title => $prod_att->{attribute}->{title},
1032 priority => $prod_att->{attribute}->{priority},
1033 12 value_map => {},
1034 attribute_values => [],
1035 };
1036 }
1037  
1038 62 my $att_record = $attributes{$name};
1039  
1040 62 foreach my $prod_att_val ( @{ $prod_att->{product_attribute_values} } )
1041 {
1042 my %attr_value = (
1043 value => $prod_att_val->{attribute_value}->{value},
1044 title => $prod_att_val->{attribute_value}->{title},
1045 priority => $prod_att_val->{attribute_value}->{priority},
1046 62 selected => 0,
1047 );
1048  
1049 62 ▶ if ( !exists $att_record->{value_map}->{ $attr_value{value} } ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $att_record->{"value_map"}{$attr_value{"value"}}) 27 35 62
1050 27 $att_record->{value_map}->{ $attr_value{value} } = \%attr_value;
1051 27 push @{$attributes{$name}->{attribute_values}}, \%attr_value;
1052 }
1053  
1054 # determined whether this is the current attribute
1055 62 ▶ if ( $args{selected} && $prod_att->{sku} eq $args{selected} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"selected"} and $prod_att->{"sku"} eq $args{"selected"}) 4 58 62
Condition100%3/3
$args{"selected"} and $prod_att->{"sku"} eq $args{"selected"}
!ll&&!rl&&r
38204
MC/DC100%2/2
$args{"selected"} and $prod_att->{"sku"} eq $args{"selected"}
$args{"selected"} $prod_att->{"sku"} eq $args{"selected"}
Truth table100%3/3
A and B
A= $args{"selected"}B= $prod_att->{"sku"} eq $args{"selected"}
ABresult
0X0
100
111
1056 $att_record->{value_map}->{ $attr_value{value} }->{selected} =
1057 4 1;
1058 }
1059 }
1060 }
1061  
1062 5 foreach my $key ( keys %attributes ) {
1063 12 delete $attributes{$key}->{value_map};
1064 }
1065  
1066 5 ▶ if ( $args{hashref} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"hashref"}) 4 1 5
1067 4 return \%attributes;
1068 }
1069  
1070 1 return [ map { $attributes{$_} } @ordered_names ];
1071 }
1072  
1073 =head2 add_variants @variants
1074  
1075 Add variants from a list of hash references.
1076  
1077 Returns product object.
1078  
1079 Each hash reference contains attributes and column
1080 data which overrides data from the canonical product.
1081  
1082 The canonical sku of the variant is automatically set.
1083  
1084 Example for the hash reference (attributes in the first line):
1085  
1086 {color => 'yellow', size => 'small',
1087 sku => 'G0001-YELLOW-S',
1088 name => 'Six Small Yellow Tulips',
1089 uri => 'six-small-yellow-tulips'}
1090  
1091 Since there is a risk that attributes names might clash with Product column
1092 names (for example L</weight>) an improved syntax exists to prevent such
1093 problems. This is considered to be the preferred syntax:
1094  
1095 {
1096 sku => 'ROD00014-2-6-mid',
1097 uri => 'fishingrod-weight-2-length-6-flex-mid',
1098 price => 355,
1099 attributes => [
1100 { weight => '2' },
1101 { length => '6' },
1102 { action => 'mid' },
1103 ],
1104 }
1105  
1106 =cut
1107  
1108 sub add_variants {
1109 61 ▶ my ( $self, @variants ) = @_;
Subroutine add_variants: called CC=12 SCAR=24.8
Pod documented
1110 61 my %attr_map;
1111 61 my $attr_rs = $self->result_source->schema->resultset('Attribute');
1112  
1113 61 for my $var_ref (@variants) {
1114 237 my %attr;
1115 my %product;
1116 237 my $sku;
1117  
1118 237 ▶ unless ( exists $var_ref->{sku} && ( $sku = $var_ref->{sku} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $var_ref->{"sku"} and $sku = $var_ref->{"sku"}) 2 235 237
Condition100%3/3
exists $var_ref->{"sku"} and $sku = $var_ref->{"sku"}
!ll&&!rl&&r
11235
MC/DC100%2/2
exists $var_ref->{"sku"} and $sku = $var_ref->{"sku"}
exists $var_ref->{"sku"} $sku = $var_ref->{"sku"}
Truth table100%3/3
A and B
A= exists $var_ref->{"sku"}B= $sku = $var_ref->{"sku"}
ABresult
0X0
100
111
1119 2 die "SKU missing in input for add_variants.";
1120 }
1121  
1122 235 ▶ if ( defined $var_ref->{attributes} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $var_ref->{"attributes"}) 1 234 235
1123  
1124 # new syntax with explicit attributes
1125  
1126 1 %attr = %{ delete $var_ref->{attributes} };
1127 }
1128  
1129 # weed out attribute values that might be mixed in with columns
1130 # as happens with old syntax
1131  
1132 235 ▶ while ( my ( $name, $value ) = each %$var_ref ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %$var_ref) 990 235 1225
1133 990 ▶ if ( $self->result_source->has_column($name) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->result_source->has_column($name)) { } 660 330 990
1134 660 $product{$name} = $value;
1135 }
1136 else {
1137 330 $attr{$name} = $value;
1138 }
1139 }
1140  
1141 235 ▶ while ( my ( $name, $value ) = each %attr ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %attr) 332 233 565
1142  
1143 332 my ( $attribute, $attribute_value );
1144  
1145 332 ▶ if ( !$attr_map{$name} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($attr_map{$name}) 76 256 332
1146 76 my $set = $attr_rs->search(
1147 {
1148 name => $name,
1149 type => 'variant',
1150 }
1151 );
1152  
1153 76 ▶ if ( !( $attribute = $set->next ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($attribute = $set->next) 1 75 76
1154 1 die "Missing variant attribute '$name' for SKU $sku";
1155 }
1156  
1157 75 $attr_map{$name} = $attribute;
1158 }
1159  
1160 # search for attribute value
1161 331 ▶ unless ( $attribute_value =
Branch: 1 branch
BranchTrueFalseTotal
unless ($attribute_value = $attr_map{$name}->find_related("attribute_values", {"value", $value})) 1 330 331
1162 $attr_map{$name}
1163 ->find_related( 'attribute_values', { value => $value } ) )
1164 {
1165 1 die "Missing variant attribute value '$value'"
1166 . " for attribute '$name' and SKU $sku";
1167 }
1168  
1169 330 $attr{$name} = $attribute_value;
1170 }
1171  
1172 # clone with new values
1173 233 $product{canonical_sku} = $self->sku;
1174  
1175 233 $self->copy( \%product );
1176  
1177 # find or create product attribute and product attribute value
1178 233 ▶ while ( my ( $name, $value ) = each %attr ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %attr) 330 233 563
1179 330 my $product_attribute = $attr_map{$name}
1180 ->find_or_create_related( 'product_attributes', { sku => $sku } );
1181  
1182 330 $product_attribute->create_related( 'product_attribute_values',
1183 { attribute_values_id => $value->id } );
1184 }
1185 }
1186  
1187 57 return $self;
1188 }
1189  
1190 =head2 discount_percent
1191  
1192 If L</selling_price> is lower than L</price> returns the rounded percentage
1193 discount or undef.
1194  
1195 B<NOTE:> for parent products (products that have variants) this will always
1196 return undef.
1197  
1198 =cut
1199  
1200 sub discount_percent {
1201 3 ▶ my $self = shift;
Subroutine discount_percent: called CC=3 SCAR=11.0
Pod documented
1202  
1203 3 ▶ if ( $self->variant_count || $self->selling_price == $self->price ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->variant_count or $self->selling_price == $self->price) 2 1 3
Condition100%3/3
$self->variant_count or $self->selling_price == $self->price
l!l&&r!l&&!r
111
MC/DC100%2/2
$self->variant_count or $self->selling_price == $self->price
$self->variant_count $self->selling_price == $self->price
Truth table100%3/3
A or B
A= $self->variant_countB= $self->selling_price == $self->price
ABresult
1X1
011
000
1204 2 return undef;
1205 }
1206  
1207 1 return sprintf( "%.0f",
1208 ( $self->price - $self->selling_price ) / $self->price * 100 );
1209  
1210 }
1211  
1212 =head2 media_by_type
1213  
1214 Return a Media resultset with the related media, filtered by type
1215 (e.g. video or image). On the results you can call
1216 C<display_uri("type")> to get the actual uri.
1217  
1218 =cut
1219  
1220 sub media_by_type {
1221 5 ▶ my ( $self, $typename ) = @_;
Subroutine media_by_type: called CC=2 SCAR=6.9
Pod documented
1222 5 my @media_out;
1223  
1224 # track back the schema and search the media type id
1225 5 my $type = $self->result_source->schema->resultset('MediaType')
1226 ->find( { type => $typename } );
1227 5 ▶ return unless $type;
Branch: 1 branch
BranchTrueFalseTotal
unless $type 1 4 5
1228 4 return $self->media->search(
1229 {
1230 media_types_id => $type->media_types_id,
1231 },
1232 {
1233 order_by => 'uri',
1234 }
1235 );
1236 }
1237  
1238 =head2 product_reviews
1239  
1240 Reviews should only be associated with parent products. This method returns the related ProductReview records for a parent product. For a child product the ProductReview records for the parent are returned.
1241  
1242 =cut
1243  
1244 sub product_reviews {
1245 418 ▶ my $self = shift;
Subroutine product_reviews: called CC=2 SCAR=6.9
Pod documented
1246 418 ▶ if ( $self->canonical_sku ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->canonical_sku) { } 1 417 418
1247 1 return $self->canonical->_product_reviews;
1248 }
1249 else {
1250 417 return $self->_product_reviews;
1251 }
1252 }
1253  
1254 =head2 reviews
1255  
1256 Reviews should only be associated with parent products. This method returns the related Message (reviews) records for a parent product. For a child product the Message records for the parent are returned.
1257  
1258 =over
1259  
1260 =item * Arguments: L<$cond|DBIx::Class::SQLMaker> | undef, L<\%attrs?|DBIx::Class::ResultSet#ATTRIBUTES>
1261  
1262 =back
1263  
1264 Arguments are passed as paremeters to search the related reviews.
1265  
1266 =cut
1267  
1268 sub reviews {
1269 21 ▶ my $self = shift;
Subroutine reviews: called CC=2 SCAR=6.9
Pod documented
1270  
1271 # use parent if I have one
1272 21 ▶ $self = $self->canonical if $self->canonical_sku;
Branch: 1 branch
BranchTrueFalseTotal
if $self->canonical_sku 5 16 21
1273  
1274 21 return $self->_reviews->search(@_);
1275 }
1276  
1277 =head2 top_reviews
1278  
1279 Returns the highest-rated approved public reviews for this product. Argument is max number of reviews to return which defaults to 5.
1280  
1281 =cut
1282  
1283 sub top_reviews {
1284 2 ▶ my ( $self, $rows ) = @_;
Subroutine top_reviews: called CC=2 SCAR=6.9
Pod documented
1285 2 ▶ $rows = 5 unless defined $rows;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rows 1 1 2
1286 2 return $self->reviews( { public => 1, approved => 1 },
1287 { rows => $rows, order_by => { -desc => 'rating' } } );
1288 }
1289  
1290 =head2 variant_count
1291  
1292 Returns the number of variants of this product. If the query was constructed
1293 using L<Interchange6::Schema::ResultSet::Product/with_variant_count> then
1294 the cached value will be used rather than running a new query.
1295  
1296 =cut
1297  
1298 sub variant_count {
1299 145 ▶ my $self = shift;
Subroutine variant_count: called CC=2 SCAR=6.9
Pod documented
1300 145 ▶ if ( $self->has_column_loaded('variant_count') ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_column_loaded('variant_count')) { } 71 74 145
1301 71 return $self->get_column('variant_count');
1302 }
1303 else {
1304 74 return $self->variants->count;
1305 }
1306 }
1307  
1308 =head2 has_variants
1309  
1310 Alias for L</variant_count> for backwards-compatibility.
1311  
1312 =cut
1313  
1314 sub has_variants {
1315 0 ▶ return shift->variant_count;
Subroutine has_variants: not called CC=1 SCAR=6.9
Pod documented
1316 }
1317  
1318 =head2 average_rating
1319  
1320 Returns the average rating across all public and approved product reviews or undef if there are no reviews. Optional argument number of decimal places of precision must be a positive integer less than 10 which defaults to 1.
1321  
1322 If the query was constructed using
1323 L<Interchange6::Schema::ResultSet::Product/with_average_rating> then
1324 the cached value will be used rather than running a new query.
1325  
1326 =cut
1327  
1328 sub average_rating {
1329 12 ▶ my ( $self, $precision ) = @_;
Subroutine average_rating: called CC=5 SCAR=16.1
Pod documented
1330 12 my $avg;
1331  
1332 12 ▶ $precision = 1 unless ( defined $precision && $precision =~ /^\d$/ );
Branch: 1 branch
BranchTrueFalseTotal
unless defined $precision and $precision =~ /^\d$/ 6 6 12
Condition66%2/3
defined $precision and $precision =~ /^\d$/
!ll&&!rl&&r
606
MC/DC50%1/2
defined $precision and $precision =~ /^\d$/
defined $precision $precision =~ /^\d$/
Truth table66%2/3
A and B
A= defined $precisionB= $precision =~ /^\d$/
ABresult
0X0
100
111
1333  
1334 12 ▶ if ( $self->has_column_loaded('average_rating') ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_column_loaded('average_rating')) { } 4 8 12
1335  
1336 # initial query on Product already included average_rating so use it
1337  
1338 4 $avg = $self->get_column('average_rating');
1339 }
1340 else {
1341  
1342 # we need a new query
1343  
1344 8 $avg = $self->reviews( { public => 1, approved => 1 } )
1345 ->get_column('rating')->func('AVG');
1346 }
1347 12 ▶ return defined $avg ? sprintf( "%.*f", $precision, $avg ) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $avg ? : 11 1 12
1348 }
1349  
1350 =head2 add_to_reviews
1351  
1352 Reviews should only be associated with parent products. This method returns the related ProductReview records for a parent product. For a child product the ProductReview records for the parent are returned.
1353  
1354 =cut
1355  
1356 # much of this was cargo-culted from DBIx::Class::Relationship::ManyToMany
1357  
1358 sub add_to_reviews {
1359 76 ▶ my $self = shift;
Subroutine add_to_reviews: called CC=6 SCAR=21.3
Pod documented
1360 76 ▶ @_ > 0
Branch: 1 branch
BranchTrueFalseTotal
@_ > 0 or $self->throw_exception("add_to_reviews needs an object or hashref") 0 76 76
1361 or $self->throw_exception( "add_to_reviews needs an object or hashref" );
1362 76 my $rset_message = $self->result_source->schema->resultset("Message");
1363 76 my $obj;
1364 76 ▶ if ( ref $_[0] ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $_[0]) { } 76 0 76
1365 76 ▶ if ( ref $_[0] eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $_[0] eq 'HASH') { } 76 0 76
1366 76 $_[0]->{type} = "product_review";
1367 76 $obj = $rset_message->create( $_[0] );
1368 }
1369 else {
1370 0 $obj = $_[0];
1371 0 ▶ unless ( my $type = $obj->message_type->name eq "product_review" ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (my $type = $obj->message_type->name eq "product_review") 0 0 0
1372 0 $self->throw_exception(
1373 "cannot add message type $type to reviews" );
1374 }
1375 }
1376 }
1377 else {
1378 0 push @_, type => "product_review";
1379 0 $obj = $rset_message->create( {@_} );
1380 }
1381 76 ▶ my $sku = $self->canonical_sku || $self->sku;
Condition66%2/3
$self->canonical_sku || $self->sku
l!l&&r!l&&!r
1750
MC/DC0%0/2
$self->canonical_sku || $self->sku
$self->canonical_sku $self->sku
Truth table66%2/3
A || B
A= $self->canonical_skuB= $self->sku
ABresult
1X1
011
000
1382 76 $self->product_reviews->create( { sku => $sku, messages_id => $obj->id } );
1383 76 return $obj;
1384 }
1385  
1386 =head2 set_reviews
1387  
1388 =over 4
1389  
1390 =item Arguments: (\@hashrefs_of_col_data | \@result_objs)
1391  
1392 =item Return Value: not defined
1393  
1394 =back
1395  
1396 Similar to L<DBIx::Class::Relationship::Base/set_$rel> except that this method DOES delete objects in the table on the right side of the relation.
1397  
1398 =cut
1399  
1400 sub set_reviews {
1401 10 ▶ my $self = shift;
Subroutine set_reviews: called CC=5 SCAR=16.8
Pod documented
1402 10 ▶ @_ > 0
Branch: 1 branch
BranchTrueFalseTotal
@_ > 0 or $self->throw_exception("set_reviews needs a list of objects or hashrefs") 0 10 10
1403 or $self->throw_exception(
1404 "set_reviews needs a list of objects or hashrefs" );
1405 10 ▶ my @to_set = ( ref( $_[0] ) eq 'ARRAY' ? @{ $_[0] } : @_ );
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq 'ARRAY' ? : 0 10 10
1406 10 $self->product_reviews->delete_all;
1407 10 ▶ $self->add_to_reviews( $_, ref( $_[1] ) ? $_[1] : {} ) for (@to_set);
Branch: 1 branch
BranchTrueFalseTotal
ref $_[1] ? : 74 1 75
1408 }
1409  
1410 =head2 quantity_in_stock
1411  
1412 Returns undef if L<inventory_exempt> is true and otherwise returns the
1413 quantity of the product in the inventory. For a product variant the
1414 quantity returned is for the variant itself whereas for a canonical
1415 (parent) product the quantity returned is the total for all variants.
1416  
1417 If the query was constructed using
1418 L<Interchange6::Schema::ResultSet::Product/with_quantity_in_stock> then
1419 the cached value will be used rather than running a new query.
1420  
1421 =cut
1422  
1423 sub quantity_in_stock {
1424 7 ▶ my $self = shift;
Subroutine quantity_in_stock: called CC=6 SCAR=18.0
Pod documented
1425  
1426 # if already loaded by resultset query then return that value
1427 7 ▶ return $self->get_column('quantity_in_stock')
Branch: 1 branch
BranchTrueFalseTotal
if $self->has_column_loaded("quantity_in_stock") 0 7 7
1428 if $self->has_column_loaded('quantity_in_stock');
1429  
1430 7 my $quantity;
1431 7 my $variants = $self->variants;
1432 7 ▶ if ( $variants->has_rows ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($variants->has_rows) { } 2 5 7
elsif (not $self->inventory_exempt) { } 4 1 5
1433 2 my $not_exempt = $variants->search( { inventory_exempt => 0 } );
1434 2 ▶ if ( $not_exempt->has_rows ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($not_exempt->has_rows) 2 0 2
1435 2 $quantity = $not_exempt->search_related( 'inventory',
1436 { quantity => { '>' => 0 } } )->get_column('quantity')->sum;
1437 }
1438 }
1439 elsif ( ! $self->inventory_exempt ) {
1440 4 my $inventory = $self->inventory;
1441 4 ▶ $quantity = defined $inventory ? $self->inventory->quantity : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $inventory ? : 3 1 4
1442 }
1443 7 return $quantity;
1444 }
1445  
1446  
1447 =head2 delete
1448  
1449 Overload delete to force removal of any product reviews. Only parent products should have reviews so in the case of child products no attempt is made to delete reviews.
1450  
1451 =cut
1452  
1453 # FIXME: (SysPete) There ought to be a way to force this with cascade delete.
1454  
1455 sub delete {
1456 565 ▶ my ( $self, @args ) = @_;
Subroutine delete: called CC=2 SCAR=6.9
Pod documented
1457 565 my $guard = $self->result_source->schema->txn_scope_guard;
1458 565 ▶ $self->product_reviews->delete_all unless defined $self->canonical_sku;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->canonical_sku 332 233 565
1459 565 $self->next::method(@args);
1460 565 $guard->commit;
1461 }
1462  
1463 2 1;
↑ Summary Test/Role/PostgreSQL.pm »