+my $cancel_reason_text = 'Supplemental package removed';
+my $cancel_reason_type = 'Cancel Reason';
+
+sub delete {
+ my $oldAutoCommit = $FS::UID::AutoCommit;
+ local $FS::UID::AutoCommit = 0;
+ my $dbh = dbh;
+
+ my $self = shift;
+
+ if ( $self->link_type eq 'supp' ) {
+ my $error = $self->remove_linked;
+ if ( $error ) {
+ $dbh->rollback if $oldAutoCommit;
+ return $error;
+ }
+ }
+
+ my $error = $self->SUPER::delete(@_);
+ if ( $error ) {
+ $dbh->rollback if $oldAutoCommit;
+ return $error;
+ }
+ $dbh->commit;
+ return;
+}
+
+=item remove_linked
+
+Removes any supplemental packages that were created by this link, by canceling
+them and setting their pkglinknum to null. This should be done in preparation
+for removing the link itself.
+
+=cut
+
+sub remove_linked {
+ my $self = shift;
+ my $pkglinknum = $self->pkglinknum;
+ my $error;
+
+ # find linked packages
+ my @pkgs = qsearch('cust_pkg', { pkglinknum => $pkglinknum });
+ warn "expiring ".scalar(@pkgs).
+ " linked packages from part_pkg_link #$pkglinknum\n";
+
+ my $reason = FS::reason->new_or_existing(
+ class => 'C',
+ type => $cancel_reason_type,
+ reason => $cancel_reason_text
+ );
+
+ foreach my $pkg (@pkgs) {
+ $pkg->set('pkglinknum' => '');
+ if ( $pkg->get('cancel') ) {
+ # then just replace it to unlink the package from this object
+ $error = $pkg->replace;
+ } else {
+ $error = $pkg->cancel(
+ 'date' => $pkg->get('bill'), # cancel on next bill, or else now
+ 'reason' => $reason->reasonnum,
+ );
+ }
+ if ( $error ) {
+ return "$error (scheduling package #".$pkg->pkgnum." for expiration)";
+ }
+ }
+}