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