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