epic-ts
[kivitendo-erp.git] / bin / mozilla / do.pl
index 8f0ea4c..ac71eca 100644 (file)
@@ -30,6 +30,7 @@
 # Delivery orders
 #======================================================================
 
+use Carp;
 use List::MoreUtils qw(uniq);
 use List::Util qw(max sum);
 use POSIX qw(strftime);
@@ -42,6 +43,7 @@ use SL::IS;
 use SL::MoreCommon qw(ary_diff);
 use SL::ReportGenerator;
 use SL::WH;
+use Sort::Naturally ();
 require "bin/mozilla/arap.pl";
 require "bin/mozilla/common.pl";
 require "bin/mozilla/invoice_io.pl";
@@ -283,7 +285,7 @@ sub form_header {
       @old_ids_cond,
     ]);
 
-  $::form->{ALL_PROJECTS}          = SL::DB::Manager::Project->get_all(query => \@conditions);
+  $::form->{ALL_PROJECTS}          = SL::DB::Manager::Project->get_all_sorted(query => \@conditions);
   $::form->{ALL_EMPLOYEES}         = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{employee_id},  deleted => 0 ] ]);
   $::form->{ALL_SALESMEN}          = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{salesman_id},  deleted => 0 ] ]);
   $::form->{ALL_SHIPTO}            = SL::DB::Manager::Shipto->get_all_sorted(query => [
@@ -323,7 +325,7 @@ sub form_header {
 
   $form->{follow_up_trans_info} = $form->{donumber} .'('. $follow_up_vc .')';
 
-  $::request->{layout}->use_javascript(map { "${_}.js" } qw(kivi.SalesPurchase ckeditor/ckeditor ckeditor/adapters/jquery));
+  $::request->{layout}->use_javascript(map { "${_}.js" } qw(kivi.SalesPurchase ckeditor/ckeditor ckeditor/adapters/jquery kivi.io autocomplete_customer autocomplete_part));
 
   $form->header();
   # Fix für Bug 1082 Erwartet wird: 'abteilungsNAME--abteilungsID'
@@ -369,6 +371,8 @@ sub update_delivery_order {
 
   set_headings($form->{"id"} ? "edit" : "add");
 
+  $form->{insertdate} = SL::DB::DeliveryOrder->new(id => $form->{id})->load->itime_as_date if $form->{id};
+
   $form->{update} = 1;
 
   my $payment_id;
@@ -390,7 +394,6 @@ sub update_delivery_order {
   #            Kunde mit Rabatt 20 -> Rabatt 5,5 i.O.
   $form->{payment_id} = $payment_id if $form->{payment_id} eq "";
 
-  # for pricegroups
   my $i = $form->{rowcount};
 
   if (   ($form->{"partnumber_$i"} eq "")
@@ -420,23 +423,39 @@ sub update_delivery_order {
 
       if ($rows > 1) {
 
-        select_item(mode => $mode);
+        select_item(mode => $mode, pre_entered_qty => $form->{"qty_$i"});
         ::end_of_request();
 
       } else {
 
+        my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
+
         map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
 
         $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
-        $form->{"sellprice_$i"}          = $form->format_amount(\%myconfig, $form->{"sellprice_$i"} * (1 - $form->{tradediscount}));
-        $form->{"lastcost_$i"}          = $form->format_amount(\%myconfig, $form->{"lastcost_$i"});
-        $form->{"qty_$i"}                = $form->format_amount(\%myconfig, $form->{"qty_$i"});
 
-        # get pricegroups for parts
-        IS->get_pricegroups_for_parts(\%myconfig, \%$form);
+        if ($sellprice) {
+          $form->{"sellprice_$i"} = $sellprice;
+        } else {
+          my $record        = _make_record();
+          my $price_source  = SL::PriceSource->new(record_item => $record->items->[$i-1], record => $record);
+          my $best_price    = $price_source->best_price;
+          my $best_discount = $price_source->best_discount;
+
+          if ($best_price) {
+            $::form->{"sellprice_$i"}           = $best_price->price;
+            $::form->{"active_price_source_$i"} = $best_price->source;
+          }
+          if ($best_discount) {
+            $::form->{"discount_$i"}               = $best_discount->discount;
+            $::form->{"active_discount_source_$i"} = $best_discount->source;
+          }
+        }
 
-        # build up html code for prices_$i
-        &set_pricegroup($i);
+        $form->{"sellprice_$i"}          = $form->format_amount(\%myconfig, $form->{"sellprice_$i"});
+        $form->{"lastcost_$i"}           = $form->format_amount(\%myconfig, $form->{"lastcost_$i"});
+        $form->{"qty_$i"}                = $form->format_amount(\%myconfig, $form->{"qty_$i"});
+        $form->{"discount_$i"}           = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100.0);
       }
 
       display_form();
@@ -475,10 +494,11 @@ sub search {
 
   $form->{vc} = $form->{type} eq 'purchase_delivery_order' ? 'vendor' : 'customer';
 
-  $form->get_lists("projects"     => { "key" => "ALL_PROJECTS",
-                                       "all" => 1 },
-                   "departments"  => "ALL_DEPARTMENTS",
-                   "$form->{vc}s" => "ALL_VC");
+  $form->get_lists("projects"       => { "key" => "ALL_PROJECTS",
+                                         "all" => 1 },
+                   "departments"    => "ALL_DEPARTMENTS",
+                   "$form->{vc}s"   => "ALL_VC",
+                   "business_types" => "ALL_BUSINESS_TYPES");
   $form->{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ deleted => 0 ]);
 
   $form->{SHOW_VC_DROP_DOWN} =  $myconfig{vclimit} > scalar @{ $form->{ALL_VC} };
@@ -518,6 +538,7 @@ sub orders {
     shipvia                 globalprojectnumber
     transaction_description department
     open                    delivered
+    insertdate
   );
 
   $form->{l_open}      = $form->{l_closed} = "Y" if ($form->{open}      && $form->{closed});
@@ -532,7 +553,8 @@ sub orders {
   my @hidden_variables = map { "l_${_}" } @columns;
   push @hidden_variables, $form->{vc}, qw(l_closed l_notdelivered open closed delivered notdelivered donumber ordnumber serialnumber cusordnumber
                                           transaction_description transdatefrom transdateto reqdatefrom reqdateto
-                                          type vc employee_id salesman_id project_id);
+                                          type vc employee_id salesman_id project_id
+                                          insertdatefrom insertdateto business_id);
 
   my $href = build_std_url('action=orders', grep { $form->{$_} } @hidden_variables);
 
@@ -554,9 +576,10 @@ sub orders {
     'open'                    => { 'text' => $locale->text('Open'), },
     'delivered'               => { 'text' => $locale->text('Delivered'), },
     'department'              => { 'text' => $locale->text('Department'), },
+    'insertdate'              => { 'text' => $locale->text('Insert Date'), },
   );
 
-  foreach my $name (qw(id transdate reqdate donumber ordnumber name employee salesman shipvia transaction_description department)) {
+  foreach my $name (qw(id transdate reqdate donumber ordnumber name employee salesman shipvia transaction_description department insertdate)) {
     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
     $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
   }
@@ -580,6 +603,9 @@ sub orders {
   if ($form->{vendor}) {
     push @options, $locale->text('Vendor') . " : $form->{vendor}";
   }
+  if ($form->{cp_name}) {
+    push @options, $locale->text('Contact Person') . " : $form->{cp_name}";
+  }
   if ($form->{department}) {
     my ($department) = split /--/, $form->{department};
     push @options, $locale->text('Department') . " : $department";
@@ -591,6 +617,10 @@ sub orders {
     push @options, $locale->text('Order Number') . " : $form->{ordnumber}";
   }
   push @options, $locale->text('Serial Number') . " : $form->{serialnumber}" if $form->{serialnumber};
+  if ($form->{business_id}) {
+    my $vc_type_label = $form->{vc} eq 'customer' ? $locale->text('Customer type') : $locale->text('Vendor type');
+    push @options, $vc_type_label . " : " . SL::DB::Business->new(id => $form->{business_id})->load->description;
+  }
   if ($form->{transaction_description}) {
     push @options, $locale->text('Transaction description') . " : $form->{transaction_description}";
   }
@@ -604,6 +634,11 @@ sub orders {
     push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{reqdatefrom}, 1)       if $form->{reqdatefrom};
     push @options, $locale->text('Bis')  . " " . $locale->date(\%myconfig, $form->{reqdateto},   1)       if $form->{reqdateto};
   };
+  if ( $form->{insertdatefrom} or $form->{insertdateto} ) {
+    push @options, $locale->text('Insert Date');
+    push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{insertdatefrom}, 1)    if $form->{insertdatefrom};
+    push @options, $locale->text('Bis')  . " " . $locale->date(\%myconfig, $form->{insertdateto},   1)    if $form->{insertdateto};
+  };
   if ($form->{open}) {
     push @options, $locale->text('Open');
   }
@@ -674,6 +709,8 @@ sub save {
   my %myconfig = %main::myconfig;
   my $locale   = $main::locale;
 
+  $form->mtime_ischanged('delivery_orders');
+
   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
 
   $form->isblank("transdate", $locale->text('Delivery Order Date missing!'));
@@ -751,6 +788,8 @@ sub invoice {
   my $locale   = $main::locale;
 
   check_do_access();
+  $form->mtime_ischanged('delivery_orders');
+
   $main::auth->assert($form->{type} eq 'purchase_delivery_order' ? 'vendor_invoice_edit' : 'invoice_edit');
 
   $form->{convert_from_do_ids} = $form->{id};
@@ -787,14 +826,15 @@ sub invoice {
         }
       }
     }
-    map { $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig, $form->{"${_}_${i}"}) if $form->{"${_}_${i}"} } qw(ship qty sellprice listprice lastcost basefactor);
+    map { $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig, $form->{"${_}_${i}"}) if $form->{"${_}_${i}"} } qw(ship qty sellprice lastcost basefactor);
     $form->{"donumber_$i"} = $form->{donumber};
+    $form->{"converted_from_delivery_order_items_id_$i"} = delete $form->{"delivery_order_items_id_$i"};
   }
 
   $form->{type} = "invoice";
 
   # locale messages
-  $main::locale = new Locale "$myconfig{countrycode}", "$script";
+  $main::locale = Locale->new("$myconfig{countrycode}", "$script");
   $locale = $main::locale;
 
   require "bin/mozilla/$form->{script}";
@@ -846,13 +886,6 @@ sub invoice {
 
   }
 
-  #  show pricegroup in newly loaded invoice when creating invoice from delivery order
-  for my $i (1 .. $form->{rowcount}) {
-    $form->{"sellprice_pg_$i"} = join '--', $form->{"sellprice_$i"}, $form->{"pricegroup_id_$i"};
-  }
-  IS->get_pricegroups_for_parts(\%myconfig, \%$form);
-  set_pricegroup($form->{rowcount});
-
   display_form();
 
   $main::lxdebug->leave_sub();
@@ -933,6 +966,7 @@ sub invoice_multi {
     $ref->{reqdate} ||= $ref->{dord_transdate}; # copy transdates into each invoice row
     map { $form->{"${_}_$form->{rowcount}"} = $ref->{$_} } keys %{ $ref };
     map { $form->{"${_}_$form->{rowcount}"} = $form->format_amount(\%myconfig, $ref->{$_}) } qw(qty sellprice lastcost);
+    $form->{"converted_from_delivery_order_items_id_$form->{rowcount}"} = delete $form->{"delivery_order_items_id_$form->{rowcount}"};
 
     if ($vc_discount){ # falls wir einen Lieferanten/Kundenrabatt haben
       # und keinen anderen discount wert an $i ...
@@ -947,20 +981,13 @@ sub invoice_multi {
   }
   delete $form->{form_details};
 
-  $locale = new Locale "$myconfig{countrycode}", "$script";
+  $locale = Locale->new("$myconfig{countrycode}", "$script");
 
   require "bin/mozilla/$form->{script}";
 
   invoice_links();
   prepare_invoice();
 
-  #  show pricegroup in newly loaded invoice when creating invoice from delivery order
-  for my $i (1 .. $form->{rowcount}) {
-    $form->{"sellprice_pg_$i"} = join '--', $form->{"sellprice_$i"}, $form->{"pricegroup_id_$i"};
-  }
-  IS->get_pricegroups_for_parts(\%myconfig, \%$form);
-  set_pricegroup($_) for 1 .. $form->{rowcount};
-
   display_form();
 
   $main::lxdebug->leave_sub();
@@ -978,7 +1005,7 @@ sub save_as_new {
   $form->{delivered} = 0;
   map { delete $form->{$_} } qw(printed emailed queued);
   delete @{ $form }{ grep { m/^stock_(?:in|out)_\d+/ } keys %{ $form } };
-
+  $form->{"converted_from_delivery_order_items_id_$_"} = delete $form->{"delivery_order_items_id_$_"} for 1 .. $form->{"rowcount"};
   # Let kivitendo assign a new order number if the user hasn't changed the
   # previous one. If it has been changed manually then use it as-is.
   $form->{donumber} =~ s/^\s*//g;
@@ -997,9 +1024,9 @@ sub e_mail {
 
   check_do_access();
 
-  my $form     = $main::form;
+  $::form->mtime_ischanged('delivery_orders','mail');
 
-  $form->{print_and_save} = 1;
+  $::form->{print_and_save} = 1;
 
   my $saved_form = save_form();
 
@@ -1107,7 +1134,8 @@ sub update_stock_in {
 
   foreach my $i (1..$form->{rowcount}) {
     $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
-    push @{ $stock_info }, { map { $_ => $form->{"${_}_${i}"} } qw(warehouse_id bin_id chargenumber bestbefore qty unit) };
+    push @{ $stock_info }, { map { $_ => $form->{"${_}_${i}"} } qw(warehouse_id bin_id chargenumber
+                                                                   bestbefore qty unit delivery_order_items_stock_id) };
   }
 
   display_stock_in_form($stock_info);
@@ -1190,7 +1218,7 @@ sub set_stock_in {
 
     next if ($form->{"qty_$i"} <= 0);
 
-    push @{ $stock_info }, { map { $_ => $form->{"${_}_${i}"} } qw(warehouse_id bin_id chargenumber bestbefore qty unit) };
+    push @{ $stock_info }, { map { $_ => $form->{"${_}_${i}"} } qw(delivery_order_items_stock_id warehouse_id bin_id chargenumber bestbefore qty unit) };
   }
 
   $form->{stock} = YAML::Dump($stock_info);
@@ -1239,7 +1267,7 @@ sub stock_out_form {
                  ($row->{chargenumber} ne $sinfo->{chargenumber}) ||
                  ($row->{bestbefore}   ne $sinfo->{bestbefore}));
 
-        map { $row->{"stock_$_"} = $sinfo->{$_} } qw(qty unit error);
+        map { $row->{"stock_$_"} = $sinfo->{$_} } qw(qty unit error delivery_order_items_stock_id);
       }
     }
 
@@ -1281,6 +1309,7 @@ sub set_stock_out {
       'qty'          => $form->{"qty_$i"},
       'unit'         => $form->{"unit_$i"},
       'row'          => $i,
+      'delivery_order_items_stock_id'  => $form->{"delivery_order_items_stock_id_$i"},
     };
   }
 
@@ -1528,7 +1557,7 @@ sub dispatcher {
   my $form     = $main::form;
   my $locale   = $main::locale;
 
-  foreach my $action (qw(update ship_to print e_mail save transfer_out transfer_out_default
+  foreach my $action (qw(update ship_to print e_mail save transfer_out transfer_out_default sort
                          transfer_in transfer_in_default mark_closed save_as_new invoice delete)) {
     if ($form->{"action_${action}"}) {
       call_sub($action);
@@ -1592,6 +1621,7 @@ sub transfer_in_out_default {
       my $base_unit_factor = $units->{ $part_info_map{$form->{"id_$i"}}->{unit} }->{factor} || 1;
       my $qty =   $form->parse_amount(\%myconfig, $form->{"qty_$i"}) * $units->{$form->{"unit_$i"}}->{factor} / $base_unit_factor;
 
+      $form->show_generic_error($locale->text("Cannot transfer negative entries." ), 'back_button' => 1) if ($qty < 0);
       # if we do not want to transfer services and this part is a service, set qty to zero
       # ... and do not create a hash entry in %qty_parts below (will skip check for bins for the transfer == out case)
       # ... and push only a empty (undef) element to @all_requests (will skip check for bin_id and warehouse_id and will not alter the row)
@@ -1599,7 +1629,7 @@ sub transfer_in_out_default {
       $qty = 0 if (!$::instance_conf->get_transfer_default_services && !defined($part_info_map{$form->{"id_$i"}}->{inventory_accno_id}) && !$part_info_map{$form->{"id_$i"}}->{assembly});
       $qty_parts{$form->{"id_$i"}} += $qty;
       if ($qty == 0) {
-        delete $qty_parts{$form->{"id_$i"}};
+        delete $qty_parts{$form->{"id_$i"}} unless $qty_parts{$form->{"id_$i"}};
         undef $form->{"stock_in_$i"};
       }
 
@@ -1612,8 +1642,7 @@ sub transfer_in_out_default {
                         'bin_id' => $part_info_map{$form->{"id_$i"}}{bin_id},
                         'qty' => $qty,
                         'parts_id' => $form->{"id_$i"},
-                        'comment' => 'Default transfer DO',
-                        'ok' => 1,
+                        'comment' => $locale->text("Default transfer delivery order"),
                         'unit' => $part_info_map{$form->{"id_$i"}}{unit},
                         'warehouse_id' => $part_info_map{$form->{"id_$i"}}{warehouse_id},
                         'oe_id' => $form->{id},
@@ -1710,3 +1739,59 @@ sub transfer_in_out_default {
   $form->redirect;
 
 }
+
+sub sort {
+  $main::lxdebug->enter_sub();
+
+  check_do_access();
+
+  my $form     = $main::form;
+  my %temp_hash;
+
+  croak ("Delivery Order needs to be saved") unless $form->{id};
+
+  # hashify partnumbers, positions. key is delivery_order_items_id
+  for my $i (1 .. ($form->{rowcount}) ) {
+    $temp_hash{$form->{"delivery_order_items_id_$i"}} = { runningnumber => $form->{"runningnumber_$i"}, partnumber => $form->{"partnumber_$i"} };
+  }
+  # naturally sort partnumbers and get a sorted array of doi_ids
+  my @sorted_doi_ids =  sort { Sort::Naturally::ncmp($temp_hash{$a}->{"partnumber"}, $temp_hash{$b}->{"partnumber"}) }  keys %temp_hash;
+
+
+  my $new_number = 1;
+
+  for (@sorted_doi_ids) {
+    $form->{"runningnumber_$temp_hash{$_}->{runningnumber}"} = $new_number;
+    $new_number++;
+  }
+    $main::lxdebug->leave_sub();
+    save();
+}
+
+__END__
+
+=pod
+
+=encoding utf8
+
+=head1 NAME
+
+do.pl - Script for all calls to delivery order
+
+
+=head1 FUNCTIONS
+
+=over 2
+
+=item C<sort>
+
+Sorts all position with Natural Sort. Can be activated in form_footer.html like this
+C<E<lt>input class="submit" type="submit" name="action_sort" id="sort_button" value="[% 'Sort and Save' | $T8 %]"E<gt>>
+
+=back
+
+=head1 TODO
+
+Sort and Save can be implemented as an optional button if configuration ca be set by client config.
+Example coding for database scripts and templates in (git show af2f24b8), check also
+autogeneration for rose (scripts/rose_auto_create_model.pl --h)