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