X-Git-Url: http://wagnertech.de/gitweb/gitweb.cgi/mfinanz.git/blobdiff_plain/fa7fc7eeb3ca718914affee06c0629a08d571288..f217d072d76183bc07723dcc29503b732bd2022d:/SL/DB/Unit.pm diff --git a/SL/DB/Unit.pm b/SL/DB/Unit.pm index e8d260c67..2c58ec66d 100644 --- a/SL/DB/Unit.pm +++ b/SL/DB/Unit.pm @@ -1,5 +1,8 @@ package SL::DB::Unit; +use List::MoreUtils qw(any); +use List::Util qw(first); + use strict; use SL::DB::MetaSetup::Unit; @@ -12,6 +15,11 @@ __PACKAGE__->meta->add_relationships( class => 'SL::DB::Unit', column_map => { base_unit => 'name' }, }, + translations => { + type => 'one to many', + class => 'SL::DB::UnitsLanguage', + column_map => { name => 'unit' }, + }, ); __PACKAGE__->meta->initialize; @@ -27,8 +35,8 @@ sub unit_class { sub convertible_units { my $self = shift; - my $all_units = scalar(@_) && (ref($_[0]) eq 'ARRAY') ? $_[0] : \@_; - $all_units = SL::DB::Manager::Unit->get_all if !@{ $all_units }; + my $all_units = scalar(@_) && (ref($_[0]) eq 'ARRAY') ? $_[0] : [ @_ ]; + $all_units = SL::DB::Manager::Unit->all_units if ! @{ $all_units }; return [ sort { $a->sortkey <=> $b->sortkey } grep { $_->unit_class->name eq $self->unit_class->name } @@ -54,7 +62,32 @@ sub convert_to { my $my_base_factor = $self->base_factor || 1; my $other_base_factor = $other_unit->base_factor || 1; - return $qty * $my_base_factor / $other_base_factor; + return ($qty // 0) * $my_base_factor / $other_base_factor; +} + +sub is_time_based { + my ($self) = @_; + + return any { $_->id == $self->id } @{ SL::DB::Manager::Unit->time_based_units }; +} + +sub get_translation_obj { + my ($self, $language) = @_; + + my $language_id = (ref($language) eq 'SL::DB::Language' ? $language->id : $language) || undef; + + return first { $_->language_id => $language_id } @{ $self->translations || [] }; +} + +sub get_translation { + my ($self, $language, $qty) = @_; + + my $translation = $self->name; # fallback, if no translation found + my $translation_obj = $self->get_translation_obj(language => $language); + if ($translation_obj) { + $translation = (($qty // 0) > 1 || ($qty // 0) == 0) ? $translation_obj->localized_plural : $translation_obj->localized; + } + return $translation; } 1;