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