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