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