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