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