]> wagnertech.de Git - mfinanz.git/blob - SL/DB/Unit.pm
Merge branch 'master' of http://wagnertech.de/git/mfinanz
[mfinanz.git] / SL / DB / Unit.pm
1 package SL::DB::Unit;
2
3 use List::MoreUtils qw(any);
4 use List::Util qw(first);
5
6 use strict;
7
8 use SL::DB::MetaSetup::Unit;
9 use SL::DB::Manager::Unit;
10 use SL::DB::Helper::ActsAsList;
11
12 __PACKAGE__->meta->add_relationships(
13   base => {
14     type         => 'many to one',
15     class        => 'SL::DB::Unit',
16     column_map   => { base_unit => 'name' },
17   },
18   translations => {
19     type         => 'one to many',
20     class        => 'SL::DB::UnitsLanguage',
21     column_map   => { name => 'unit' },
22   },
23 );
24
25 __PACKAGE__->meta->initialize;
26
27 #methods
28
29 sub unit_class {
30   my $self   = shift;
31
32   return $self if !$self->base_unit || $self->name eq $self->base_unit;
33   return $self->base->unit_class;
34 }
35
36 sub convertible_units {
37   my $self = shift;
38   my $all_units = scalar(@_) && (ref($_[0]) eq 'ARRAY') ? $_[0] : [ @_ ];
39   $all_units    = SL::DB::Manager::Unit->all_units if ! @{ $all_units };
40   return [
41     sort { $a->sortkey <=> $b->sortkey }
42     grep { $_->unit_class->name eq $self->unit_class->name }
43     @{ $all_units }
44   ];
45 }
46
47 sub base_factor {
48   my ($self) = @_;
49
50   my $cache = $::request->cache('base_factor');
51
52   if (!defined $cache->{$self->id}) {
53     $cache->{$self->id} = !$self->base_unit || !$self->factor || ($self->name eq $self->base_unit) ? 1 : $self->factor * $self->base->base_factor;
54   }
55
56   return $cache->{$self->id};
57 }
58
59 sub convert_to {
60   my ($self, $qty, $other_unit) = @_;
61
62   my $my_base_factor    = $self->base_factor       || 1;
63   my $other_base_factor = $other_unit->base_factor || 1;
64
65   return ($qty // 0) * $my_base_factor / $other_base_factor;
66 }
67
68 sub is_time_based {
69   my ($self) = @_;
70
71   return any { $_->id == $self->id } @{ SL::DB::Manager::Unit->time_based_units };
72 }
73
74 sub get_translation_obj {
75   my ($self, $language) = @_;
76
77   my $language_id = (ref($language) eq 'SL::DB::Language' ? $language->id : $language) || undef;
78
79   return first { $_->language_id => $language_id } @{ $self->translations || [] };
80 }
81
82 sub get_translation {
83   my ($self, $language, $qty) = @_;
84
85   my $translation     = $self->name; # fallback, if no translation found
86   my $translation_obj = $self->get_translation_obj(language => $language);
87   if ($translation_obj) {
88     $translation = (($qty // 0) > 1 || ($qty // 0) == 0) ? $translation_obj->localized_plural : $translation_obj->localized;
89   }
90   return $translation;
91 }
92
93 1;