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