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