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