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