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