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