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