421c76ef26f02cfc26f7a6024f38de30bacccf1c
[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, "ordnumber"      if $form->{type} =~ /_quotation$/;
337   push @custom_hiddens, "customer_klass" if $form->{vc} eq 'customer';
338
339   $credittext = $locale->text('Credit Limit exceeded!!!');
340
341   my $follow_up_vc                =  $form->{ $form->{vc} eq 'customer' ? 'customer' : 'vendor' };
342   $follow_up_vc                   =~ s/--.*?//;
343   $TMPL_VAR{follow_up_trans_info} =  ($form->{type} =~ /_quotation$/ ? $form->{quonumber} : $form->{ordnumber}) . " ($follow_up_vc)";
344
345   if ($form->{id}) {
346     my $follow_ups = FU->follow_ups('trans_id' => $form->{id});
347
348     if (scalar @{ $follow_ups }) {
349       $TMPL_VAR{num_follow_ups}     = scalar                    @{ $follow_ups };
350       $TMPL_VAR{num_due_follow_ups} = sum map { $_->{due} * 1 } @{ $follow_ups };
351     }
352   }
353
354   $onload = ($form->{resubmit} && ($form->{format} eq "html")) ? "window.open('about:blank','Beleg'); document.oe.target = 'Beleg';document.oe.submit()"
355           : ($form->{resubmit})                                ? "document.oe.submit()"
356           : ($creditwarning)                                   ? "alert('$credittext')"
357           :                                                      "focus()";
358
359   $onload .= qq|;setupDateFormat('|. $myconfig{dateformat} .qq|', '|. $locale->text("Falsches Datumsformat!") .qq|')|;
360   $onload .= qq|;setupPoints('|.   $myconfig{numberformat} .qq|', '|. $locale->text("wrongformat") .qq|')|;
361   $TMPL_VAR{onload} = $onload;
362
363   $form->{javascript} .= qq|<script type="text/javascript" src="js/show_form_details.js"></script>|;
364   $form->{javascript} .= qq|<script type="text/javascript" src="js/show_history.js"></script>|;
365   $form->{javascript} .= qq|<script type="text/javascript" src="js/show_vc_details.js"></script>|;
366
367   $form->header;
368
369   $TMPL_VAR{HIDDENS} = [ map { name => $_, value => $form->{$_} },
370      qw(id action type vc formname media format proforma queued printed emailed
371         title creditlimit creditremaining tradediscount business
372         max_dunning_level dunning_amount shiptoname shiptostreet shiptozipcode
373         shiptocity shiptocountry shiptocontact shiptophone shiptofax
374         shiptodepartment_1 shiptodepartment_2 shiptoemail
375         message email subject cc bcc taxpart taxservice taxaccounts cursor_fokus),
376         @custom_hiddens,
377         map { $_.'_rate', $_.'_description' } split / /, $form->{taxaccounts} ];  # deleted: discount
378
379   %TMPL_VAR = (
380      %TMPL_VAR,
381      is_sales        => scalar ($form->{type} =~ /^sales_/),              # these vars are exported, so that the template
382      is_order        => scalar ($form->{type} =~ /_order$/),              # may determine what to show
383      is_sales_quo    => scalar ($form->{type} =~ /sales_quotation$/),
384      is_req_quo      => scalar ($form->{type} =~ /request_quotation$/),
385      is_sales_ord    => scalar ($form->{type} =~ /sales_order$/),
386      is_pur_ord      => scalar ($form->{type} =~ /purchase_order$/),
387   );
388
389   print $form->parse_html_template("oe/form_header", { %TMPL_VAR });
390
391   $lxdebug->leave_sub();
392 }
393
394 sub form_footer {
395   $lxdebug->enter_sub();
396
397   check_oe_access();
398
399   $form->{invtotal} = $form->{invsubtotal};
400
401   $rows    = max 2, $form->numtextrows($form->{notes}, 25, 8);
402   $introws = max 2, $form->numtextrows($form->{intnotes}, 35, 8);
403   $rows    = max $rows, $introws;
404
405   $TMPL_VAR{notes}    = qq|<textarea name=notes rows=$rows cols=25 wrap=soft>| . H($form->{notes}) . qq|</textarea>|;
406   $TMPL_VAR{intnotes} = qq|<textarea name=intnotes rows=$introws cols=35 wrap=soft>| . H($form->{intnotes}) . qq|</textarea>|;
407
408   if (!$form->{taxincluded}) {
409
410     foreach $item (split / /, $form->{taxaccounts}) {
411       if ($form->{"${item}_base"}) {
412         $form->{invtotal} += $form->{"${item}_total"} = $form->round_amount( $form->{"${item}_base"} * $form->{"${item}_rate"}, 2);
413         $form->{"${item}_total"} = $form->format_amount(\%myconfig, $form->{"${item}_total"}, 2);
414
415         $TMPL_VAR{tax} .= qq|
416               <tr>
417                 <th align=right>$form->{"${item}_description"}&nbsp;| . $form->{"${item}_rate"} * 100 .qq|%</th>
418                 <td align=right>$form->{"${item}_total"}</td>
419               </tr> |;
420       }
421     }
422
423 #    $form->{invsubtotal} = $form->format_amount(\%myconfig, $form->{invsubtotal}, 2, 0); # template does this
424
425   } else {
426     foreach $item (split / /, $form->{taxaccounts}) {
427       if ($form->{"${item}_base"}) {
428         $form->{"${item}_total"} = $form->round_amount( ($form->{"${item}_base"} * $form->{"${item}_rate"} / (1 + $form->{"${item}_rate"})), 2);
429         $form->{"${item}_netto"} = $form->round_amount( ($form->{"${item}_base"} - $form->{"${item}_total"}), 2);
430         $form->{"${item}_total"} = $form->format_amount(\%myconfig, $form->{"${item}_total"}, 2);
431         $form->{"${item}_netto"} = $form->format_amount(\%myconfig, $form->{"${item}_netto"}, 2);
432
433         $TMPL_VAR{tax} .= qq|
434               <tr>
435                 <th align=right>Enthaltene $form->{"${item}_description"}&nbsp;| . $form->{"${item}_rate"} * 100 .qq|%</th>
436                 <td align=right>$form->{"${item}_total"}</td>
437               </tr>
438               <tr>
439                 <th align=right>Nettobetrag</th>
440                 <td align=right>$form->{"${item}_netto"}</td>
441               </tr> |;
442       }
443     }
444   }
445
446   $form->{oldinvtotal} = $form->{invtotal};
447
448   print $form->parse_html_template("oe/form_footer", {
449      %TMPL_VAR,
450      webdav          => $webdav,
451      print_options   => print_options(inline => 1),
452      label_edit      => $locale->text("Edit the $form->{type}"),
453      label_workflow  => $locale->text("Workflow $form->{type}"),
454   });
455
456   $lxdebug->leave_sub();
457 }
458
459 sub update {
460   $lxdebug->enter_sub();
461   
462   my ($recursive_call) = shift;
463
464   check_oe_access();
465
466   set_headings($form->{"id"} ? "edit" : "add");
467
468   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) } qw(exchangerate) unless $recursive_call;
469   $form->{update} = 1;
470       
471   $payment_id = $form->{payment_id} if $form->{payment_id};
472   
473   &check_name($form->{vc});
474   
475   $form->{payment_id} = $payment_id if $form->{payment_id} eq "";
476   
477   $buysell              = 'buy';
478   $buysell              = 'sell' if ($form->{vc} eq 'vendor');
479   $form->{forex}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{transdate}, $buysell);
480   $form->{exchangerate} = $form->{forex} if $form->{forex};
481
482   $exchangerate = $form->{exchangerate} || 1;
483
484 ##################### process items ######################################
485   # for pricegroups
486   $i = $form->{rowcount};
487   if (   ($form->{"partnumber_$i"} eq "")
488       && ($form->{"description_$i"} eq "")
489       && ($form->{"partsgroup_$i"}  eq "")) {
490
491     $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
492     &check_form;
493
494   } else {
495
496     if ($form->{type} =~ /^sales/) {
497       IS->retrieve_item(\%myconfig, \%$form);
498     } else {
499       IR->retrieve_item(\%myconfig, \%$form);
500     }
501
502     my $rows = scalar @{ $form->{item_list} };
503
504     $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{discount} * 100);
505
506     if ($rows) {
507       $form->{"qty_$i"} = 1 unless ($form->{"qty_$i"});
508
509       if ($rows > 1) {
510
511         &select_item;
512         exit;
513
514       } else {
515
516         $sellprice             = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
517         $form->{"discount_$i"} = 0 if $form->{"not_discountable_$i"};
518         map { $form->{item_list}[$i]{$_} =~ s/\"/&quot;/g }    qw(partnumber description unit);
519         map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
520         $form->{payment_id} = $form->{"part_payment_id_$i"} if $form->{"part_payment_id_$i"} ne "";
521
522         $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
523
524         ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
525         $decimalplaces = max 2, length $1;
526
527         if ($sellprice) {
528           $form->{"sellprice_$i"} = $sellprice;
529         } else {
530           $form->{"sellprice_$i"} *= (1 - $form->{tradediscount});
531           $form->{"sellprice_$i"} /= $exchangerate;   # if there is an exchange rate adjust sellprice
532         }
533
534         $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"} / 100);
535         map { $form->{"${_}_base"} = 0 }                                 split / /, $form->{taxaccounts};
536         map { $form->{"${_}_base"} += $amount }                          split / /, $form->{"taxaccounts_$i"};
537         map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /, $form->{taxaccounts} if !$form->{taxincluded};
538
539         $form->{creditremaining} -= $amount;
540
541         $form->{"sellprice_$i"} = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
542         $form->{"qty_$i"}       = $form->format_amount(\%myconfig, $form->{"qty_$i"}, $dec_qty);
543
544         # get pricegroups for parts
545         IS->get_pricegroups_for_parts(\%myconfig, \%$form);
546
547         # build up html code for prices_$i
548         &set_pricegroup($i);
549       }
550
551       display_form();
552     } else {
553
554       # ok, so this is a new part
555       # ask if it is a part or service item
556
557       if (   $form->{"partsgroup_$i"}
558           && ($form->{"partsnumber_$i"} eq "")
559           && ($form->{"description_$i"} eq "")) {
560         $form->{rowcount}--;
561         $form->{"discount_$i"} = "";
562
563         display_form();
564       } else {
565         $form->{"id_$i"}   = 0;
566         new_item();
567       }
568     }
569   }
570 ##################### process items ######################################
571
572
573   $lxdebug->leave_sub();
574 }
575
576 sub search {
577   $lxdebug->enter_sub();
578
579   check_oe_access();
580
581   if ($form->{type} eq 'purchase_order') {
582     $form->{title} = $locale->text('Purchase Orders');
583     $form->{vc}    = 'vendor';
584     $ordlabel      = $locale->text('Order Number');
585     $ordnumber     = 'ordnumber';
586     $employee      = $locale->text('Employee');
587   }
588
589   if ($form->{type} eq 'request_quotation') {
590     $form->{title} = $locale->text('Request for Quotations');
591     $form->{vc}    = 'vendor';
592     $ordlabel      = $locale->text('RFQ Number');
593     $ordnumber     = 'quonumber';
594     $employee      = $locale->text('Employee');
595   }
596
597   if ($form->{type} eq 'sales_order') {
598     $form->{title} = $locale->text('Sales Orders');
599     $form->{vc}    = 'customer';
600     $ordlabel      = $locale->text('Order Number');
601     $ordnumber     = 'ordnumber';
602     $employee      = $locale->text('Employee');
603   }
604
605   if ($form->{type} eq 'sales_quotation') {
606     $form->{title} = $locale->text('Quotations');
607     $form->{vc}    = 'customer';
608     $ordlabel      = $locale->text('Quotation Number');
609     $ordnumber     = 'quonumber';
610     $employee      = $locale->text('Employee');
611   }
612
613   # setup vendor / customer selection
614   $form->all_vc(\%myconfig, $form->{vc},
615                 ($form->{vc} eq 'customer') ? "AR" : "AP");
616
617   # departments
618   if (@{ $form->{all_departments} }) {
619     $form->{selectdepartment} = "<option>\n";
620
621     map {
622       $form->{selectdepartment} .=
623         "<option>$_->{description}--$_->{id}</option>\n"
624     } (@{ $form->{all_departments} });
625   }
626
627   $department = qq|
628         <tr>
629           <th align=right nowrap>| . $locale->text('Department') . qq|</th>
630           <td colspan=3><select name=department>$form->{selectdepartment}</select></td>
631         </tr>
632 | if $form->{selectdepartment};
633
634   my $delivered;
635   if (($form->{"type"} eq "sales_order") ||
636       ($form->{"type"} eq "purchase_order")) {
637     $delivered = qq|
638         <tr>
639           <td><input name="notdelivered" id="notdelivered" class="checkbox" type="checkbox" value="1" checked>
640             <label for="notdelivered">|. $locale->text('Not delivered') . qq|</label></td>
641           <td><input name="delivered" id="delivered" class="checkbox" type="checkbox" value="1" checked>
642             <label for="delivered">| . $locale->text('Delivered') . qq|</label></td>
643         </tr>
644 |;
645   }
646
647   # use JavaScript Calendar or not
648   $form->{jsscript} = 1;
649   $jsscript = "";
650
651   $button1 = qq|
652      <td><input name=transdatefrom id=transdatefrom size=11 title="$myconfig{dateformat}" onBlur=\"check_right_date_format(this)\">
653      <input type=button name=transdatefrom id="trigger3" value=|
654     . $locale->text('button') . qq|></td>
655     |;
656   $button2 = qq|
657      <td><input name=transdateto id=transdateto size=11 title="$myconfig{dateformat}" onBlur=\"check_right_date_format(this)\">
658      <input type=button name=transdateto name=transdateto id="trigger4" value=|
659     . $locale->text('button') . qq|></td>
660    |;
661
662   #write Trigger
663   $jsscript =
664     Form->write_trigger(\%myconfig, "2", "transdatefrom", "BR", "trigger3",
665                         "transdateto", "BL", "trigger4");
666
667   my $vc = $form->{vc} eq "customer" ? "customers" : "vendors";
668
669   $form->get_lists("projects"  => { "key" => "ALL_PROJECTS",
670                                     "all" => 1 },
671                    "employees" => "ALL_EMPLOYEES",
672                    "salesmen"  => "ALL_SALESMEN",
673                    $vc         => "ALL_" . uc($vc)
674                   );
675
676   my %labels = ();
677   my @values = ("");
678   foreach my $item (@{ $form->{"ALL_PROJECTS"} }) {
679     push(@values, $item->{"id"});
680     $labels{$item->{"id"}} = $item->{"projectnumber"};
681   }
682   my $projectnumber =
683     NTI($cgi->popup_menu('-name' => 'project_id', '-values' => \@values,
684                          '-labels' => \%labels));
685
686   #employees
687   %labels = ();
688   @values = ("");
689   foreach my $item (@{ $form->{"ALL_EMPLOYEES"} }) {
690     push(@values, $item->{"id"});
691     $labels{$item->{"id"}} = $item->{"name"} ne "" ? $item->{"name"} : $item->{"login"};
692   }
693   
694   #salesmen
695   my %labels_salesmen = ();
696   my @values_salesmen = ('');
697   foreach my $item (@{ $form->{"ALL_SALESMEN"} }) {
698     push(@values_salesmen, $item->{"id"});
699     $labels_salesmen{$item->{"id"}} = $item->{"name"} ne "" ? $item->{"name"} : $item->{"login"};
700   }
701
702   my $employee_block = qq|
703     <tr>
704       <th align="right">| . $locale->text('Employee') . qq|</th>
705       <td>| .  NTI($cgi->popup_menu('-name'   => 'employee_id', '-values' => \@values, '-labels' => \%labels)) . qq|</td>
706     </tr>
707     <tr>
708       <th align="right">| . $locale->text('Salesman') . qq|</th>
709       <td>| .
710         NTI($cgi->popup_menu('-name'   => 'salesman_id',
711                              '-values' => \@values_salesmen,
712                              '-labels' => \%labels_salesmen)) . qq|
713       </td>
714     </tr>|;
715
716   %labels = ();
717   @values = ("");
718
719   foreach my $item (@{ $form->{($form->{vc} eq "customer" ? "ALL_CUSTOMERS" : "ALL_VENDORS")}}) {
720     push(@values, $item->{name}.qq|--|.$item->{"id"});
721     $labels{$item->{name}.qq|--|.$item->{"id"}} = $item->{"name"};
722   }
723
724   my $vc_label = $form->{vc} eq "customer" ? $locale->text('Customer') : $locale->text('Vendor');
725   $vc =
726     $myconfig{vclimit} <=  scalar(@values)
727     ? qq|<input type="text" value="| . H(($form->{"old$form->{vc}"} =~ /^(.*)\-\-.*$/)) . qq|" name="$form->{vc}">| 
728     : NTI($cgi->popup_menu('-name' => "$form->{vc}",
729                            '-default' => $form->{"old$form->{vc}"},
730                            '-onChange' => 'document.getElementById(\'update_button\').click();',
731                            '-values' => \@values,
732                            '-labels' => \%labels));
733   $form->header;
734
735   print qq|
736 <body>
737
738 <form method=post action=$form->{script}>
739
740 <table width=100%>
741   <tr>
742     <th class=listtop>$form->{title}</th>
743   </tr>
744   <tr height="5"></tr>
745   <tr>
746     <td>
747       <table>
748         <tr>
749           <th align=right>$vc_label</th>
750           <td colspan=3>$vc</td>
751         </tr>
752 $department
753         <tr>
754           <th align=right>$ordlabel</th>
755           <td colspan=3><input name="$ordnumber" size=20></td>
756         </tr>
757 $employee_block
758         <tr>
759           <th align="right">| . $locale->text('Transaction description') . qq|</th>
760           <td colspan="3"><input name="transaction_description" size=20></td>
761         </tr>
762         <tr>
763           <th align="right">| . $locale->text("Project Number") . qq|</th>
764           <td colspan="3">$projectnumber</td>
765         </tr>
766         <tr>
767           <th align=right>| . $locale->text('From') . qq|</th> $button1
768           <th align=right>| . $locale->text('Bis') . qq|</th> $button2
769         </tr>
770         <input type=hidden name=sort value=transdate>
771         <tr>
772           <th align=right>| . $locale->text('Include in Report') . qq|</th>
773           <td colspan=5>
774             <table>
775         <tr>
776           <td><input type="checkbox" name="open" value="1" id="open" checked> <label for="open">| . $locale->text("Open") . qq|</td>
777           <td><input type="checkbox" name="closed" value="1" id="closed"> <label for="closed">| . $locale->text("Closed") . qq|</td>
778         </tr>
779         $delivered
780               <tr>
781                 <td><input name="l_id" class=checkbox type=checkbox value=Y> | . $locale->text('ID') . qq|</td>
782                 <td><input name="l_$ordnumber" class=checkbox type=checkbox value=Y checked> $ordlabel</td>
783               </tr>
784               <tr>
785                 <td><input name="l_transdate" class=checkbox type=checkbox value=Y checked> | . $locale->text('Date') . qq|</td>
786                 <td><input name="l_reqdate" class=checkbox type=checkbox value=Y checked> | . $locale->text('Required by') . qq|</td>
787               </tr>
788               <tr>
789                 <td><input name="l_name" class=checkbox type=checkbox value=Y checked> $vc_label</td>
790                 <td><input name="l_employee" class=checkbox type=checkbox value=Y checked> $employee</td>
791                 
792                 <td><input name="l_shipvia" class=checkbox type=checkbox value=Y> | . $locale->text('Ship via') . qq|</td>
793               </tr>
794               <tr>
795                 <td><input name="l_netamount" class=checkbox type=checkbox value=Y> | . $locale->text('Amount') . qq|</td>
796                 <td><input name="l_tax" class=checkbox type=checkbox value=Y> | . $locale->text('Tax') . qq|</td>
797                 <td><input name="l_amount" class=checkbox type=checkbox value=Y checked> | . $locale->text('Total') . qq|</td>
798               </tr>
799               <tr>
800                 <td><input name="l_marge_total" class=checkbox type=checkbox value=Y> | .             $locale->text('Ertrag') . qq|</td>
801                 <td><input name="l_marge_percent" class=checkbox type=checkbox value=Y> | .             $locale->text('Ertrag prozentual') . qq|</td>
802               </tr>
803               <tr>
804           <td><input name="l_globalprojectnumber" class=checkbox type=checkbox value=Y> | . $locale->text('Project Number') . qq|</td>
805           <td><input name="l_transaction_description" class=checkbox type=checkbox value=Y> | . $locale->text('Transaction description') . qq|</td>
806               </tr>
807               <tr>
808                 <td><input name="l_subtotal" class=checkbox type=checkbox value=Y> | . $locale->text('Subtotal') . qq|</td>
809                 <td><input name="l_salesman" class="checkbox" type="checkbox" value="Y"> | . $locale->text('Salesman') . qq|</td>
810               </tr>
811             </table>
812           </td>
813         </tr>
814       </table>
815     </td>
816   </tr>
817   <tr><td colspan=4><hr size=3 noshade></td></tr>
818 </table>
819
820 $jsscript
821
822 <br>
823 <input type=hidden name=nextsub value=orders>
824 <input type=hidden name=vc value=$form->{vc}>
825 <input type=hidden name=type value=$form->{type}>
826
827 <input class=submit type=submit name=action value="|
828     . $locale->text('Continue') . qq|">
829 </form>
830
831 </body>
832 </html>
833 |;
834
835   $lxdebug->leave_sub();
836 }
837
838 sub create_subtotal_row {
839   $lxdebug->enter_sub();
840
841   my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
842
843   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
844
845   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
846
847   $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
848
849   map { $totals->{$_} = 0 } @{ $subtotal_columns };
850
851   $lxdebug->leave_sub();
852
853   return $row;
854 }
855
856 sub orders {
857   $lxdebug->enter_sub();
858
859   check_oe_access();
860
861   $ordnumber = ($form->{type} =~ /_order$/) ? "ordnumber" : "quonumber";
862
863   ($form->{ $form->{vc} }, $form->{"${form->{vc}}_id"}) = split(/--/, $form->{ $form->{vc} });
864
865   report_generator_set_default_sort('transdate', 1);
866
867   OE->transactions(\%myconfig, \%$form);
868
869   $form->{rowcount} = scalar @{ $form->{OE} };
870
871   my @columns = (
872     "transdate",               "reqdate",
873     "id",                      $ordnumber,
874     "name",                    "netamount",
875     "tax",                     "amount",
876     "curr",                    "employee",
877     "salesman",
878     "shipvia",                 "globalprojectnumber",
879     "transaction_description", "open",
880     "delivered", "marge_total", "marge_percent"
881   );
882
883   # only show checkboxes if gotten here via sales_order form.
884   my $allow_multiple_orders = $form->{type} eq 'sales_order';
885   if ($allow_multiple_orders) {
886     unshift @columns, "ids";
887   }
888
889   $form->{l_open}      = $form->{l_closed} = "Y" if ($form->{open}      && $form->{closed});
890   $form->{l_delivered} = "Y"                     if ($form->{delivered} && $form->{notdelivered});
891
892   my $attachment_basename;
893   if ($form->{vc} eq 'vendor') {
894     if ($form->{type} eq 'purchase_order') {
895       $form->{title}       = $locale->text('Purchase Orders');
896       $attachment_basename = $locale->text('purchase_order_list');
897     } else {
898       $form->{title}       = $locale->text('Request for Quotations');
899       $attachment_basename = $locale->text('rfq_list');
900     }
901
902   } else {
903     if ($form->{type} eq 'sales_order') {
904       $form->{title}       = $locale->text('Sales Orders');
905       $attachment_basename = $locale->text('sales_order_list');
906     } else {
907       $form->{title}       = $locale->text('Quotations');
908       $attachment_basename = $locale->text('quotation_list');
909     }
910   }
911
912   my $report = SL::ReportGenerator->new(\%myconfig, $form);
913
914   my @hidden_variables = map { "l_${_}" } @columns;
915   push @hidden_variables, "l_subtotal", $form->{vc}, qw(l_closed l_notdelivered open closed delivered notdelivered ordnumber quonumber
916                                                         transaction_description transdatefrom transdateto type vc employee_id salesman_id);
917
918   my $href = build_std_url('action=orders', grep { $form->{$_} } @hidden_variables);
919
920   my %column_defs = (
921     'ids'                     => { 'text' => '', },
922     'transdate'               => { 'text' => $locale->text('Date'), },
923     'reqdate'                 => { 'text' => $locale->text('Required by'), },
924     'id'                      => { 'text' => $locale->text('ID'), },
925     'ordnumber'               => { 'text' => $locale->text('Order'), },
926     'quonumber'               => { 'text' => $form->{type} eq "request_quotation" ? $locale->text('RFQ') : $locale->text('Quotation'), },
927     'name'                    => { 'text' => $form->{vc} eq 'customer' ? $locale->text('Customer') : $locale->text('Vendor'), },
928     'netamount'               => { 'text' => $locale->text('Amount'), },
929     'tax'                     => { 'text' => $locale->text('Tax'), },
930     'amount'                  => { 'text' => $locale->text('Total'), },
931     'curr'                    => { 'text' => $locale->text('Curr'), },
932     'employee'                => { 'text' => $locale->text('Employee'), },
933     'salesman'                => { 'text' => $locale->text('Salesman'), },
934     'shipvia'                 => { 'text' => $locale->text('Ship via'), },
935     'globalprojectnumber'     => { 'text' => $locale->text('Project Number'), },
936     'transaction_description' => { 'text' => $locale->text('Transaction description'), },
937     'open'                    => { 'text' => $locale->text('Open'), },
938     'delivered'               => { 'text' => $locale->text('Delivered'), },
939     'marge_total'             => { 'text' => $locale->text('Ertrag'), },
940     'marge_percent'           => { 'text' => $locale->text('Ertrag prozentual'), }
941   );
942
943   foreach my $name (qw(id transdate reqdate quonumber ordnumber name employee salesman shipvia transaction_description)) {
944     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
945     $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
946   }
947
948   my %column_alignment = map { $_ => 'right' } qw(netamount tax amount curr);
949
950   $form->{"l_type"} = "Y";
951   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
952   $column_defs{ids}->{visible} = $allow_multiple_orders ? 'HTML' : 0;
953
954   $report->set_columns(%column_defs);
955   $report->set_column_order(@columns);
956   $report->set_export_options('orders', @hidden_variables);
957   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
958
959   my @options;
960   my ($department) = split m/--/, $form->{department};
961
962   push @options, $locale->text('Customer')                . " : $form->{customer}"                        if $form->{customer};
963   push @options, $locale->text('Vendor')                  . " : $form->{vendor}"                          if $form->{vendor};
964   push @options, $locale->text('Department')              . " : $department"                              if $form->{department};
965   push @options, $locale->text('Order Number')            . " : $form->{ordnumber}"                       if $form->{ordnumber};
966   push @options, $locale->text('Notes')                   . " : $form->{notes}"                           if $form->{notes};
967   push @options, $locale->text('Transaction description') . " : $form->{transaction_description}"         if $form->{transaction_description};
968   push @options, $locale->text('From') . "&nbsp;" . $locale->date(\%myconfig, $form->{transdatefrom}, 1)  if $form->{transdatefrom};
969   push @options, $locale->text('Bis')  . "&nbsp;" . $locale->date(\%myconfig, $form->{transdateto},   1)  if $form->{transdateto};
970   push @options, $locale->text('Open')                                                                    if $form->{open};
971   push @options, $locale->text('Closed')                                                                  if $form->{closed};
972   push @options, $locale->text('Delivered')                                                               if $form->{delivered};
973   push @options, $locale->text('Not delivered')                                                           if $form->{notdelivered};
974
975   $report->set_options('top_info_text'        => join("\n", @options),
976                        'raw_top_info_text'    => $form->parse_html_template('oe/orders_top'),
977                        'raw_bottom_info_text' => $form->parse_html_template('oe/orders_bottom', { 'SHOW_CONTINUE_BUTTON' => $allow_multiple_orders }),
978                        'output_format'        => 'HTML',
979                        'title'                => $form->{title},
980                        'attachment_basename'  => $attachment_basename . strftime('_%Y%m%d', localtime time),
981     );
982   $report->set_options_from_form();
983
984   # add sort and escape callback, this one we use for the add sub
985   $form->{callback} = $href .= "&sort=$form->{sort}";
986
987   # escape callback for href
988   $callback = $form->escape($href);
989
990   my @subtotal_columns = qw(netamount amount marge_total marge_percent);
991
992   my %totals    = map { $_ => 0 } @subtotal_columns;
993   my %subtotals = map { $_ => 0 } @subtotal_columns;
994
995   my $idx = 0;
996
997   my $edit_url = build_std_url('action=edit', 'type', 'vc');
998
999   foreach $oe (@{ $form->{OE} }) {
1000     map { $oe->{$_} *= $oe->{exchangerate} } @subtotal_columns;
1001
1002     $oe->{tax}       = $oe->{amount} - $oe->{netamount};
1003     $oe->{open}      = $oe->{closed}    ? $locale->text('No')  : $locale->text('Yes');
1004     $oe->{delivered} = $oe->{delivered} ? $locale->text('Yes') : $locale->text('No');
1005
1006     map { $subtotals{$_} += $oe->{$_};
1007           $totals{$_}    += $oe->{$_} } @subtotal_columns;
1008
1009     $subtotals{marge_percent} = $subtotals{netamount} ? ($subtotals{marge_total} * 100 / $subtotals{netamount}) : 0;
1010     $totals{marge_percent}    = $totals{netamount}    ? ($totals{marge_total}    * 100 / $totals{netamount}   ) : 0;
1011
1012     map { $oe->{$_} = $form->format_amount(\%myconfig, $oe->{$_}, 2) } qw(netamount tax amount marge_total marge_percent);
1013
1014     my $row = { };
1015
1016     foreach my $column (@columns) {
1017       next if ($column eq 'ids');
1018       $row->{$column} = {
1019         'data'  => $oe->{$column},
1020         'align' => $column_alignment{$column},
1021       };
1022     }
1023
1024     $row->{ids} = {
1025       'raw_data' =>   $cgi->hidden('-name' => "trans_id_${idx}", '-value' => $oe->{id})
1026                     . $cgi->checkbox('-name' => "multi_id_${idx}", '-value' => 1, '-label' => ''),
1027       'valign'   => 'center',
1028       'align'    => 'center',
1029     };
1030
1031     $row->{$ordnumber}->{link} = $edit_url . "&id=" . E($oe->{id}) . "&callback=${callback}";
1032
1033     my $row_set = [ $row ];
1034
1035     if (($form->{l_subtotal} eq 'Y')
1036         && (($idx == (scalar @{ $form->{OE} } - 1))
1037             || ($oe->{ $form->{sort} } ne $form->{OE}->[$idx + 1]->{ $form->{sort} }))) {
1038       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
1039     }
1040
1041     $report->add_data($row_set);
1042
1043     $idx++;
1044   }
1045
1046   $report->add_separator();
1047   $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
1048
1049   $report->generate_with_headers();
1050
1051   $lxdebug->leave_sub();
1052 }
1053
1054 sub check_delivered_flag {
1055   $lxdebug->enter_sub();
1056
1057   check_oe_access();
1058
1059   if (($form->{type} ne 'sales_order') && ($form->{type} ne 'purchase_order')) {
1060     return $lxdebug->leave_sub();
1061   }
1062
1063   my $all_delivered = 0;
1064
1065   foreach my $i (1 .. $form->{rowcount}) {
1066     next if (!$form->{"id_$i"});
1067
1068     if ($form->parse_amount(\%myconfig, $form->{"qty_$i"}) == $form->parse_amount(\%myconfig, $form->{"ship_$i"})) {
1069       $all_delivered = 1;
1070       next;
1071     }
1072
1073     $all_delivered = 0;
1074     last;
1075   }
1076
1077   $form->{delivered} = 1 if $all_delivered;
1078
1079   $lxdebug->leave_sub();
1080 }
1081
1082 sub save_and_close {
1083   $lxdebug->enter_sub();
1084
1085   check_oe_access();
1086
1087   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
1088
1089   if ($form->{type} =~ /_order$/) {
1090     $form->isblank("transdate", $locale->text('Order Date missing!'));
1091   } else {
1092     $form->isblank("transdate", $locale->text('Quotation Date missing!'));
1093   }
1094
1095   my $idx = $form->{type} =~ /_quotation$/ ? "quonumber" : "ordnumber";
1096   $form->{$idx} =~ s/^\s*//g;
1097   $form->{$idx} =~ s/\s*$//g;
1098
1099   $msg = ucfirst $form->{vc};
1100   $form->isblank($form->{vc}, $locale->text($msg . " missing!"));
1101
1102   # $locale->text('Customer missing!');
1103   # $locale->text('Vendor missing!');
1104
1105   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
1106     if ($form->{currency} ne $form->{defaultcurrency});
1107
1108   &validate_items;
1109   
1110   if($form->{payment_id}) { 
1111     $payment_id = $form->{payment_id};
1112   }
1113   
1114   # if the name changed get new values
1115   if (&check_name($form->{vc})) {
1116     if($form->{payment_id} eq "") { 
1117       $form->{payment_id} = $payment_id;
1118     }
1119     &update;
1120     exit;
1121   }
1122
1123   $form->{id} = 0 if $form->{saveasnew};
1124
1125   # this is for the internal notes section for the [email] Subject
1126   if ($form->{type} =~ /_order$/) {
1127     if ($form->{type} eq 'sales_order') {
1128       $form->{label} = $locale->text('Sales Order');
1129
1130       $numberfld = "sonumber";
1131       $ordnumber = "ordnumber";
1132     } else {
1133       $form->{label} = $locale->text('Purchase Order');
1134
1135       $numberfld = "ponumber";
1136       $ordnumber = "ordnumber";
1137     }
1138
1139     $err = $locale->text('Cannot save order!');
1140
1141     check_delivered_flag();
1142
1143   } else {
1144     if ($form->{type} eq 'sales_quotation') {
1145       $form->{label} = $locale->text('Quotation');
1146
1147       $numberfld = "sqnumber";
1148       $ordnumber = "quonumber";
1149     } else {
1150       $form->{label} = $locale->text('Request for Quotation');
1151
1152       $numberfld = "rfqnumber";
1153       $ordnumber = "quonumber";
1154     }
1155
1156     $err = $locale->text('Cannot save quotation!');
1157
1158   }
1159
1160   # get new number in sequence if no number is given or if saveasnew was requested
1161   if (!$form->{$ordnumber} || $form->{saveasnew}) {
1162     $form->{$ordnumber} = $form->update_defaults(\%myconfig, $numberfld);
1163   }
1164
1165   relink_accounts();
1166
1167   $form->error($err) if (!OE->save(\%myconfig, \%$form));
1168
1169   # saving the history
1170   if(!exists $form->{addition}) {
1171     $form->{snumbers} = qq|ordnumber_| . $form->{ordnumber};
1172         $form->{addition} = "SAVED";
1173         $form->save_history($form->dbconnect(\%myconfig));
1174   }
1175   # /saving the history
1176
1177   $form->redirect($form->{label} . " $form->{$ordnumber} " .
1178                   $locale->text('saved!'));
1179
1180   $lxdebug->leave_sub();
1181 }
1182
1183 sub save {
1184   $lxdebug->enter_sub();
1185
1186   check_oe_access();
1187
1188   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
1189
1190
1191   if ($form->{type} =~ /_order$/) {
1192     $form->isblank("transdate", $locale->text('Order Date missing!'));
1193   } else {
1194     $form->isblank("transdate", $locale->text('Quotation Date missing!'));
1195   }
1196
1197   my $idx = $form->{type} =~ /_quotation$/ ? "quonumber" : "ordnumber";
1198   $form->{$idx} =~ s/^\s*//g;
1199   $form->{$idx} =~ s/\s*$//g;
1200
1201   $msg = ucfirst $form->{vc};
1202   $form->isblank($form->{vc}, $locale->text($msg . " missing!"));
1203
1204   # $locale->text('Customer missing!');
1205   # $locale->text('Vendor missing!');
1206
1207   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
1208     if ($form->{currency} ne $form->{defaultcurrency});
1209
1210   &validate_items;
1211   
1212   if($form->{payment_id}) { 
1213     $payment_id = $form->{payment_id};
1214   }
1215   
1216   # if the name changed get new values
1217   if (&check_name($form->{vc})) {
1218     if($form->{payment_id} eq "") { 
1219       $form->{payment_id} = $payment_id;
1220     }
1221     &update;
1222     exit;
1223   }
1224
1225   $form->{id} = 0 if $form->{saveasnew};
1226
1227   # this is for the internal notes section for the [email] Subject
1228   if ($form->{type} =~ /_order$/) {
1229     if ($form->{type} eq 'sales_order') {
1230       $form->{label} = $locale->text('Sales Order');
1231
1232       $numberfld = "sonumber";
1233       $ordnumber = "ordnumber";
1234     } else {
1235       $form->{label} = $locale->text('Purchase Order');
1236
1237       $numberfld = "ponumber";
1238       $ordnumber = "ordnumber";
1239     }
1240
1241     $err = $locale->text('Cannot save order!');
1242
1243     check_delivered_flag();
1244
1245   } else {
1246     if ($form->{type} eq 'sales_quotation') {
1247       $form->{label} = $locale->text('Quotation');
1248
1249       $numberfld = "sqnumber";
1250       $ordnumber = "quonumber";
1251     } else {
1252       $form->{label} = $locale->text('Request for Quotation');
1253
1254       $numberfld = "rfqnumber";
1255       $ordnumber = "quonumber";
1256     }
1257
1258     $err = $locale->text('Cannot save quotation!');
1259
1260   }
1261
1262   $form->{$ordnumber} = $form->update_defaults(\%myconfig, $numberfld)
1263     unless $form->{$ordnumber};
1264
1265   relink_accounts();
1266
1267   OE->save(\%myconfig, \%$form);
1268
1269   # saving the history
1270   if(!exists $form->{addition}) {
1271     $form->{snumbers} = qq|ordnumber_| . $form->{ordnumber};
1272         $form->{addition} = "SAVED";
1273         $form->save_history($form->dbconnect(\%myconfig));
1274   }
1275   # /saving the history 
1276
1277   $form->{simple_save} = 1;
1278   if(!$form->{print_and_save}) {
1279     set_headings("edit");
1280     &update;
1281     exit;
1282   }
1283   $lxdebug->leave_sub();
1284 }
1285
1286 sub delete {
1287   $lxdebug->enter_sub();
1288
1289   check_oe_access();
1290
1291   $form->header;
1292
1293   if ($form->{type} =~ /_order$/) {
1294     $msg       = $locale->text('Are you sure you want to delete Order Number');
1295     $ordnumber = 'ordnumber';
1296   } else {
1297     $msg = $locale->text('Are you sure you want to delete Quotation Number');
1298     $ordnumber = 'quonumber';
1299   }
1300
1301   print qq|
1302 <body>
1303
1304 <form method=post action=$form->{script}>
1305 |;
1306
1307   # delete action variable
1308   map { delete $form->{$_} } qw(action header);
1309
1310   foreach $key (keys %$form) {
1311     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
1312     $form->{$key} =~ s/\"/&quot;/g;
1313     print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
1314   }
1315
1316   print qq|
1317 <h2 class=confirm>| . $locale->text('Confirm!') . qq|</h2>
1318
1319 <h4>$msg $form->{$ordnumber}</h4>
1320 <p>
1321 <input type="hidden" name="yes_nextsub" value="delete_order_quotation">
1322 <input name=action class=submit type=submit value="|
1323     . $locale->text('Yes') . qq|">
1324 <button class=submit type=button onclick="history.back()">|
1325     . $locale->text('No') . qq|</button>
1326 </form>
1327
1328 </body>
1329 </html>
1330 |;
1331
1332   $lxdebug->leave_sub();
1333 }
1334
1335 sub delete_order_quotation {
1336   $lxdebug->enter_sub();
1337
1338   check_oe_access();
1339
1340   if ($form->{type} =~ /_order$/) {
1341     $msg = $locale->text('Order deleted!');
1342     $err = $locale->text('Cannot delete order!');
1343   } else {
1344     $msg = $locale->text('Quotation deleted!');
1345     $err = $locale->text('Cannot delete quotation!');
1346   }
1347   if (OE->delete(\%myconfig, \%$form, $spool)){
1348     # saving the history
1349     if(!exists $form->{addition}) {
1350       $form->{snumbers} = qq|ordnumber_| . $form->{ordnumber};
1351           $form->{addition} = "DELETED";
1352           $form->save_history($form->dbconnect(\%myconfig));
1353     }
1354     # /saving the history 
1355     $form->info($msg);
1356     exit();
1357   }
1358   $form->error($err);
1359
1360   $lxdebug->leave_sub();
1361 }
1362
1363 sub invoice {
1364   $lxdebug->enter_sub();
1365
1366   check_oe_access();
1367   $auth->assert($form->{type} eq 'purchase_order' || $form->{type} eq 'request_quotation' ? 'vendor_invoice_edit' : 'invoice_edit');
1368
1369   $form->{old_employee_id} = $form->{employee_id};
1370   $form->{old_salesman_id} = $form->{salesman_id};
1371
1372   if ($form->{type} =~ /_order$/) {
1373
1374     # these checks only apply if the items don't bring their own ordnumbers/transdates.
1375     # The if clause ensures that by searching for empty ordnumber_#/transdate_# fields.
1376     $form->isblank("ordnumber", $locale->text('Order Number missing!'))
1377       if (+{ map { $form->{"ordnumber_$_"}, 1 } (1 .. $form->{rowcount} - 1) }->{''});
1378     $form->isblank("transdate", $locale->text('Order Date missing!'))
1379       if (+{ map { $form->{"transdate_$_"}, 1 } (1 .. $form->{rowcount} - 1) }->{''});
1380
1381     # also copy deliverydate from the order
1382     $form->{deliverydate} = $form->{reqdate} if $form->{reqdate};
1383     $form->{orddate}      = $form->{transdate};
1384   } else {
1385     $form->isblank("quonumber", $locale->text('Quotation Number missing!'));
1386     $form->isblank("transdate", $locale->text('Quotation Date missing!'));
1387     $form->{ordnumber}    = "";
1388     $form->{quodate}      = $form->{transdate};
1389   }
1390   
1391   $payment_id = $form->{payment_id} if $form->{payment_id};
1392   
1393   # if the name changed get new values
1394   if (&check_name($form->{vc})) {
1395     $form->{payment_id} = $payment_id if $form->{payment_id} eq "";
1396     &update;
1397     exit;
1398   }
1399
1400   $form->{cp_id} *= 1;
1401
1402   for $i (1 .. $form->{rowcount}) {
1403     for (qw(ship qty sellprice listprice basefactor)) {
1404       $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig, $form->{"${_}_${i}"}) if $form->{"${_}_${i}"};
1405     }
1406   }
1407
1408   if (   $form->{type} =~ /_order/
1409       && $form->{currency} ne $form->{defaultcurrency}) {
1410
1411     # check if we need a new exchangerate
1412     $buysell = ($form->{type} eq 'sales_order') ? "buy" : "sell";
1413
1414     $orddate      = $form->current_date(\%myconfig);
1415     $exchangerate = $form->check_exchangerate(\%myconfig, $form->{currency}, $orddate, $buysell);
1416
1417     if (!$exchangerate) {
1418       &backorder_exchangerate($orddate, $buysell);
1419       exit;
1420     }
1421   }
1422
1423   $form->{convert_from_oe_ids} = $form->{id};
1424   $form->{transdate}           = $form->{invdate} = $form->current_date(\%myconfig);
1425   $form->{duedate}             = $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
1426   $form->{shipto}              = 1;
1427   $form->{defaultcurrency}     = $form->get_default_currency(\%myconfig);
1428
1429   delete @{$form}{qw(id closed)};
1430   $form->{rowcount}--;
1431
1432   if ($form->{type} =~ /_order$/) {
1433     $form->{exchangerate} = $exchangerate;
1434     &create_backorder;
1435   }
1436
1437   if (   $form->{type} eq 'purchase_order'
1438       || $form->{type} eq 'request_quotation') {
1439     $form->{title}  = $locale->text('Add Vendor Invoice');
1440     $form->{script} = 'ir.pl';
1441     $script         = "ir";
1442     $buysell        = 'sell';
1443   }
1444
1445   if (   $form->{type} eq 'sales_order' 
1446       || $form->{type} eq 'sales_quotation') {
1447     $form->{title}  = $locale->text('Add Sales Invoice');
1448     $form->{script} = 'is.pl';
1449     $script         = "is";
1450     $buysell        = 'buy';
1451   }
1452
1453   # bo creates the id, reset it
1454   map { delete $form->{$_} } qw(id subject message cc bcc printed emailed queued);
1455   $form->{ $form->{vc} } =~ s/--.*//g;
1456   $form->{type} = "invoice";
1457
1458   # locale messages
1459   $locale = new Locale "$myconfig{countrycode}", "$script";
1460
1461   require "bin/mozilla/$form->{script}";
1462
1463   map { $form->{"select$_"} = "" } ($form->{vc}, currency);
1464
1465   $currency = $form->{currency};
1466   &invoice_links;
1467
1468   $form->{currency}     = $currency;
1469   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{invdate}, $buysell);
1470   $form->{exchangerate} = $form->{forex} || '';
1471
1472   $form->{creditremaining} -= ($form->{oldinvtotal} - $form->{ordtotal});
1473
1474   &prepare_invoice;
1475
1476   # format amounts
1477   for $i (1 .. $form->{rowcount}) {
1478     $form->{"discount_$i"} =
1479       $form->format_amount(\%myconfig, $form->{"discount_$i"});
1480
1481     ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
1482     $dec           = length $dec;
1483     $decimalplaces = ($dec > 2) ? $dec : 2;
1484
1485     # copy delivery date from reqdate for order -> invoice conversion
1486     $form->{"deliverydate_$i"} = $form->{"reqdate_$i"}
1487       unless $form->{"deliverydate_$i"};
1488
1489     $form->{"sellprice_$i"} =
1490       $form->format_amount(\%myconfig, $form->{"sellprice_$i"},
1491                            $decimalplaces);
1492
1493     (my $dec_qty) = ($form->{"qty_$i"} =~ /\.(\d+)/);
1494     $dec_qty = length $dec_qty;
1495     $form->{"qty_$i"} =
1496       $form->format_amount(\%myconfig, $form->{"qty_$i"}, $dec_qty);
1497
1498     map { $form->{"${_}_$i"} =~ s/\"/&quot;/g }
1499       qw(partnumber description unit);
1500
1501   }
1502
1503   &display_form;
1504
1505   $lxdebug->leave_sub();
1506 }
1507
1508 sub backorder_exchangerate {
1509   $lxdebug->enter_sub();
1510
1511   check_oe_access();
1512
1513   my ($orddate, $buysell) = @_;
1514
1515   $form->header;
1516
1517   print qq|
1518 <body>
1519
1520 <form method=post action=$form->{script}>
1521 |;
1522
1523   # delete action variable
1524   map { delete $form->{$_} } qw(action header exchangerate);
1525
1526   foreach $key (keys %$form) {
1527     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
1528     $form->{$key} =~ s/\"/&quot;/g;
1529     print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
1530   }
1531
1532   $form->{title} = $locale->text('Add Exchangerate');
1533
1534   print qq|
1535
1536 <input type=hidden name=exchangeratedate value=$orddate>
1537 <input type=hidden name=buysell value=$buysell>
1538
1539 <table width=100%>
1540   <tr><th class=listtop>$form->{title}</th></tr>
1541   <tr height="5"></tr>
1542   <tr>
1543     <td>
1544       <table>
1545         <tr>
1546           <th align=right>| . $locale->text('Currency') . qq|</th>
1547           <td>$form->{currency}</td>
1548         </tr>
1549         <tr>
1550           <th align=right>| . $locale->text('Date') . qq|</th>
1551           <td>$orddate</td>
1552         </tr>
1553         <tr>
1554           <th align=right>| . $locale->text('Exchangerate') . qq|</th>
1555           <td><input name=exchangerate size=11></td>
1556         </tr>
1557       </table>
1558     </td>
1559   </tr>
1560 </table>
1561
1562 <hr size=3 noshade>
1563
1564 <br>
1565 <input type=hidden name=nextsub value=save_exchangerate>
1566
1567 <input name=action class=submit type=submit value="|
1568     . $locale->text('Continue') . qq|">
1569
1570 </form>
1571
1572 </body>
1573 </html>
1574 |;
1575
1576   $lxdebug->leave_sub();
1577 }
1578
1579 sub save_exchangerate {
1580   $lxdebug->enter_sub();
1581
1582   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'));
1583   $form->{exchangerate} =
1584     $form->parse_amount(\%myconfig, $form->{exchangerate});
1585   $form->save_exchangerate(\%myconfig, $form->{currency},
1586                            $form->{exchangeratedate},
1587                            $form->{exchangerate}, $form->{buysell});
1588
1589   &invoice;
1590
1591   $lxdebug->leave_sub();
1592 }
1593
1594 sub create_backorder {
1595   $lxdebug->enter_sub();
1596
1597   $form->{shipped} = 1;
1598
1599   # figure out if we need to create a backorder
1600   # items aren't saved if qty != 0
1601
1602   for $i (1 .. $form->{rowcount}) {
1603     $totalqty  += $qty  = $form->{"qty_$i"};
1604     $totalship += $ship = $form->{"ship_$i"};
1605
1606     $form->{"qty_$i"} = $qty - $ship;
1607   }
1608
1609   if ($totalship == 0) {
1610     map { $form->{"ship_$_"} = $form->{"qty_$_"} } (1 .. $form->{rowcount});
1611     $form->{ordtotal} = 0;
1612     $form->{shipped}  = 0;
1613     return;
1614   }
1615
1616   if ($totalqty == $totalship) {
1617     map { $form->{"qty_$_"} = $form->{"ship_$_"} } (1 .. $form->{rowcount});
1618     $form->{ordtotal} = 0;
1619     return;
1620   }
1621
1622   @flds = (
1623     qw(partnumber description qty ship unit sellprice discount id inventory_accno bin income_accno expense_accno listprice assembly taxaccounts partsgroup)
1624   );
1625
1626   for $i (1 .. $form->{rowcount}) {
1627     map {
1628       $form->{"${_}_$i"} =
1629         $form->format_amount(\%myconfig, $form->{"${_}_$i"})
1630     } qw(sellprice discount);
1631   }
1632
1633   relink_accounts();
1634
1635   OE->save(\%myconfig, \%$form);
1636
1637   # rebuild rows for invoice
1638   @a     = ();
1639   $count = 0;
1640
1641   for $i (1 .. $form->{rowcount}) {
1642     $form->{"qty_$i"} = $form->{"ship_$i"};
1643
1644     if ($form->{"qty_$i"}) {
1645       push @a, {};
1646       $j = $#a;
1647       map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
1648       $count++;
1649     }
1650   }
1651
1652   $form->redo_rows(\@flds, \@a, $count, $form->{rowcount});
1653   $form->{rowcount} = $count;
1654
1655   $lxdebug->leave_sub();
1656 }
1657
1658 sub save_as_new {
1659   $lxdebug->enter_sub();
1660
1661   check_oe_access();
1662
1663   $form->{saveasnew} = 1;
1664   $form->{closed}    = 0;
1665   map { delete $form->{$_} } qw(printed emailed queued);
1666
1667   # Let Lx-Office assign a new order number if the user hasn't changed the
1668   # previous one. If it has been changed manually then use it as-is.
1669   my $idx = $form->{type} =~ /_quotation$/ ? "quonumber" : "ordnumber";
1670   $form->{$idx} =~ s/^\s*//g;
1671   $form->{$idx} =~ s/\s*$//g;
1672   if ($form->{saved_xyznumber} &&
1673       ($form->{saved_xyznumber} eq $form->{$idx})) {
1674     delete($form->{$idx});
1675   }
1676
1677   &save;
1678
1679   $lxdebug->leave_sub();
1680 }
1681
1682 sub check_for_direct_delivery_yes {
1683   $lxdebug->enter_sub();
1684
1685   check_oe_access();
1686
1687   $form->{direct_delivery_checked} = 1;
1688   delete @{$form}{grep /^shipto/, keys %{ $form }};
1689   map { s/^CFDD_//; $form->{$_} = $form->{"CFDD_${_}"} } grep /^CFDD_/, keys %{ $form };
1690   $form->{shipto} = 1;
1691   purchase_order();
1692   $lxdebug->leave_sub();
1693 }
1694
1695 sub check_for_direct_delivery_no {
1696   $lxdebug->enter_sub();
1697
1698   check_oe_access();
1699
1700   $form->{direct_delivery_checked} = 1;
1701   delete @{$form}{grep /^shipto/, keys %{ $form }};
1702   purchase_order();
1703
1704   $lxdebug->leave_sub();
1705 }
1706
1707 sub check_for_direct_delivery {
1708   $lxdebug->enter_sub();
1709
1710   check_oe_access();
1711
1712   if ($form->{direct_delivery_checked}
1713       || (!$form->{shiptoname} && !$form->{shiptostreet} && !$form->{shipto_id})) {
1714     $lxdebug->leave_sub();
1715     return;
1716   }
1717
1718   if ($form->{shipto_id}) {
1719     Common->get_shipto_by_id(\%myconfig, $form, $form->{shipto_id}, "CFDD_");
1720
1721   } else {
1722     map { $form->{"CFDD_${_}"} = $form->{$_ } } grep /^shipto/, keys %{ $form };
1723   }
1724
1725   delete $form->{action};
1726   $form->{VARIABLES} = [ map { { "key" => $_, "value" => $form->{$_} } } grep { ($_ ne 'login') && ($_ ne 'password') && (ref $_ eq "") } keys %{ $form } ];
1727
1728   $form->header();
1729   print $form->parse_html_template("oe/check_for_direct_delivery");
1730
1731   $lxdebug->leave_sub();
1732
1733   exit 0;
1734 }
1735
1736 sub purchase_order {
1737   $lxdebug->enter_sub();
1738
1739   check_oe_access();
1740   $auth->assert('purchase_order_edit');
1741
1742   if ($form->{type} eq 'sales_order') {
1743     check_for_direct_delivery();
1744   }
1745
1746   if ($form->{type} =~ /^sales_/) {
1747     delete($form->{ordnumber});
1748   }
1749
1750   $form->{cp_id} *= 1;
1751
1752   $form->{title} = $locale->text('Add Purchase Order');
1753   $form->{vc}    = "vendor";
1754   $form->{type}  = "purchase_order";
1755
1756   &poso;
1757
1758   $lxdebug->leave_sub();
1759 }
1760
1761 sub sales_order {
1762   $lxdebug->enter_sub();
1763
1764   check_oe_access();
1765   $auth->assert('sales_order_edit');
1766
1767   if ($form->{type} eq "purchase_order") {
1768     delete($form->{ordnumber});
1769   }
1770
1771   $form->{cp_id} *= 1;
1772
1773   $form->{title}  = $locale->text('Add Sales Order');
1774   $form->{vc}     = "customer";
1775   $form->{type}   = "sales_order";
1776
1777   &poso;
1778
1779   $lxdebug->leave_sub();
1780 }
1781
1782 sub poso {
1783   $lxdebug->enter_sub();
1784
1785   check_oe_access();
1786   $auth->assert('purchase_order_edit | sales_order_edit');
1787
1788   $form->{transdate} = $form->current_date(\%myconfig);
1789   delete $form->{duedate};
1790
1791   $form->{convert_from_oe_ids} = $form->{id};
1792   $form->{closed}              = 0;
1793
1794   $form->{old_employee_id}     = $form->{employee_id};
1795   $form->{old_salesman_id}     = $form->{salesman_id};
1796
1797   # reset
1798   map { delete $form->{$_} } qw(id subject message cc bcc printed emailed queued customer vendor creditlimit creditremaining discount tradediscount oldinvtotal delivered);
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