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