Angebots/Auftragssuche: keine Multibox verwenden
[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   $::request->{layout}->use_javascript(map { "${_}.js" } qw(autocomplete_project));
797
798   $form->header();
799
800   print $form->parse_html_template('oe/search', {
801     is_order => scalar($form->{type} =~ /_order/),
802   });
803
804   $main::lxdebug->leave_sub();
805 }
806
807 sub create_subtotal_row {
808   $main::lxdebug->enter_sub();
809
810   my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
811
812   my $form     = $main::form;
813   my %myconfig = %main::myconfig;
814
815   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
816
817   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
818
819   $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
820
821   map { $totals->{$_} = 0 } @{ $subtotal_columns };
822
823   $main::lxdebug->leave_sub();
824
825   return $row;
826 }
827
828 sub orders {
829   $main::lxdebug->enter_sub();
830
831   my $form     = $main::form;
832   my %myconfig = %main::myconfig;
833   my $locale   = $main::locale;
834   my $cgi      = $::request->{cgi};
835
836   check_oe_access();
837
838   my $ordnumber = ($form->{type} =~ /_order$/) ? "ordnumber" : "quonumber";
839
840   ($form->{ $form->{vc} }, $form->{"$form->{vc}_id"}) = split(/--/, $form->{ $form->{vc} });
841
842   report_generator_set_default_sort('transdate', 1);
843
844   OE->transactions(\%myconfig, \%$form);
845
846   $form->{rowcount} = scalar @{ $form->{OE} };
847
848   my @columns = (
849     "transdate",               "reqdate",
850     "id",                      $ordnumber,             "edit_exp",
851     "cusordnumber",            "customernumber",
852     "name",                    "netamount",
853     "tax",                     "amount",
854     "remaining_netamount",     "remaining_amount",
855     "curr",                    "employee",
856     "salesman",
857     "shipvia",                 "globalprojectnumber",
858     "transaction_description", "open",
859     "delivered",               "periodic_invoices",
860     "marge_total",             "marge_percent",
861     "vcnumber",                "ustid",
862     "country",                 "shippingpoint",
863     "taxzone",                 "insertdate",
864     "order_probability",       "expected_billing_date", "expected_netamount",
865     "payment_terms",
866   );
867
868   # only show checkboxes if gotten here via sales_order form.
869   my $allow_multiple_orders = $form->{type} eq 'sales_order';
870   if ($allow_multiple_orders) {
871     unshift @columns, "ids";
872   }
873
874   $form->{l_open}              = $form->{l_closed} = "Y" if ($form->{open}      && $form->{closed});
875   $form->{l_delivered}         = "Y"                     if ($form->{delivered} && $form->{notdelivered});
876   $form->{l_periodic_invoices} = "Y"                     if ($form->{periodic_invoices_active} && $form->{periodic_invoices_inactive});
877   $form->{l_edit_exp}          = "Y"                     if (any { $form->{type} eq $_ } qw(sales_order purchase_order));
878   map { $form->{"l_${_}"} = 'Y' } qw(order_probability expected_billing_date expected_netamount) if $form->{l_order_probability_expected_billing_date};
879
880   my $attachment_basename;
881   if ($form->{vc} eq 'vendor') {
882     if ($form->{type} eq 'purchase_order') {
883       $form->{title}       = $locale->text('Purchase Orders');
884       $attachment_basename = $locale->text('purchase_order_list');
885     } else {
886       $form->{title}       = $locale->text('Request for Quotations');
887       $attachment_basename = $locale->text('rfq_list');
888     }
889
890   } else {
891     if ($form->{type} eq 'sales_order') {
892       $form->{title}       = $locale->text('Sales Orders');
893       $attachment_basename = $locale->text('sales_order_list');
894     } else {
895       $form->{title}       = $locale->text('Quotations');
896       $attachment_basename = $locale->text('quotation_list');
897     }
898   }
899
900   my $report = SL::ReportGenerator->new(\%myconfig, $form);
901
902   my $ct_cvar_configs = CVar->get_configs('module' => 'CT');
903   my @ct_includeable_custom_variables = grep { $_->{includeable} } @{ $ct_cvar_configs };
904   my @ct_searchable_custom_variables  = grep { $_->{searchable} }  @{ $ct_cvar_configs };
905
906   my %column_defs_cvars            = map { +"cvar_$_->{name}" => { 'text' => $_->{description} } } @ct_includeable_custom_variables;
907   push @columns, map { "cvar_$_->{name}" } @ct_includeable_custom_variables;
908
909   my @hidden_variables = map { "l_${_}" } @columns;
910   push @hidden_variables, "l_subtotal", $form->{vc}, qw(l_closed l_notdelivered open closed delivered notdelivered ordnumber quonumber cusordnumber
911                                                         transaction_description transdatefrom transdateto type vc employee_id salesman_id
912                                                         reqdatefrom reqdateto projectnumber project_id periodic_invoices_active periodic_invoices_inactive
913                                                         business_id shippingpoint taxzone_id reqdate_unset_or_old insertdatefrom insertdateto
914                                                         order_probability_op order_probability_value expected_billing_date_from expected_billing_date_to
915                                                         parts_partnumber parts_description all department_id);
916   push @hidden_variables, map { "cvar_$_->{name}" } @ct_searchable_custom_variables;
917
918   my   @keys_for_url = grep { $form->{$_} } @hidden_variables;
919   push @keys_for_url, 'taxzone_id' if $form->{taxzone_id} ne ''; # taxzone_id could be 0
920
921   my $href = build_std_url('action=orders', @keys_for_url);
922
923   my %column_defs = (
924     'ids'                     => { 'text' => '', },
925     'transdate'               => { 'text' => $locale->text('Date'), },
926     'reqdate'                 => { 'text' => $form->{type} =~ /_order/ ? $locale->text('Required by') : $locale->text('Valid until') },
927     'id'                      => { 'text' => $locale->text('ID'), },
928     'ordnumber'               => { 'text' => $locale->text('Order'), },
929     'quonumber'               => { 'text' => $form->{type} eq "request_quotation" ? $locale->text('RFQ') : $locale->text('Quotation'), },
930     'cusordnumber'            => { 'text' => $locale->text('Customer Order Number'), },
931     'name'                    => { 'text' => $form->{vc} eq 'customer' ? $locale->text('Customer') : $locale->text('Vendor'), },
932     'customernumber'          => { 'text' => $locale->text('Customer Number'), },
933     'netamount'               => { 'text' => $locale->text('Amount'), },
934     'tax'                     => { 'text' => $locale->text('Tax'), },
935     'amount'                  => { 'text' => $locale->text('Total'), },
936     'remaining_amount'        => { 'text' => $locale->text('Remaining Amount'), },
937     'remaining_netamount'     => { 'text' => $locale->text('Remaining Net Amount'), },
938     'curr'                    => { 'text' => $locale->text('Curr'), },
939     'employee'                => { 'text' => $locale->text('Employee'), },
940     'salesman'                => { 'text' => $locale->text('Salesman'), },
941     'shipvia'                 => { 'text' => $locale->text('Ship via'), },
942     'globalprojectnumber'     => { 'text' => $locale->text('Project Number'), },
943     'transaction_description' => { 'text' => $locale->text('Transaction description'), },
944     'open'                    => { 'text' => $locale->text('Open'), },
945     'delivered'               => { 'text' => $locale->text('Delivery Order created'), },
946     'marge_total'             => { 'text' => $locale->text('Ertrag'), },
947     'marge_percent'           => { 'text' => $locale->text('Ertrag prozentual'), },
948     'vcnumber'                => { 'text' => $form->{vc} eq 'customer' ? $locale->text('Customer Number') : $locale->text('Vendor Number'), },
949     'country'                 => { 'text' => $locale->text('Country'), },
950     'ustid'                   => { 'text' => $locale->text('USt-IdNr.'), },
951     'periodic_invoices'       => { 'text' => $locale->text('Per. Inv.'), },
952     'shippingpoint'           => { 'text' => $locale->text('Shipping Point'), },
953     'taxzone'                 => { 'text' => $locale->text('Steuersatz'), },
954     'insertdate'              => { 'text' => $locale->text('Insert Date'), },
955     'order_probability'       => { 'text' => $locale->text('Order probability'), },
956     'expected_billing_date'   => { 'text' => $locale->text('Exp. bill. date'), },
957     'expected_netamount'      => { 'text' => $locale->text('Exp. netamount'), },
958     'payment_terms'           => { 'text' => $locale->text('Payment Terms'), },
959     'edit_exp'                => { 'text' => $locale->text('Edit (experimental)'), },
960     %column_defs_cvars,
961   );
962
963   foreach my $name (qw(id transdate reqdate quonumber ordnumber cusordnumber name employee salesman shipvia transaction_description shippingpoint taxzone insertdate payment_terms)) {
964     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
965     $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
966   }
967
968   my %column_alignment = map { $_ => 'right' } qw(netamount tax amount curr remaining_amount remaining_netamount order_probability expected_billing_date expected_netamount);
969
970   $form->{"l_type"} = "Y";
971   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
972   $column_defs{ids}->{visible} = $allow_multiple_orders ? 'HTML' : 0;
973
974   $report->set_columns(%column_defs);
975   $report->set_column_order(@columns);
976   $report->set_export_options('orders', @hidden_variables, qw(sort sortdir));
977   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
978
979   CVar->add_custom_variables_to_report('module'         => 'CT',
980                                        'trans_id_field' => "$form->{vc}_id",
981                                        'configs'        => $ct_cvar_configs,
982                                        'column_defs'    => \%column_defs,
983                                        'data'           => $form->{OE});
984
985   my @options;
986
987   push @options, $locale->text('Customer')                . " : $form->{customer}"                        if $form->{customer};
988   push @options, $locale->text('Vendor')                  . " : $form->{vendor}"                          if $form->{vendor};
989   push @options, $locale->text('Contact Person')          . " : $form->{cp_name}"                         if $form->{cp_name};
990   push @options, $locale->text('Department')              . " : $form->{department}"                      if $form->{department};
991   push @options, $locale->text('Order Number')            . " : $form->{ordnumber}"                       if $form->{ordnumber};
992   push @options, $locale->text('Customer Order Number')   . " : $form->{cusordnumber}"                    if $form->{cusordnumber};
993   push @options, $locale->text('Notes')                   . " : $form->{notes}"                           if $form->{notes};
994   push @options, $locale->text('Transaction description') . " : $form->{transaction_description}"         if $form->{transaction_description};
995   push @options, $locale->text('Quick Search')            . " : $form->{all}"                             if $form->{all};
996   push @options, $locale->text('Shipping Point')          . " : $form->{shippingpoint}"                   if $form->{shippingpoint};
997   push @options, $locale->text('Part Description')        . " : $form->{parts_description}"               if $form->{parts_description};
998   push @options, $locale->text('Part Number')             . " : $form->{parts_partnumber}"                if $form->{parts_partnumber};
999   if ( $form->{transdatefrom} or $form->{transdateto} ) {
1000     push @options, $locale->text('Order Date');
1001     push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1)     if $form->{transdatefrom};
1002     push @options, $locale->text('Bis')  . " " . $locale->date(\%myconfig, $form->{transdateto},   1)     if $form->{transdateto};
1003   };
1004   if ( $form->{reqdatefrom} or $form->{reqdateto} ) {
1005     push @options, $locale->text('Delivery Date');
1006     push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{reqdatefrom}, 1)       if $form->{reqdatefrom};
1007     push @options, $locale->text('Bis')  . " " . $locale->date(\%myconfig, $form->{reqdateto},   1)       if $form->{reqdateto};
1008   };
1009   if ( $form->{insertdatefrom} or $form->{insertdateto} ) {
1010     push @options, $locale->text('Insert Date');
1011     push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{insertdatefrom}, 1)    if $form->{insertdatefrom};
1012     push @options, $locale->text('Bis')  . " " . $locale->date(\%myconfig, $form->{insertdateto},   1)    if $form->{insertdateto};
1013   };
1014   push @options, $locale->text('Open')                                                                    if $form->{open};
1015   push @options, $locale->text('Closed')                                                                  if $form->{closed};
1016   push @options, $locale->text('Delivery Order created')                                                               if $form->{delivered};
1017   push @options, $locale->text('Not delivered')                                                           if $form->{notdelivered};
1018   push @options, $locale->text('Periodic invoices active')                                                if $form->{periodic_invoices_active};
1019   push @options, $locale->text('Reqdate not set or before current month')                                 if $form->{reqdate_unset_or_old};
1020
1021   if ($form->{business_id}) {
1022     my $vc_type_label = $form->{vc} eq 'customer' ? $locale->text('Customer type') : $locale->text('Vendor type');
1023     push @options, $vc_type_label . " : " . SL::DB::Business->new(id => $form->{business_id})->load->description;
1024   }
1025   if ($form->{taxzone_id} ne '') { # taxzone_id could be 0
1026     push @options, $locale->text('Steuersatz') . " : " . SL::DB::TaxZone->new(id => $form->{taxzone_id})->load->description;
1027   }
1028
1029   if ($form->{department_id}) {
1030     push @options, $locale->text('Department') . " : " . SL::DB::Department->new(id => $form->{department_id})->load->description;
1031   }
1032
1033   if (($form->{order_probability_value} || '') ne '') {
1034     push @options, $::locale->text('Order probability') . ' ' . ($form->{order_probability_op} eq 'le' ? '<=' : '>=') . ' ' . $form->{order_probability_value} . '%';
1035   }
1036
1037   if ($form->{expected_billing_date_from} or $form->{expected_billing_date_to}) {
1038     push @options, $locale->text('Expected billing date');
1039     push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{expected_billing_date_from}, 1) if $form->{expected_billing_date_from};
1040     push @options, $locale->text('Bis')  . " " . $locale->date(\%myconfig, $form->{expected_billing_date_to},   1) if $form->{expected_billing_date_to};
1041   }
1042
1043   $report->set_options('top_info_text'        => join("\n", @options),
1044                        'raw_top_info_text'    => $form->parse_html_template('oe/orders_top'),
1045                        'raw_bottom_info_text' => $form->parse_html_template('oe/orders_bottom', { 'SHOW_CONTINUE_BUTTON' => $allow_multiple_orders }),
1046                        'output_format'        => 'HTML',
1047                        'title'                => $form->{title},
1048                        'attachment_basename'  => $attachment_basename . strftime('_%Y%m%d', localtime time),
1049     );
1050   $report->set_options_from_form();
1051   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
1052
1053   # add sort and escape callback, this one we use for the add sub
1054   $form->{callback} = $href .= "&sort=$form->{sort}";
1055
1056   # escape callback for href
1057   my $callback = $form->escape($href);
1058
1059   my @subtotal_columns = qw(netamount amount marge_total marge_percent remaining_amount remaining_netamount);
1060   push @subtotal_columns, 'expected_netamount' if $form->{l_order_probability_expected_billing_date};
1061
1062   my %totals    = map { $_ => 0 } @subtotal_columns;
1063   my %subtotals = map { $_ => 0 } @subtotal_columns;
1064
1065   my $idx = 1;
1066
1067   my $edit_url = build_std_url('action=edit', 'type', 'vc');
1068
1069   foreach my $oe (@{ $form->{OE} }) {
1070     map { $oe->{$_} *= $oe->{exchangerate} } @subtotal_columns;
1071
1072     $oe->{tax}               = $oe->{amount} - $oe->{netamount};
1073     $oe->{open}              = $oe->{closed}            ? $locale->text('No')  : $locale->text('Yes');
1074     $oe->{delivered}         = $oe->{delivered}         ? $locale->text('Yes') : $locale->text('No');
1075     $oe->{periodic_invoices} = $oe->{periodic_invoices} ? $locale->text('On')  : $locale->text('Off');
1076
1077     map { $subtotals{$_} += $oe->{$_};
1078           $totals{$_}    += $oe->{$_} } @subtotal_columns;
1079
1080     $subtotals{marge_percent} = $subtotals{netamount} ? ($subtotals{marge_total} * 100 / $subtotals{netamount}) : 0;
1081     $totals{marge_percent}    = $totals{netamount}    ? ($totals{marge_total}    * 100 / $totals{netamount}   ) : 0;
1082
1083     map { $oe->{$_} = $form->format_amount(\%myconfig, $oe->{$_}, 2) } qw(netamount tax amount marge_total marge_percent remaining_amount remaining_netamount expected_netamount);
1084
1085     $oe->{order_probability} = ($oe->{order_probability} || 0) . '%';
1086
1087     my $row = { };
1088
1089     foreach my $column (@columns) {
1090       next if ($column eq 'ids');
1091       next if ($column eq 'edit_exp');
1092       $row->{$column} = {
1093         'data'  => $oe->{$column},
1094         'align' => $column_alignment{$column},
1095       };
1096     }
1097
1098     $row->{ids} = {
1099       'raw_data' =>   $cgi->hidden('-name' => "trans_id_${idx}", '-value' => $oe->{id})
1100                     . $cgi->checkbox('-name' => "multi_id_${idx}", '-value' => 1, '-label' => ''),
1101       'valign'   => 'center',
1102       'align'    => 'center',
1103     };
1104
1105     $row->{$ordnumber}->{link} = $edit_url . "&id=" . E($oe->{id}) . "&callback=${callback}";
1106
1107     $row->{edit_exp}->{data}   = $oe->{ordnumber};
1108     $row->{edit_exp}->{link}   = build_std_url('script=controller.pl', 'action=Order/edit', "type=$form->{type}", 'id=' . E($oe->{id}));
1109
1110     my $row_set = [ $row ];
1111
1112     if (($form->{l_subtotal} eq 'Y')
1113         && (($idx == (scalar @{ $form->{OE} }))
1114             || ($oe->{ $form->{sort} } ne $form->{OE}->[$idx]->{ $form->{sort} }))) {
1115       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
1116     }
1117
1118     $report->add_data($row_set);
1119
1120     $idx++;
1121   }
1122
1123   $report->add_separator();
1124   $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
1125
1126   $report->generate_with_headers();
1127
1128   $main::lxdebug->leave_sub();
1129 }
1130
1131 sub check_delivered_flag {
1132   $main::lxdebug->enter_sub();
1133
1134   my $form     = $main::form;
1135   my %myconfig = %main::myconfig;
1136
1137   check_oe_access();
1138
1139   if (($form->{type} ne 'sales_order') && ($form->{type} ne 'purchase_order')) {
1140     return $main::lxdebug->leave_sub();
1141   }
1142
1143   my $all_delivered = 0;
1144
1145   foreach my $i (1 .. $form->{rowcount}) {
1146     next if (!$form->{"id_$i"});
1147
1148     if ($form->parse_amount(\%myconfig, $form->{"qty_$i"}) == $form->parse_amount(\%myconfig, $form->{"ship_$i"})) {
1149       $all_delivered = 1;
1150       next;
1151     }
1152
1153     $all_delivered = 0;
1154     last;
1155   }
1156
1157   $form->{delivered} = 1 if $all_delivered;
1158
1159   $main::lxdebug->leave_sub();
1160 }
1161
1162 sub save_and_close {
1163   $main::lxdebug->enter_sub();
1164
1165   my $form     = $main::form;
1166   my %myconfig = %main::myconfig;
1167   my $locale   = $main::locale;
1168
1169   check_oe_access();
1170   $form->mtime_ischanged('oe');
1171
1172   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
1173
1174   if ($form->{type} =~ /_order$/) {
1175     $form->isblank("transdate", $locale->text('Order Date missing!'));
1176   } else {
1177     $form->isblank("transdate", $locale->text('Quotation Date missing!'));
1178   }
1179
1180   my $idx = $form->{type} =~ /_quotation$/ ? "quonumber" : "ordnumber";
1181   $form->{$idx} =~ s/^\s*//g;
1182   $form->{$idx} =~ s/\s*$//g;
1183
1184   my $msg = ucfirst $form->{vc};
1185   $form->isblank($form->{vc}, $locale->text($msg . " missing!"));
1186
1187   # $locale->text('Customer missing!');
1188   # $locale->text('Vendor missing!');
1189
1190   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
1191     if ($form->{currency} ne $form->{defaultcurrency});
1192
1193   &validate_items;
1194
1195   my $payment_id;
1196   if($form->{payment_id}) {
1197     $payment_id = $form->{payment_id};
1198   }
1199
1200   # if the name changed get new values
1201   if (&check_name($form->{vc})) {
1202     if($form->{payment_id} eq "") {
1203       $form->{payment_id} = $payment_id;
1204     }
1205     &update;
1206     $::dispatcher->end_request;
1207   }
1208
1209   $form->{id} = 0 if $form->{saveasnew};
1210
1211   my ($numberfld, $ordnumber, $err);
1212   # this is for the internal notes section for the [email] Subject
1213   if ($form->{type} =~ /_order$/) {
1214     if ($form->{type} eq 'sales_order') {
1215       $form->{label} = $locale->text('Sales Order');
1216
1217       $numberfld = "sonumber";
1218       $ordnumber = "ordnumber";
1219     } else {
1220       $form->{label} = $locale->text('Purchase Order');
1221
1222       $numberfld = "ponumber";
1223       $ordnumber = "ordnumber";
1224     }
1225
1226     $err = $locale->text('Cannot save order!');
1227
1228     check_delivered_flag();
1229
1230   } else {
1231     if ($form->{type} eq 'sales_quotation') {
1232       $form->{label} = $locale->text('Quotation');
1233
1234       $numberfld = "sqnumber";
1235       $ordnumber = "quonumber";
1236     } else {
1237       $form->{label} = $locale->text('Request for Quotation');
1238
1239       $numberfld = "rfqnumber";
1240       $ordnumber = "quonumber";
1241     }
1242
1243     $err = $locale->text('Cannot save quotation!');
1244
1245   }
1246
1247   # get new number in sequence if saveasnew was requested
1248   delete $form->{$ordnumber} if $form->{saveasnew};
1249
1250   relink_accounts();
1251
1252   $form->error($err) if (!OE->save(\%myconfig, \%$form));
1253
1254   # saving the history
1255   if(!exists $form->{addition}) {
1256     $form->{snumbers} = qq|ordnumber_| . $form->{ordnumber};
1257     $form->{addition} = "SAVED";
1258     $form->save_history;
1259   }
1260   # /saving the history
1261
1262   $form->redirect($form->{label} . " $form->{$ordnumber} " .
1263                   $locale->text('saved!'));
1264
1265   $main::lxdebug->leave_sub();
1266 }
1267
1268 sub save {
1269   $main::lxdebug->enter_sub();
1270
1271   my $form     = $main::form;
1272   my %myconfig = %main::myconfig;
1273   my $locale   = $main::locale;
1274
1275   check_oe_access();
1276
1277   $form->mtime_ischanged('oe');
1278   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
1279
1280
1281   if ($form->{type} =~ /_order$/) {
1282     $form->isblank("transdate", $locale->text('Order Date missing!'));
1283   } else {
1284     $form->isblank("transdate", $locale->text('Quotation Date missing!'));
1285   }
1286
1287   my $idx = $form->{type} =~ /_quotation$/ ? "quonumber" : "ordnumber";
1288   $form->{$idx} =~ s/^\s*//g;
1289   $form->{$idx} =~ s/\s*$//g;
1290
1291   my $msg = ucfirst $form->{vc};
1292   $form->isblank($form->{vc}, $locale->text($msg . " missing!"));
1293
1294   # $locale->text('Customer missing!');
1295   # $locale->text('Vendor missing!');
1296
1297   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
1298     if ($form->{currency} ne $form->{defaultcurrency});
1299
1300   remove_emptied_rows();
1301   &validate_items;
1302
1303   my $payment_id;
1304   if($form->{payment_id}) {
1305     $payment_id = $form->{payment_id};
1306   }
1307
1308   # if the name changed get new values
1309   if (&check_name($form->{vc})) {
1310     if($form->{payment_id} eq "") {
1311       $form->{payment_id} = $payment_id;
1312     }
1313     &update;
1314     $::dispatcher->end_request;
1315   }
1316
1317   $form->{id} = 0 if $form->{saveasnew};
1318
1319   my ($numberfld, $ordnumber, $err);
1320
1321   # this is for the internal notes section for the [email] Subject
1322   if ($form->{type} =~ /_order$/) {
1323     if ($form->{type} eq 'sales_order') {
1324       $form->{label} = $locale->text('Sales Order');
1325
1326       $numberfld = "sonumber";
1327       $ordnumber = "ordnumber";
1328     } else {
1329       $form->{label} = $locale->text('Purchase Order');
1330
1331       $numberfld = "ponumber";
1332       $ordnumber = "ordnumber";
1333     }
1334
1335     $err = $locale->text('Cannot save order!');
1336
1337     check_delivered_flag();
1338
1339   } else {
1340     if ($form->{type} eq 'sales_quotation') {
1341       $form->{label} = $locale->text('Quotation');
1342
1343       $numberfld = "sqnumber";
1344       $ordnumber = "quonumber";
1345     } else {
1346       $form->{label} = $locale->text('Request for Quotation');
1347
1348       $numberfld = "rfqnumber";
1349       $ordnumber = "quonumber";
1350     }
1351
1352     $err = $locale->text('Cannot save quotation!');
1353
1354   }
1355
1356   relink_accounts();
1357
1358   OE->save(\%myconfig, \%$form);
1359
1360   # saving the history
1361   if(!exists $form->{addition}) {
1362     if ( $form->{formname} eq 'sales_quotation' or  $form->{formname} eq 'request_quotation' ) {
1363         $form->{snumbers} = qq|quonumber_| . $form->{quonumber};
1364     } elsif ( $form->{formname} eq 'sales_order' or $form->{formname} eq 'purchase_order') {
1365         $form->{snumbers} = qq|ordnumber_| . $form->{ordnumber};
1366     };
1367     $form->{what_done} = $form->{formname};
1368     $form->{addition} = "SAVED";
1369     $form->save_history;
1370   }
1371   # /saving the history
1372
1373   $form->{simple_save} = 1;
1374   if(!$form->{print_and_save}) {
1375     delete @{$form}{ary_diff([keys %{ $form }], [qw(login id script type cursor_fokus)])};
1376     edit();
1377     $::dispatcher->end_request;
1378   }
1379   $main::lxdebug->leave_sub();
1380 }
1381
1382 sub delete {
1383   $main::lxdebug->enter_sub();
1384
1385   my $form     = $main::form;
1386   my %myconfig = %main::myconfig;
1387   my $locale   = $main::locale;
1388
1389   check_oe_access();
1390
1391   my ($msg, $err);
1392   if ($form->{type} =~ /_order$/) {
1393     $msg = $locale->text('Order deleted!');
1394     $err = $locale->text('Cannot delete order!');
1395   } else {
1396     $msg = $locale->text('Quotation deleted!');
1397     $err = $locale->text('Cannot delete quotation!');
1398   }
1399   if (OE->delete(\%myconfig, \%$form)){
1400     # saving the history
1401     if(!exists $form->{addition}) {
1402       if ( $form->{formname} eq 'sales_quotation' or  $form->{formname} eq 'request_quotation' ) {
1403           $form->{snumbers} = qq|quonumber_| . $form->{quonumber};
1404       } elsif ( $form->{formname} eq 'sales_order' or $form->{formname} eq 'purchase_order') {
1405           $form->{snumbers} = qq|ordnumber_| . $form->{ordnumber};
1406       };
1407         $form->{what_done} = $form->{formname};
1408         $form->{addition} = "DELETED";
1409         $form->save_history;
1410     }
1411     # /saving the history
1412     $form->info($msg);
1413     $::dispatcher->end_request;
1414   }
1415   $form->error($err);
1416
1417   $main::lxdebug->leave_sub();
1418 }
1419
1420 sub invoice {
1421   $main::lxdebug->enter_sub();
1422
1423   my $form     = $main::form;
1424   my %myconfig = %main::myconfig;
1425   my $locale   = $main::locale;
1426
1427   check_oe_access();
1428   check_oe_conversion_to_sales_invoice_allowed();
1429   $form->mtime_ischanged('oe');
1430
1431   $main::auth->assert($form->{type} eq 'purchase_order' || $form->{type} eq 'request_quotation' ? 'vendor_invoice_edit' : 'invoice_edit');
1432
1433   $form->{old_salesman_id} = $form->{salesman_id};
1434   $form->get_employee();
1435
1436
1437   if ($form->{type} =~ /_order$/) {
1438
1439     # these checks only apply if the items don't bring their own ordnumbers/transdates.
1440     # The if clause ensures that by searching for empty ordnumber_#/transdate_# fields.
1441     $form->isblank("ordnumber", $locale->text('Order Number missing!'))
1442       if (+{ map { $form->{"ordnumber_$_"}, 1 } (1 .. $form->{rowcount} - 1) }->{''});
1443     $form->isblank("transdate", $locale->text('Order Date missing!'))
1444       if (+{ map { $form->{"transdate_$_"}, 1 } (1 .. $form->{rowcount} - 1) }->{''});
1445
1446     # also copy deliverydate from the order
1447     $form->{deliverydate} = $form->{reqdate} if $form->{reqdate};
1448     $form->{orddate}      = $form->{transdate};
1449   } else {
1450     $form->isblank("quonumber", $locale->text('Quotation Number missing!'));
1451     $form->isblank("transdate", $locale->text('Quotation Date missing!'));
1452     $form->{ordnumber}    = "";
1453     $form->{quodate}      = $form->{transdate};
1454   }
1455
1456   my $payment_id;
1457   if ($form->{payment_id}) {
1458     $payment_id = $form->{payment_id};
1459   }
1460
1461   # if the name changed get new values
1462   if (&check_name($form->{vc})) {
1463     $form->{payment_id} = $payment_id if $form->{payment_id} eq "";
1464     &update;
1465     $::dispatcher->end_request;
1466   }
1467
1468   _oe_remove_delivered_or_billed_rows(id => $form->{id}, type => 'billed');
1469
1470   $form->{cp_id} *= 1;
1471
1472   for my $i (1 .. $form->{rowcount}) {
1473     for (qw(ship qty sellprice basefactor discount)) {
1474       $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig, $form->{"${_}_${i}"}) if $form->{"${_}_${i}"};
1475     }
1476     $form->{"converted_from_orderitems_id_$i"} = delete $form->{"orderitems_id_$i"};
1477   }
1478
1479   my ($buysell, $orddate, $exchangerate);
1480   if (   $form->{type} =~ /_order/
1481       && $form->{currency} ne $form->{defaultcurrency}) {
1482
1483     # check if we need a new exchangerate
1484     $buysell = ($form->{type} eq 'sales_order') ? "buy" : "sell";
1485
1486     $orddate      = $form->current_date(\%myconfig);
1487     $exchangerate = $form->check_exchangerate(\%myconfig, $form->{currency}, $orddate, $buysell);
1488
1489     if (!$exchangerate) {
1490       $exchangerate = 0;
1491     }
1492   }
1493
1494   $form->{convert_from_oe_ids} = $form->{id};
1495   $form->{transdate}           = $form->{invdate} = $form->current_date(\%myconfig);
1496   $form->{duedate}             = $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
1497   $form->{defaultcurrency}     = $form->get_default_currency(\%myconfig);
1498
1499   delete @{$form}{qw(id closed)};
1500   $form->{rowcount}--;
1501
1502   my ($script);
1503   if (   $form->{type} eq 'purchase_order'
1504       || $form->{type} eq 'request_quotation') {
1505     $form->{title}  = $locale->text('Add Vendor Invoice');
1506     $form->{script} = 'ir.pl';
1507     $script         = "ir";
1508     $buysell        = 'sell';
1509   }
1510
1511   if (   $form->{type} eq 'sales_order'
1512       || $form->{type} eq 'sales_quotation') {
1513     $form->{title}  = $locale->text('Add Sales Invoice');
1514     $form->{script} = 'is.pl';
1515     $script         = "is";
1516     $buysell        = 'buy';
1517   }
1518
1519   # bo creates the id, reset it
1520   map { delete $form->{$_} } qw(id subject message cc bcc printed emailed queued);
1521   $form->{ $form->{vc} } =~ s/--.*//g;
1522   $form->{type} = "invoice";
1523
1524   # locale messages
1525   $main::locale = Locale->new("$myconfig{countrycode}", "$script");
1526   $locale = $main::locale;
1527
1528   require "bin/mozilla/$form->{script}";
1529
1530   map { $form->{"select$_"} = "" } ($form->{vc}, "currency");
1531
1532   my $currency = $form->{currency};
1533   &invoice_links;
1534
1535   $form->{currency}     = $currency;
1536   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{invdate}, $buysell);
1537   $form->{exchangerate} = $form->{forex} || '';
1538
1539   $form->{creditremaining} -= ($form->{oldinvtotal} - $form->{ordtotal});
1540
1541   &prepare_invoice;
1542
1543   # format amounts
1544   for my $i (1 .. $form->{rowcount}) {
1545     $form->{"discount_$i"} =
1546       $form->format_amount(\%myconfig, $form->{"discount_$i"});
1547
1548     my ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
1549     $dec           = length $dec;
1550     my $decimalplaces = ($dec > 2) ? $dec : 2;
1551
1552     # copy delivery date from reqdate for order -> invoice conversion
1553     $form->{"deliverydate_$i"} = $form->{"reqdate_$i"}
1554       unless $form->{"deliverydate_$i"};
1555
1556     $form->{"sellprice_$i"} =
1557       $form->format_amount(\%myconfig, $form->{"sellprice_$i"},
1558                            $decimalplaces);
1559
1560     (my $dec_qty) = ($form->{"qty_$i"} =~ /\.(\d+)/);
1561     $dec_qty = length $dec_qty;
1562     $form->{"qty_$i"} =
1563       $form->format_amount(\%myconfig, $form->{"qty_$i"}, $dec_qty);
1564   }
1565
1566   &display_form;
1567
1568   $main::lxdebug->leave_sub();
1569 }
1570
1571 sub save_exchangerate {
1572   $main::lxdebug->enter_sub();
1573
1574   my $form     = $main::form;
1575   my %myconfig = %main::myconfig;
1576   my $locale   = $main::locale;
1577
1578   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'));
1579   $form->{exchangerate} =
1580     $form->parse_amount(\%myconfig, $form->{exchangerate});
1581   $form->save_exchangerate(\%myconfig, $form->{currency},
1582                            $form->{exchangeratedate},
1583                            $form->{exchangerate}, $form->{buysell});
1584
1585   &invoice;
1586
1587   $main::lxdebug->leave_sub();
1588 }
1589
1590 sub save_as_new {
1591   $main::lxdebug->enter_sub();
1592
1593   my $form     = $main::form;
1594
1595   check_oe_access();
1596
1597   $form->{saveasnew} = 1;
1598   map { delete $form->{$_} } qw(printed emailed queued delivered closed);
1599   $form->{"converted_from_orderitems_id_$_"} = delete $form->{"orderitems_id_$_"} for 1 .. $form->{"rowcount"};
1600
1601   # Let kivitendo assign a new order number if the user hasn't changed the
1602   # previous one. If it has been changed manually then use it as-is.
1603   my $idx = $form->{type} =~ /_quotation$/ ? "quonumber" : "ordnumber";
1604   $form->{$idx} =~ s/^\s*//g;
1605   $form->{$idx} =~ s/\s*$//g;
1606   if ($form->{saved_xyznumber} &&
1607       ($form->{saved_xyznumber} eq $form->{$idx})) {
1608     delete($form->{$idx});
1609   }
1610
1611   # clear reqdate and transdate unless changed
1612   if ( $form->{reqdate} && $form->{id} ) {
1613     my $saved_order = OE->retrieve_simple(id => $form->{id});
1614     if ( $saved_order && $saved_order->{reqdate} eq $form->{reqdate} && $saved_order->{transdate} eq $form->{transdate} ) {
1615       my $extra_days     = $form->{type} eq 'sales_quotation' ? $::instance_conf->get_reqdate_interval : 1;
1616       $form->{reqdate}   = DateTime->today_local->next_workday(extra_days => $extra_days)->to_kivitendo;
1617       $form->{transdate} = DateTime->today_local->to_kivitendo;
1618     }
1619   }
1620
1621   # update employee
1622   $form->get_employee();
1623
1624   &save;
1625
1626   $main::lxdebug->leave_sub();
1627 }
1628
1629 sub check_for_direct_delivery_yes {
1630   $main::lxdebug->enter_sub();
1631
1632   my $form     = $main::form;
1633
1634   check_oe_access();
1635
1636   $form->{direct_delivery_checked} = 1;
1637   delete @{$form}{grep /^shipto/, keys %{ $form }};
1638   map { s/^CFDD_//; $form->{$_} = $form->{"CFDD_${_}"} } grep /^CFDD_/, keys %{ $form };
1639   $form->{CFDD_shipto} = 1;
1640   purchase_order();
1641   $main::lxdebug->leave_sub();
1642 }
1643
1644 sub check_for_direct_delivery_no {
1645   $main::lxdebug->enter_sub();
1646
1647   my $form     = $main::form;
1648
1649   check_oe_access();
1650
1651   $form->{direct_delivery_checked} = 1;
1652   delete @{$form}{grep /^shipto/, keys %{ $form }};
1653   $form->{CFDD_shipto} = 0;
1654   purchase_order();
1655
1656   $main::lxdebug->leave_sub();
1657 }
1658
1659 sub check_for_direct_delivery {
1660   $main::lxdebug->enter_sub();
1661
1662   my $form     = $main::form;
1663   my %myconfig = %main::myconfig;
1664
1665   check_oe_access();
1666
1667   if ($form->{direct_delivery_checked}
1668       || (!$form->{shiptoname} && !$form->{shiptostreet} && !$form->{shipto_id})) {
1669     $main::lxdebug->leave_sub();
1670     return;
1671   }
1672
1673   my $cvars = SL::DB::Shipto->new->cvars_by_config;
1674
1675   if ($form->{shipto_id}) {
1676     Common->get_shipto_by_id(\%myconfig, $form, $form->{shipto_id}, "CFDD_");
1677
1678   } else {
1679     map { $form->{"CFDD_${_}"} = $form->{$_ } } grep /^shipto/, keys %{ $form };
1680   }
1681
1682   $_->value($::form->{"CFDD_shiptocvar_" . $_->config->name}) for @{ $cvars };
1683
1684   delete $form->{action};
1685   $form->{VARIABLES} = [ map { { "key" => $_, "value" => $form->{$_} } } grep { ($_ ne 'login') && ($_ ne 'password') && (ref $_ eq "") } keys %{ $form } ];
1686
1687   $form->header();
1688   print $form->parse_html_template("oe/check_for_direct_delivery", { cvars => $cvars });
1689
1690   $main::lxdebug->leave_sub();
1691
1692   $::dispatcher->end_request;
1693 }
1694
1695 sub purchase_order {
1696   $main::lxdebug->enter_sub();
1697
1698   my $form     = $main::form;
1699   my $locale   = $main::locale;
1700
1701   check_oe_access();
1702   $form->mtime_ischanged('oe');
1703
1704   $main::auth->assert('purchase_order_edit');
1705
1706   $form->{sales_order_to_purchase_order} = 0;
1707   if ($form->{type} eq 'sales_order') {
1708     $form->{sales_order_to_purchase_order} = 1;
1709     check_for_direct_delivery();
1710   }
1711
1712   if ($form->{type} =~ /^sales_/) {
1713     delete($form->{ordnumber});
1714     delete($form->{payment_id});
1715     delete($form->{delivery_term_id});
1716   }
1717
1718   $form->{cp_id} *= 1;
1719
1720   my $source_type = $form->{type};
1721   $form->{title} = $locale->text('Add Purchase Order');
1722   $form->{vc}    = "vendor";
1723   $form->{type}  = "purchase_order";
1724
1725   $form->get_employee();
1726
1727   poso(source_type => $form->{type});
1728
1729   delete $form->{sales_order_to_purchase_order};
1730
1731   $main::lxdebug->leave_sub();
1732 }
1733
1734 sub sales_order {
1735   $main::lxdebug->enter_sub();
1736
1737   my $form     = $main::form;
1738   my $locale   = $main::locale;
1739
1740   check_oe_access();
1741   $main::auth->assert('sales_order_edit');
1742   $form->mtime_ischanged('oe');
1743
1744   if ($form->{type} eq "purchase_order") {
1745     delete($form->{ordnumber});
1746     $form->{"lastcost_$_"} = $form->{"sellprice_$_"} for (1..$form->{rowcount});
1747   }
1748
1749   $form->{cp_id} *= 1;
1750
1751   my $source_type = $form->{type};
1752   $form->{title}  = $locale->text('Add Sales Order');
1753   $form->{vc}     = "customer";
1754   $form->{type}   = "sales_order";
1755
1756   $form->get_employee();
1757
1758   poso(source_type => $source_type);
1759
1760   $main::lxdebug->leave_sub();
1761 }
1762
1763 sub poso {
1764   $main::lxdebug->enter_sub();
1765
1766   my %param    = @_;
1767   my $form     = $main::form;
1768   my %myconfig = %main::myconfig;
1769
1770   check_oe_access();
1771   $main::auth->assert('purchase_order_edit | sales_order_edit');
1772
1773   $form->{transdate} = $form->current_date(\%myconfig);
1774   delete $form->{duedate};
1775
1776   # "reqdate" is the validity date for a quotation and the delivery
1777   # date for an order. Therefore it makes no sense to keep the value
1778   # when converting from one into the other.
1779   delete $form->{reqdate} if ($param{source_type} =~ /_quotation$/) == ($form->{type} =~ /_quotation$/);
1780
1781   $form->{convert_from_oe_ids} = $form->{id};
1782   $form->{closed}              = 0;
1783
1784   $form->{old_employee_id}     = $form->{employee_id};
1785   $form->{old_salesman_id}     = $form->{salesman_id};
1786
1787   # reset
1788   map { delete $form->{$_} } qw(id subject message cc bcc printed emailed queued customer vendor creditlimit creditremaining discount tradediscount oldinvtotal delivered ordnumber);
1789   # this converted variable is also used for sales_order to purchase order and vice versa
1790   $form->{"converted_from_orderitems_id_$_"} = delete $form->{"orderitems_id_$_"} for 1 .. $form->{"rowcount"};
1791
1792   # if purchase_order was generated from sales_order, use  lastcost_$i as sellprice_$i
1793   # also reset discounts
1794   if ( $form->{sales_order_to_purchase_order} ) {
1795     for my $i (1 .. $form->{rowcount}) {
1796       $form->{"sellprice_${i}"} = $form->{"lastcost_${i}"};
1797       $form->{"discount_${i}"}  = 0;
1798     };
1799   };
1800
1801   for my $i (1 .. $form->{rowcount}) {
1802     map { $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig, $form->{"${_}_${i}"}) if ($form->{"${_}_${i}"}) } qw(ship qty sellprice basefactor discount lastcost);
1803   }
1804
1805   my %saved_vars = map { $_ => $form->{$_} } grep { $form->{$_} } qw(currency);
1806
1807   &order_links;
1808
1809   map { $form->{$_} = $saved_vars{$_} } keys %saved_vars;
1810
1811   # prepare_order assumes that the discount is in db-notation (0.05) and not user-notation (5)
1812   # and therefore multiplies the values by 100 in the case of reading from db or making an order
1813   # from several quotation, so we convert this back into percent-notation for the user interface by multiplying with 0.01
1814   # ergänzung 03.10.2010 muss vor prepare_order passieren (s.a. Svens Kommentar zu Bug 1017)
1815   # das parse_amount wird oben schon ausgeführt, deswegen an dieser stelle raus (wichtig: kommawerte bei discount testen)
1816   for my $i (1 .. $form->{rowcount}) {
1817     $form->{"discount_$i"} /=100;
1818   };
1819
1820   &prepare_order;
1821   &update;
1822
1823   $main::lxdebug->leave_sub();
1824 }
1825
1826 sub delivery_order {
1827   $main::lxdebug->enter_sub();
1828
1829   my $form     = $main::form;
1830   my %myconfig = %main::myconfig;
1831
1832   $form->mtime_ischanged('oe');
1833
1834   if ($form->{type} =~ /^sales/) {
1835     $main::auth->assert('sales_delivery_order_edit');
1836
1837     $form->{vc}    = 'customer';
1838     $form->{type}  = 'sales_delivery_order';
1839
1840   } else {
1841     $main::auth->assert('purchase_delivery_order_edit');
1842
1843     $form->{vc}    = 'vendor';
1844     $form->{type}  = 'purchase_delivery_order';
1845   }
1846
1847   $form->get_employee();
1848
1849   require "bin/mozilla/do.pl";
1850
1851   $form->{script}               = 'do.pl';
1852   $form->{cp_id}               *= 1;
1853   $form->{convert_from_oe_ids}  = $form->{id};
1854   $form->{transdate}            = $form->current_date(\%myconfig);
1855   delete $form->{duedate};
1856
1857   $form->{old_employee_id}  = $form->{employee_id};
1858   $form->{old_salesman_id}  = $form->{salesman_id};
1859
1860   _oe_remove_delivered_or_billed_rows(id => $form->{id}, type => 'delivered');
1861
1862   # reset
1863   delete @{$form}{qw(id subject message cc bcc printed emailed queued creditlimit creditremaining discount tradediscount oldinvtotal closed delivered)};
1864
1865   for my $i (1 .. $form->{rowcount}) {
1866     map { $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig, $form->{"${_}_${i}"}) if ($form->{"${_}_${i}"}) } qw(ship qty sellprice lastcost basefactor discount);
1867     $form->{"converted_from_orderitems_id_$i"} = delete $form->{"orderitems_id_$i"};
1868   }
1869
1870   my %old_values = map { $_ => $form->{$_} } qw(customer_id oldcustomer customer vendor_id oldvendor vendor shipto_id);
1871
1872   order_links();
1873
1874   prepare_order();
1875
1876   map { $form->{$_} = $old_values{$_} if ($old_values{$_}) } keys %old_values;
1877
1878   for my $i (1 .. $form->{rowcount}) {
1879     (my $dummy, $form->{"pricegroup_id_$i"}) = split /--/, $form->{"sellprice_pg_$i"};
1880   }
1881   update();
1882
1883   $main::lxdebug->leave_sub();
1884 }
1885
1886 sub oe_delivery_order_from_order {
1887
1888   return if !$::form->{id};
1889
1890   my $order = SL::DB::Order->new(id => $::form->{id})->load;
1891   $order->flatten_to_form($::form, format_amounts => 1);
1892
1893   # fake last empty row
1894   $::form->{rowcount}++;
1895
1896   delivery_order();
1897 }
1898
1899 sub e_mail {
1900   $main::lxdebug->enter_sub();
1901
1902   my $form     = $main::form;
1903
1904   check_oe_access();
1905
1906   $form->mtime_ischanged('oe','mail');
1907   $form->{print_and_save} = 1;
1908
1909   my $saved_form = save_form();
1910
1911   save();
1912
1913   restore_form($saved_form, 0, qw(id ordnumber quonumber));
1914
1915   edit_e_mail();
1916
1917   $main::lxdebug->leave_sub();
1918 }
1919
1920 sub yes {
1921   call_sub($main::form->{yes_nextsub});
1922 }
1923
1924 sub no {
1925   call_sub($main::form->{no_nextsub});
1926 }
1927
1928 ######################################################################################################
1929 # IO ENTKOPPLUNG
1930 # ###############################################################################################
1931 sub display_form {
1932   $main::lxdebug->enter_sub();
1933
1934   my $form     = $main::form;
1935   my %myconfig = %main::myconfig;
1936
1937   check_oe_access();
1938
1939   retrieve_partunits() if ($form->{type} =~ /_delivery_order$/);
1940
1941   $form->{"taxaccounts"} =~ s/\s*$//;
1942   $form->{"taxaccounts"} =~ s/^\s*//;
1943   foreach my $accno (split(/\s*/, $form->{"taxaccounts"})) {
1944     map({ delete($form->{"${accno}_${_}"}); } qw(rate description taxnumber));
1945   }
1946   $form->{"taxaccounts"} = "";
1947
1948   IC->retrieve_accounts(\%myconfig, $form, map { $_ => $form->{"id_$_"} } 1 .. $form->{rowcount});
1949
1950   $form->{rowcount}++;
1951   $form->{"project_id_$form->{rowcount}"} = $form->{globalproject_id};
1952
1953   $form->language_payment(\%myconfig);
1954
1955   Common::webdav_folder($form);
1956
1957   &form_header;
1958
1959   # create rows
1960   display_row($form->{rowcount}) if $form->{rowcount};
1961
1962   &form_footer;
1963
1964   $main::lxdebug->leave_sub();
1965 }
1966
1967 sub report_for_todo_list {
1968   $main::lxdebug->enter_sub();
1969
1970   my $form     = $main::form;
1971
1972   my $quotations = OE->transactions_for_todo_list();
1973   my $content;
1974
1975   if (@{ $quotations }) {
1976     my $edit_url = build_std_url('script=oe.pl', 'action=edit');
1977
1978     $content     = $form->parse_html_template('oe/report_for_todo_list', { 'QUOTATIONS' => $quotations,
1979                                                                            'edit_url'   => $edit_url });
1980   }
1981
1982   $main::lxdebug->leave_sub();
1983
1984   return $content;
1985 }
1986
1987 sub edit_periodic_invoices_config {
1988   $::lxdebug->enter_sub();
1989
1990   $::form->{type} = 'sales_order';
1991
1992   check_oe_access();
1993
1994   my $config;
1995   $config = YAML::Load($::form->{periodic_invoices_config}) if $::form->{periodic_invoices_config};
1996
1997   if ('HASH' ne ref $config) {
1998     $config =  { periodicity             => 'm',
1999                  order_value_periodicity => 'p', # = same as periodicity
2000                  start_date_as_date      => $::form->{transdate} || $::form->current_date,
2001                  extend_automatically_by => 12,
2002                  active                  => 1,
2003                };
2004   }
2005
2006   $config->{periodicity}             = 'm' if none { $_ eq $config->{periodicity}             }       @SL::DB::PeriodicInvoicesConfig::PERIODICITIES;
2007   $config->{order_value_periodicity} = 'p' if none { $_ eq $config->{order_value_periodicity} } ('p', @SL::DB::PeriodicInvoicesConfig::ORDER_VALUE_PERIODICITIES);
2008
2009   $::form->get_lists(printers => "ALL_PRINTERS",
2010                      charts   => { key       => 'ALL_CHARTS',
2011                                    transdate => 'current_date' });
2012
2013   $::form->{AR}    = [ grep { $_->{link} =~ m/(?:^|:)AR(?::|$)/ } @{ $::form->{ALL_CHARTS} } ];
2014   $::form->{title} = $::locale->text('Edit the configuration for periodic invoices');
2015
2016   if ($::form->{customer_id}) {
2017     $::form->{ALL_CONTACTS} = SL::DB::Manager::Contact->get_all_sorted(where => [ cp_cv_id => $::form->{customer_id} ]);
2018   }
2019
2020   $::form->header(no_layout => 1);
2021   print $::form->parse_html_template('oe/edit_periodic_invoices_config', $config);
2022
2023   $::lxdebug->leave_sub();
2024 }
2025
2026 sub save_periodic_invoices_config {
2027   $::lxdebug->enter_sub();
2028
2029   $::form->{type} = 'sales_order';
2030
2031   check_oe_access();
2032
2033   $::form->isblank('start_date_as_date', $::locale->text('The start date is missing.'));
2034
2035   my $config = { active                  => $::form->{active}     ? 1 : 0,
2036                  terminated              => $::form->{terminated} ? 1 : 0,
2037                  direct_debit            => $::form->{direct_debit} ? 1 : 0,
2038                  periodicity             => (any { $_ eq $::form->{periodicity}             }       @SL::DB::PeriodicInvoicesConfig::PERIODICITIES)              ? $::form->{periodicity}             : 'm',
2039                  order_value_periodicity => (any { $_ eq $::form->{order_value_periodicity} } ('p', @SL::DB::PeriodicInvoicesConfig::ORDER_VALUE_PERIODICITIES)) ? $::form->{order_value_periodicity} : 'p',
2040                  start_date_as_date      => $::form->{start_date_as_date},
2041                  end_date_as_date        => $::form->{end_date_as_date},
2042                  first_billing_date_as_date => $::form->{first_billing_date_as_date},
2043                  print                   => $::form->{print} ? 1 : 0,
2044                  printer_id              => $::form->{print} ? $::form->{printer_id} * 1 : undef,
2045                  copies                  => $::form->{copies} * 1 ? $::form->{copies} : 1,
2046                  extend_automatically_by => $::form->{extend_automatically_by} * 1 || undef,
2047                  ar_chart_id             => $::form->{ar_chart_id} * 1,
2048                  send_email                 => $::form->{send_email} ? 1 : 0,
2049                  email_recipient_contact_id => $::form->{email_recipient_contact_id} * 1 || undef,
2050                  email_recipient_address    => $::form->{email_recipient_address},
2051                  email_sender               => $::form->{email_sender},
2052                  email_subject              => $::form->{email_subject},
2053                  email_body                 => $::form->{email_body},
2054                };
2055
2056   $::form->{periodic_invoices_config} = YAML::Dump($config);
2057
2058   $::form->{title} = $::locale->text('Edit the configuration for periodic invoices');
2059   $::form->header;
2060   print $::form->parse_html_template('oe/save_periodic_invoices_config', $config);
2061
2062   $::lxdebug->leave_sub();
2063 }
2064
2065 sub _remove_full_delivered_rows {
2066
2067   my @fields = map { s/_1$//; $_ } grep { m/_1$/ } keys %{ $::form };
2068   my @new_rows;
2069
2070   my $removed_rows = 0;
2071   my $row          = 0;
2072   while ($row < $::form->{rowcount}) {
2073     $row++;
2074     next unless $::form->{"id_$row"};
2075     my $base_factor = SL::DB::Manager::Unit->find_by(name => $::form->{"unit_$row"})->base_factor;
2076     my $base_qty = $::form->parse_amount(\%::myconfig, $::form->{"qty_$row"}) *  $base_factor;
2077     my $ship_qty = $::form->parse_amount(\%::myconfig, $::form->{"ship_$row"}) *  $base_factor;
2078     #$main::lxdebug->message(LXDebug->DEBUG2(),"shipto=".$ship_qty." qty=".$base_qty);
2079
2080     if (!$ship_qty || ($ship_qty < $base_qty)) {
2081       $::form->{"qty_$row"}  = $::form->format_amount(\%::myconfig, ($base_qty - $ship_qty) / $base_factor );
2082       $::form->{"ship_$row"} = 0;
2083       push @new_rows, { map { $_ => $::form->{"${_}_${row}"} } @fields };
2084
2085     } else {
2086       $removed_rows++;
2087     }
2088   }
2089   $::form->redo_rows(\@fields, \@new_rows, scalar(@new_rows), $::form->{rowcount});
2090   $::form->{rowcount} -= $removed_rows;
2091 }
2092
2093 sub _oe_remove_delivered_or_billed_rows {
2094   my (%params) = @_;
2095
2096   return if !$params{id} || !$params{type};
2097
2098   my $ord_quot = SL::DB::Order->new(id => $params{id})->load;
2099   return if !$ord_quot;
2100
2101   # Prüfung ob itemlinks existieren, falls ja dann neue Implementierung
2102
2103   if (  $params{type} eq 'delivered' ) {
2104       my $orderitem = SL::DB::Manager::OrderItem->get_first( where => [trans_id => $ord_quot->id]);
2105       if ( $orderitem) {
2106           my @links = $orderitem->linked_records(to => 'SL::DB::DeliveryOrderItem');
2107           if ( scalar(@links ) > 0 ) {
2108               #$main::lxdebug->message(LXDebug->DEBUG2(),"item recordlinks vorhanden");
2109               return _remove_full_delivered_rows();
2110           }
2111       }
2112   }
2113   my %args    = (
2114     direction => 'to',
2115     to        =>   $params{type} eq 'delivered' ? 'DeliveryOrder' : 'Invoice',
2116     via       => [ $params{type} eq 'delivered' ? qw(Order)       : qw(Order DeliveryOrder) ],
2117   );
2118
2119   my %handled_base_qtys;
2120   foreach my $record (@{ $ord_quot->linked_records(%args) }) {
2121     next if $ord_quot->is_sales != $record->is_sales;
2122     next if $record->type eq 'invoice' && $record->storno;
2123
2124     foreach my $item (@{ $record->items }) {
2125       my $key  = $item->parts_id;
2126       $key    .= ':' . $item->serialnumber if $item->serialnumber;
2127       $handled_base_qtys{$key} += $item->qty * $item->unit_obj->base_factor;
2128     }
2129   }
2130
2131   _remove_billed_or_delivered_rows(quantities => \%handled_base_qtys);
2132 }
2133
2134 # iterate all positions and match articlenumber
2135 sub check_transport_cost_reminder_article_number {
2136   $main::lxdebug->enter_sub();
2137
2138   my $form     = $main::form;
2139
2140   check_oe_access();
2141
2142   my $transport_article_id = $::instance_conf->get_transport_cost_reminder_article_number_id;
2143   for my $i (1 .. $form->{rowcount}) {
2144     return if $form->{"id_${i}"} eq $transport_article_id;
2145   }
2146
2147   # simply return the name of the part
2148   return SL::DB::Part->new(id => $transport_article_id)->load()->partnumber;
2149
2150   $main::lxdebug->leave_sub();
2151 }
2152 sub dispatcher {
2153   foreach my $action (qw(delete delivery_order e_mail invoice print purchase_order quotation
2154                          request_for_quotation sales_order save save_and_close save_as_new ship_to update)) {
2155     if ($::form->{"action_${action}"}) {
2156       call_sub($action);
2157       return;
2158     }
2159   }
2160
2161   $::form->error($::locale->text('No action defined.'));
2162 }