neue SL::DB::Part Methode used_in_record.
[kivitendo-erp.git] / SL / DB / Part.pm
index a2c3a73..c2cb641 100644 (file)
@@ -165,6 +165,24 @@ sub last_modification {
   return $self->mtime // $self->itime;
 };
 
+sub used_in_record {
+  my ($self) = @_;
+  die 'not an accessor' if @_ > 1;
+
+  return 1 unless $self->id;
+
+  my @relations = qw(
+    SL::DB::InvoiceItem
+    SL::DB::OrderItem
+    SL::DB::DeliveryOrderItem
+  );
+
+  for my $class (@relations) {
+    eval "require $class";
+    return 1 if $class->_get_manager_class->get_all_count(query => [ parts_id => $self->id ]);
+  }
+  return 0;
+}
 sub orphaned {
   my ($self) = @_;
   die 'not an accessor' if @_ > 1;
@@ -176,7 +194,6 @@ sub orphaned {
     SL::DB::OrderItem
     SL::DB::DeliveryOrderItem
     SL::DB::Inventory
-    SL::DB::Assembly
     SL::DB::AssortmentItem
   );
 
@@ -263,6 +280,36 @@ sub get_chart {
   return $charts->{$taxzone}->{$type};
 }
 
+sub get_stock {
+  my ($self, %params) = @_;
+
+  return undef unless $self->id;
+
+  my $query = 'SELECT SUM(qty) FROM inventory WHERE parts_id = ?';
+  my @values = ($self->id);
+
+  if ( $params{bin_id} ) {
+    $query .= ' AND bin_id = ?';
+    push(@values, $params{bin_id});
+  }
+
+  if ( $params{warehouse_id} ) {
+    $query .= ' AND warehouse_id = ?';
+    push(@values, $params{warehouse_id});
+  }
+
+  if ( $params{shippingdate} ) {
+    die unless ref($params{shippingdate}) eq 'DateTime';
+    $query .= ' AND shippingdate <= ?';
+    push(@values, $params{shippingdate});
+  }
+
+  my ($stock) = selectrow_query($::form, $self->db->dbh, $query, @values);
+
+  return $stock || 0; # never return undef
+};
+
+
 # this is designed to ignore chargenumbers, expiration dates and just give a list of how much <-> where
 sub get_simple_stock {
   my ($self, %params) = @_;
@@ -493,6 +540,10 @@ fields belonging to the tax zone given by C<$params{taxzone}>.
 
 The information retrieved by the function is cached.
 
+=item C<used_in_record>
+
+Checks if this article has been used in orders, invoices or delivery orders.
+
 =item C<orphaned>
 
 Checks if this article is used in orders, invoices, delivery orders or
@@ -520,6 +571,20 @@ Non-recursive lastcost sum of all the assembly item lastcosts.
 
 Non-recursive lastcost sum of all the assortment item lastcosts.
 
+=item C<get_stock %params>
+
+Fetches stock qty in the default unit for a part.
+
+bin_id and warehouse_id may be passed as params. If only a bin_id is passed,
+the stock qty for that bin is returned. If only a warehouse_id is passed, the
+stock qty for all bins in that warehouse is returned.  If a shippingdate is
+passed the stock qty for that date is returned.
+
+Examples:
+ my $qty = $part->get_stock(bin_id => 52);
+
+ $part->get_stock(shippingdate => DateTime->today->add(days => -5));
+
 =back
 
 =head1 AUTHORS