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