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