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