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