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