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