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