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