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