epic-s6ts
[kivitendo-erp.git] / SL / DB / Manager / Unit.pm
1 package SL::DB::Manager::Unit;
2
3 use strict;
4
5 use SL::DB::Helper::Manager;
6 use base qw(SL::DB::Helper::Manager);
7
8 use SL::DB::Helper::Sorted;
9 use SL::DB::Helper::Filtered;
10
11 use List::Util qw(first);
12
13 sub object_class { 'SL::DB::Unit' }
14
15 __PACKAGE__->make_manager_methods;
16 __PACKAGE__->add_filter_specs(
17   convertible_to => sub {
18     my ($key, $value, $prefix) = @_;
19     return __PACKAGE__->convertible_to_filter($key, $value, $prefix);
20   },
21 );
22
23 sub _sort_spec {
24   return ( default => [ 'sortkey', 1 ],
25            columns => { SIMPLE => 'ALL',
26                         name   => 'lower(name)',
27                       });
28 }
29
30 sub convertible_to_filter {
31   my ($class, $key, $unit_name, $prefix) = @_;
32
33   return () unless $unit_name;
34
35   $prefix //= '';
36
37   my $unit = $class->find_by(name => $unit_name);
38   if (!$unit) {
39     $::lxdebug->warn("Unit manager: No unit with name $unit_name");
40     return ();
41   }
42
43   return ("${prefix}name" => [ map { $_->name } @{ $unit->convertible_units } ]);
44 }
45
46 sub all_units {
47   my ($class) = @_;
48   $::request->cache('all_units')->{sorted} //= $class->get_all_sorted;
49 }
50
51 sub find_h_unit {
52   my ($class) = @_;
53
54   return $::request->cache('unit_manager')->{h_unit} //= first { $_->name =~ m{^(?: Std | h | Stunde )$}x } @{ $class->all_units };
55 }
56
57 sub time_based_units {
58   my ($class) = @_;
59
60   my $h_unit = $class->find_h_unit;
61   return [] if !$h_unit;
62   return $::request->cache('unit_manager')->{units} //= $h_unit->convertible_units;
63 }
64
65 1;