DisplayableNamePrefs: Mandantenkonfiguration
[kivitendo-erp.git] / SL / Controller / ClientConfig.pm
1 package SL::Controller::ClientConfig;
2
3 use strict;
4 use parent qw(SL::Controller::Base);
5
6 use File::Copy::Recursive ();
7 use List::Util qw(first);
8
9 use SL::DB::Chart;
10 use SL::DB::Currency;
11 use SL::DB::Default;
12 use SL::DB::Language;
13 use SL::DB::Part;
14 use SL::DB::Unit;
15 use SL::DB::Customer;
16 use SL::Helper::Flash;
17 use SL::Locale::String qw(t8);
18 use SL::PriceSource::ALL;
19 use SL::Template;
20 use SL::Controller::TopQuickSearch;
21 use SL::Helper::ShippedQty;
22
23 __PACKAGE__->run_before('check_auth');
24
25 use Rose::Object::MakeMethods::Generic (
26   'scalar --get_set_init' => [ qw(defaults all_warehouses all_weightunits all_languages all_currencies all_templates all_price_sources h_unit_name available_quick_search_modules available_shipped_qty_item_identity_fields
27                                   all_project_statuses all_project_types
28                                   posting_options payment_options accounting_options inventory_options profit_options balance_startdate_method_options
29                                   displayable_name_specs_by_module) ],
30 );
31
32 sub action_edit {
33   my ($self, %params) = @_;
34
35   $::form->{use_templates} = $self->defaults->templates ? 'existing' : 'new';
36   $::form->{feature_datev} = $self->defaults->feature_datev;
37   $self->edit_form;
38 }
39
40 sub action_save {
41   my ($self, %params)      = @_;
42
43   my $defaults             = delete($::form->{defaults}) || {};
44   my $entered_currencies   = delete($::form->{currencies}) || [];
45   my $original_currency_id = $self->defaults->currency_id;
46   $defaults->{disabled_price_sources} ||= [];
47
48   # undef several fields if an empty value has been selected.
49   foreach (qw(warehouse_id bin_id warehouse_id_ignore_onhand bin_id_ignore_onhand)) {
50     undef $defaults->{$_} if !$defaults->{$_};
51   }
52
53   $defaults->{$_} = $::form->parse_amount(\%::myconfig, $defaults->{$_}) for qw(customer_hourly_rate);
54
55   $self->defaults->assign_attributes(%{ $defaults });
56
57   my %errors_idx;
58
59   # Handle currencies
60   my (%new_currency_names);
61   foreach my $existing_currency (@{ $self->all_currencies }) {
62     my $new_name     = $existing_currency->name;
63     my $new_currency = first { $_->{id} == $existing_currency->id } @{ $entered_currencies };
64     $new_name        = $new_currency->{name} if $new_currency;
65
66     if (!$new_name) {
67       $errors_idx{0} = t8('Currency names must not be empty.');
68     } elsif ($new_currency_names{$new_name}) {
69       $errors_idx{1} = t8('Currency names must be unique.');
70     }
71
72     if ($new_name) {
73       $new_currency_names{$new_name} = 1;
74       $existing_currency->name($new_name);
75     }
76   }
77
78   if ($::form->{new_currency} && $new_currency_names{ $::form->{new_currency} }) {
79     $errors_idx{1} = t8('Currency names must be unique.');
80   }
81
82   my @errors = map { $errors_idx{$_} } sort keys %errors_idx;
83
84   # Check templates
85   $::form->{new_templates}        =~ s:/::g;
86   $::form->{new_master_templates} =~ s:/::g;
87
88   if (($::form->{use_templates} eq 'existing') && ($self->defaults->templates !~ m:^templates/[^/]+$:)) {
89     push @errors, t8('You must select existing print templates or create a new set.');
90
91   } elsif ($::form->{use_templates} eq 'new') {
92     if (!$::form->{new_templates}) {
93       push @errors, t8('You must enter a name for your new print templates.');
94     } elsif (-d "templates/" . $::form->{new_templates}) {
95       push @errors, t8('A directory with the name for the new print templates exists already.');
96     } elsif (! -d "templates/print/" . $::form->{new_master_templates}) {
97       push @errors, t8('The master templates where not found.');
98     }
99   }
100
101   # Show form again if there were any errors. Nothing's been changed
102   # yet in the database.
103   if (@errors) {
104     flash('error', @errors);
105     return $self->edit_form;
106   }
107
108   # Save currencies. As the names must be unique we cannot simply save
109   # them as they are -- the user might want to swap to names. So make
110   # them unique first and assign the actual names in a second step.
111   my %currency_names_by_id = map { ($_->id => $_->name) } @{ $self->all_currencies };
112   $_->update_attributes(name => '__039519735__' . $_->{id})        for @{ $self->all_currencies };
113   $_->update_attributes(name => $currency_names_by_id{ $_->{id} }) for @{ $self->all_currencies };
114
115   # Create new currency if required
116   my $new_currency;
117   if ($::form->{new_currency}) {
118     $new_currency = SL::DB::Currency->new(name => $::form->{new_currency});
119     $new_currency->save;
120   }
121
122   # If the user wants the new currency to be the default then replace
123   # the ID placeholder with the proper value. However, if no new
124   # currency has been created then don't change the value at all.
125   if (-1 == $self->defaults->currency_id) {
126     $self->defaults->currency_id($new_currency ? $new_currency->id : $original_currency_id);
127   }
128
129   # Create new templates if requested.
130   if ($::form->{use_templates} eq 'new') {
131     local $File::Copy::Recursive::SkipFlop = 1;
132     File::Copy::Recursive::dircopy('templates/print/' . $::form->{new_master_templates}, 'templates/' . $::form->{new_templates});
133     $self->defaults->templates('templates/' . $::form->{new_templates});
134   }
135
136   # Displayable name preferences
137   foreach my $specs (@{ $::form->{displayable_name_specs} }) {
138     $self->displayable_name_specs_by_module->{$specs->{module}}->{prefs}->store_default($specs->{default});
139   }
140
141   # Finally save defaults.
142   $self->defaults->save;
143
144   flash_later('info', t8('Client Configuration saved!'));
145
146   $self->redirect_to(action => 'edit');
147 }
148
149 #
150 # initializers
151 #
152
153 sub init_defaults        { SL::DB::Default->get                                                                          }
154 sub init_all_warehouses  { SL::DB::Manager::Warehouse->get_all_sorted                                                    }
155 sub init_all_languages   { SL::DB::Manager::Language->get_all_sorted                                                     }
156 sub init_all_currencies  { SL::DB::Manager::Currency->get_all_sorted                                                     }
157 sub init_all_weightunits { my $unit = SL::DB::Manager::Unit->find_by(name => 'kg'); $unit ? $unit->convertible_units : [] }
158 sub init_all_templates   { +{ SL::Template->available_templates }                                                        }
159 sub init_h_unit_name     { first { SL::DB::Manager::Unit->find_by(name => $_) } qw(Std h Stunde)                         }
160 sub init_all_project_types    { SL::DB::Manager::ProjectType->get_all_sorted                                             }
161 sub init_all_project_statuses { SL::DB::Manager::ProjectStatus->get_all_sorted                                           }
162
163 sub init_posting_options {
164   [ { title => t8("never"),           value => 0           },
165     { title => t8("every time"),      value => 1           },
166     { title => t8("on the same day"), value => 2           }, ]
167 }
168
169 sub init_payment_options {
170   [ { title => t8("never"),           value => 0           },
171     { title => t8("every time"),      value => 1           },
172     { title => t8("on the same day"), value => 2           }, ]
173 }
174
175 sub init_accounting_options {
176   [ { title => t8("Accrual"),         value => "accrual"   },
177     { title => t8("cash"),            value => "cash"      }, ]
178 }
179
180 sub init_inventory_options {
181   [ { title => t8("perpetual"),       value => "perpetual" },
182     { title => t8("periodic"),        value => "periodic"  }, ]
183 }
184
185 sub init_profit_options {
186   [ { title => t8("balance"),         value => "balance"   },
187     { title => t8("income"),          value => "income"    }, ]
188 }
189
190 sub init_balance_startdate_method_options {
191   [ { title => t8("After closed period"),                       value => "closed_to"                   },
192     { title => t8("Start of year"),                             value => "start_of_year"               },
193     { title => t8("All transactions"),                          value => "all_transactions"            },
194     { title => t8("Last opening balance or all transactions"),  value => "last_ob_or_all_transactions" },
195     { title => t8("Last opening balance or start of year"),     value => "last_ob_or_start_of_year"    }, ]
196 }
197
198 sub init_all_price_sources {
199   my @classes = SL::PriceSource::ALL->all_price_sources;
200
201   [ map { [ $_->name, $_->description ] } @classes ];
202 }
203
204 sub init_available_quick_search_modules {
205   [ SL::Controller::TopQuickSearch->new->available_modules ];
206 }
207
208 sub init_available_shipped_qty_item_identity_fields {
209   [ SL::Helper::ShippedQty->new->available_item_identity_fields ];
210 }
211
212 sub init_displayable_name_specs_by_module {
213   +{
214      'SL::DB::Customer' => {
215        specs => SL::DB::Customer->displayable_name_specs,
216        prefs => SL::DB::Customer->displayable_name_prefs,
217      },
218      'SL::DB::Vendor' => {
219        specs => SL::DB::Vendor->displayable_name_specs,
220        prefs => SL::DB::Vendor->displayable_name_prefs,
221      },
222      'SL::DB::Part' => {
223        specs => SL::DB::Part->displayable_name_specs,
224        prefs => SL::DB::Part->displayable_name_prefs,
225      },
226   };
227 }
228
229 #
230 # filters
231 #
232
233 sub check_auth {
234   $::auth->assert('admin');
235 }
236
237 #
238 # helpers
239 #
240
241 sub edit_form {
242   my ($self) = @_;
243
244   $::request->layout->use_javascript("${_}.js") for qw(jquery.selectboxes jquery.multiselect2side kivi.File);
245
246   $self->setup_edit_form_action_bar;
247   $self->render('client_config/form', title => t8('Client Configuration'),
248                 make_chart_title     => sub { $_[0]->accno . '--' . $_[0]->description },
249                 make_templates_value => sub { 'templates/' . $_[0] },
250               );
251 }
252
253 sub setup_edit_form_action_bar {
254   my ($self) = @_;
255
256   for my $bar ($::request->layout->get('actionbar')) {
257     $bar->add(
258       action => [
259         t8('Save'),
260         submit    => [ '#form', { action => 'ClientConfig/save' } ],
261         accesskey => 'enter',
262       ],
263     );
264   }
265 }
266
267 1;