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