Verkauf->Berichte: Auftrag und Angebot Suche nach Salesman implementiert.
[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                    "salesmen"  => "ALL_SALESMEN",
1314                    $vc         => "ALL_" . uc($vc)
1315                   );
1316
1317   my %labels = ();
1318   my @values = ("");
1319   foreach my $item (@{ $form->{"ALL_PROJECTS"} }) {
1320     push(@values, $item->{"id"});
1321     $labels{$item->{"id"}} = $item->{"projectnumber"};
1322   }
1323   my $projectnumber =
1324     NTI($cgi->popup_menu('-name' => 'project_id', '-values' => \@values,
1325                          '-labels' => \%labels));
1326
1327   #employees
1328   %labels = ();
1329   @values = ("");
1330   foreach my $item (@{ $form->{"ALL_EMPLOYEES"} }) {
1331     push(@values, $item->{"id"});
1332     $labels{$item->{"id"}} = $item->{"name"} ne "" ? $item->{"name"} : $item->{"login"};
1333   }
1334   
1335   #salesmen
1336   my %labels_salesmen = ();
1337   my @values_salesmen = ('');
1338   foreach my $item (@{ $form->{"ALL_SALESMEN"} }) {
1339     push(@values_salesmen, $item->{"id"});
1340     $labels_salesmen{$item->{"id"}} = $item->{"name"} ne "" ? $item->{"name"} : $item->{"login"};
1341   }
1342
1343   my $employee_block = qq|
1344     <tr>
1345       <th align="right">| . $locale->text('Employee') . qq|</th>
1346       <td>| .
1347         NTI($cgi->popup_menu('-name'   => 'employee_id',
1348                              '-values' => \@values,
1349                              '-labels' => \%labels)) . qq|
1350       </td>
1351     </tr>
1352     <tr>
1353       <th align="right">| . $locale->text('Salesman') . qq|</th>
1354       <td>| .
1355         NTI($cgi->popup_menu('-name'   => 'salesman_id',
1356                              '-values' => \@values_salesmen,
1357                              '-labels' => \%labels_salesmen)) . qq|
1358       </td>
1359     </tr>|;
1360
1361   %labels = ();
1362   @values = ("");
1363
1364   foreach my $item (@{ $form->{($form->{vc} eq "customer" ? "ALL_CUSTOMERS" : "ALL_VENDORS")}}) {
1365     push(@values, $item->{name}.qq|--|.$item->{"id"});
1366     $labels{$item->{name}.qq|--|.$item->{"id"}} = $item->{"name"};
1367   }
1368
1369   my $vc_label = $form->{vc} eq "customer" ? $locale->text('Customer') : $locale->text('Vendor');
1370   $vc =
1371     $myconfig{vclimit} <=  scalar(@values)
1372     ? qq|<input type="text" value="| . H(($form->{"old$form->{vc}"} =~ /^(.*)\-\-.*$/)) . qq|" name="$form->{vc}">| 
1373     : NTI($cgi->popup_menu('-name' => "$form->{vc}",
1374                            '-default' => $form->{"old$form->{vc}"},
1375                            '-onChange' => 'document.getElementById(\'update_button\').click();',
1376                            '-values' => \@values,
1377                            '-labels' => \%labels));
1378   $form->header;
1379
1380   print qq|
1381 <body>
1382
1383 <form method=post action=$form->{script}>
1384
1385 <table width=100%>
1386   <tr>
1387     <th class=listtop>$form->{title}</th>
1388   </tr>
1389   <tr height="5"></tr>
1390   <tr>
1391     <td>
1392       <table>
1393         <tr>
1394           <th align=right>$vc_label</th>
1395           <td colspan=3>$vc</td>
1396         </tr>
1397         $department
1398         <tr>
1399           <th align=right>$ordlabel</th>
1400           <td colspan=3><input name="$ordnumber" size=20></td>
1401         </tr>
1402   $employee_block
1403         <tr>
1404           <th align="right">| . $locale->text('Transaction description') . qq|</th>
1405           <td colspan="3"><input name="transaction_description" size=20></td>
1406         </tr>
1407         <tr>
1408           <th align="right">| . $locale->text("Project Number") . qq|</th>
1409           <td colspan="3">$projectnumber</td>
1410         </tr>
1411         <tr>
1412           <th align=right>| . $locale->text('From') . qq|</th>
1413           $button1
1414           <th align=right>| . $locale->text('Bis') . qq|</th>
1415           $button2
1416         </tr>
1417         <input type=hidden name=sort value=transdate>
1418         <tr>
1419           <th align=right>| . $locale->text('Include in Report') . qq|</th>
1420           <td colspan=5>
1421             <table>
1422         <tr>
1423           <td><input type="checkbox" name="open" value="1" id="open" checked>
1424             <label for="open">| . $locale->text("Open") . qq|</td>
1425           <td><input type="checkbox" name="closed" value="1" id="closed">
1426             <label for="closed">| . $locale->text("Closed") . qq|</td>
1427         </tr>
1428         $delivered
1429               <tr>
1430                 <td><input name="l_id" class=checkbox type=checkbox value=Y>
1431                 | . $locale->text('ID') . qq|</td>
1432                 <td><input name="l_$ordnumber" class=checkbox type=checkbox value=Y checked> $ordlabel</td>
1433                 <td><input name="l_transdate" class=checkbox type=checkbox value=Y checked> |
1434     . $locale->text('Date') . qq|</td>
1435                 <td><input name="l_reqdate" class=checkbox type=checkbox value=Y checked> |
1436     . $locale->text('Required by') . qq|</td>
1437               </tr>
1438               <tr>
1439                 <td><input name="l_name" class=checkbox type=checkbox value=Y checked> $vc_label</td>
1440                 <td><input name="l_employee" class=checkbox type=checkbox value=Y checked> $employee</td>
1441                 
1442                 <td><input name="l_shipvia" class=checkbox type=checkbox value=Y> |
1443     . $locale->text('Ship via') . qq|</td>
1444               </tr>
1445               <tr>
1446                 <td><input name="l_netamount" class=checkbox type=checkbox value=Y> |
1447     . $locale->text('Amount') . qq|</td>
1448                 <td><input name="l_tax" class=checkbox type=checkbox value=Y> |
1449     . $locale->text('Tax') . qq|</td>
1450                 <td><input name="l_amount" class=checkbox type=checkbox value=Y checked> |
1451     . $locale->text('Total') . qq|</td>
1452               </tr>
1453               <tr>
1454                 <td><input name="l_marge_total" class=checkbox type=checkbox value=Y> |
1455     .             $locale->text('Ertrag') . qq|</td>
1456                 <td><input name="l_marge_percent" class=checkbox type=checkbox value=Y> |
1457     .             $locale->text('Ertrag prozentual') . qq|</td>
1458               </tr>
1459               <tr>
1460           <td><input name="l_globalprojectnumber" class=checkbox type=checkbox value=Y> |
1461           . $locale->text('Project Number') . qq|</td>
1462           <td><input name="l_transaction_description" class=checkbox type=checkbox value=Y> |
1463           . $locale->text('Transaction description') . qq|</td>
1464               </tr>
1465               <tr>
1466                 <td><input name="l_subtotal" class=checkbox type=checkbox value=Y> |
1467     . $locale->text('Subtotal') . qq|</td>
1468                 <td><input name="l_salesman" class="checkbox" type="checkbox" value="Y"> |
1469     . $locale->text('Salesman') . qq|</td>
1470               </tr>
1471             </table>
1472           </td>
1473         </tr>
1474       </table>
1475     </td>
1476   </tr>
1477   <tr><td colspan=4><hr size=3 noshade></td></tr>
1478 </table>
1479
1480 $jsscript
1481
1482 <br>
1483 <input type=hidden name=nextsub value=orders>
1484 <input type=hidden name=login value=$form->{login}>
1485 <input type=hidden name=password value=$form->{password}>
1486 <input type=hidden name=vc value=$form->{vc}>
1487 <input type=hidden name=type value=$form->{type}>
1488
1489 <input class=submit type=submit name=action value="|
1490     . $locale->text('Continue') . qq|">
1491 </form>
1492
1493 </body>
1494 </html>
1495 |;
1496
1497   $lxdebug->leave_sub();
1498 }
1499
1500 sub create_subtotal_row {
1501   $lxdebug->enter_sub();
1502
1503   my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
1504
1505   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
1506
1507   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
1508
1509   $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
1510
1511   map { $totals->{$_} = 0 } @{ $subtotal_columns };
1512
1513   $lxdebug->leave_sub();
1514
1515   return $row;
1516 }
1517
1518 sub orders {
1519   $lxdebug->enter_sub();
1520
1521   $ordnumber = ($form->{type} =~ /_order$/) ? "ordnumber" : "quonumber";
1522
1523   ($form->{ $form->{vc} }, $form->{"${form->{vc}}_id"}) = split(/--/, $form->{ $form->{vc} });
1524
1525   $form->{sort} ||= 'transdate';
1526
1527   OE->transactions(\%myconfig, \%$form);
1528
1529   $form->{rowcount} = scalar @{ $form->{OE} };
1530
1531   my @columns = (
1532     "transdate",               "reqdate",
1533     "id",                      $ordnumber,
1534     "name",                    "netamount",
1535     "tax",                     "amount",
1536     "curr",                    "employee",
1537     "salesman",
1538     "shipvia",                 "globalprojectnumber",
1539     "transaction_description", "open",
1540     "delivered", "marge_total", "marge_percent"
1541   );
1542
1543   # only show checkboxes if gotten here via sales_order form.
1544   my $allow_multiple_orders = $form->{type} eq 'sales_order';
1545   if ($allow_multiple_orders) {
1546     unshift @columns, "ids";
1547   }
1548
1549   $form->{l_open}      = $form->{l_closed} = "Y" if ($form->{open}      && $form->{closed});
1550   $form->{l_delivered} = "Y"                     if ($form->{delivered} && $form->{notdelivered});
1551
1552   my $attachment_basename;
1553   if ($form->{vc} eq 'vendor') {
1554     if ($form->{type} eq 'purchase_order') {
1555       $form->{title}       = $locale->text('Purchase Orders');
1556       $attachment_basename = $locale->text('purchase_order_list');
1557     } else {
1558       $form->{title}       = $locale->text('Request for Quotations');
1559       $attachment_basename = $locale->text('rfq_list');
1560     }
1561
1562   } else {
1563     if ($form->{type} eq 'sales_order') {
1564       $form->{title}       = $locale->text('Sales Orders');
1565       $attachment_basename = $locale->text('sales_order_list');
1566     } else {
1567       $form->{title}       = $locale->text('Quotations');
1568       $attachment_basename = $locale->text('quotation_list');
1569     }
1570   }
1571
1572   my $report = SL::ReportGenerator->new(\%myconfig, $form);
1573
1574   my @hidden_variables = map { "l_${_}" } @columns;
1575   push @hidden_variables, "l_subtotal", $form->{vc}, qw(l_closed l_notdelivered open closed delivered notdelivered ordnumber quonumber
1576                                                         transaction_description transdatefrom transdateto type vc employee_id salesman_id);
1577
1578   my $href = build_std_url('action=orders', grep { $form->{$_} } @hidden_variables);
1579
1580   my %column_defs = (
1581     'ids'                     => { 'text' => '', },
1582     'transdate'               => { 'text' => $locale->text('Date'), },
1583     'reqdate'                 => { 'text' => $locale->text('Required by'), },
1584     'id'                      => { 'text' => $locale->text('ID'), },
1585     'ordnumber'               => { 'text' => $locale->text('Order'), },
1586     'quonumber'               => { 'text' => $form->{type} eq "request_quotation" ? $locale->text('RFQ') : $locale->text('Quotation'), },
1587     'name'                    => { 'text' => $form->{vc} eq 'customer' ? $locale->text('Customer') : $locale->text('Vendor'), },
1588     'netamount'               => { 'text' => $locale->text('Amount'), },
1589     'tax'                     => { 'text' => $locale->text('Tax'), },
1590     'amount'                  => { 'text' => $locale->text('Total'), },
1591     'curr'                    => { 'text' => $locale->text('Curr'), },
1592     'employee'                => { 'text' => $locale->text('Employee'), },
1593     'salesman'                => { 'text' => $locale->text('Salesman'), },
1594     'shipvia'                 => { 'text' => $locale->text('Ship via'), },
1595     'globalprojectnumber'     => { 'text' => $locale->text('Project Number'), },
1596     'transaction_description' => { 'text' => $locale->text('Transaction description'), },
1597     'open'                    => { 'text' => $locale->text('Open'), },
1598     'delivered'               => { 'text' => $locale->text('Delivered'), },
1599     'marge_total'                   => { 'text' => $locale->text('Ertrag'), },
1600     'marge_percent'           => { 'text' => $locale->text('Ertrag prozentual'), }
1601   );
1602
1603   foreach my $name (qw(id transdate reqdate quonumber ordnumber name employee salesman shipvia)) {
1604     $column_defs{$name}->{link} = $href . "&sort=$name";
1605   }
1606
1607   my %column_alignment = map { $_ => 'right' } qw(netamount tax amount curr);
1608
1609   $form->{"l_type"} = "Y";
1610   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
1611   $column_defs{ids}->{visible} = $allow_multiple_orders ? 'HTML' : 0;
1612
1613   $report->set_columns(%column_defs);
1614   $report->set_column_order(@columns);
1615
1616   $report->set_export_options('orders', @hidden_variables);
1617
1618   $report->set_sort_indicator($form->{sort}, 1);
1619
1620   my @options;
1621   if ($form->{customer}) {
1622     push @options, $locale->text('Customer') . " : $form->{customer}";
1623   }
1624   if ($form->{vendor}) {
1625     push @options, $locale->text('Vendor') . " : $form->{vendor}";
1626   }
1627   if ($form->{department}) {
1628     ($department) = split /--/, $form->{department};
1629     push @options, $locale->text('Department') . " : $department";
1630   }
1631   if ($form->{ordnumber}) {
1632     push @options, $locale->text('Order Number') . " : $form->{ordnumber}";
1633   }
1634   if ($form->{notes}) {
1635     push @options, $locale->text('Notes') . " : $form->{notes}";
1636   }
1637   if ($form->{transaction_description}) {
1638     push @options, $locale->text('Transaction description') . " : $form->{transaction_description}";
1639   }
1640   if ($form->{transdatefrom}) {
1641     push @options, $locale->text('From') . "&nbsp;" . $locale->date(\%myconfig, $form->{transdatefrom}, 1);
1642   }
1643   if ($form->{transdateto}) {
1644     push @options, $locale->text('Bis') . "&nbsp;" . $locale->date(\%myconfig, $form->{transdateto}, 1);
1645   }
1646   if ($form->{open}) {
1647     push @options, $locale->text('Open');
1648   }
1649   if ($form->{closed}) {
1650     push @options, $locale->text('Closed');
1651   }
1652   if ($form->{delivered}) {
1653     push @options, $locale->text('Delivered');
1654   }
1655   if ($form->{notdelivered}) {
1656     push @options, $locale->text('Not delivered');
1657   }
1658
1659   $report->set_options('top_info_text'        => join("\n", @options),
1660                        'raw_top_info_text'    => $form->parse_html_template('oe/orders_top'),
1661                        'raw_bottom_info_text' => $form->parse_html_template('oe/orders_bottom', { 'SHOW_CONTINUE_BUTTON' => $allow_multiple_orders }),
1662                        'output_format'        => 'HTML',
1663                        'title'                => $form->{title},
1664                        'attachment_basename'  => $attachment_basename . strftime('_%Y%m%d', localtime time),
1665     );
1666   $report->set_options_from_form();
1667
1668   # add sort and escape callback, this one we use for the add sub
1669   $form->{callback} = $href .= "&sort=$form->{sort}";
1670
1671   # escape callback for href
1672   $callback = $form->escape($href);
1673
1674   my @subtotal_columns = qw(netamount amount marge_total marge_percent);
1675
1676   my %totals    = map { $_ => 0 } @subtotal_columns;
1677   my %subtotals = map { $_ => 0 } @subtotal_columns;
1678
1679   my $idx = 0;
1680
1681   my $edit_url = build_std_url('action=edit', 'type', 'vc');
1682
1683   foreach $oe (@{ $form->{OE} }) {
1684     map { $oe->{$_} *= $oe->{exchangerate} } @subtotal_columns;
1685
1686     $oe->{tax}       = $oe->{amount} - $oe->{netamount};
1687     $oe->{open}      = $oe->{closed}    ? $locale->text('No')  : $locale->text('Yes');
1688     $oe->{delivered} = $oe->{delivered} ? $locale->text('Yes') : $locale->text('No');
1689
1690     map { $subtotals{$_} += $oe->{$_};
1691           $totals{$_}    += $oe->{$_} } @subtotal_columns;
1692
1693     $subtotals{marge_percent} = $subtotals{netamount} ? ($subtotals{marge_total} * 100 / $subtotals{netamount}) : 0;
1694     $totals{marge_percent}    = $totals{netamount}    ? ($totals{marge_total}    * 100 / $totals{netamount}   ) : 0;
1695
1696     map { $oe->{$_} = $form->format_amount(\%myconfig, $oe->{$_}, 2) } qw(netamount tax amount marge_total marge_percent);
1697
1698     my $row = { };
1699
1700     foreach my $column (@columns) {
1701       next if ($column eq 'ids');
1702       $row->{$column} = {
1703         'data'  => $oe->{$column},
1704         'align' => $column_alignment{$column},
1705       };
1706     }
1707
1708     $row->{ids} = {
1709       'raw_data' =>   $cgi->hidden('-name' => "trans_id_${idx}", '-value' => $oe->{id})
1710                     . $cgi->checkbox('-name' => "multi_id_${idx}", '-value' => 1, '-label' => ''),
1711       'valign'   => 'center',
1712       'align'    => 'center',
1713     };
1714
1715     $row->{$ordnumber}->{link} = $edit_url . "&id=" . E($oe->{id}) . "&callback=${callback}";
1716
1717     my $row_set = [ $row ];
1718
1719     if (($form->{l_subtotal} eq 'Y')
1720         && (($idx == (scalar @{ $form->{OE} } - 1))
1721             || ($oe->{ $form->{sort} } ne $form->{OE}->[$idx + 1]->{ $form->{sort} }))) {
1722       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
1723     }
1724
1725     $report->add_data($row_set);
1726
1727     $idx++;
1728   }
1729
1730   $report->add_separator();
1731   $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
1732
1733   $report->generate_with_headers();
1734
1735   $lxdebug->leave_sub();
1736 }
1737
1738 sub check_delivered_flag {
1739   $lxdebug->enter_sub();
1740
1741   if (($form->{type} ne 'sales_order') && ($form->{type} ne 'purchase_order')) {
1742     return $lxdebug->leave_sub();
1743   }
1744
1745   my $all_delivered = 0;
1746
1747   foreach my $i (1 .. $form->{rowcount}) {
1748     next if (!$form->{"id_$i"});
1749
1750     if ($form->parse_amount(\%myconfig, $form->{"qty_$i"}) == $form->parse_amount(\%myconfig, $form->{"ship_$i"})) {
1751       $all_delivered = 1;
1752       next;
1753     }
1754
1755     $all_delivered = 0;
1756     last;
1757   }
1758
1759   $form->{delivered} = 1 if $all_delivered;
1760
1761   $lxdebug->leave_sub();
1762 }
1763
1764 sub save_and_close {
1765   $lxdebug->enter_sub();
1766
1767   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
1768
1769   if ($form->{type} =~ /_order$/) {
1770     $form->isblank("transdate", $locale->text('Order Date missing!'));
1771   } else {
1772     $form->isblank("transdate", $locale->text('Quotation Date missing!'));
1773   }
1774
1775   my $idx = $form->{type} =~ /_quotation$/ ? "quonumber" : "ordnumber";
1776   $form->{$idx} =~ s/^\s*//g;
1777   $form->{$idx} =~ s/\s*$//g;
1778
1779   $msg = ucfirst $form->{vc};
1780   $form->isblank($form->{vc}, $locale->text($msg . " missing!"));
1781
1782   # $locale->text('Customer missing!');
1783   # $locale->text('Vendor missing!');
1784
1785   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
1786     if ($form->{currency} ne $form->{defaultcurrency});
1787
1788   &validate_items;
1789   
1790   if($form->{payment_id}) { 
1791     $payment_id = $form->{payment_id};
1792   }
1793   
1794   # if the name changed get new values
1795   if (&check_name($form->{vc})) {
1796     if($form->{payment_id} eq "") { 
1797       $form->{payment_id} = $payment_id;
1798     }
1799     &update;
1800     exit;
1801   }
1802
1803   $form->{id} = 0 if $form->{saveasnew};
1804
1805   # this is for the internal notes section for the [email] Subject
1806   if ($form->{type} =~ /_order$/) {
1807     if ($form->{type} eq 'sales_order') {
1808       $form->{label} = $locale->text('Sales Order');
1809
1810       $numberfld = "sonumber";
1811       $ordnumber = "ordnumber";
1812     } else {
1813       $form->{label} = $locale->text('Purchase Order');
1814
1815       $numberfld = "ponumber";
1816       $ordnumber = "ordnumber";
1817     }
1818
1819     $err = $locale->text('Cannot save order!');
1820
1821     check_delivered_flag();
1822
1823   } else {
1824     if ($form->{type} eq 'sales_quotation') {
1825       $form->{label} = $locale->text('Quotation');
1826
1827       $numberfld = "sqnumber";
1828       $ordnumber = "quonumber";
1829     } else {
1830       $form->{label} = $locale->text('Request for Quotation');
1831
1832       $numberfld = "rfqnumber";
1833       $ordnumber = "quonumber";
1834     }
1835
1836     $err = $locale->text('Cannot save quotation!');
1837
1838   }
1839
1840   # get new number in sequence if no number is given or if saveasnew was requested
1841   if (!$form->{$ordnumber} || $form->{saveasnew}) {
1842     $form->{$ordnumber} = $form->update_defaults(\%myconfig, $numberfld);
1843   }
1844
1845   relink_accounts();
1846
1847   $form->error($err) if (!OE->save(\%myconfig, \%$form));
1848
1849   # saving the history
1850   if(!exists $form->{addition}) {
1851     $form->{snumbers} = qq|ordnumber_| . $form->{ordnumber};
1852         $form->{addition} = "SAVED";
1853         $form->save_history($form->dbconnect(\%myconfig));
1854   }
1855   # /saving the history
1856
1857   $form->redirect($form->{label} . " $form->{$ordnumber} " .
1858                   $locale->text('saved!'));
1859
1860   $lxdebug->leave_sub();
1861 }
1862
1863 sub save {
1864   $lxdebug->enter_sub();
1865
1866   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
1867
1868
1869   if ($form->{type} =~ /_order$/) {
1870     $form->isblank("transdate", $locale->text('Order Date missing!'));
1871   } else {
1872     $form->isblank("transdate", $locale->text('Quotation Date missing!'));
1873   }
1874
1875   my $idx = $form->{type} =~ /_quotation$/ ? "quonumber" : "ordnumber";
1876   $form->{$idx} =~ s/^\s*//g;
1877   $form->{$idx} =~ s/\s*$//g;
1878
1879   $msg = ucfirst $form->{vc};
1880   $form->isblank($form->{vc}, $locale->text($msg . " missing!"));
1881
1882   # $locale->text('Customer missing!');
1883   # $locale->text('Vendor missing!');
1884
1885   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
1886     if ($form->{currency} ne $form->{defaultcurrency});
1887
1888   &validate_items;
1889   
1890   if($form->{payment_id}) { 
1891     $payment_id = $form->{payment_id};
1892   }
1893   
1894   # if the name changed get new values
1895   if (&check_name($form->{vc})) {
1896     if($form->{payment_id} eq "") { 
1897       $form->{payment_id} = $payment_id;
1898     }
1899     &update;
1900     exit;
1901   }
1902
1903   $form->{id} = 0 if $form->{saveasnew};
1904
1905   # this is for the internal notes section for the [email] Subject
1906   if ($form->{type} =~ /_order$/) {
1907     if ($form->{type} eq 'sales_order') {
1908       $form->{label} = $locale->text('Sales Order');
1909
1910       $numberfld = "sonumber";
1911       $ordnumber = "ordnumber";
1912     } else {
1913       $form->{label} = $locale->text('Purchase Order');
1914
1915       $numberfld = "ponumber";
1916       $ordnumber = "ordnumber";
1917     }
1918
1919     $err = $locale->text('Cannot save order!');
1920
1921     check_delivered_flag();
1922
1923   } else {
1924     if ($form->{type} eq 'sales_quotation') {
1925       $form->{label} = $locale->text('Quotation');
1926
1927       $numberfld = "sqnumber";
1928       $ordnumber = "quonumber";
1929     } else {
1930       $form->{label} = $locale->text('Request for Quotation');
1931
1932       $numberfld = "rfqnumber";
1933       $ordnumber = "quonumber";
1934     }
1935
1936     $err = $locale->text('Cannot save quotation!');
1937
1938   }
1939
1940   $form->{$ordnumber} = $form->update_defaults(\%myconfig, $numberfld)
1941     unless $form->{$ordnumber};
1942
1943   relink_accounts();
1944
1945   OE->save(\%myconfig, \%$form);
1946
1947   # saving the history
1948   if(!exists $form->{addition}) {
1949     $form->{snumbers} = qq|ordnumber_| . $form->{ordnumber};
1950         $form->{addition} = "SAVED";
1951         $form->save_history($form->dbconnect(\%myconfig));
1952   }
1953   # /saving the history 
1954
1955   $form->{simple_save} = 1;
1956   if(!$form->{print_and_save}) {
1957     set_headings("edit");
1958     &update;
1959     exit;
1960   }
1961   $lxdebug->leave_sub();
1962 }
1963
1964 sub delete {
1965   $lxdebug->enter_sub();
1966
1967   $form->header;
1968
1969   if ($form->{type} =~ /_order$/) {
1970     $msg       = $locale->text('Are you sure you want to delete Order Number');
1971     $ordnumber = 'ordnumber';
1972   } else {
1973     $msg = $locale->text('Are you sure you want to delete Quotation Number');
1974     $ordnumber = 'quonumber';
1975   }
1976
1977   print qq|
1978 <body>
1979
1980 <form method=post action=$form->{script}>
1981 |;
1982
1983   # delete action variable
1984   map { delete $form->{$_} } qw(action header);
1985
1986   foreach $key (keys %$form) {
1987     $form->{$key} =~ s/\"/&quot;/g;
1988     print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
1989   }
1990
1991   print qq|
1992 <h2 class=confirm>| . $locale->text('Confirm!') . qq|</h2>
1993
1994 <h4>$msg $form->{$ordnumber}</h4>
1995 <p>
1996 <input type="hidden" name="yes_nextsub" value="delete_order_quotation">
1997 <input name=action class=submit type=submit value="|
1998     . $locale->text('Yes') . qq|">
1999 <button class=submit type=button onclick="history.back()">|
2000     . $locale->text('No') . qq|</button>
2001 </form>
2002
2003 </body>
2004 </html>
2005 |;
2006
2007   $lxdebug->leave_sub();
2008 }
2009
2010 sub delete_order_quotation {
2011   $lxdebug->enter_sub();
2012
2013   if ($form->{type} =~ /_order$/) {
2014     $msg = $locale->text('Order deleted!');
2015     $err = $locale->text('Cannot delete order!');
2016   } else {
2017     $msg = $locale->text('Quotation deleted!');
2018     $err = $locale->text('Cannot delete quotation!');
2019   }
2020   if (OE->delete(\%myconfig, \%$form, $spool)){
2021     # saving the history
2022     if(!exists $form->{addition}) {
2023       $form->{snumbers} = qq|ordnumber_| . $form->{ordnumber};
2024           $form->{addition} = "DELETED";
2025           $form->save_history($form->dbconnect(\%myconfig));
2026     }
2027     # /saving the history 
2028     $form->info($msg);
2029     exit();
2030   }
2031   $form->error($err);
2032
2033   $lxdebug->leave_sub();
2034 }
2035
2036 sub invoice {
2037   $lxdebug->enter_sub();
2038
2039   $form->{old_employee_id} = $form->{employee_id};
2040   $form->{old_salesman_id} = $form->{salesman_id};
2041
2042   if ($form->{type} =~ /_order$/) {
2043
2044     # these checks only apply if the items don't bring their own ordnumbers/transdates.
2045     # The if clause ensures that by searching for empty ordnumber_#/transdate_# fields.
2046     $form->isblank("ordnumber", $locale->text('Order Number missing!'))
2047       if (+{ map { $form->{"ordnumber_$_"}, 1 } (1 .. $form->{rowcount} - 1) }->{''});
2048     $form->isblank("transdate", $locale->text('Order Date missing!'))
2049       if (+{ map { $form->{"transdate_$_"}, 1 } (1 .. $form->{rowcount} - 1) }->{''});
2050
2051     # also copy deliverydate from the order
2052     $form->{deliverydate} = $form->{reqdate} if $form->{reqdate};
2053     $form->{orddate}      = $form->{transdate};
2054   } else {
2055     $form->isblank("quonumber", $locale->text('Quotation Number missing!'));
2056     $form->isblank("transdate", $locale->text('Quotation Date missing!'));
2057     $form->{ordnumber}    = "";
2058     $form->{quodate}      = $form->{transdate};
2059   }
2060   
2061   $payment_id = $form->{payment_id} if $form->{payment_id};
2062   
2063   # if the name changed get new values
2064   if (&check_name($form->{vc})) {
2065     $form->{payment_id} = $payment_id if $form->{payment_id} eq "";
2066     &update;
2067     exit;
2068   }
2069
2070   $form->{cp_id} *= 1;
2071
2072   for $i (1 .. $form->{rowcount}) {
2073     for (qw(ship qty sellprice listprice basefactor)) {
2074       $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig, $form->{"${_}_${i}"}) if $form->{"${_}_${i}"};
2075     }
2076   }
2077
2078   if (   $form->{type} =~ /_order/
2079       && $form->{currency} ne $form->{defaultcurrency}) {
2080
2081     # check if we need a new exchangerate
2082     $buysell = ($form->{type} eq 'sales_order') ? "buy" : "sell";
2083
2084     $orddate      = $form->current_date(\%myconfig);
2085     $exchangerate = $form->check_exchangerate(\%myconfig, $form->{currency}, $orddate, $buysell);
2086
2087     if (!$exchangerate) {
2088       &backorder_exchangerate($orddate, $buysell);
2089       exit;
2090     }
2091   }
2092
2093   # close orders/quotations
2094   $form->{closed} = 1;
2095
2096   # save order if one ordnumber has been given
2097   # if not it's most likely a collective order, which can't be saved back
2098   # so they just have to be closed
2099   if (($form->{ordnumber} ne '') || ($form->{quonumber} ne '')) {
2100     OE->close_order(\%myconfig, \%$form) if ($form->{id});
2101   } else {
2102     OE->close_orders(\%myconfig, \%$form);
2103   }
2104
2105   $form->{transdate} = $form->{invdate} = $form->current_date(\%myconfig);
2106   $form->{duedate}   = $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
2107
2108   $form->{id}     = '';
2109   $form->{closed} = 0;
2110   $form->{rowcount}--;
2111   $form->{shipto} = 1;
2112
2113   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
2114
2115   if ($form->{type} =~ /_order$/) {
2116     $form->{exchangerate} = $exchangerate;
2117     &create_backorder;
2118   }
2119
2120   if (   $form->{type} eq 'purchase_order'
2121       || $form->{type} eq 'request_quotation') {
2122     $form->{title}  = $locale->text('Add Vendor Invoice');
2123     $form->{script} = 'ir.pl';
2124     $script         = "ir";
2125     $buysell        = 'sell';
2126   }
2127
2128   if (   $form->{type} eq 'sales_order' 
2129       || $form->{type} eq 'sales_quotation') {
2130     $form->{title}  = $locale->text('Add Sales Invoice');
2131     $form->{script} = 'is.pl';
2132     $script         = "is";
2133     $buysell        = 'buy';
2134   }
2135
2136   # bo creates the id, reset it
2137   map { delete $form->{$_} } qw(id subject message cc bcc printed emailed queued);
2138   $form->{ $form->{vc} } =~ s/--.*//g;
2139   $form->{type} = "invoice";
2140
2141   # locale messages
2142   $locale = new Locale "$myconfig{countrycode}", "$script";
2143
2144   require "bin/mozilla/$form->{script}";
2145
2146   map { $form->{"select$_"} = "" } ($form->{vc}, currency);
2147
2148   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
2149     qw(creditlimit creditremaining);
2150
2151   $currency = $form->{currency};
2152   &invoice_links;
2153
2154   $form->{currency}     = $currency;
2155   $form->{exchangerate} = "";
2156   $form->{forex}        = "";
2157   $form->{exchangerate} = $exchangerate
2158     if (
2159         $form->{forex} = (
2160                     $exchangerate =
2161                       $form->check_exchangerate(
2162                       \%myconfig, $form->{currency}, $form->{invdate}, $buysell
2163                       )));
2164
2165   $form->{creditremaining} -= ($form->{oldinvtotal} - $form->{ordtotal});
2166
2167   &prepare_invoice;
2168
2169   # format amounts
2170   for $i (1 .. $form->{rowcount}) {
2171     $form->{"discount_$i"} =
2172       $form->format_amount(\%myconfig, $form->{"discount_$i"});
2173
2174     ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
2175     $dec           = length $dec;
2176     $decimalplaces = ($dec > 2) ? $dec : 2;
2177
2178     # copy delivery date from reqdate for order -> invoice conversion
2179     $form->{"deliverydate_$i"} = $form->{"reqdate_$i"}
2180       unless $form->{"deliverydate_$i"};
2181
2182     $form->{"sellprice_$i"} =
2183       $form->format_amount(\%myconfig, $form->{"sellprice_$i"},
2184                            $decimalplaces);
2185
2186     (my $dec_qty) = ($form->{"qty_$i"} =~ /\.(\d+)/);
2187     $dec_qty = length $dec_qty;
2188     $form->{"qty_$i"} =
2189       $form->format_amount(\%myconfig, $form->{"qty_$i"}, $dec_qty);
2190
2191     map { $form->{"${_}_$i"} =~ s/\"/&quot;/g }
2192       qw(partnumber description unit);
2193
2194   }
2195
2196   &display_form;
2197
2198   $lxdebug->leave_sub();
2199 }
2200
2201 sub backorder_exchangerate {
2202   $lxdebug->enter_sub();
2203   my ($orddate, $buysell) = @_;
2204
2205   $form->header;
2206
2207   print qq|
2208 <body>
2209
2210 <form method=post action=$form->{script}>
2211 |;
2212
2213   # delete action variable
2214   map { delete $form->{$_} } qw(action header exchangerate);
2215
2216   foreach $key (keys %$form) {
2217     $form->{$key} =~ s/\"/&quot;/g;
2218     print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
2219   }
2220
2221   $form->{title} = $locale->text('Add Exchangerate');
2222
2223   print qq|
2224
2225 <input type=hidden name=login value=$form->{login}>
2226 <input type=hidden name=password value=$form->{password}>
2227
2228 <input type=hidden name=exchangeratedate value=$orddate>
2229 <input type=hidden name=buysell value=$buysell>
2230
2231 <table width=100%>
2232   <tr><th class=listtop>$form->{title}</th></tr>
2233   <tr height="5"></tr>
2234   <tr>
2235     <td>
2236       <table>
2237         <tr>
2238           <th align=right>| . $locale->text('Currency') . qq|</th>
2239           <td>$form->{currency}</td>
2240         </tr>
2241         <tr>
2242           <th align=right>| . $locale->text('Date') . qq|</th>
2243           <td>$orddate</td>
2244         </tr>
2245         <tr>
2246           <th align=right>| . $locale->text('Exchangerate') . qq|</th>
2247           <td><input name=exchangerate size=11></td>
2248         </tr>
2249       </table>
2250     </td>
2251   </tr>
2252 </table>
2253
2254 <hr size=3 noshade>
2255
2256 <br>
2257 <input type=hidden name=nextsub value=save_exchangerate>
2258
2259 <input name=action class=submit type=submit value="|
2260     . $locale->text('Continue') . qq|">
2261
2262 </form>
2263
2264 </body>
2265 </html>
2266 |;
2267
2268   $lxdebug->leave_sub();
2269 }
2270
2271 sub save_exchangerate {
2272   $lxdebug->enter_sub();
2273
2274   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'));
2275   $form->{exchangerate} =
2276     $form->parse_amount(\%myconfig, $form->{exchangerate});
2277   $form->save_exchangerate(\%myconfig, $form->{currency},
2278                            $form->{exchangeratedate},
2279                            $form->{exchangerate}, $form->{buysell});
2280
2281   &invoice;
2282
2283   $lxdebug->leave_sub();
2284 }
2285
2286 sub create_backorder {
2287   $lxdebug->enter_sub();
2288
2289   $form->{shipped} = 1;
2290
2291   # figure out if we need to create a backorder
2292   # items aren't saved if qty != 0
2293
2294   for $i (1 .. $form->{rowcount}) {
2295     $totalqty  += $qty  = $form->{"qty_$i"};
2296     $totalship += $ship = $form->{"ship_$i"};
2297
2298     $form->{"qty_$i"} = $qty - $ship;
2299   }
2300
2301   if ($totalship == 0) {
2302     map { $form->{"ship_$_"} = $form->{"qty_$_"} } (1 .. $form->{rowcount});
2303     $form->{ordtotal} = 0;
2304     $form->{shipped}  = 0;
2305     return;
2306   }
2307
2308   if ($totalqty == $totalship) {
2309     map { $form->{"qty_$_"} = $form->{"ship_$_"} } (1 .. $form->{rowcount});
2310     $form->{ordtotal} = 0;
2311     return;
2312   }
2313
2314   @flds = (
2315     qw(partnumber description qty ship unit sellprice discount id inventory_accno bin income_accno expense_accno listprice assembly taxaccounts partsgroup)
2316   );
2317
2318   for $i (1 .. $form->{rowcount}) {
2319     map {
2320       $form->{"${_}_$i"} =
2321         $form->format_amount(\%myconfig, $form->{"${_}_$i"})
2322     } qw(sellprice discount);
2323   }
2324
2325   relink_accounts();
2326
2327   OE->save(\%myconfig, \%$form);
2328
2329   # rebuild rows for invoice
2330   @a     = ();
2331   $count = 0;
2332
2333   for $i (1 .. $form->{rowcount}) {
2334     $form->{"qty_$i"} = $form->{"ship_$i"};
2335
2336     if ($form->{"qty_$i"}) {
2337       push @a, {};
2338       $j = $#a;
2339       map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
2340       $count++;
2341     }
2342   }
2343
2344   $form->redo_rows(\@flds, \@a, $count, $form->{rowcount});
2345   $form->{rowcount} = $count;
2346
2347   $lxdebug->leave_sub();
2348 }
2349
2350 sub save_as_new {
2351   $lxdebug->enter_sub();
2352
2353   $form->{saveasnew} = 1;
2354   $form->{closed}    = 0;
2355   map { delete $form->{$_} } qw(printed emailed queued);
2356
2357   # Let Lx-Office assign a new order number if the user hasn't changed the
2358   # previous one. If it has been changed manually then use it as-is.
2359   my $idx = $form->{type} =~ /_quotation$/ ? "quonumber" : "ordnumber";
2360   $form->{$idx} =~ s/^\s*//g;
2361   $form->{$idx} =~ s/\s*$//g;
2362   if ($form->{saved_xyznumber} &&
2363       ($form->{saved_xyznumber} eq $form->{$idx})) {
2364     delete($form->{$idx});
2365   }
2366
2367   &save;
2368
2369   $lxdebug->leave_sub();
2370 }
2371
2372 sub check_for_direct_delivery_yes {
2373   $lxdebug->enter_sub();
2374
2375   $form->{direct_delivery_checked} = 1;
2376   delete @{$form}{grep /^shipto/, keys %{ $form }};
2377   map { s/^CFDD_//; $form->{$_} = $form->{"CFDD_${_}"} } grep /^CFDD_/, keys %{ $form };
2378   $form->{shipto} = 1;
2379   purchase_order();
2380   $lxdebug->leave_sub();
2381 }
2382
2383 sub check_for_direct_delivery_no {
2384   $lxdebug->enter_sub();
2385
2386   $form->{direct_delivery_checked} = 1;
2387   delete @{$form}{grep /^shipto/, keys %{ $form }};
2388   purchase_order();
2389
2390   $lxdebug->leave_sub();
2391 }
2392
2393 sub check_for_direct_delivery {
2394   $lxdebug->enter_sub();
2395
2396   if ($form->{direct_delivery_checked}
2397       || (!$form->{shiptoname} && !$form->{shiptostreet} && !$form->{shipto_id})) {
2398     $lxdebug->leave_sub();
2399     return;
2400   }
2401
2402   if ($form->{shipto_id}) {
2403     Common->get_shipto_by_id(\%myconfig, $form, $form->{shipto_id}, "CFDD_");
2404
2405   } else {
2406     map { $form->{"CFDD_${_}"} = $form->{$_ } } grep /^shipto/, keys %{ $form };
2407   }
2408
2409   delete $form->{action};
2410   $form->{VARIABLES} = [ map { { "key" => $_, "value" => $form->{$_} } } grep { ref $_ eq "" } keys %{ $form } ];
2411
2412   $form->header();
2413   print $form->parse_html_template("oe/check_for_direct_delivery");
2414
2415   $lxdebug->leave_sub();
2416
2417   exit 0;
2418 }
2419
2420 sub purchase_order {
2421   $lxdebug->enter_sub();
2422
2423   if ($form->{type} eq 'sales_order') {
2424     check_for_direct_delivery();
2425   }
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} =~ /^sales_/) {
2433     delete($form->{ordnumber});
2434   }
2435
2436   $form->{cp_id} *= 1;
2437
2438   $form->{title} = $locale->text('Add Purchase Order');
2439   $form->{vc}    = "vendor";
2440   $form->{type}  = "purchase_order";
2441
2442   &poso;
2443
2444   $lxdebug->leave_sub();
2445 }
2446
2447 sub sales_order {
2448   $lxdebug->enter_sub();
2449
2450   if (   $form->{type} eq 'sales_quotation'
2451       || $form->{type} eq 'request_quotation') {
2452     OE->close_order(\%myconfig, $form);
2453   }
2454
2455   if ($form->{type} eq "purchase_order") {
2456     delete($form->{ordnumber});
2457   }
2458
2459   $form->{cp_id} *= 1;
2460
2461   $form->{title} = $locale->text('Add Sales Order');
2462   $form->{vc}    = "customer";
2463   $form->{type}  = "sales_order";
2464
2465   &poso;
2466
2467   $lxdebug->leave_sub();
2468 }
2469
2470 sub poso {
2471   $lxdebug->enter_sub();
2472
2473   $form->{transdate} = $form->current_date(\%myconfig);
2474   delete $form->{duedate};
2475
2476   $form->{closed} = 0;
2477
2478   $form->{old_employee_id} = $form->{employee_id};
2479   $form->{old_salesman_id} = $form->{salesman_id};
2480
2481   # reset
2482   map { delete $form->{$_} }
2483     qw(id subject message cc bcc printed emailed queued customer vendor creditlimit creditremaining discount tradediscount oldinvtotal);
2484
2485   for $i (1 .. $form->{rowcount}) {
2486     map({ $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig,
2487                                                      $form->{"${_}_${i}"})
2488             if ($form->{"${_}_${i}"}) }
2489         qw(ship qty sellprice listprice basefactor));
2490   }
2491
2492   &order_links;
2493
2494   &prepare_order;
2495
2496   # format amounts
2497   for $i (1 .. $form->{rowcount} - 1) {
2498     map { $form->{"${_}_$i"} =~ s/\"/&quot;/g }
2499       qw(partnumber description unit);
2500   }
2501
2502   map { $form->{$_} = $form->format_amount(\%myconfig, $form->{$_}, 0, "0") }
2503     qw(creditlimit creditremaining);
2504
2505   &update;
2506
2507   $lxdebug->leave_sub();
2508 }
2509
2510 sub e_mail {
2511   $lxdebug->enter_sub();
2512
2513   $form->{print_and_save} = 1;
2514
2515   $print_post = 1;
2516
2517   my $saved_form = save_form();
2518
2519   save();
2520
2521   my %saved_vars;
2522   map({ $saved_vars{$_} = $form->{$_}; } qw(id ordnumber quonumber));
2523   restore_form($saved_form);
2524   map({ $form->{$_} = $saved_vars{$_}; } qw(id ordnumber quonumber));
2525
2526   edit_e_mail();
2527
2528   $lxdebug->leave_sub();
2529 }
2530
2531 sub yes {
2532   call_sub($form->{yes_nextsub});
2533 }
2534
2535 sub no {
2536   call_sub($form->{no_nextsub});
2537 }