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