correctly choose a default locationnum for prospects, #32489, #25343
[freeside.git] / FS / FS / quotation_pkg.pm
index c579e35..dcd68c9 100644 (file)
@@ -193,6 +193,20 @@ sub check {
     || $self->ut_enum('waive_setup', [ '', 'Y'] )
   ;
 
+  if ($self->locationnum eq '') {
+    # use the customer default
+    my $quotation = $self->quotation;
+    if ($quotation->custnum) {
+      $self->set('locationnum', $quotation->cust_main->ship_locationnum);
+    } elsif ($quotation->prospectnum) {
+      # use the first non-disabled location for that prospect
+      my $cust_location = qsearchs('cust_location',
+        { prospectnum => $quotation->prospectnum,
+          disabled => '' });
+      $self->set('locationnum', $cust_location->locationnum) if $cust_location;
+    } # else the quotation is invalid
+  }
+
   return $error if $error;
 
   $self->SUPER::check;
@@ -442,7 +456,7 @@ Returns the customer (L<FS::cust_main> object).
 
 sub cust_main {
   my $self = shift;
-  my $quotation = FS::quotation->by_key($self->quotationnum) or return '';
+  my $quotation = $self->quotation or return '';
   $quotation->cust_main;
 }
 
@@ -454,18 +468,26 @@ Returns the prospect (L<FS::prospect_main> object).
 
 sub prospect_main {
   my $self = shift;
-  my $quotation = FS::quotation->by_key($self->quotationnum) or return '';
+  my $quotation = $self->quotation or return '';
   $quotation->prospect_main;
 }
 
-sub quotation_pkg_tax {
-  my $self = shift;
-  qsearch('quotation_pkg_tax', { quotationpkgnum => $self->quotationpkgnum });
-}
 
-sub cust_location {
-  my $self = shift;
-  $self->locationnum ? qsearchs('cust_location', { locationnum => $self->locationnum }) : '';
+sub _upgrade_data {
+  my $class = shift;
+  my @quotation_pkg_without_location =
+    qsearch( 'quotation_pkg', { locationnum => '' } );
+  if (@quotation_pkg_without_location) {
+    warn "setting default location on quotation_pkg records\n";
+    foreach my $quotation_pkg (@quotation_pkg_without_location) {
+      # check() will fix this
+      my $error = $quotation_pkg->replace;
+      if ($error) {
+        die "quotation #".$quotation_pkg->quotationnum.": $error\n";
+      }
+    }
+  }
+  '';
 }
 
 =back