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