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