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