Form->show_generic_error: Parameter action, back_button entfernt
[kivitendo-erp.git] / bin / mozilla / oe.pl
1 #=====================================================================
2 # LX-Office ERP
3 # Copyright (C) 2004
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
6 #
7 #=====================================================================
8 # SQL-Ledger, Accounting
9 # Copyright (c) 1998-2003
10 #
11 #  Author: Dieter Simader
12 #   Email: dsimader@sql-ledger.org
13 #     Web: http://www.sql-ledger.org
14 #
15 #
16 # This program is free software; you can redistribute it and/or modify
17 # it under the terms of the GNU General Public License as published by
18 # the Free Software Foundation; either version 2 of the License, or
19 # (at your option) any later version.
20 #
21 # This program is distributed in the hope that it will be useful,
22 # but WITHOUT ANY WARRANTY; without even the implied warranty of
23 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24 # GNU General Public License for more details.
25 # You should have received a copy of the GNU General Public License
26 # along with this program; if not, write to the Free Software
27 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
28 # MA 02110-1335, USA.
29 #======================================================================
30 #
31 # Order entry module
32 # Quotation module
33 #======================================================================
34
35
36 use Carp;
37 use POSIX qw(strftime);
38
39 use SL::DB::Order;
40 use SL::DO;
41 use SL::FU;
42 use SL::OE;
43 use SL::IR;
44 use SL::IS;
45 use SL::MoreCommon qw(ary_diff restore_form save_form);
46 use SL::ReportGenerator;
47 use List::MoreUtils qw(uniq any none);
48 use List::Util qw(min max reduce sum);
49 use Data::Dumper;
50
51 use SL::DB::Customer;
52 use SL::DB::TaxZone;
53 use SL::DB::PaymentTerm;
54
55 require "bin/mozilla/io.pl";
56 require "bin/mozilla/arap.pl";
57 require "bin/mozilla/reportgenerator.pl";
58
59 use strict;
60
61 our %TMPL_VAR;
62
63 1;
64
65 # end of main
66
67 # For locales.pl:
68 # $locale->text('Edit the purchase_order');
69 # $locale->text('Edit the sales_order');
70 # $locale->text('Edit the request_quotation');
71 # $locale->text('Edit the sales_quotation');
72
73 # $locale->text('Workflow purchase_order');
74 # $locale->text('Workflow sales_order');
75 # $locale->text('Workflow request_quotation');
76 # $locale->text('Workflow sales_quotation');
77
78 my $oe_access_map = {
79   'sales_order'       => 'sales_order_edit',
80   'purchase_order'    => 'purchase_order_edit',
81   'request_quotation' => 'request_quotation_edit',
82   'sales_quotation'   => 'sales_quotation_edit',
83 };
84
85 sub check_oe_access {
86   my $form     = $main::form;
87
88   my $right   = $oe_access_map->{$form->{type}};
89   $right    ||= 'DOES_NOT_EXIST';
90
91   $main::auth->assert($right);
92 }
93
94 sub check_oe_conversion_to_sales_invoice_allowed {
95   return 1 if  $::form->{type} !~ m/^sales/;
96   return 1 if ($::form->{type} =~ m/quotation/) && $::instance_conf->get_allow_sales_invoice_from_sales_quotation;
97   return 1 if ($::form->{type} =~ m/order/)     && $::instance_conf->get_allow_sales_invoice_from_sales_order;
98
99   $::form->show_generic_error($::locale->text("You do not have the permissions to access this function."));
100
101   return 0;
102 }
103
104 sub set_headings {
105   $main::lxdebug->enter_sub();
106
107   my $form     = $main::form;
108   my $locale   = $main::locale;
109
110   check_oe_access();
111
112   my ($action) = @_;
113
114   if ($form->{type} eq 'purchase_order') {
115     $form->{title}   = $action eq "edit" ?
116       $locale->text('Edit Purchase Order') :
117       $locale->text('Add Purchase Order');
118     $form->{heading} = $locale->text('Purchase Order');
119     $form->{vc}      = 'vendor';
120   }
121   if ($form->{type} eq 'sales_order') {
122     $form->{title}   = $action eq "edit" ?
123       $locale->text('Edit Sales Order') :
124       $locale->text('Add Sales Order');
125     $form->{heading} = $locale->text('Sales Order');
126     $form->{vc}      = 'customer';
127   }
128   if ($form->{type} eq 'request_quotation') {
129     $form->{title}   = $action eq "edit" ?
130       $locale->text('Edit Request for Quotation') :
131       $locale->text('Add Request for Quotation');
132     $form->{heading} = $locale->text('Request for Quotation');
133     $form->{vc}      = 'vendor';
134   }
135   if ($form->{type} eq 'sales_quotation') {
136     $form->{title}   = $action eq "edit" ?
137       $locale->text('Edit Quotation') :
138       $locale->text('Add Quotation');
139     $form->{heading} = $locale->text('Quotation');
140     $form->{vc}      = 'customer';
141   }
142
143   $main::lxdebug->leave_sub();
144 }
145
146 sub add {
147   $main::lxdebug->enter_sub();
148
149   my $form     = $main::form;
150
151   check_oe_access();
152
153   set_headings("add");
154
155   $form->{callback} =
156     "$form->{script}?action=add&type=$form->{type}&vc=$form->{vc}"
157     unless $form->{callback};
158
159   $form->{show_details} = $::myconfig{show_form_details};
160
161   &order_links;
162   &prepare_order;
163   &display_form;
164
165   $main::lxdebug->leave_sub();
166 }
167
168 sub edit {
169   $main::lxdebug->enter_sub();
170
171   my $form     = $main::form;
172
173   check_oe_access();
174
175   $form->{show_details}                = $::myconfig{show_form_details};
176   $form->{taxincluded_changed_by_user} = 1;
177
178   # show history button
179   $form->{javascript} = qq|<script type="text/javascript" src="js/show_history.js"></script>|;
180   #/show hhistory button
181
182   $form->{simple_save} = 0;
183
184   set_headings("edit");
185
186   # editing without stuff to edit? try adding it first
187   if ($form->{rowcount} && !$form->{print_and_save}) {
188     my $id;
189     map { $id++ if $form->{"multi_id_$_"} } (1 .. $form->{rowcount});
190     if (!$id) {
191
192       # reset rowcount
193       undef $form->{rowcount};
194       &add;
195       $main::lxdebug->leave_sub();
196       return;
197     }
198   } elsif (!$form->{id}) {
199     &add;
200     $main::lxdebug->leave_sub();
201     return;
202   }
203
204   my ($language_id, $printer_id);
205   if ($form->{print_and_save}) {
206     $form->{action}   = "dispatcher";
207     $form->{action_print}   = "1";
208     $form->{resubmit} = 1;
209     $language_id = $form->{language_id};
210     $printer_id = $form->{printer_id};
211   }
212
213   set_headings("edit");
214
215   &order_links;
216
217   $form->{rowcount} = 0;
218   foreach my $ref (@{ $form->{form_details} }) {
219     $form->{rowcount}++;
220     map { $form->{"${_}_$form->{rowcount}"} = $ref->{$_} } keys %{$ref};
221   }
222
223   &prepare_order;
224
225   if ($form->{print_and_save}) {
226     $form->{language_id} = $language_id;
227     $form->{printer_id} = $printer_id;
228   }
229
230   &display_form;
231
232   $main::lxdebug->leave_sub();
233 }
234
235 sub order_links {
236   $main::lxdebug->enter_sub();
237
238   my $form     = $main::form;
239   my %myconfig = %main::myconfig;
240   my $locale   = $main::locale;
241
242   check_oe_access();
243
244   # get customer/vendor
245   $form->all_vc(\%myconfig, $form->{vc}, ($form->{vc} eq 'customer') ? "AR" : "AP");
246
247   # retrieve order/quotation
248   my $editing = $form->{id};
249
250   OE->retrieve(\%myconfig, \%$form);
251
252   # if multiple rowcounts (== collective order) then check if the
253   # there were more than one customer (in that case OE::retrieve removes
254   # the content from the field)
255   $form->error($locale->text('Collective Orders only work for orders from one customer!'))
256     if          $form->{rowcount}  && $form->{type}     eq 'sales_order'
257      && defined $form->{customer}  && $form->{customer} eq '';
258
259   $form->{"$form->{vc}_id"} ||= $form->{"all_$form->{vc}"}->[0]->{id} if $form->{"all_$form->{vc}"};
260
261   $form->backup_vars(qw(payment_id language_id taxzone_id salesman_id taxincluded cp_id intnotes shipto_id delivery_term_id currency));
262
263   # get customer / vendor
264   IR->get_vendor(\%myconfig, \%$form)   if $form->{type} =~ /(purchase_order|request_quotation)/;
265   IS->get_customer(\%myconfig, \%$form) if $form->{type} =~ /sales_(order|quotation)/;
266
267   $form->restore_vars(qw(payment_id language_id taxzone_id intnotes cp_id shipto_id delivery_term_id));
268   $form->restore_vars(qw(currency))    if $form->{id};
269   $form->restore_vars(qw(taxincluded)) if $form->{id};
270   $form->restore_vars(qw(salesman_id)) if $editing;
271   $form->{forex}       = $form->{exchangerate};
272   $form->{employee}    = "$form->{employee}--$form->{employee_id}";
273
274   # build vendor/customer drop down comatibility... don't ask
275   if (@{ $form->{"all_$form->{vc}"} || [] }) {
276     $form->{"select$form->{vc}"} = 1;
277     $form->{$form->{vc}}         = qq|$form->{$form->{vc}}--$form->{"$form->{vc}_id"}|;
278   }
279
280   $form->{"old$form->{vc}"}  = $form->{$form->{vc}};
281
282   if ($form->{"old$form->{vc}"} !~ m/--\d+$/ && $form->{"$form->{vc}_id"}) {
283     $form->{"old$form->{vc}"} .= qq|--$form->{"$form->{vc}_id"}|
284   }
285
286   $main::lxdebug->leave_sub();
287 }
288
289 sub prepare_order {
290   $main::lxdebug->enter_sub();
291
292   my $form     = $main::form;
293   my %myconfig = %main::myconfig;
294
295   check_oe_access();
296
297   $form->{formname} ||= $form->{type};
298
299   # format discounts if values come from db. either as single id, or as a collective order
300   my $format_discounts = $form->{id} || $form->{convert_from_oe_ids};
301
302   for my $i (1 .. $form->{rowcount}) {
303     $form->{"reqdate_$i"} ||= $form->{"deliverydate_$i"};
304     $form->{"discount_$i"}  = $form->format_amount(\%myconfig, $form->{"discount_$i"} * ($format_discounts ? 100 : 1));
305     $form->{"sellprice_$i"} = $form->format_amount(\%myconfig, $form->{"sellprice_$i"});
306     $form->{"lastcost_$i"}  = $form->format_amount(\%myconfig, $form->{"lastcost_$i"});
307     $form->{"qty_$i"}       = $form->format_amount(\%myconfig, $form->{"qty_$i"});
308   }
309
310   $main::lxdebug->leave_sub();
311 }
312
313 sub form_header {
314   $main::lxdebug->enter_sub();
315   my @custom_hiddens;
316
317   my $form     = $main::form;
318   my %myconfig = %main::myconfig;
319   my $locale   = $main::locale;
320   my $cgi      = $::request->{cgi};
321
322   check_oe_access();
323
324   # Container for template variables. Unfortunately this has to be
325   # visible in form_footer too, so package local level and not my here.
326   %TMPL_VAR = ();
327   if ($form->{id}) {
328     my $obj = SL::DB::Order->new(id => $form->{id})->load;
329     $TMPL_VAR{warn_save_active_periodic_invoice} =
330          $obj->is_type('sales_order')
331       && $obj->periodic_invoices_config
332       && $obj->periodic_invoices_config->active
333       && (   !$obj->periodic_invoices_config->end_date
334           || ($obj->periodic_invoices_config->end_date > DateTime->today_local))
335       && $obj->periodic_invoices_config->get_previous_billed_period_start_date;
336
337     $TMPL_VAR{oe_obj} = $obj;
338   }
339
340   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
341
342   $form->{employee_id} = $form->{old_employee_id} if $form->{old_employee_id};
343   $form->{salesman_id} = $form->{old_salesman_id} if $form->{old_salesman_id};
344
345   # openclosed checkboxes
346   my @tmp;
347   push @tmp, sprintf qq|<input name="delivered" id="delivered" type="checkbox" class="checkbox" value="1" %s><label for="delivered">%s</label>|,
348                         $form->{"delivered"} ? "checked" : "",  $locale->text('Delivery Order(s) for full qty created') if $form->{"type"} =~ /_order$/;
349   push @tmp, sprintf qq|<input name="closed" id="closed" type="checkbox" class="checkbox" value="1" %s><label for="closed">%s</label>|,
350                         $form->{"closed"}    ? "checked" : "",  $locale->text('Closed')    if $form->{id};
351   $TMPL_VAR{openclosed} = sprintf qq|<tr><td colspan=%d align=center>%s</td></tr>\n|, 2 * scalar @tmp, join "\n", @tmp if @tmp;
352
353   my $vc = $form->{vc} eq "customer" ? "customers" : "vendors";
354
355   $form->get_lists("taxzones"      => ($form->{id} ? "ALL_TAXZONES" : "ALL_ACTIVE_TAXZONES"),
356                    "currencies"    => "ALL_CURRENCIES",
357                    $vc             => { key   => "ALL_" . uc($vc),
358                                         limit => $myconfig{vclimit} + 1 },
359                    "price_factors" => "ALL_PRICE_FACTORS");
360   $form->{ALL_PAYMENTS} = SL::DB::Manager::PaymentTerm->get_all( where => [ or => [ obsolete => 0, id => $form->{payment_id} || undef ] ]);
361
362   $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all;
363
364   # Projects
365   my @old_project_ids = uniq grep { $_ } map { $_ * 1 } ($form->{"globalproject_id"}, map { $form->{"project_id_$_"} } 1..$form->{"rowcount"});
366   my @old_ids_cond    = @old_project_ids ? (id => \@old_project_ids) : ();
367   my @customer_cond;
368   if (($vc eq 'customers') && $::instance_conf->get_customer_projects_only_in_sales) {
369     @customer_cond = (
370       or => [
371         customer_id          => $::form->{customer_id},
372         billable_customer_id => $::form->{customer_id},
373       ]);
374   }
375   my @conditions = (
376     or => [
377       and => [ active => 1, @customer_cond ],
378       @old_ids_cond,
379     ]);
380
381   $TMPL_VAR{ALL_PROJECTS}          = SL::DB::Manager::Project->get_all_sorted(query => \@conditions);
382   $form->{ALL_PROJECTS}            = $TMPL_VAR{ALL_PROJECTS}; # make projects available for second row drop-down in io.pl
383
384   # label subs
385   my $employee_list_query_gen      = sub { $::form->{$_[0]} ? [ or => [ id => $::form->{$_[0]}, deleted => 0 ] ] : [ deleted => 0 ] };
386   $TMPL_VAR{ALL_EMPLOYEES}         = SL::DB::Manager::Employee->get_all_sorted(query => $employee_list_query_gen->('employee_id'));
387   $TMPL_VAR{ALL_SALESMEN}          = SL::DB::Manager::Employee->get_all_sorted(query => $employee_list_query_gen->('salesman_id'));
388   $TMPL_VAR{ALL_SHIPTO}            = SL::DB::Manager::Shipto->get_all_sorted(query => [
389     or => [ trans_id  => $::form->{"$::form->{vc}_id"} * 1, and => [ shipto_id => $::form->{shipto_id} * 1, trans_id => undef ] ]
390   ]);
391   $TMPL_VAR{ALL_CONTACTS}          = SL::DB::Manager::Contact->get_all_sorted(query => [
392     or => [
393       cp_cv_id => $::form->{"$::form->{vc}_id"} * 1,
394       and      => [
395         cp_cv_id => undef,
396         cp_id    => $::form->{cp_id} * 1
397       ]
398     ]
399   ]);
400   $TMPL_VAR{sales_employee_labels} = sub { $_[0]->{name} || $_[0]->{login} };
401
402   # vendor/customer
403   $TMPL_VAR{vc_keys} = sub { "$_[0]->{name}--$_[0]->{id}" };
404   $TMPL_VAR{vclimit} = $myconfig{vclimit};
405   $TMPL_VAR{vc_select} = "customer_or_vendor_selection_window('$form->{vc}', '', @{[ $form->{vc} eq 'vendor' ? 1 : 0 ]}, 0)";
406   push @custom_hiddens, "$form->{vc}_id";
407   push @custom_hiddens, "old$form->{vc}";
408   push @custom_hiddens, "select$form->{vc}";
409
410   # currencies and exchangerate
411   my @values = map { $_ } @{ $form->{ALL_CURRENCIES} };
412   my %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
413   $form->{currency}            = $form->{defaultcurrency} unless $form->{currency};
414   $TMPL_VAR{show_exchangerate} = $form->{currency} ne $form->{defaultcurrency};
415   $TMPL_VAR{currencies}        = NTI($cgi->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
416                                                       '-values' => \@values, '-labels' => \%labels,
417                                                       '-onchange' => "document.getElementById('update_button').click();"
418                                      )) if scalar @values;
419   push @custom_hiddens, "forex";
420   push @custom_hiddens, "exchangerate" if $form->{forex};
421
422   # credit remaining
423   my $creditwarning = (($form->{creditlimit} != 0) && ($form->{creditremaining} < 0) && !$form->{update}) ? 1 : 0;
424   $TMPL_VAR{is_credit_remaining_negativ} = ($form->{creditremaining} =~ /-/) ? "0" : "1";
425
426   # business
427   $TMPL_VAR{business_label} = ($form->{vc} eq "customer" ? $locale->text('Customer type') : $locale->text('Vendor type'));
428
429   push @custom_hiddens, "customer_pricegroup_id" if $form->{vc} eq 'customer';
430
431   my $credittext = $locale->text('Credit Limit exceeded!!!');
432
433   my $follow_up_vc                =  $form->{ $form->{vc} eq 'customer' ? 'customer' : 'vendor' };
434   $follow_up_vc                   =~ s/--\d*\s*$//;
435   $TMPL_VAR{follow_up_trans_info} =  ($form->{type} =~ /_quotation$/ ? $form->{quonumber} : $form->{ordnumber}) . " ($follow_up_vc)";
436
437   if ($form->{id}) {
438     my $follow_ups = FU->follow_ups('trans_id' => $form->{id}, 'not_done' => 1);
439
440     if (scalar @{ $follow_ups }) {
441       $TMPL_VAR{num_follow_ups}     = scalar                    @{ $follow_ups };
442       $TMPL_VAR{num_due_follow_ups} = sum map { $_->{due} * 1 } @{ $follow_ups };
443     }
444   }
445
446   my $dispatch_to_popup = '';
447   if ($form->{resubmit} && ($form->{format} eq "html")) {
448       $dispatch_to_popup  = "window.open('about:blank','Beleg'); document.oe.target = 'Beleg';";
449       $dispatch_to_popup .= "document.do.submit();";
450   } elsif ($form->{resubmit}) {
451     # emulate click for resubmitting actions
452     $dispatch_to_popup  = "document.oe.${_}.click(); " for grep { /^action_/ } keys %$form;
453   } elsif ($creditwarning) {
454     $::request->{layout}->add_javascripts_inline("alert('$credittext');");
455   }
456
457   $::request->{layout}->add_javascripts_inline("\$(function(){$dispatch_to_popup});");
458   $TMPL_VAR{dateformat}          = $myconfig{dateformat};
459   $TMPL_VAR{numberformat}        = $myconfig{numberformat};
460
461   if ($form->{type} eq 'sales_order') {
462     if (!$form->{periodic_invoices_config}) {
463       $form->{periodic_invoices_status} = $locale->text('not configured');
464
465     } else {
466       my $config                        = YAML::Load($form->{periodic_invoices_config});
467       $form->{periodic_invoices_status} = $config->{active} ? $locale->text('active') : $locale->text('inactive');
468     }
469   }
470
471   $::request->{layout}->use_javascript(map { "${_}.js" } qw(kivi.SalesPurchase show_form_details show_history show_vc_details ckeditor/ckeditor ckeditor/adapters/jquery kivi.io autocomplete_customer autocomplete_part));
472
473   $form->header;
474   if ($form->{CFDD_shipto} && $form->{CFDD_shipto_id} ) {
475       $form->{shipto_id} = $form->{CFDD_shipto_id};
476   }
477
478   push @custom_hiddens, map { "shiptocvar_" . $_->name } @{ SL::DB::Manager::CustomVariableConfig->get_all(where => [ module => 'ShipTo' ]) };
479
480   $TMPL_VAR{HIDDENS} = [ map { name => $_, value => $form->{$_} },
481      qw(id action type vc formname media format proforma queued printed emailed
482         title creditlimit creditremaining tradediscount business
483         max_dunning_level dunning_amount shiptoname shiptostreet shiptozipcode
484         CFDD_shipto CFDD_shipto_id shiptocity shiptocountry shiptogln shiptocontact shiptophone shiptofax
485         shiptodepartment_1 shiptodepartment_2 shiptoemail shiptocp_gender
486         message email subject cc bcc taxpart taxservice taxaccounts cursor_fokus
487         show_details useasnew),
488         @custom_hiddens,
489         map { $_.'_rate', $_.'_description', $_.'_taxnumber' } split / /, $form->{taxaccounts} ];  # deleted: discount
490
491   %TMPL_VAR = (
492      %TMPL_VAR,
493      is_sales        => scalar ($form->{type} =~ /^sales_/),              # these vars are exported, so that the template
494      is_order        => scalar ($form->{type} =~ /_order$/),              # may determine what to show
495      is_sales_quo    => scalar ($form->{type} =~ /sales_quotation$/),
496      is_req_quo      => scalar ($form->{type} =~ /request_quotation$/),
497      is_sales_ord    => scalar ($form->{type} =~ /sales_order$/),
498      is_pur_ord      => scalar ($form->{type} =~ /purchase_order$/),
499   );
500
501   $TMPL_VAR{ORDER_PROBABILITIES} = [ map { { title => ($_ * 10) . '%', id => $_ * 10 } } (0..10) ];
502
503   print $form->parse_html_template("oe/form_header", { %TMPL_VAR });
504
505   $main::lxdebug->leave_sub();
506 }
507
508 sub form_footer {
509   $main::lxdebug->enter_sub();
510
511   my $form     = $main::form;
512   my %myconfig = %main::myconfig;
513   my $locale   = $main::locale;
514
515   check_oe_access();
516
517   $form->{invtotal} = $form->{invsubtotal};
518
519   my $introws = max 5, $form->numtextrows($form->{intnotes}, 35, 8);
520
521   $TMPL_VAR{notes}    = qq|<textarea name="notes" class="texteditor" wrap="soft" style="width: 350px; height: 150px">| . H($form->{notes}) . qq|</textarea>|;
522   $TMPL_VAR{intnotes} = qq|<textarea name=intnotes rows="$introws" cols="35">| . H($form->{intnotes}) . qq|</textarea>|;
523
524   if( $form->{customer_id} && !$form->{taxincluded_changed_by_user} ) {
525     my $customer = SL::DB::Customer->new(id => $form->{customer_id})->load();
526     $form->{taxincluded} = defined($customer->taxincluded_checked) ? $customer->taxincluded_checked : $myconfig{taxincluded_checked};
527   }
528
529   if (!$form->{taxincluded}) {
530
531     foreach my $item (split / /, $form->{taxaccounts}) {
532       if ($form->{"${item}_base"}) {
533         $form->{invtotal} += $form->{"${item}_total"} = $form->round_amount( $form->{"${item}_base"} * $form->{"${item}_rate"}, 2);
534         $form->{"${item}_total"} = $form->format_amount(\%myconfig, $form->{"${item}_total"}, 2);
535
536         $TMPL_VAR{tax} .= qq|
537               <tr>
538                 <th align=right>$form->{"${item}_description"}&nbsp;| . $form->{"${item}_rate"} * 100 .qq|%</th>
539                 <td align=right>$form->{"${item}_total"}</td>
540               </tr> |;
541       }
542     }
543   } else {
544     foreach my $item (split / /, $form->{taxaccounts}) {
545       if ($form->{"${item}_base"}) {
546         $form->{"${item}_total"} = $form->round_amount( ($form->{"${item}_base"} * $form->{"${item}_rate"} / (1 + $form->{"${item}_rate"})), 2);
547         $form->{"${item}_netto"} = $form->round_amount( ($form->{"${item}_base"} - $form->{"${item}_total"}), 2);
548         $form->{"${item}_total"} = $form->format_amount(\%myconfig, $form->{"${item}_total"}, 2);
549         $form->{"${item}_netto"} = $form->format_amount(\%myconfig, $form->{"${item}_netto"}, 2);
550
551         $TMPL_VAR{tax} .= qq|
552               <tr>
553                 <th align=right>Enthaltene $form->{"${item}_description"}&nbsp;| . $form->{"${item}_rate"} * 100 .qq|%</th>
554                 <td align=right>$form->{"${item}_total"}</td>
555               </tr>
556               <tr>
557                 <th align=right>Nettobetrag</th>
558                 <td align=right>$form->{"${item}_netto"}</td>
559               </tr> |;
560       }
561     }
562   }
563
564   my $grossamount = $form->{invtotal};
565   $form->{invtotal} = $form->round_amount( $form->{invtotal}, 2, 1);
566   $form->{rounding} = $form->round_amount(
567     $form->{invtotal} - $form->round_amount($grossamount, 2),
568     2
569   );
570   $form->{oldinvtotal} = $form->{invtotal};
571
572   $TMPL_VAR{ALL_DELIVERY_TERMS} = SL::DB::Manager::DeliveryTerm->get_all_sorted();
573
574   my $tpca_reminder;
575   $tpca_reminder = check_transport_cost_reminder_article_number() if $::instance_conf->get_transport_cost_reminder_article_number_id;
576   print $form->parse_html_template("oe/form_footer", {
577      %TMPL_VAR,
578      tpca_reminder   => $tpca_reminder,
579      print_options   => print_options(inline => 1),
580      label_edit      => $locale->text("Edit the $form->{type}"),
581      label_workflow  => $locale->text("Workflow $form->{type}"),
582      is_sales        => scalar ($form->{type} =~ /^sales_/),              # these vars are exported, so that the template
583      is_order        => scalar ($form->{type} =~ /_order$/),              # may determine what to show
584      is_sales_quo    => scalar ($form->{type} =~ /sales_quotation$/),
585      is_req_quo      => scalar ($form->{type} =~ /request_quotation$/),
586      is_sales_ord    => scalar ($form->{type} =~ /sales_order$/),
587      is_pur_ord      => scalar ($form->{type} =~ /purchase_order$/),
588   });
589
590   $main::lxdebug->leave_sub();
591 }
592
593 sub update {
594   $main::lxdebug->enter_sub();
595
596   my ($recursive_call) = @_;
597
598   my $form     = $main::form;
599   my %myconfig = %main::myconfig;
600
601   check_oe_access();
602
603   set_headings($form->{"id"} ? "edit" : "add");
604
605   $form->{update} = 1;
606
607   &check_name($form->{vc});
608
609   if (!$form->{forex}) {        # read exchangerate from input field (not hidden)
610     map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) } qw(exchangerate) unless $recursive_call;
611   }
612   my $buysell           = 'buy';
613   $buysell              = 'sell' if ($form->{vc} eq 'vendor');
614   $form->{forex}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{transdate}, $buysell);
615   $form->{exchangerate} = $form->{forex} if $form->{forex};
616
617   my $exchangerate = $form->{exchangerate} || 1;
618
619 ##################### process items ######################################
620   # for pricegroups
621   my $i = $form->{rowcount};
622   if (   ($form->{"partnumber_$i"} eq "")
623       && ($form->{"description_$i"} eq "")
624       && ($form->{"partsgroup_$i"}  eq "")) {
625
626     $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
627
628     &check_form;
629   } else {
630
631     my $mode;
632     if ($form->{type} =~ /^sales/) {
633       IS->retrieve_item(\%myconfig, \%$form);
634       $mode = 'IS';
635     } else {
636       IR->retrieve_item(\%myconfig, \%$form);
637       $mode = 'IR';
638     }
639
640     my $rows = scalar @{ $form->{item_list} };
641
642     $form->{"discount_$i"}   = $form->parse_amount(\%myconfig, $form->{"discount_$i"}) / 100.0;
643     $form->{"discount_$i"} ||= $form->{"$form->{vc}_discount"};
644
645     $form->{"lastcost_$i"} = $form->parse_amount(\%myconfig, $form->{"lastcost_$i"});
646
647     if ($rows) {
648
649       $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
650       if( !$form->{"qty_$i"} ) {
651         $form->{"qty_$i"} = 1;
652       }
653
654       if ($rows > 1) {
655
656         select_item(mode => $mode, pre_entered_qty => $form->{"qty_$i"});
657         $::dispatcher->end_request;
658
659       } else {
660
661         my $sellprice             = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
662         # hier werden parts (Artikeleigenschaften) aus item_list (retrieve_item aus IS.pm)
663         # (item wahrscheinlich synonym für parts) entsprechend in die form geschrieben ...
664
665         # Wäre dieses Mapping nicht besser in retrieve_items aufgehoben?
666         #(Eine Funktion bekommt Daten -> ARBEIT -> Rückgabe DATEN)
667         #  Das quot sieht doch auch nach Ãœberarbeitung aus ... (hmm retrieve_items gibt es in IS und IR)
668         map { $form->{item_list}[$i]{$_} =~ s/\"/&quot;/g }    qw(partnumber description unit);
669         map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
670
671         # ... deswegen muss die prüfung, ob es sich um einen nicht rabattierfähigen artikel handelt später erfolgen (Bug 1136)
672         $form->{"discount_$i"} = 0 if $form->{"not_discountable_$i"};
673         $form->{payment_id} = $form->{"part_payment_id_$i"} if $form->{"part_payment_id_$i"} ne "";
674
675         $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
676
677         ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
678         my $dec_qty       = length $1;
679         my $decimalplaces = max 2, $dec_qty;
680
681         if ($sellprice) {
682           $form->{"sellprice_$i"} = $sellprice;
683         } else {
684           my $record        = _make_record();
685           my $price_source  = SL::PriceSource->new(record_item => $record->items->[$i-1], record => $record);
686           my $best_price    = $price_source->best_price;
687           my $best_discount = $price_source->best_discount;
688
689           if ($best_price) {
690             $::form->{"sellprice_$i"}           = $best_price->price;
691             $::form->{"active_price_source_$i"} = $best_price->source;
692           }
693           if ($best_discount) {
694             $::form->{"discount_$i"}               = $best_discount->discount;
695             $::form->{"active_discount_source_$i"} = $best_discount->source;
696           }
697
698           $form->{"sellprice_$i"} /= $exchangerate;   # if there is an exchange rate adjust sellprice
699         }
700
701         my $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"});
702         map { $form->{"${_}_base"} = 0 }                                 split / /, $form->{taxaccounts};
703         map { $form->{"${_}_base"} += $amount }                          split / /, $form->{"taxaccounts_$i"};
704         map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /, $form->{taxaccounts} if !$form->{taxincluded};
705
706         $form->{creditremaining} -= $amount;
707
708         $form->{"sellprice_$i"} = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
709         $form->{"lastcost_$i"}  = $form->format_amount(\%myconfig, $form->{"lastcost_$i"}, $decimalplaces);
710         $form->{"qty_$i"}       = $form->format_amount(\%myconfig, $form->{"qty_$i"}, $dec_qty);
711         $form->{"discount_$i"}  = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100.0);
712       }
713
714       display_form();
715     } else {
716
717       # ok, so this is a new part
718       # ask if it is a part or service item
719
720       if (   $form->{"partsgroup_$i"}
721           && ($form->{"partsnumber_$i"} eq "")
722           && ($form->{"description_$i"} eq "")) {
723         $form->{rowcount}--;
724         $form->{"discount_$i"} = "";
725
726         display_form();
727       } else {
728         $form->{"id_$i"}   = 0;
729         new_item();
730       }
731     }
732   }
733 ##################### process items ######################################
734
735
736   $main::lxdebug->leave_sub();
737 }
738
739 sub search {
740   $main::lxdebug->enter_sub();
741
742   my $form     = $main::form;
743   my %myconfig = %main::myconfig;
744   my $locale   = $main::locale;
745
746   check_oe_access();
747
748   if ($form->{type} eq 'purchase_order') {
749     $form->{vc}        = 'vendor';
750     $form->{ordnrname} = 'ordnumber';
751     $form->{title}     = $locale->text('Purchase Orders');
752     $form->{ordlabel}  = $locale->text('Order Number');
753
754   } elsif ($form->{type} eq 'request_quotation') {
755     $form->{vc}        = 'vendor';
756     $form->{ordnrname} = 'quonumber';
757     $form->{title}     = $locale->text('Request for Quotations');
758     $form->{ordlabel}  = $locale->text('RFQ Number');
759
760   } elsif ($form->{type} eq 'sales_order') {
761     $form->{vc}        = 'customer';
762     $form->{ordnrname} = 'ordnumber';
763     $form->{title}     = $locale->text('Sales Orders');
764     $form->{ordlabel}  = $locale->text('Order Number');
765
766   } elsif ($form->{type} eq 'sales_quotation') {
767     $form->{vc}        = 'customer';
768     $form->{ordnrname} = 'quonumber';
769     $form->{title}     = $locale->text('Quotations');
770     $form->{ordlabel}  = $locale->text('Quotation Number');
771
772   } else {
773     $form->show_generic_error($locale->text('oe.pl::search called with unknown type'));
774   }
775
776   # setup vendor / customer data
777   $form->all_vc(\%myconfig, $form->{vc}, ($form->{vc} eq 'customer') ? "AR" : "AP");
778   $form->get_lists("projects"     => { "key" => "ALL_PROJECTS", "all" => 1 },
779                    "$form->{vc}s" => "ALL_VC",
780                    "taxzones"     => "ALL_TAXZONES",
781                    "business_types" => "ALL_BUSINESS_TYPES",);
782   $form->{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ deleted => 0 ]);
783   $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all;
784
785   $form->{CT_CUSTOM_VARIABLES}                  = CVar->get_configs('module' => 'CT');
786   ($form->{CT_CUSTOM_VARIABLES_FILTER_CODE},
787    $form->{CT_CUSTOM_VARIABLES_INCLUSION_CODE}) = CVar->render_search_options('variables'      => $form->{CT_CUSTOM_VARIABLES},
788                                                                               'include_prefix' => 'l_',
789                                                                               'include_value'  => 'Y');
790
791   # constants and subs for template
792   $form->{vc_keys}         = sub { "$_[0]->{name}--$_[0]->{id}" };
793
794   $form->{ORDER_PROBABILITIES} = [ map { { title => ($_ * 10) . '%', id => $_ * 10 } } (0..10) ];
795
796   $form->header();
797
798   print $form->parse_html_template('oe/search', {
799     is_order => scalar($form->{type} =~ /_order/),
800   });
801
802   $main::lxdebug->leave_sub();
803 }
804
805 sub create_subtotal_row {
806   $main::lxdebug->enter_sub();
807
808   my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
809
810   my $form     = $main::form;
811   my %myconfig = %main::myconfig;
812
813   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
814
815   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
816
817   $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
818
819   map { $totals->{$_} = 0 } @{ $subtotal_columns };
820
821   $main::lxdebug->leave_sub();
822
823   return $row;
824 }
825
826 sub orders {
827   $main::lxdebug->enter_sub();
828
829   my $form     = $main::form;
830   my %myconfig = %main::myconfig;
831   my $locale   = $main::locale;
832   my $cgi      = $::request->{cgi};
833
834   check_oe_access();
835
836   my $ordnumber = ($form->{type} =~ /_order$/) ? "ordnumber" : "quonumber";
837
838   ($form->{ $form->{vc} }, $form->{"$form->{vc}_id"}) = split(/--/, $form->{ $form->{vc} });
839
840   report_generator_set_default_sort('transdate', 1);
841
842   OE->transactions(\%myconfig, \%$form);
843
844   $form->{rowcount} = scalar @{ $form->{OE} };
845
846   my @columns = (
847     "transdate",               "reqdate",
848     "id",                      $ordnumber,             "edit_exp",
849     "cusordnumber",            "customernumber",
850     "name",                    "netamount",
851     "tax",                     "amount",
852     "remaining_netamount",     "remaining_amount",
853     "curr",                    "employee",
854     "salesman",
855     "shipvia",                 "globalprojectnumber",
856     "transaction_description", "open",
857     "delivered",               "periodic_invoices",
858     "marge_total",             "marge_percent",
859     "vcnumber",                "ustid",
860     "country",                 "shippingpoint",
861     "taxzone",                 "insertdate",
862     "order_probability",       "expected_billing_date", "expected_netamount",
863     "payment_terms",
864   );
865
866   # only show checkboxes if gotten here via sales_order form.
867   my $allow_multiple_orders = $form->{type} eq 'sales_order';
868   if ($allow_multiple_orders) {
869     unshift @columns, "ids";
870   }
871
872   $form->{l_open}              = $form->{l_closed} = "Y" if ($form->{open}      && $form->{closed});
873   $form->{l_delivered}         = "Y"                     if ($form->{delivered} && $form->{notdelivered});
874   $form->{l_periodic_invoices} = "Y"                     if ($form->{periodic_invoices_active} && $form->{periodic_invoices_inactive});
875   $form->{l_edit_exp}          = "Y"                     if (any { $form->{type} eq $_ } qw(sales_order purchase_order));
876   map { $form->{"l_${_}"} = 'Y' } qw(order_probability expected_billing_date expected_netamount) if $form->{l_order_probability_expected_billing_date};
877
878   my $attachment_basename;
879   if ($form->{vc} eq 'vendor') {
880     if ($form->{type} eq 'purchase_order') {
881       $form->{title}       = $locale->text('Purchase Orders');
882       $attachment_basename = $locale->text('purchase_order_list');
883     } else {
884       $form->{title}       = $locale->text('Request for Quotations');
885       $attachment_basename = $locale->text('rfq_list');
886     }
887
888   } else {
889     if ($form->{type} eq 'sales_order') {
890       $form->{title}       = $locale->text('Sales Orders');
891       $attachment_basename = $locale->text('sales_order_list');
892     } else {
893       $form->{title}       = $locale->text('Quotations');
894       $attachment_basename = $locale->text('quotation_list');
895     }
896   }
897
898   my $report = SL::ReportGenerator->new(\%myconfig, $form);
899
900   my $ct_cvar_configs = CVar->get_configs('module' => 'CT');
901   my @ct_includeable_custom_variables = grep { $_->{includeable} } @{ $ct_cvar_configs };
902   my @ct_searchable_custom_variables  = grep { $_->{searchable} }  @{ $ct_cvar_configs };
903
904   my %column_defs_cvars            = map { +"cvar_$_->{name}" => { 'text' => $_->{description} } } @ct_includeable_custom_variables;
905   push @columns, map { "cvar_$_->{name}" } @ct_includeable_custom_variables;
906
907   my @hidden_variables = map { "l_${_}" } @columns;
908   push @hidden_variables, "l_subtotal", $form->{vc}, qw(l_closed l_notdelivered open closed delivered notdelivered ordnumber quonumber cusordnumber
909                                                         transaction_description transdatefrom transdateto type vc employee_id salesman_id
910                                                         reqdatefrom reqdateto projectnumber project_id periodic_invoices_active periodic_invoices_inactive
911                                                         business_id shippingpoint taxzone_id reqdate_unset_or_old insertdatefrom insertdateto
912                                                         order_probability_op order_probability_value expected_billing_date_from expected_billing_date_to
913                                                         parts_partnumber parts_description all department_id);
914   push @hidden_variables, map { "cvar_$_->{name}" } @ct_searchable_custom_variables;
915
916   my   @keys_for_url = grep { $form->{$_} } @hidden_variables;
917   push @keys_for_url, 'taxzone_id' if $form->{taxzone_id} ne ''; # taxzone_id could be 0
918
919   my $href = build_std_url('action=orders', @keys_for_url);
920
921   my %column_defs = (
922     'ids'                     => { 'text' => '', },
923     'transdate'               => { 'text' => $locale->text('Date'), },
924     'reqdate'                 => { 'text' => $form->{type} =~ /_order/ ? $locale->text('Required by') : $locale->text('Valid until') },
925     'id'                      => { 'text' => $locale->text('ID'), },
926     'ordnumber'               => { 'text' => $locale->text('Order'), },
927     'quonumber'               => { 'text' => $form->{type} eq "request_quotation" ? $locale->text('RFQ') : $locale->text('Quotation'), },
928     'cusordnumber'            => { 'text' => $locale->text('Customer Order Number'), },
929     'name'                    => { 'text' => $form->{vc} eq 'customer' ? $locale->text('Customer') : $locale->text('Vendor'), },
930     'customernumber'          => { 'text' => $locale->text('Customer Number'), },
931     'netamount'               => { 'text' => $locale->text('Amount'), },
932     'tax'                     => { 'text' => $locale->text('Tax'), },
933     'amount'                  => { 'text' => $locale->text('Total'), },
934     'remaining_amount'        => { 'text' => $locale->text('Remaining Amount'), },
935     'remaining_netamount'     => { 'text' => $locale->text('Remaining Net Amount'), },
936     'curr'                    => { 'text' => $locale->text('Curr'), },
937     'employee'                => { 'text' => $locale->text('Employee'), },
938     'salesman'                => { 'text' => $locale->text('Salesman'), },
939     'shipvia'                 => { 'text' => $locale->text('Ship via'), },
940     'globalprojectnumber'     => { 'text' => $locale->text('Project Number'), },
941     'transaction_description' => { 'text' => $locale->text('Transaction description'), },
942     'open'                    => { 'text' => $locale->text('Open'), },
943     'delivered'               => { 'text' => $locale->text('Delivery Order created'), },
944     'marge_total'             => { 'text' => $locale->text('Ertrag'), },
945     'marge_percent'           => { 'text' => $locale->text('Ertrag prozentual'), },
946     'vcnumber'                => { 'text' => $form->{vc} eq 'customer' ? $locale->text('Customer Number') : $locale->text('Vendor Number'), },
947     'country'                 => { 'text' => $locale->text('Country'), },
948     'ustid'                   => { 'text' => $locale->text('USt-IdNr.'), },
949     'periodic_invoices'       => { 'text' => $locale->text('Per. Inv.'), },
950     'shippingpoint'           => { 'text' => $locale->text('Shipping Point'), },
951     'taxzone'                 => { 'text' => $locale->text('Steuersatz'), },
952     'insertdate'              => { 'text' => $locale->text('Insert Date'), },
953     'order_probability'       => { 'text' => $locale->text('Order probability'), },
954     'expected_billing_date'   => { 'text' => $locale->text('Exp. bill. date'), },
955     'expected_netamount'      => { 'text' => $locale->text('Exp. netamount'), },
956     'payment_terms'           => { 'text' => $locale->text('Payment Terms'), },
957     'edit_exp'                => { 'text' => $locale->text('Edit (experimental)'), },
958     %column_defs_cvars,
959   );
960
961   foreach my $name (qw(id transdate reqdate quonumber ordnumber cusordnumber name employee salesman shipvia transaction_description shippingpoint taxzone insertdate payment_terms)) {
962     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
963     $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
964   }
965
966   my %column_alignment = map { $_ => 'right' } qw(netamount tax amount curr remaining_amount remaining_netamount order_probability expected_billing_date expected_netamount);
967
968   $form->{"l_type"} = "Y";
969   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
970   $column_defs{ids}->{visible} = $allow_multiple_orders ? 'HTML' : 0;
971
972   $report->set_columns(%column_defs);
973   $report->set_column_order(@columns);
974   $report->set_export_options('orders', @hidden_variables, qw(sort sortdir));
975   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
976
977   CVar->add_custom_variables_to_report('module'         => 'CT',
978                                        'trans_id_field' => "$form->{vc}_id",
979                                        'configs'        => $ct_cvar_configs,
980                                        'column_defs'    => \%column_defs,
981                                        'data'           => $form->{OE});
982
983   my @options;
984
985   push @options, $locale->text('Customer')                . " : $form->{customer}"                        if $form->{customer};
986   push @options, $locale->text('Vendor')                  . " : $form->{vendor}"                          if $form->{vendor};
987   push @options, $locale->text('Contact Person')          . " : $form->{cp_name}"                         if $form->{cp_name};
988   push @options, $locale->text('Department')              . " : $form->{department}"                      if $form->{department};
989   push @options, $locale->text('Order Number')            . " : $form->{ordnumber}"                       if $form->{ordnumber};
990   push @options, $locale->text('Customer Order Number')   . " : $form->{cusordnumber}"                    if $form->{cusordnumber};
991   push @options, $locale->text('Notes')                   . " : $form->{notes}"                           if $form->{notes};
992   push @options, $locale->text('Transaction description') . " : $form->{transaction_description}"         if $form->{transaction_description};
993   push @options, $locale->text('Quick Search')            . " : $form->{all}"                             if $form->{all};
994   push @options, $locale->text('Shipping Point')          . " : $form->{shippingpoint}"                   if $form->{shippingpoint};
995   push @options, $locale->text('Part Description')        . " : $form->{parts_description}"               if $form->{parts_description};
996   push @options, $locale->text('Part Number')             . " : $form->{parts_partnumber}"                if $form->{parts_partnumber};
997   if ( $form->{transdatefrom} or $form->{transdateto} ) {
998     push @options, $locale->text('Order Date');
999     push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1)     if $form->{transdatefrom};
1000     push @options, $locale->text('Bis')  . " " . $locale->date(\%myconfig, $form->{transdateto},   1)     if $form->{transdateto};
1001   };
1002   if ( $form->{reqdatefrom} or $form->{reqdateto} ) {
1003     push @options, $locale->text('Delivery Date');
1004     push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{reqdatefrom}, 1)       if $form->{reqdatefrom};
1005     push @options, $locale->text('Bis')  . " " . $locale->date(\%myconfig, $form->{reqdateto},   1)       if $form->{reqdateto};
1006   };
1007   if ( $form->{insertdatefrom} or $form->{insertdateto} ) {
1008     push @options, $locale->text('Insert Date');
1009     push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{insertdatefrom}, 1)    if $form->{insertdatefrom};
1010     push @options, $locale->text('Bis')  . " " . $locale->date(\%myconfig, $form->{insertdateto},   1)    if $form->{insertdateto};
1011   };
1012   push @options, $locale->text('Open')                                                                    if $form->{open};
1013   push @options, $locale->text('Closed')                                                                  if $form->{closed};
1014   push @options, $locale->text('Delivery Order created')                                                               if $form->{delivered};
1015   push @options, $locale->text('Not delivered')                                                           if $form->{notdelivered};
1016   push @options, $locale->text('Periodic invoices active')                                                if $form->{periodic_invoices_active};
1017   push @options, $locale->text('Reqdate not set or before current month')                                 if $form->{reqdate_unset_or_old};
1018
1019   if ($form->{business_id}) {
1020     my $vc_type_label = $form->{vc} eq 'customer' ? $locale->text('Customer type') : $locale->text('Vendor type');
1021     push @options, $vc_type_label . " : " . SL::DB::Business->new(id => $form->{business_id})->load->description;
1022   }
1023   if ($form->{taxzone_id} ne '') { # taxzone_id could be 0
1024     push @options, $locale->text('Steuersatz') . " : " . SL::DB::TaxZone->new(id => $form->{taxzone_id})->load->description;
1025   }
1026
1027   if ($form->{department_id}) {
1028     push @options, $locale->text('Department') . " : " . SL::DB::Department->new(id => $form->{department_id})->load->description;
1029   }
1030
1031   if (($form->{order_probability_value} || '') ne '') {
1032     push @options, $::locale->text('Order probability') . ' ' . ($form->{order_probability_op} eq 'le' ? '<=' : '>=') . ' ' . $form->{order_probability_value} . '%';
1033   }
1034
1035   if ($form->{expected_billing_date_from} or $form->{expected_billing_date_to}) {
1036     push @options, $locale->text('Expected billing date');
1037     push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{expected_billing_date_from}, 1) if $form->{expected_billing_date_from};
1038     push @options, $locale->text('Bis')  . " " . $locale->date(\%myconfig, $form->{expected_billing_date_to},   1) if $form->{expected_billing_date_to};
1039   }
1040
1041   $report->set_options('top_info_text'        => join("\n", @options),
1042                        'raw_top_info_text'    => $form->parse_html_template('oe/orders_top'),
1043                        'raw_bottom_info_text' => $form->parse_html_template('oe/orders_bottom', { 'SHOW_CONTINUE_BUTTON' => $allow_multiple_orders }),
1044                        'output_format'        => 'HTML',
1045                        'title'                => $form->{title},
1046                        'attachment_basename'  => $attachment_basename . strftime('_%Y%m%d', localtime time),
1047     );
1048   $report->set_options_from_form();
1049   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
1050
1051   # add sort and escape callback, this one we use for the add sub
1052   $form->{callback} = $href .= "&sort=$form->{sort}";
1053
1054   # escape callback for href
1055   my $callback = $form->escape($href);
1056
1057   my @subtotal_columns = qw(netamount amount marge_total marge_percent remaining_amount remaining_netamount);
1058   push @subtotal_columns, 'expected_netamount' if $form->{l_order_probability_expected_billing_date};
1059
1060   my %totals    = map { $_ => 0 } @subtotal_columns;
1061   my %subtotals = map { $_ => 0 } @subtotal_columns;
1062
1063   my $idx = 1;
1064
1065   my $edit_url = build_std_url('action=edit', 'type', 'vc');
1066
1067   foreach my $oe (@{ $form->{OE} }) {
1068     map { $oe->{$_} *= $oe->{exchangerate} } @subtotal_columns;
1069
1070     $oe->{tax}               = $oe->{amount} - $oe->{netamount};
1071     $oe->{open}              = $oe->{closed}            ? $locale->text('No')  : $locale->text('Yes');
1072     $oe->{delivered}         = $oe->{delivered}         ? $locale->text('Yes') : $locale->text('No');
1073     $oe->{periodic_invoices} = $oe->{periodic_invoices} ? $locale->text('On')  : $locale->text('Off');
1074
1075     map { $subtotals{$_} += $oe->{$_};
1076           $totals{$_}    += $oe->{$_} } @subtotal_columns;
1077
1078     $subtotals{marge_percent} = $subtotals{netamount} ? ($subtotals{marge_total} * 100 / $subtotals{netamount}) : 0;
1079     $totals{marge_percent}    = $totals{netamount}    ? ($totals{marge_total}    * 100 / $totals{netamount}   ) : 0;
1080
1081     map { $oe->{$_} = $form->format_amount(\%myconfig, $oe->{$_}, 2) } qw(netamount tax amount marge_total marge_percent remaining_amount remaining_netamount expected_netamount);
1082
1083     $oe->{order_probability} = ($oe->{order_probability} || 0) . '%';
1084
1085     my $row = { };
1086
1087     foreach my $column (@columns) {
1088       next if ($column eq 'ids');
1089       next if ($column eq 'edit_exp');
1090       $row->{$column} = {
1091         'data'  => $oe->{$column},
1092         'align' => $column_alignment{$column},
1093       };
1094     }
1095
1096     $row->{ids} = {
1097       'raw_data' =>   $cgi->hidden('-name' => "trans_id_${idx}", '-value' => $oe->{id})
1098                     . $cgi->checkbox('-name' => "multi_id_${idx}", '-value' => 1, '-label' => ''),
1099       'valign'   => 'center',
1100       'align'    => 'center',
1101     };
1102
1103     $row->{$ordnumber}->{link} = $edit_url . "&id=" . E($oe->{id}) . "&callback=${callback}";
1104
1105     $row->{edit_exp}->{data}   = $oe->{ordnumber};
1106     $row->{edit_exp}->{link}   = build_std_url('script=controller.pl', 'action=Order/edit', "type=$form->{type}", 'id=' . E($oe->{id}));
1107
1108     my $row_set = [ $row ];
1109
1110     if (($form->{l_subtotal} eq 'Y')
1111         && (($idx == (scalar @{ $form->{OE} }))
1112             || ($oe->{ $form->{sort} } ne $form->{OE}->[$idx]->{ $form->{sort} }))) {
1113       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
1114     }
1115
1116     $report->add_data($row_set);
1117
1118     $idx++;
1119   }
1120
1121   $report->add_separator();
1122   $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
1123
1124   $report->generate_with_headers();
1125
1126   $main::lxdebug->leave_sub();
1127 }
1128
1129 sub check_delivered_flag {
1130   $main::lxdebug->enter_sub();
1131
1132   my $form     = $main::form;
1133   my %myconfig = %main::myconfig;
1134
1135   check_oe_access();
1136
1137   if (($form->{type} ne 'sales_order') && ($form->{type} ne 'purchase_order')) {
1138     return $main::lxdebug->leave_sub();
1139   }
1140
1141   my $all_delivered = 0;
1142
1143   foreach my $i (1 .. $form->{rowcount}) {
1144     next if (!$form->{"id_$i"});
1145
1146     if ($form->parse_amount(\%myconfig, $form->{"qty_$i"}) == $form->parse_amount(\%myconfig, $form->{"ship_$i"})) {
1147       $all_delivered = 1;
1148       next;
1149     }
1150
1151     $all_delivered = 0;
1152     last;
1153   }
1154
1155   $form->{delivered} = 1 if $all_delivered;
1156
1157   $main::lxdebug->leave_sub();
1158 }
1159
1160 sub save_and_close {
1161   $main::lxdebug->enter_sub();
1162
1163   my $form     = $main::form;
1164   my %myconfig = %main::myconfig;
1165   my $locale   = $main::locale;
1166
1167   check_oe_access();
1168   $form->mtime_ischanged('oe');
1169
1170   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
1171
1172   if ($form->{type} =~ /_order$/) {
1173     $form->isblank("transdate", $locale->text('Order Date missing!'));
1174   } else {
1175     $form->isblank("transdate", $locale->text('Quotation Date missing!'));
1176   }
1177
1178   my $idx = $form->{type} =~ /_quotation$/ ? "quonumber" : "ordnumber";
1179   $form->{$idx} =~ s/^\s*//g;
1180   $form->{$idx} =~ s/\s*$//g;
1181
1182   my $msg = ucfirst $form->{vc};
1183   $form->isblank($form->{vc}, $locale->text($msg . " missing!"));
1184
1185   # $locale->text('Customer missing!');
1186   # $locale->text('Vendor missing!');
1187
1188   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
1189     if ($form->{currency} ne $form->{defaultcurrency});
1190
1191   &validate_items;
1192
1193   my $payment_id;
1194   if($form->{payment_id}) {
1195     $payment_id = $form->{payment_id};
1196   }
1197
1198   # if the name changed get new values
1199   if (&check_name($form->{vc})) {
1200     if($form->{payment_id} eq "") {
1201       $form->{payment_id} = $payment_id;
1202     }
1203     &update;
1204     $::dispatcher->end_request;
1205   }
1206
1207   $form->{id} = 0 if $form->{saveasnew};
1208
1209   my ($numberfld, $ordnumber, $err);
1210   # this is for the internal notes section for the [email] Subject
1211   if ($form->{type} =~ /_order$/) {
1212     if ($form->{type} eq 'sales_order') {
1213       $form->{label} = $locale->text('Sales Order');
1214
1215       $numberfld = "sonumber";
1216       $ordnumber = "ordnumber";
1217     } else {
1218       $form->{label} = $locale->text('Purchase Order');
1219
1220       $numberfld = "ponumber";
1221       $ordnumber = "ordnumber";
1222     }
1223
1224     $err = $locale->text('Cannot save order!');
1225
1226     check_delivered_flag();
1227
1228   } else {
1229     if ($form->{type} eq 'sales_quotation') {
1230       $form->{label} = $locale->text('Quotation');
1231
1232       $numberfld = "sqnumber";
1233       $ordnumber = "quonumber";
1234     } else {
1235       $form->{label} = $locale->text('Request for Quotation');
1236
1237       $numberfld = "rfqnumber";
1238       $ordnumber = "quonumber";
1239     }
1240
1241     $err = $locale->text('Cannot save quotation!');
1242
1243   }
1244
1245   # get new number in sequence if saveasnew was requested
1246   delete $form->{$ordnumber} if $form->{saveasnew};
1247
1248   relink_accounts();
1249
1250   $form->error($err) if (!OE->save(\%myconfig, \%$form));
1251
1252   # saving the history
1253   if(!exists $form->{addition}) {
1254     $form->{snumbers} = qq|ordnumber_| . $form->{ordnumber};
1255     $form->{addition} = "SAVED";
1256     $form->save_history;
1257   }
1258   # /saving the history
1259
1260   $form->redirect($form->{label} . " $form->{$ordnumber} " .
1261                   $locale->text('saved!'));
1262
1263   $main::lxdebug->leave_sub();
1264 }
1265
1266 sub save {
1267   $main::lxdebug->enter_sub();
1268
1269   my $form     = $main::form;
1270   my %myconfig = %main::myconfig;
1271   my $locale   = $main::locale;
1272
1273   check_oe_access();
1274
1275   $form->mtime_ischanged('oe');
1276   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
1277
1278
1279   if ($form->{type} =~ /_order$/) {
1280     $form->isblank("transdate", $locale->text('Order Date missing!'));
1281   } else {
1282     $form->isblank("transdate", $locale->text('Quotation Date missing!'));
1283   }
1284
1285   my $idx = $form->{type} =~ /_quotation$/ ? "quonumber" : "ordnumber";
1286   $form->{$idx} =~ s/^\s*//g;
1287   $form->{$idx} =~ s/\s*$//g;
1288
1289   my $msg = ucfirst $form->{vc};
1290   $form->isblank($form->{vc}, $locale->text($msg . " missing!"));
1291
1292   # $locale->text('Customer missing!');
1293   # $locale->text('Vendor missing!');
1294
1295   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
1296     if ($form->{currency} ne $form->{defaultcurrency});
1297
1298   remove_emptied_rows();
1299   &validate_items;
1300
1301   my $payment_id;
1302   if($form->{payment_id}) {
1303     $payment_id = $form->{payment_id};
1304   }
1305
1306   # if the name changed get new values
1307   if (&check_name($form->{vc})) {
1308     if($form->{payment_id} eq "") {
1309       $form->{payment_id} = $payment_id;
1310     }
1311     &update;
1312     $::dispatcher->end_request;
1313   }
1314
1315   $form->{id} = 0 if $form->{saveasnew};
1316
1317   my ($numberfld, $ordnumber, $err);
1318
1319   # this is for the internal notes section for the [email] Subject
1320   if ($form->{type} =~ /_order$/) {
1321     if ($form->{type} eq 'sales_order') {
1322       $form->{label} = $locale->text('Sales Order');
1323
1324       $numberfld = "sonumber";
1325       $ordnumber = "ordnumber";
1326     } else {
1327       $form->{label} = $locale->text('Purchase Order');
1328
1329       $numberfld = "ponumber";
1330       $ordnumber = "ordnumber";
1331     }
1332
1333     $err = $locale->text('Cannot save order!');
1334
1335     check_delivered_flag();
1336
1337   } else {
1338     if ($form->{type} eq 'sales_quotation') {
1339       $form->{label} = $locale->text('Quotation');
1340
1341       $numberfld = "sqnumber";
1342       $ordnumber = "quonumber";
1343     } else {
1344       $form->{label} = $locale->text('Request for Quotation');
1345
1346       $numberfld = "rfqnumber";
1347       $ordnumber = "quonumber";
1348     }
1349
1350     $err = $locale->text('Cannot save quotation!');
1351
1352   }
1353
1354   relink_accounts();
1355
1356   OE->save(\%myconfig, \%$form);
1357
1358   # saving the history
1359   if(!exists $form->{addition}) {
1360     if ( $form->{formname} eq 'sales_quotation' or  $form->{formname} eq 'request_quotation' ) {
1361         $form->{snumbers} = qq|quonumber_| . $form->{quonumber};
1362     } elsif ( $form->{formname} eq 'sales_order' or $form->{formname} eq 'purchase_order') {
1363         $form->{snumbers} = qq|ordnumber_| . $form->{ordnumber};
1364     };
1365     $form->{what_done} = $form->{formname};
1366     $form->{addition} = "SAVED";
1367     $form->save_history;
1368   }
1369   # /saving the history
1370
1371   $form->{simple_save} = 1;
1372   if(!$form->{print_and_save}) {
1373     delete @{$form}{ary_diff([keys %{ $form }], [qw(login id script type cursor_fokus)])};
1374     edit();
1375     $::dispatcher->end_request;
1376   }
1377   $main::lxdebug->leave_sub();
1378 }
1379
1380 sub delete {
1381   $main::lxdebug->enter_sub();
1382
1383   my $form     = $main::form;
1384   my %myconfig = %main::myconfig;
1385   my $locale   = $main::locale;
1386
1387   check_oe_access();
1388
1389   my ($msg, $err);
1390   if ($form->{type} =~ /_order$/) {
1391     $msg = $locale->text('Order deleted!');
1392     $err = $locale->text('Cannot delete order!');
1393   } else {
1394     $msg = $locale->text('Quotation deleted!');
1395     $err = $locale->text('Cannot delete quotation!');
1396   }
1397   if (OE->delete(\%myconfig, \%$form)){
1398     # saving the history
1399     if(!exists $form->{addition}) {
1400       if ( $form->{formname} eq 'sales_quotation' or  $form->{formname} eq 'request_quotation' ) {
1401           $form->{snumbers} = qq|quonumber_| . $form->{quonumber};
1402       } elsif ( $form->{formname} eq 'sales_order' or $form->{formname} eq 'purchase_order') {
1403           $form->{snumbers} = qq|ordnumber_| . $form->{ordnumber};
1404       };
1405         $form->{what_done} = $form->{formname};
1406         $form->{addition} = "DELETED";
1407         $form->save_history;
1408     }
1409     # /saving the history
1410     $form->info($msg);
1411     $::dispatcher->end_request;
1412   }
1413   $form->error($err);
1414
1415   $main::lxdebug->leave_sub();
1416 }
1417
1418 sub invoice {
1419   $main::lxdebug->enter_sub();
1420
1421   my $form     = $main::form;
1422   my %myconfig = %main::myconfig;
1423   my $locale   = $main::locale;
1424
1425   check_oe_access();
1426   check_oe_conversion_to_sales_invoice_allowed();
1427   $form->mtime_ischanged('oe');
1428
1429   $main::auth->assert($form->{type} eq 'purchase_order' || $form->{type} eq 'request_quotation' ? 'vendor_invoice_edit' : 'invoice_edit');
1430
1431   $form->{old_salesman_id} = $form->{salesman_id};
1432   $form->get_employee();
1433
1434
1435   if ($form->{type} =~ /_order$/) {
1436
1437     # these checks only apply if the items don't bring their own ordnumbers/transdates.
1438     # The if clause ensures that by searching for empty ordnumber_#/transdate_# fields.
1439     $form->isblank("ordnumber", $locale->text('Order Number missing!'))
1440       if (+{ map { $form->{"ordnumber_$_"}, 1 } (1 .. $form->{rowcount} - 1) }->{''});
1441     $form->isblank("transdate", $locale->text('Order Date missing!'))
1442       if (+{ map { $form->{"transdate_$_"}, 1 } (1 .. $form->{rowcount} - 1) }->{''});
1443
1444     # also copy deliverydate from the order
1445     $form->{deliverydate} = $form->{reqdate} if $form->{reqdate};
1446     $form->{orddate}      = $form->{transdate};
1447   } else {
1448     $form->isblank("quonumber", $locale->text('Quotation Number missing!'));
1449     $form->isblank("transdate", $locale->text('Quotation Date missing!'));
1450     $form->{ordnumber}    = "";
1451     $form->{quodate}      = $form->{transdate};
1452   }
1453
1454   my $payment_id;
1455   if ($form->{payment_id}) {
1456     $payment_id = $form->{payment_id};
1457   }
1458
1459   # if the name changed get new values
1460   if (&check_name($form->{vc})) {
1461     $form->{payment_id} = $payment_id if $form->{payment_id} eq "";
1462     &update;
1463     $::dispatcher->end_request;
1464   }
1465
1466   _oe_remove_delivered_or_billed_rows(id => $form->{id}, type => 'billed');
1467
1468   $form->{cp_id} *= 1;
1469
1470   for my $i (1 .. $form->{rowcount}) {
1471     for (qw(ship qty sellprice basefactor discount)) {
1472       $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig, $form->{"${_}_${i}"}) if $form->{"${_}_${i}"};
1473     }
1474     $form->{"converted_from_orderitems_id_$i"} = delete $form->{"orderitems_id_$i"};
1475   }
1476
1477   my ($buysell, $orddate, $exchangerate);
1478   if (   $form->{type} =~ /_order/
1479       && $form->{currency} ne $form->{defaultcurrency}) {
1480
1481     # check if we need a new exchangerate
1482     $buysell = ($form->{type} eq 'sales_order') ? "buy" : "sell";
1483
1484     $orddate      = $form->current_date(\%myconfig);
1485     $exchangerate = $form->check_exchangerate(\%myconfig, $form->{currency}, $orddate, $buysell);
1486
1487     if (!$exchangerate) {
1488       $exchangerate = 0;
1489     }
1490   }
1491
1492   $form->{convert_from_oe_ids} = $form->{id};
1493   $form->{transdate}           = $form->{invdate} = $form->current_date(\%myconfig);
1494   $form->{duedate}             = $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
1495   $form->{defaultcurrency}     = $form->get_default_currency(\%myconfig);
1496
1497   delete @{$form}{qw(id closed)};
1498   $form->{rowcount}--;
1499
1500   my ($script);
1501   if (   $form->{type} eq 'purchase_order'
1502       || $form->{type} eq 'request_quotation') {
1503     $form->{title}  = $locale->text('Add Vendor Invoice');
1504     $form->{script} = 'ir.pl';
1505     $script         = "ir";
1506     $buysell        = 'sell';
1507   }
1508
1509   if (   $form->{type} eq 'sales_order'
1510       || $form->{type} eq 'sales_quotation') {
1511     $form->{title}  = $locale->text('Add Sales Invoice');
1512     $form->{script} = 'is.pl';
1513     $script         = "is";
1514     $buysell        = 'buy';
1515   }
1516
1517   # bo creates the id, reset it
1518   map { delete $form->{$_} } qw(id subject message cc bcc printed emailed queued);
1519   $form->{ $form->{vc} } =~ s/--.*//g;
1520   $form->{type} = "invoice";
1521
1522   # locale messages
1523   $main::locale = Locale->new("$myconfig{countrycode}", "$script");
1524   $locale = $main::locale;
1525
1526   require "bin/mozilla/$form->{script}";
1527
1528   map { $form->{"select$_"} = "" } ($form->{vc}, "currency");
1529
1530   my $currency = $form->{currency};
1531   &invoice_links;
1532
1533   $form->{currency}     = $currency;
1534   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{invdate}, $buysell);
1535   $form->{exchangerate} = $form->{forex} || '';
1536
1537   $form->{creditremaining} -= ($form->{oldinvtotal} - $form->{ordtotal});
1538
1539   &prepare_invoice;
1540
1541   # format amounts
1542   for my $i (1 .. $form->{rowcount}) {
1543     $form->{"discount_$i"} =
1544       $form->format_amount(\%myconfig, $form->{"discount_$i"});
1545
1546     my ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
1547     $dec           = length $dec;
1548     my $decimalplaces = ($dec > 2) ? $dec : 2;
1549
1550     # copy delivery date from reqdate for order -> invoice conversion
1551     $form->{"deliverydate_$i"} = $form->{"reqdate_$i"}
1552       unless $form->{"deliverydate_$i"};
1553
1554     $form->{"sellprice_$i"} =
1555       $form->format_amount(\%myconfig, $form->{"sellprice_$i"},
1556                            $decimalplaces);
1557
1558     (my $dec_qty) = ($form->{"qty_$i"} =~ /\.(\d+)/);
1559     $dec_qty = length $dec_qty;
1560     $form->{"qty_$i"} =
1561       $form->format_amount(\%myconfig, $form->{"qty_$i"}, $dec_qty);
1562   }
1563
1564   &display_form;
1565
1566   $main::lxdebug->leave_sub();
1567 }
1568
1569 sub save_exchangerate {
1570   $main::lxdebug->enter_sub();
1571
1572   my $form     = $main::form;
1573   my %myconfig = %main::myconfig;
1574   my $locale   = $main::locale;
1575
1576   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'));
1577   $form->{exchangerate} =
1578     $form->parse_amount(\%myconfig, $form->{exchangerate});
1579   $form->save_exchangerate(\%myconfig, $form->{currency},
1580                            $form->{exchangeratedate},
1581                            $form->{exchangerate}, $form->{buysell});
1582
1583   &invoice;
1584
1585   $main::lxdebug->leave_sub();
1586 }
1587
1588 sub save_as_new {
1589   $main::lxdebug->enter_sub();
1590
1591   my $form     = $main::form;
1592
1593   check_oe_access();
1594
1595   $form->{saveasnew} = 1;
1596   map { delete $form->{$_} } qw(printed emailed queued delivered closed);
1597   $form->{"converted_from_orderitems_id_$_"} = delete $form->{"orderitems_id_$_"} for 1 .. $form->{"rowcount"};
1598
1599   # Let kivitendo assign a new order number if the user hasn't changed the
1600   # previous one. If it has been changed manually then use it as-is.
1601   my $idx = $form->{type} =~ /_quotation$/ ? "quonumber" : "ordnumber";
1602   $form->{$idx} =~ s/^\s*//g;
1603   $form->{$idx} =~ s/\s*$//g;
1604   if ($form->{saved_xyznumber} &&
1605       ($form->{saved_xyznumber} eq $form->{$idx})) {
1606     delete($form->{$idx});
1607   }
1608
1609   # clear reqdate and transdate unless changed
1610   if ( $form->{reqdate} && $form->{id} ) {
1611     my $saved_order = OE->retrieve_simple(id => $form->{id});
1612     if ( $saved_order && $saved_order->{reqdate} eq $form->{reqdate} && $saved_order->{transdate} eq $form->{transdate} ) {
1613       my $extra_days     = $form->{type} eq 'sales_quotation' ? $::instance_conf->get_reqdate_interval : 1;
1614       $form->{reqdate}   = DateTime->today_local->next_workday(extra_days => $extra_days)->to_kivitendo;
1615       $form->{transdate} = DateTime->today_local->to_kivitendo;
1616     }
1617   }
1618
1619   # update employee
1620   $form->get_employee();
1621
1622   &save;
1623
1624   $main::lxdebug->leave_sub();
1625 }
1626
1627 sub check_for_direct_delivery_yes {
1628   $main::lxdebug->enter_sub();
1629
1630   my $form     = $main::form;
1631
1632   check_oe_access();
1633
1634   $form->{direct_delivery_checked} = 1;
1635   delete @{$form}{grep /^shipto/, keys %{ $form }};
1636   map { s/^CFDD_//; $form->{$_} = $form->{"CFDD_${_}"} } grep /^CFDD_/, keys %{ $form };
1637   $form->{CFDD_shipto} = 1;
1638   purchase_order();
1639   $main::lxdebug->leave_sub();
1640 }
1641
1642 sub check_for_direct_delivery_no {
1643   $main::lxdebug->enter_sub();
1644
1645   my $form     = $main::form;
1646
1647   check_oe_access();
1648
1649   $form->{direct_delivery_checked} = 1;
1650   delete @{$form}{grep /^shipto/, keys %{ $form }};
1651   $form->{CFDD_shipto} = 0;
1652   purchase_order();
1653
1654   $main::lxdebug->leave_sub();
1655 }
1656
1657 sub check_for_direct_delivery {
1658   $main::lxdebug->enter_sub();
1659
1660   my $form     = $main::form;
1661   my %myconfig = %main::myconfig;
1662
1663   check_oe_access();
1664
1665   if ($form->{direct_delivery_checked}
1666       || (!$form->{shiptoname} && !$form->{shiptostreet} && !$form->{shipto_id})) {
1667     $main::lxdebug->leave_sub();
1668     return;
1669   }
1670
1671   my $cvars = SL::DB::Shipto->new->cvars_by_config;
1672
1673   if ($form->{shipto_id}) {
1674     Common->get_shipto_by_id(\%myconfig, $form, $form->{shipto_id}, "CFDD_");
1675
1676   } else {
1677     map { $form->{"CFDD_${_}"} = $form->{$_ } } grep /^shipto/, keys %{ $form };
1678   }
1679
1680   $_->value($::form->{"CFDD_shiptocvar_" . $_->config->name}) for @{ $cvars };
1681
1682   delete $form->{action};
1683   $form->{VARIABLES} = [ map { { "key" => $_, "value" => $form->{$_} } } grep { ($_ ne 'login') && ($_ ne 'password') && (ref $_ eq "") } keys %{ $form } ];
1684
1685   $form->header();
1686   print $form->parse_html_template("oe/check_for_direct_delivery", { cvars => $cvars });
1687
1688   $main::lxdebug->leave_sub();
1689
1690   $::dispatcher->end_request;
1691 }
1692
1693 sub purchase_order {
1694   $main::lxdebug->enter_sub();
1695
1696   my $form     = $main::form;
1697   my $locale   = $main::locale;
1698
1699   check_oe_access();
1700   $form->mtime_ischanged('oe');
1701
1702   $main::auth->assert('purchase_order_edit');
1703
1704   $form->{sales_order_to_purchase_order} = 0;
1705   if ($form->{type} eq 'sales_order') {
1706     $form->{sales_order_to_purchase_order} = 1;
1707     check_for_direct_delivery();
1708   }
1709
1710   if ($form->{type} =~ /^sales_/) {
1711     delete($form->{ordnumber});
1712     delete($form->{payment_id});
1713     delete($form->{delivery_term_id});
1714   }
1715
1716   $form->{cp_id} *= 1;
1717
1718   my $source_type = $form->{type};
1719   $form->{title} = $locale->text('Add Purchase Order');
1720   $form->{vc}    = "vendor";
1721   $form->{type}  = "purchase_order";
1722
1723   $form->get_employee();
1724
1725   poso(source_type => $form->{type});
1726
1727   delete $form->{sales_order_to_purchase_order};
1728
1729   $main::lxdebug->leave_sub();
1730 }
1731
1732 sub sales_order {
1733   $main::lxdebug->enter_sub();
1734
1735   my $form     = $main::form;
1736   my $locale   = $main::locale;
1737
1738   check_oe_access();
1739   $main::auth->assert('sales_order_edit');
1740   $form->mtime_ischanged('oe');
1741
1742   if ($form->{type} eq "purchase_order") {
1743     delete($form->{ordnumber});
1744     $form->{"lastcost_$_"} = $form->{"sellprice_$_"} for (1..$form->{rowcount});
1745   }
1746
1747   $form->{cp_id} *= 1;
1748
1749   my $source_type = $form->{type};
1750   $form->{title}  = $locale->text('Add Sales Order');
1751   $form->{vc}     = "customer";
1752   $form->{type}   = "sales_order";
1753
1754   $form->get_employee();
1755
1756   poso(source_type => $source_type);
1757
1758   $main::lxdebug->leave_sub();
1759 }
1760
1761 sub poso {
1762   $main::lxdebug->enter_sub();
1763
1764   my %param    = @_;
1765   my $form     = $main::form;
1766   my %myconfig = %main::myconfig;
1767
1768   check_oe_access();
1769   $main::auth->assert('purchase_order_edit | sales_order_edit');
1770
1771   $form->{transdate} = $form->current_date(\%myconfig);
1772   delete $form->{duedate};
1773
1774   # "reqdate" is the validity date for a quotation and the delivery
1775   # date for an order. Therefore it makes no sense to keep the value
1776   # when converting from one into the other.
1777   delete $form->{reqdate} if ($param{source_type} =~ /_quotation$/) == ($form->{type} =~ /_quotation$/);
1778
1779   $form->{convert_from_oe_ids} = $form->{id};
1780   $form->{closed}              = 0;
1781
1782   $form->{old_employee_id}     = $form->{employee_id};
1783   $form->{old_salesman_id}     = $form->{salesman_id};
1784
1785   # reset
1786   map { delete $form->{$_} } qw(id subject message cc bcc printed emailed queued customer vendor creditlimit creditremaining discount tradediscount oldinvtotal delivered ordnumber);
1787   # this converted variable is also used for sales_order to purchase order and vice versa
1788   $form->{"converted_from_orderitems_id_$_"} = delete $form->{"orderitems_id_$_"} for 1 .. $form->{"rowcount"};
1789
1790   # if purchase_order was generated from sales_order, use  lastcost_$i as sellprice_$i
1791   # also reset discounts
1792   if ( $form->{sales_order_to_purchase_order} ) {
1793     for my $i (1 .. $form->{rowcount}) {
1794       $form->{"sellprice_${i}"} = $form->{"lastcost_${i}"};
1795       $form->{"discount_${i}"}  = 0;
1796     };
1797   };
1798
1799   for my $i (1 .. $form->{rowcount}) {
1800     map { $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig, $form->{"${_}_${i}"}) if ($form->{"${_}_${i}"}) } qw(ship qty sellprice basefactor discount lastcost);
1801   }
1802
1803   my %saved_vars = map { $_ => $form->{$_} } grep { $form->{$_} } qw(currency);
1804
1805   &order_links;
1806
1807   map { $form->{$_} = $saved_vars{$_} } keys %saved_vars;
1808
1809   # prepare_order assumes that the discount is in db-notation (0.05) and not user-notation (5)
1810   # and therefore multiplies the values by 100 in the case of reading from db or making an order
1811   # from several quotation, so we convert this back into percent-notation for the user interface by multiplying with 0.01
1812   # ergänzung 03.10.2010 muss vor prepare_order passieren (s.a. Svens Kommentar zu Bug 1017)
1813   # das parse_amount wird oben schon ausgeführt, deswegen an dieser stelle raus (wichtig: kommawerte bei discount testen)
1814   for my $i (1 .. $form->{rowcount}) {
1815     $form->{"discount_$i"} /=100;
1816   };
1817
1818   &prepare_order;
1819   &update;
1820
1821   $main::lxdebug->leave_sub();
1822 }
1823
1824 sub delivery_order {
1825   $main::lxdebug->enter_sub();
1826
1827   my $form     = $main::form;
1828   my %myconfig = %main::myconfig;
1829
1830   $form->mtime_ischanged('oe');
1831
1832   if ($form->{type} =~ /^sales/) {
1833     $main::auth->assert('sales_delivery_order_edit');
1834
1835     $form->{vc}    = 'customer';
1836     $form->{type}  = 'sales_delivery_order';
1837
1838   } else {
1839     $main::auth->assert('purchase_delivery_order_edit');
1840
1841     $form->{vc}    = 'vendor';
1842     $form->{type}  = 'purchase_delivery_order';
1843   }
1844
1845   $form->get_employee();
1846
1847   require "bin/mozilla/do.pl";
1848
1849   $form->{script}               = 'do.pl';
1850   $form->{cp_id}               *= 1;
1851   $form->{convert_from_oe_ids}  = $form->{id};
1852   $form->{transdate}            = $form->current_date(\%myconfig);
1853   delete $form->{duedate};
1854
1855   $form->{old_employee_id}  = $form->{employee_id};
1856   $form->{old_salesman_id}  = $form->{salesman_id};
1857
1858   _oe_remove_delivered_or_billed_rows(id => $form->{id}, type => 'delivered');
1859
1860   # reset
1861   delete @{$form}{qw(id subject message cc bcc printed emailed queued creditlimit creditremaining discount tradediscount oldinvtotal closed delivered)};
1862
1863   for my $i (1 .. $form->{rowcount}) {
1864     map { $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig, $form->{"${_}_${i}"}) if ($form->{"${_}_${i}"}) } qw(ship qty sellprice lastcost basefactor discount);
1865     $form->{"converted_from_orderitems_id_$i"} = delete $form->{"orderitems_id_$i"};
1866   }
1867
1868   my %old_values = map { $_ => $form->{$_} } qw(customer_id oldcustomer customer vendor_id oldvendor vendor shipto_id);
1869
1870   order_links();
1871
1872   prepare_order();
1873
1874   map { $form->{$_} = $old_values{$_} if ($old_values{$_}) } keys %old_values;
1875
1876   for my $i (1 .. $form->{rowcount}) {
1877     (my $dummy, $form->{"pricegroup_id_$i"}) = split /--/, $form->{"sellprice_pg_$i"};
1878   }
1879   update();
1880
1881   $main::lxdebug->leave_sub();
1882 }
1883
1884 sub oe_delivery_order_from_order {
1885
1886   return if !$::form->{id};
1887
1888   my $order = SL::DB::Order->new(id => $::form->{id})->load;
1889   $order->flatten_to_form($::form, format_amounts => 1);
1890
1891   # fake last empty row
1892   $::form->{rowcount}++;
1893
1894   delivery_order();
1895 }
1896
1897 sub e_mail {
1898   $main::lxdebug->enter_sub();
1899
1900   my $form     = $main::form;
1901
1902   check_oe_access();
1903
1904   $form->mtime_ischanged('oe','mail');
1905   $form->{print_and_save} = 1;
1906
1907   my $saved_form = save_form();
1908
1909   save();
1910
1911   restore_form($saved_form, 0, qw(id ordnumber quonumber));
1912
1913   edit_e_mail();
1914
1915   $main::lxdebug->leave_sub();
1916 }
1917
1918 sub yes {
1919   call_sub($main::form->{yes_nextsub});
1920 }
1921
1922 sub no {
1923   call_sub($main::form->{no_nextsub});
1924 }
1925
1926 ######################################################################################################
1927 # IO ENTKOPPLUNG
1928 # ###############################################################################################
1929 sub display_form {
1930   $main::lxdebug->enter_sub();
1931
1932   my $form     = $main::form;
1933   my %myconfig = %main::myconfig;
1934
1935   check_oe_access();
1936
1937   retrieve_partunits() if ($form->{type} =~ /_delivery_order$/);
1938
1939   $form->{"taxaccounts"} =~ s/\s*$//;
1940   $form->{"taxaccounts"} =~ s/^\s*//;
1941   foreach my $accno (split(/\s*/, $form->{"taxaccounts"})) {
1942     map({ delete($form->{"${accno}_${_}"}); } qw(rate description taxnumber));
1943   }
1944   $form->{"taxaccounts"} = "";
1945
1946   IC->retrieve_accounts(\%myconfig, $form, map { $_ => $form->{"id_$_"} } 1 .. $form->{rowcount});
1947
1948   $form->{rowcount}++;
1949   $form->{"project_id_$form->{rowcount}"} = $form->{globalproject_id};
1950
1951   $form->language_payment(\%myconfig);
1952
1953   Common::webdav_folder($form);
1954
1955   &form_header;
1956
1957   # create rows
1958   display_row($form->{rowcount}) if $form->{rowcount};
1959
1960   &form_footer;
1961
1962   $main::lxdebug->leave_sub();
1963 }
1964
1965 sub report_for_todo_list {
1966   $main::lxdebug->enter_sub();
1967
1968   my $form     = $main::form;
1969
1970   my $quotations = OE->transactions_for_todo_list();
1971   my $content;
1972
1973   if (@{ $quotations }) {
1974     my $edit_url = build_std_url('script=oe.pl', 'action=edit');
1975
1976     $content     = $form->parse_html_template('oe/report_for_todo_list', { 'QUOTATIONS' => $quotations,
1977                                                                            'edit_url'   => $edit_url });
1978   }
1979
1980   $main::lxdebug->leave_sub();
1981
1982   return $content;
1983 }
1984
1985 sub edit_periodic_invoices_config {
1986   $::lxdebug->enter_sub();
1987
1988   $::form->{type} = 'sales_order';
1989
1990   check_oe_access();
1991
1992   my $config;
1993   $config = YAML::Load($::form->{periodic_invoices_config}) if $::form->{periodic_invoices_config};
1994
1995   if ('HASH' ne ref $config) {
1996     $config =  { periodicity             => 'm',
1997                  order_value_periodicity => 'p', # = same as periodicity
1998                  start_date_as_date      => $::form->{transdate} || $::form->current_date,
1999                  extend_automatically_by => 12,
2000                  active                  => 1,
2001                };
2002   }
2003
2004   $config->{periodicity}             = 'm' if none { $_ eq $config->{periodicity}             }       @SL::DB::PeriodicInvoicesConfig::PERIODICITIES;
2005   $config->{order_value_periodicity} = 'p' if none { $_ eq $config->{order_value_periodicity} } ('p', @SL::DB::PeriodicInvoicesConfig::ORDER_VALUE_PERIODICITIES);
2006
2007   $::form->get_lists(printers => "ALL_PRINTERS",
2008                      charts   => { key       => 'ALL_CHARTS',
2009                                    transdate => 'current_date' });
2010
2011   $::form->{AR}    = [ grep { $_->{link} =~ m/(?:^|:)AR(?::|$)/ } @{ $::form->{ALL_CHARTS} } ];
2012   $::form->{title} = $::locale->text('Edit the configuration for periodic invoices');
2013
2014   if ($::form->{customer_id}) {
2015     $::form->{ALL_CONTACTS} = SL::DB::Manager::Contact->get_all_sorted(where => [ cp_cv_id => $::form->{customer_id} ]);
2016   }
2017
2018   $::form->header(no_layout => 1);
2019   print $::form->parse_html_template('oe/edit_periodic_invoices_config', $config);
2020
2021   $::lxdebug->leave_sub();
2022 }
2023
2024 sub save_periodic_invoices_config {
2025   $::lxdebug->enter_sub();
2026
2027   $::form->{type} = 'sales_order';
2028
2029   check_oe_access();
2030
2031   $::form->isblank('start_date_as_date', $::locale->text('The start date is missing.'));
2032
2033   my $config = { active                  => $::form->{active}     ? 1 : 0,
2034                  terminated              => $::form->{terminated} ? 1 : 0,
2035                  direct_debit            => $::form->{direct_debit} ? 1 : 0,
2036                  periodicity             => (any { $_ eq $::form->{periodicity}             }       @SL::DB::PeriodicInvoicesConfig::PERIODICITIES)              ? $::form->{periodicity}             : 'm',
2037                  order_value_periodicity => (any { $_ eq $::form->{order_value_periodicity} } ('p', @SL::DB::PeriodicInvoicesConfig::ORDER_VALUE_PERIODICITIES)) ? $::form->{order_value_periodicity} : 'p',
2038                  start_date_as_date      => $::form->{start_date_as_date},
2039                  end_date_as_date        => $::form->{end_date_as_date},
2040                  first_billing_date_as_date => $::form->{first_billing_date_as_date},
2041                  print                   => $::form->{print} ? 1 : 0,
2042                  printer_id              => $::form->{print} ? $::form->{printer_id} * 1 : undef,
2043                  copies                  => $::form->{copies} * 1 ? $::form->{copies} : 1,
2044                  extend_automatically_by => $::form->{extend_automatically_by} * 1 || undef,
2045                  ar_chart_id             => $::form->{ar_chart_id} * 1,
2046                  send_email                 => $::form->{send_email} ? 1 : 0,
2047                  email_recipient_contact_id => $::form->{email_recipient_contact_id} * 1 || undef,
2048                  email_recipient_address    => $::form->{email_recipient_address},
2049                  email_sender               => $::form->{email_sender},
2050                  email_subject              => $::form->{email_subject},
2051                  email_body                 => $::form->{email_body},
2052                };
2053
2054   $::form->{periodic_invoices_config} = YAML::Dump($config);
2055
2056   $::form->{title} = $::locale->text('Edit the configuration for periodic invoices');
2057   $::form->header;
2058   print $::form->parse_html_template('oe/save_periodic_invoices_config', $config);
2059
2060   $::lxdebug->leave_sub();
2061 }
2062
2063 sub _remove_full_delivered_rows {
2064
2065   my @fields = map { s/_1$//; $_ } grep { m/_1$/ } keys %{ $::form };
2066   my @new_rows;
2067
2068   my $removed_rows = 0;
2069   my $row          = 0;
2070   while ($row < $::form->{rowcount}) {
2071     $row++;
2072     next unless $::form->{"id_$row"};
2073     my $base_factor = SL::DB::Manager::Unit->find_by(name => $::form->{"unit_$row"})->base_factor;
2074     my $base_qty = $::form->parse_amount(\%::myconfig, $::form->{"qty_$row"}) *  $base_factor;
2075     my $ship_qty = $::form->parse_amount(\%::myconfig, $::form->{"ship_$row"}) *  $base_factor;
2076     #$main::lxdebug->message(LXDebug->DEBUG2(),"shipto=".$ship_qty." qty=".$base_qty);
2077
2078     if (!$ship_qty || ($ship_qty < $base_qty)) {
2079       $::form->{"qty_$row"}  = $::form->format_amount(\%::myconfig, ($base_qty - $ship_qty) / $base_factor );
2080       $::form->{"ship_$row"} = 0;
2081       push @new_rows, { map { $_ => $::form->{"${_}_${row}"} } @fields };
2082
2083     } else {
2084       $removed_rows++;
2085     }
2086   }
2087   $::form->redo_rows(\@fields, \@new_rows, scalar(@new_rows), $::form->{rowcount});
2088   $::form->{rowcount} -= $removed_rows;
2089 }
2090
2091 sub _oe_remove_delivered_or_billed_rows {
2092   my (%params) = @_;
2093
2094   return if !$params{id} || !$params{type};
2095
2096   my $ord_quot = SL::DB::Order->new(id => $params{id})->load;
2097   return if !$ord_quot;
2098
2099   # Prüfung ob itemlinks existieren, falls ja dann neue Implementierung
2100
2101   if (  $params{type} eq 'delivered' ) {
2102       my $orderitem = SL::DB::Manager::OrderItem->get_first( where => [trans_id => $ord_quot->id]);
2103       if ( $orderitem) {
2104           my @links = $orderitem->linked_records(to => 'SL::DB::DeliveryOrderItem');
2105           if ( scalar(@links ) > 0 ) {
2106               #$main::lxdebug->message(LXDebug->DEBUG2(),"item recordlinks vorhanden");
2107               return _remove_full_delivered_rows();
2108           }
2109       }
2110   }
2111   my %args    = (
2112     direction => 'to',
2113     to        =>   $params{type} eq 'delivered' ? 'DeliveryOrder' : 'Invoice',
2114     via       => [ $params{type} eq 'delivered' ? qw(Order)       : qw(Order DeliveryOrder) ],
2115   );
2116
2117   my %handled_base_qtys;
2118   foreach my $record (@{ $ord_quot->linked_records(%args) }) {
2119     next if $ord_quot->is_sales != $record->is_sales;
2120     next if $record->type eq 'invoice' && $record->storno;
2121
2122     foreach my $item (@{ $record->items }) {
2123       my $key  = $item->parts_id;
2124       $key    .= ':' . $item->serialnumber if $item->serialnumber;
2125       $handled_base_qtys{$key} += $item->qty * $item->unit_obj->base_factor;
2126     }
2127   }
2128
2129   _remove_billed_or_delivered_rows(quantities => \%handled_base_qtys);
2130 }
2131
2132 # iterate all positions and match articlenumber
2133 sub check_transport_cost_reminder_article_number {
2134   $main::lxdebug->enter_sub();
2135
2136   my $form     = $main::form;
2137
2138   check_oe_access();
2139
2140   my $transport_article_id = $::instance_conf->get_transport_cost_reminder_article_number_id;
2141   for my $i (1 .. $form->{rowcount}) {
2142     return if $form->{"id_${i}"} eq $transport_article_id;
2143   }
2144
2145   # simply return the name of the part
2146   return SL::DB::Part->new(id => $transport_article_id)->load()->partnumber;
2147
2148   $main::lxdebug->leave_sub();
2149 }
2150 sub dispatcher {
2151   foreach my $action (qw(delete delivery_order e_mail invoice print purchase_order quotation
2152                          request_for_quotation sales_order save save_and_close save_as_new ship_to update)) {
2153     if ($::form->{"action_${action}"}) {
2154       call_sub($action);
2155       return;
2156     }
2157   }
2158
2159   $::form->error($::locale->text('No action defined.'));
2160 }