2 use base qw( FS::cust_pkg::Search FS::cust_pkg::API
3 FS::otaker_Mixin FS::cust_main_Mixin FS::Sales_Mixin
4 FS::contact_Mixin FS::location_Mixin
5 FS::m2m_Common FS::option_Common
10 use Scalar::Util qw( blessed );
11 use List::Util qw(min max);
13 use Time::Local qw( timelocal timelocal_nocheck );
15 use FS::UID qw( dbh driver_name );
16 use FS::Record qw( qsearch qsearchs fields );
22 use FS::cust_location;
24 use FS::cust_bill_pkg;
25 use FS::cust_pkg_detail;
26 use FS::cust_pkg_usage;
27 use FS::cdr_cust_pkg_usage;
32 use FS::cust_pkg_reason;
34 use FS::cust_pkg_usageprice;
35 use FS::cust_pkg_discount;
41 # temporary fix; remove this once (un)suspend admin notices are cleaned up
42 use FS::Misc qw(send_email);
44 # need to 'use' these instead of 'require' in sub { cancel, suspend, unsuspend,
46 # because they load configuration by setting FS::UID::callback (see TODO)
52 # for sending cancel emails in sub cancel
55 our ($disable_agentcheck, $DEBUG, $me, $import) = (0, 0, '[FS::cust_pkg]', 0);
57 our $upgrade = 0; #go away after setup+start dates cleaned up for old customers
59 our $cache_enabled = 0;
62 my( $self, $hashref ) = @_;
63 if ( $cache_enabled && $hashref->{'pkg'} && $hashref->{'plan'} ) {
64 $self->{'_pkgpart'} = FS::part_pkg->new($hashref);
70 my ( $hashref, $cache ) = @_;
71 # #if ( $hashref->{'pkgpart'} ) {
72 # if ( $hashref->{'pkg'} ) {
73 # # #@{ $self->{'_pkgnum'} } = ();
74 # # my $subcache = $cache->subcache('pkgpart', 'part_pkg');
75 # # $self->{'_pkgpart'} = $subcache;
76 # # #push @{ $self->{'_pkgnum'} },
77 # # FS::part_pkg->new_or_cached($hashref, $subcache);
78 # $self->{'_pkgpart'} = FS::part_pkg->new($hashref);
80 if ( exists $hashref->{'svcnum'} ) {
81 #@{ $self->{'_pkgnum'} } = ();
82 my $subcache = $cache->subcache('svcnum', 'cust_svc', $hashref->{pkgnum});
83 $self->{'_svcnum'} = $subcache;
84 #push @{ $self->{'_pkgnum'} },
85 FS::cust_svc->new_or_cached($hashref, $subcache) if $hashref->{svcnum};
91 FS::cust_pkg - Object methods for cust_pkg objects
97 $record = new FS::cust_pkg \%hash;
98 $record = new FS::cust_pkg { 'column' => 'value' };
100 $error = $record->insert;
102 $error = $new_record->replace($old_record);
104 $error = $record->delete;
106 $error = $record->check;
108 $error = $record->cancel;
110 $error = $record->suspend;
112 $error = $record->unsuspend;
114 $part_pkg = $record->part_pkg;
116 @labels = $record->labels;
118 $seconds = $record->seconds_since($timestamp);
120 #bulk cancel+order... perhaps slightly deprecated, only used by the bulk
121 # cancel+order in the web UI and nowhere else (edit/process/cust_pkg.cgi)
122 $error = FS::cust_pkg::order( $custnum, \@pkgparts );
123 $error = FS::cust_pkg::order( $custnum, \@pkgparts, \@remove_pkgnums ] );
127 An FS::cust_pkg object represents a customer billing item. FS::cust_pkg
128 inherits from FS::Record. The following fields are currently supported:
134 Primary key (assigned automatically for new billing items)
138 Customer (see L<FS::cust_main>)
142 Billing item definition (see L<FS::part_pkg>)
146 Optional link to package location (see L<FS::location>)
150 date package was ordered (also remains same on changes)
162 date (next bill date)
190 order taker (see L<FS::access_user>)
194 If this field is set to 1, disables the automatic
195 unsuspension of this package when using the B<unsuspendauto> config option.
199 If not set, defaults to 1
203 Date of change from previous package
213 =item change_locationnum
221 The pkgnum of the package that this package is supplemental to, if any.
225 The package link (L<FS::part_pkg_link>) that defines this supplemental
226 package, if it is one.
228 =item change_to_pkgnum
230 The pkgnum of the package this one will be "changed to" in the future
231 (on its expiration date).
235 Note: setup, last_bill, bill, adjourn, susp, expire, cancel and change_date
236 are specified as UNIX timestamps; see L<perlfunc/"time">. Also see
237 L<Time::Local> and L<Date::Parse> for conversion functions.
245 Create a new billing item. To add the item to the database, see L<"insert">.
249 sub table { 'cust_pkg'; }
250 sub cust_linked { $_[0]->cust_main_custnum || $_[0]->custnum }
251 sub cust_unlinked_msg {
253 "WARNING: can't find cust_main.custnum ". $self->custnum.
254 ' (cust_pkg.pkgnum '. $self->pkgnum. ')';
257 =item set_initial_timers
259 If required by the package definition, sets any automatic expire, adjourn,
260 or contract_end timers to some number of months after the start date
261 (or setup date, if the package has already been setup). If the package has
262 a delayed setup fee after a period of "free days", will also set the
263 start date to the end of that period.
265 If the package has an automatic transfer rule (C<change_to_pkgnum>), then
266 this will also order the package and set its start date.
270 sub set_initial_timers {
272 my $part_pkg = $self->part_pkg;
273 my $start = $self->start_date || $self->setup || time;
275 foreach my $action ( qw(expire adjourn contract_end) ) {
276 my $months = $part_pkg->get("${action}_months");
277 if($months and !$self->get($action)) {
278 $self->set($action, $part_pkg->add_freq($start, $months) );
282 # if this package has an expire date and a change_to_pkgpart, set automatic
284 # (but don't call change_later, as that would call $self->replace, and we're
285 # probably in the middle of $self->insert right now)
286 if ( $part_pkg->expire_months and $part_pkg->change_to_pkgpart ) {
287 if ( $self->change_to_pkgnum ) {
288 # this can happen if a package is ordered on hold, scheduled for a
289 # future change _while on hold_, and then released from hold, causing
290 # the automatic transfer to schedule.
292 # what's correct behavior in that case? I think it's to disallow
293 # future-changing an on-hold package that has an automatic transfer.
294 # but if we DO get into this situation, let the manual package change
296 warn "pkgnum ".$self->pkgnum.": manual future package change blocks ".
297 "automatic transfer.\n";
299 my $change_to = FS::cust_pkg->new( {
300 start_date => $self->get('expire'),
301 pkgpart => $part_pkg->change_to_pkgpart,
302 map { $_ => $self->get($_) }
303 qw( custnum locationnum quantity refnum salesnum contract_end )
305 my $error = $change_to->insert;
307 return $error if $error;
308 $self->set('change_to_pkgnum', $change_to->pkgnum);
312 # if this package has "free days" and delayed setup fee, then
313 # set start date that many days in the future.
314 # (this should have been set in the UI, but enforce it here)
315 if ( $part_pkg->option('free_days',1)
316 && $part_pkg->option('delay_setup',1)
319 $self->start_date( $part_pkg->default_start_date );
325 =item insert [ OPTION => VALUE ... ]
327 Adds this billing item to the database ("Orders" the item). If there is an
328 error, returns the error, otherwise returns false.
330 If the additional field I<promo_code> is defined instead of I<pkgpart>, it
331 will be used to look up the package definition and agent restrictions will be
334 If the additional field I<refnum> is defined, an FS::pkg_referral record will
335 be created and inserted. Multiple FS::pkg_referral records can be created by
336 setting I<refnum> to an array reference of refnums or a hash reference with
337 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
338 record will be created corresponding to cust_main.refnum.
340 If the additional field I<cust_pkg_usageprice> is defined, it will be treated
341 as an arrayref of FS::cust_pkg_usageprice objects, which will be inserted.
342 (Note that this field cannot be set with a usual ->cust_pkg_usageprice method.
343 It can be set as part of the hash when creating the object, or with the B<set>
346 The following options are available:
352 If set true, supresses actions that should only be taken for new package
353 orders. (Currently this includes: intro periods when delay_setup is on,
354 auto-adding a 1st start date, auto-adding expiration/adjourn/contract_end dates)
358 cust_pkg_option records will be created
362 a ticket will be added to this customer with this subject
366 an optional queue name for ticket additions
370 Don't check the legality of the package definition. This should be used
371 when performing a package change that doesn't change the pkgpart (i.e.
379 my( $self, %options ) = @_;
381 my $oldAutoCommit = $FS::UID::AutoCommit;
382 local $FS::UID::AutoCommit = 0;
386 $error = $self->check_pkgpart unless $options{'allow_pkgpart'};
388 my $part_pkg = $self->part_pkg;
390 if ( ! $import && ! $options{'change'} ) {
392 # set order date to now
393 $self->order_date(time) unless ($import && $self->order_date);
395 # if the package def says to start only on the first of the month:
396 if ( $part_pkg->option('start_1st', 1) && !$self->start_date ) {
397 my ($sec,$min,$hour,$mday,$mon,$year) = (localtime(time) )[0,1,2,3,4,5];
398 $mon += 1 unless $mday == 1;
399 until ( $mon < 12 ) { $mon -= 12; $year++; }
400 $self->start_date( timelocal_nocheck(0,0,0,1,$mon,$year) );
403 if ($self->susp eq 'now' or $part_pkg->start_on_hold) {
404 # if the package was ordered on hold:
406 # - don't set the start date (it will be started manually)
407 $self->set('susp', $self->order_date);
408 $self->set('start_date', '');
410 # set expire/adjourn/contract_end timers, and free days, if appropriate
411 # and automatic package transfer, which can fail, so capture the result
412 $error = $self->set_initial_timers;
414 } # else this is a package change, and shouldn't have "new package" behavior
416 $error ||= $self->SUPER::insert($options{options} ? %{$options{options}} : ());
418 $dbh->rollback if $oldAutoCommit;
422 $self->refnum($self->cust_main->refnum) unless $self->refnum;
423 $self->refnum( [ $self->refnum ] ) unless ref($self->refnum);
424 $self->process_m2m( 'link_table' => 'pkg_referral',
425 'target_table' => 'part_referral',
426 'params' => $self->refnum,
429 if ( $self->hashref->{cust_pkg_usageprice} ) {
430 for my $cust_pkg_usageprice ( @{ $self->hashref->{cust_pkg_usageprice} } ) {
431 $cust_pkg_usageprice->pkgnum( $self->pkgnum );
432 my $error = $cust_pkg_usageprice->insert;
434 $dbh->rollback if $oldAutoCommit;
440 if ( $self->setup_discountnum || $self->recur_discountnum ) {
441 my $error = $self->insert_discount();
443 $dbh->rollback if $oldAutoCommit;
448 my $conf = new FS::Conf;
450 if ( ! $import && $conf->config('ticket_system') && $options{ticket_subject} ) {
452 #this init stuff is still inefficient, but at least its limited to
453 # the small number (any?) folks using ticket emailing on pkg order
456 # use lib ( "/opt/rt3/local/lib", "/opt/rt3/lib" );
463 use FS::TicketSystem;
464 FS::TicketSystem->init();
466 my $q = new RT::Queue($RT::SystemUser);
467 $q->Load($options{ticket_queue}) if $options{ticket_queue};
468 my $t = new RT::Ticket($RT::SystemUser);
469 my $mime = new MIME::Entity;
470 $mime->build( Type => 'text/plain', Data => $options{ticket_subject} );
471 $t->Create( $options{ticket_queue} ? (Queue => $q) : (),
472 Subject => $options{ticket_subject},
475 $t->AddLink( Type => 'MemberOf',
476 Target => 'freeside://freeside/cust_main/'. $self->custnum,
480 if (! $import && $conf->config('welcome_letter') && $self->cust_main->num_pkgs == 1) {
481 my $queue = new FS::queue {
482 'job' => 'FS::cust_main::queueable_print',
484 $error = $queue->insert(
485 'custnum' => $self->custnum,
486 'template' => 'welcome_letter',
490 warn "can't send welcome letter: $error";
495 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
502 This method now works but you probably shouldn't use it.
504 You don't want to delete packages, because there would then be no record
505 the customer ever purchased the package. Instead, see the cancel method and
506 hide cancelled packages.
510 # this is still used internally to abort future package changes, so it
516 # The following foreign keys to cust_pkg are not cleaned up here, and will
517 # cause package deletion to fail:
519 # cust_credit.pkgnum and commission_pkgnum (and cust_credit_void)
520 # cust_credit_bill.pkgnum
521 # cust_pay_pending.pkgnum
522 # cust_pay.pkgnum (and cust_pay_void)
523 # cust_bill_pay.pkgnum (wtf, shouldn't reference pkgnum)
524 # cust_pkg_usage.pkgnum
525 # cust_pkg.uncancel_pkgnum, change_pkgnum, main_pkgnum, and change_to_pkgnum
527 # cust_svc is handled by canceling the package before deleting it
528 # cust_pkg_option is handled via option_Common
530 my $oldAutoCommit = $FS::UID::AutoCommit;
531 local $FS::UID::AutoCommit = 0;
534 foreach my $cust_pkg_discount ($self->cust_pkg_discount) {
535 my $error = $cust_pkg_discount->delete;
537 $dbh->rollback if $oldAutoCommit;
541 #cust_bill_pkg_discount?
543 foreach my $cust_pkg_detail ($self->cust_pkg_detail) {
544 my $error = $cust_pkg_detail->delete;
546 $dbh->rollback if $oldAutoCommit;
551 foreach my $cust_pkg_reason (
553 'table' => 'cust_pkg_reason',
554 'hashref' => { 'pkgnum' => $self->pkgnum },
558 my $error = $cust_pkg_reason->delete;
560 $dbh->rollback if $oldAutoCommit;
565 foreach my $pkg_referral ( $self->pkg_referral ) {
566 my $error = $pkg_referral->delete;
568 $dbh->rollback if $oldAutoCommit;
573 my $error = $self->SUPER::delete(@_);
575 $dbh->rollback if $oldAutoCommit;
579 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
585 =item replace [ OLD_RECORD ] [ HASHREF | OPTION => VALUE ... ]
587 Replaces the OLD_RECORD with this one in the database. If there is an error,
588 returns the error, otherwise returns false.
590 Currently, custnum, setup, bill, adjourn, susp, expire, and cancel may be changed.
592 Changing pkgpart may have disasterous effects. See the order subroutine.
594 setup and bill are normally updated by calling the bill method of a customer
595 object (see L<FS::cust_main>).
597 suspend is normally updated by the suspend and unsuspend methods.
599 cancel is normally updated by the cancel method (and also the order subroutine
602 Available options are:
608 can be set to a cancellation reason (see L<FS:reason>), either a reasonnum of an existing reason, or passing a hashref will create a new reason. The hashref should have the following keys: typenum - Reason type (see L<FS::reason_type>, reason - Text of the new reason.
612 the access_user (see L<FS::access_user>) providing the reason
616 hashref of keys and values - cust_pkg_option records will be created, updated or removed as appopriate
625 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
630 ( ref($_[0]) eq 'HASH' )
634 #return "Can't (yet?) change pkgpart!" if $old->pkgpart != $new->pkgpart;
635 #return "Can't change otaker!" if $old->otaker ne $new->otaker;
638 #return "Can't change setup once it exists!"
639 # if $old->getfield('setup') &&
640 # $old->getfield('setup') != $new->getfield('setup');
642 #some logic for bill, susp, cancel?
644 local($disable_agentcheck) = 1 if $old->pkgpart == $new->pkgpart;
646 my $oldAutoCommit = $FS::UID::AutoCommit;
647 local $FS::UID::AutoCommit = 0;
650 foreach my $method ( qw(adjourn expire) ) { # How many reasons?
651 if ($options->{'reason'} && $new->$method && $old->$method ne $new->$method) {
652 my $error = $new->insert_reason(
653 'reason' => $options->{'reason'},
654 'date' => $new->$method,
656 'reason_otaker' => $options->{'reason_otaker'},
659 dbh->rollback if $oldAutoCommit;
660 return "Error inserting cust_pkg_reason: $error";
665 #save off and freeze RADIUS attributes for any associated svc_acct records
667 if ( $old->part_pkg->is_prepaid || $new->part_pkg->is_prepaid ) {
669 #also check for specific exports?
670 # to avoid spurious modify export events
671 @svc_acct = map { $_->svc_x }
672 grep { $_->part_svc->svcdb eq 'svc_acct' }
675 $_->snapshot foreach @svc_acct;
679 my $error = $new->export_pkg_change($old)
680 || $new->SUPER::replace( $old,
682 ? $options->{options}
686 $dbh->rollback if $oldAutoCommit;
690 #for prepaid packages,
691 #trigger export of new RADIUS Expiration attribute when cust_pkg.bill changes
692 foreach my $old_svc_acct ( @svc_acct ) {
693 my $new_svc_acct = new FS::svc_acct { $old_svc_acct->hash };
695 $new_svc_acct->replace( $old_svc_acct,
696 'depend_jobnum' => $options->{depend_jobnum},
699 $dbh->rollback if $oldAutoCommit;
704 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
711 Checks all fields to make sure this is a valid billing item. If there is an
712 error, returns the error, otherwise returns false. Called by the insert and
720 if ( !$self->locationnum or $self->locationnum == -1 ) {
721 $self->set('locationnum', $self->cust_main->ship_locationnum);
725 $self->ut_numbern('pkgnum')
726 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum')
727 || $self->ut_numbern('pkgpart')
728 || $self->ut_foreign_keyn('contactnum', 'contact', 'contactnum' )
729 || $self->ut_foreign_keyn('locationnum', 'cust_location', 'locationnum')
730 || $self->ut_foreign_keyn('salesnum', 'sales', 'salesnum')
731 || $self->ut_numbern('quantity')
732 || $self->ut_numbern('start_date')
733 || $self->ut_numbern('setup')
734 || $self->ut_numbern('bill')
735 || $self->ut_numbern('susp')
736 || $self->ut_numbern('cancel')
737 || $self->ut_numbern('adjourn')
738 || $self->ut_numbern('resume')
739 || $self->ut_numbern('expire')
740 || $self->ut_numbern('dundate')
741 || $self->ut_flag('no_auto', [ '', 'Y' ])
742 || $self->ut_flag('waive_setup', [ '', 'Y' ])
743 || $self->ut_flag('separate_bill')
744 || $self->ut_textn('agent_pkgid')
745 || $self->ut_enum('recur_show_zero', [ '', 'Y', 'N', ])
746 || $self->ut_enum('setup_show_zero', [ '', 'Y', 'N', ])
747 || $self->ut_foreign_keyn('main_pkgnum', 'cust_pkg', 'pkgnum')
748 || $self->ut_foreign_keyn('pkglinknum', 'part_pkg_link', 'pkglinknum')
749 || $self->ut_foreign_keyn('change_to_pkgnum', 'cust_pkg', 'pkgnum')
751 return $error if $error;
753 return "A package with both start date (future start) and setup date (already started) will never bill"
754 if $self->start_date && $self->setup && ! $upgrade;
756 return "A future unsuspend date can only be set for a package with a suspend date"
757 if $self->resume and !$self->susp and !$self->adjourn;
759 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
761 if ( $self->dbdef_table->column('manual_flag') ) {
762 $self->manual_flag('') if $self->manual_flag eq ' ';
763 $self->manual_flag =~ /^([01]?)$/
764 or return "Illegal manual_flag ". $self->manual_flag;
765 $self->manual_flag($1);
773 Check the pkgpart to make sure it's allowed with the reg_code and/or
774 promo_code of the package (if present) and with the customer's agent.
775 Called from C<insert>, unless we are doing a package change that doesn't
783 # my $error = $self->ut_numbern('pkgpart'); # already done
786 if ( $self->reg_code ) {
788 unless ( grep { $self->pkgpart == $_->pkgpart }
789 map { $_->reg_code_pkg }
790 qsearchs( 'reg_code', { 'code' => $self->reg_code,
791 'agentnum' => $self->cust_main->agentnum })
793 return "Unknown registration code";
796 } elsif ( $self->promo_code ) {
799 qsearchs('part_pkg', {
800 'pkgpart' => $self->pkgpart,
801 'promo_code' => { op=>'ILIKE', value=>$self->promo_code },
803 return 'Unknown promotional code' unless $promo_part_pkg;
807 unless ( $disable_agentcheck ) {
809 qsearchs( 'agent', { 'agentnum' => $self->cust_main->agentnum } );
810 return "agent ". $agent->agentnum. ':'. $agent->agent.
811 " can't purchase pkgpart ". $self->pkgpart
812 unless $agent->pkgpart_hashref->{ $self->pkgpart }
813 || $agent->agentnum == $self->part_pkg->agentnum;
816 $error = $self->ut_foreign_key('pkgpart', 'part_pkg', 'pkgpart' );
817 return $error if $error;
825 =item cancel [ OPTION => VALUE ... ]
827 Cancels and removes all services (see L<FS::cust_svc> and L<FS::part_svc>)
828 in this package, then cancels the package itself (sets the cancel field to
831 Available options are:
835 =item quiet - can be set true to supress email cancellation notices.
837 =item time - can be set to cancel the package based on a specific future or
838 historical date. Using time ensures that the remaining amount is calculated
839 correctly. Note however that this is an immediate cancel and just changes
840 the date. You are PROBABLY looking to expire the account instead of using
843 =item reason - can be set to a cancellation reason (see L<FS:reason>),
844 either a reasonnum of an existing reason, or passing a hashref will create
845 a new reason. The hashref should have the following keys: typenum - Reason
846 type (see L<FS::reason_type>, reason - Text of the new reason.
848 =item date - can be set to a unix style timestamp to specify when to
851 =item nobill - can be set true to skip billing if it might otherwise be done.
853 =item unused_credit - can be set to 1 to credit the remaining time, or 0 to
854 not credit it. This must be set (by change()) when changing the package
855 to a different pkgpart or location, and probably shouldn't be in any other
856 case. If it's not set, the 'unused_credit_cancel' part_pkg option will
859 =item no_delay_cancel - prevents delay_cancel behavior
860 no matter what other options say, for use when changing packages (or any
861 other time you're really sure you want an immediate cancel)
865 If there is an error, returns the error, otherwise returns false.
869 #NOT DOCUMENTING - this should only be used when calling recursively
870 #=item delay_cancel - for internal use, to allow proper handling of
871 #supplemental packages when the main package is flagged to suspend
872 #before cancelling, probably shouldn't be used otherwise (set the
873 #corresponding package option instead)
876 my( $self, %options ) = @_;
879 # supplemental packages can now be separately canceled, though the UI
880 # shouldn't permit it
882 ## pass all suspend/cancel actions to the main package
883 ## (unless the pkglinknum has been removed, then the link is defunct and
884 ## this package can be canceled on its own)
885 #if ( $self->main_pkgnum and $self->pkglinknum and !$options{'from_main'} ) {
886 # return $self->main_pkg->cancel(%options);
889 my $conf = new FS::Conf;
891 warn "cust_pkg::cancel called with options".
892 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
895 my $oldAutoCommit = $FS::UID::AutoCommit;
896 local $FS::UID::AutoCommit = 0;
899 my $old = $self->select_for_update;
901 if ( $old->get('cancel') || $self->get('cancel') ) {
902 dbh->rollback if $oldAutoCommit;
903 return ""; # no error
906 # XXX possibly set cancel_time to the expire date?
907 my $cancel_time = $options{'time'} || time;
908 my $date = $options{'date'} if $options{'date'}; # expire/cancel later
909 $date = '' if ($date && $date <= $cancel_time); # complain instead?
911 my $delay_cancel = $options{'no_delay_cancel'} ? 0 : $options{'delay_cancel'};
912 if ( !$date && $self->part_pkg->option('delay_cancel',1)
913 && (($self->status eq 'active') || ($self->status eq 'suspended'))
914 && !$options{'no_delay_cancel'}
916 my $expdays = $conf->config('part_pkg-delay_cancel-days') || 1;
917 my $expsecs = 60*60*24*$expdays;
918 my $suspfor = $self->susp ? $cancel_time - $self->susp : 0;
919 $expsecs = $expsecs - $suspfor if $suspfor;
920 unless ($expsecs <= 0) { #if it's already been suspended long enough, don't re-suspend
922 $date = $cancel_time + $expsecs;
926 #race condition: usage could be ongoing until unprovisioned
927 #resolved by performing a change package instead (which unprovisions) and
929 if ( !$options{nobill} && !$date ) {
930 # && $conf->exists('bill_usage_on_cancel') ) { #calc_cancel checks this
931 my $copy = $self->new({$self->hash});
933 $copy->cust_main->bill( 'pkg_list' => [ $copy ],
935 'time' => $cancel_time );
936 warn "Error billing during cancel, custnum ".
937 #$self->cust_main->custnum. ": $error"
942 if ( $options{'reason'} ) {
943 $error = $self->insert_reason( 'reason' => $options{'reason'},
944 'action' => $date ? 'expire' : 'cancel',
945 'date' => $date ? $date : $cancel_time,
946 'reason_otaker' => $options{'reason_otaker'},
949 dbh->rollback if $oldAutoCommit;
950 return "Error inserting cust_pkg_reason: $error";
954 my %svc_cancel_opt = ();
955 $svc_cancel_opt{'date'} = $date if $date;
956 foreach my $cust_svc (
959 sort { $a->[1] <=> $b->[1] }
960 map { [ $_, $_->svc_x ? $_->svc_x->table_info->{'cancel_weight'} : -1 ]; }
961 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
963 my $part_svc = $cust_svc->part_svc;
964 next if ( defined($part_svc) and $part_svc->preserve );
965 my $error = $cust_svc->cancel( %svc_cancel_opt );
968 $dbh->rollback if $oldAutoCommit;
969 return 'Error '. ($svc_cancel_opt{'date'} ? 'expiring' : 'canceling' ).
974 # if a reasonnum was passed, get the actual reason object so we can check
978 if ($options{'reason'} =~ /^\d+$/) {
979 $reason = FS::reason->by_key($options{'reason'});
983 # credit remaining time if any of these are true:
984 # - unused_credit => 1 was passed (this happens when canceling a package
985 # for a package change when unused_credit_change is set)
986 # - no unused_credit option, and there is a cancel reason, and the cancel
987 # reason says to credit the package
988 # - no unused_credit option, and the package definition says to credit the
989 # package on cancellation
991 if ( exists($options{'unused_credit'}) ) {
992 $do_credit = $options{'unused_credit'};
993 } elsif ( defined($reason) && $reason->unused_credit ) {
996 $do_credit = $self->part_pkg->option('unused_credit_cancel', 1);
999 my $error = $self->credit_remaining('cancel', $cancel_time);
1001 $dbh->rollback if $oldAutoCommit;
1007 my %hash = $self->hash;
1009 $hash{'expire'} = $date;
1010 if ($delay_cancel) {
1011 # just to be sure these are clear
1012 $hash{'adjourn'} = undef;
1013 $hash{'resume'} = undef;
1016 $hash{'cancel'} = $cancel_time;
1018 $hash{'change_custnum'} = $options{'change_custnum'};
1020 # if this is a supplemental package that's lost its part_pkg_link, and it's
1021 # being canceled for real, unlink it completely
1022 if ( !$date and ! $self->pkglinknum ) {
1023 $hash{main_pkgnum} = '';
1026 # if there is a future package change scheduled, unlink from it (like
1027 # abort_change) first, then delete it.
1028 $hash{'change_to_pkgnum'} = '';
1030 # save the package state
1031 my $new = new FS::cust_pkg ( \%hash );
1032 $error = $new->replace( $self, options => { $self->options } );
1034 if ( $self->change_to_pkgnum ) {
1035 my $change_to = FS::cust_pkg->by_key($self->change_to_pkgnum);
1036 $error ||= $change_to->cancel('no_delay_cancel' => 1) || $change_to->delete;
1039 $dbh->rollback if $oldAutoCommit;
1043 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1044 $error = $supp_pkg->cancel(%options,
1046 'date' => $date, #in case it got changed by delay_cancel
1047 'delay_cancel' => $delay_cancel,
1050 $dbh->rollback if $oldAutoCommit;
1051 return "canceling supplemental pkg#".$supp_pkg->pkgnum.": $error";
1055 if ($delay_cancel && !$options{'from_main'}) {
1056 $error = $new->suspend(
1058 'time' => $cancel_time
1063 foreach my $usage ( $self->cust_pkg_usage ) {
1064 $error = $usage->delete;
1066 $dbh->rollback if $oldAutoCommit;
1067 return "deleting usage pools: $error";
1072 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1073 return '' if $date; #no errors
1075 my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ } $self->cust_main->invoicing_list;
1076 if ( !$options{'quiet'} &&
1077 $conf->exists('emailcancel', $self->cust_main->agentnum) &&
1079 my $msgnum = $conf->config('cancel_msgnum', $self->cust_main->agentnum);
1082 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum });
1083 $error = $msg_template->send( 'cust_main' => $self->cust_main,
1084 'object' => $self );
1086 #should this do something on errors?
1093 =item cancel_if_expired [ NOW_TIMESTAMP ]
1095 Cancels this package if its expire date has been reached.
1099 sub cancel_if_expired {
1101 my $time = shift || time;
1102 return '' unless $self->expire && $self->expire <= $time;
1103 my $error = $self->cancel;
1105 return "Error cancelling expired pkg ". $self->pkgnum. " for custnum ".
1106 $self->custnum. ": $error";
1113 "Un-cancels" this package: Orders a new package with the same custnum, pkgpart,
1114 locationnum, (other fields?). Attempts to re-provision cancelled services
1115 using history information (errors at this stage are not fatal).
1117 cust_pkg: pass a scalar reference, will be filled in with the new cust_pkg object
1119 svc_fatal: service provisioning errors are fatal
1121 svc_errors: pass an array reference, will be filled in with any provisioning errors
1123 main_pkgnum: link the package as a supplemental package of this one. For
1129 my( $self, %options ) = @_;
1131 #in case you try do do $uncancel-date = $cust_pkg->uncacel
1132 return '' unless $self->get('cancel');
1134 if ( $self->main_pkgnum and !$options{'main_pkgnum'} ) {
1135 return $self->main_pkg->uncancel(%options);
1142 my $oldAutoCommit = $FS::UID::AutoCommit;
1143 local $FS::UID::AutoCommit = 0;
1147 # insert the new package
1150 my $cust_pkg = new FS::cust_pkg {
1151 last_bill => ( $options{'last_bill'} || $self->get('last_bill') ),
1152 bill => ( $options{'bill'} || $self->get('bill') ),
1154 uncancel_pkgnum => $self->pkgnum,
1155 main_pkgnum => ($options{'main_pkgnum'} || ''),
1156 map { $_ => $self->get($_) } qw(
1157 custnum pkgpart locationnum
1159 susp adjourn resume expire start_date contract_end dundate
1160 change_date change_pkgpart change_locationnum
1161 manual_flag no_auto separate_bill quantity agent_pkgid
1162 recur_show_zero setup_show_zero
1166 my $error = $cust_pkg->insert(
1167 'change' => 1, #supresses any referral credit to a referring customer
1168 'allow_pkgpart' => 1, # allow this even if the package def is disabled
1171 $dbh->rollback if $oldAutoCommit;
1179 #find historical services within this timeframe before the package cancel
1180 # (incompatible with "time" option to cust_pkg->cancel?)
1181 my $fuzz = 2 * 60; #2 minutes? too much? (might catch separate unprovision)
1182 # too little? (unprovisioing export delay?)
1183 my($end, $start) = ( $self->get('cancel'), $self->get('cancel') - $fuzz );
1184 my @h_cust_svc = $self->h_cust_svc( $end, $start );
1187 foreach my $h_cust_svc (@h_cust_svc) {
1188 my $h_svc_x = $h_cust_svc->h_svc_x( $end, $start );
1189 #next unless $h_svc_x; #should this happen?
1190 (my $table = $h_svc_x->table) =~ s/^h_//;
1191 require "FS/$table.pm";
1192 my $class = "FS::$table";
1193 my $svc_x = $class->new( {
1194 'pkgnum' => $cust_pkg->pkgnum,
1195 'svcpart' => $h_cust_svc->svcpart,
1196 map { $_ => $h_svc_x->get($_) } fields($table)
1200 if ( $h_svc_x->isa('FS::h_svc_Radius_Mixin') ) {
1201 $svc_x->usergroup( [ $h_svc_x->h_usergroup($end, $start) ] );
1204 my $svc_error = $svc_x->insert;
1206 if ( $options{svc_fatal} ) {
1207 $dbh->rollback if $oldAutoCommit;
1210 # if we've failed to insert the svc_x object, svc_Common->insert
1211 # will have removed the cust_svc already. if not, then both records
1212 # were inserted but we failed for some other reason (export, most
1213 # likely). in that case, report the error and delete the records.
1214 push @svc_errors, $svc_error;
1215 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svc_x->svcnum });
1217 # except if export_insert failed, export_delete probably won't be
1219 local $FS::svc_Common::noexport_hack = 1;
1220 my $cleanup_error = $svc_x->delete; # also deletes cust_svc
1221 if ( $cleanup_error ) { # and if THAT fails, then run away
1222 $dbh->rollback if $oldAutoCommit;
1223 return $cleanup_error;
1228 } #foreach $h_cust_svc
1230 #these are pretty rare, but should handle them
1231 # - dsl_device (mac addresses)
1232 # - phone_device (mac addresses)
1233 # - dsl_note (ikano notes)
1234 # - domain_record (i.e. restore DNS information w/domains)
1235 # - inventory_item(?) (inventory w/un-cancelling service?)
1236 # - nas (svc_broaband nas stuff)
1237 #this stuff is unused in the wild afaik
1238 # - mailinglistmember
1240 # - svc_domain.parent_svcnum?
1241 # - acct_snarf (ancient mail fetching config)
1242 # - cgp_rule (communigate)
1243 # - cust_svc_option (used by our Tron stuff)
1244 # - acct_rt_transaction (used by our time worked stuff)
1247 # also move over any services that didn't unprovision at cancellation
1250 foreach my $cust_svc ( qsearch('cust_svc', { pkgnum => $self->pkgnum } ) ) {
1251 $cust_svc->pkgnum( $cust_pkg->pkgnum );
1252 my $error = $cust_svc->replace;
1254 $dbh->rollback if $oldAutoCommit;
1260 # Uncancel any supplemental packages, and make them supplemental to the
1264 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1266 $error = $supp_pkg->uncancel(%options, 'main_pkgnum' => $cust_pkg->pkgnum);
1268 $dbh->rollback if $oldAutoCommit;
1269 return "canceling supplemental pkg#".$supp_pkg->pkgnum.": $error";
1277 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1279 ${ $options{cust_pkg} } = $cust_pkg if ref($options{cust_pkg});
1280 @{ $options{svc_errors} } = @svc_errors if ref($options{svc_errors});
1287 Cancels any pending expiration (sets the expire field to null).
1289 If there is an error, returns the error, otherwise returns false.
1294 my( $self, %options ) = @_;
1297 my $oldAutoCommit = $FS::UID::AutoCommit;
1298 local $FS::UID::AutoCommit = 0;
1301 my $old = $self->select_for_update;
1303 my $pkgnum = $old->pkgnum;
1304 if ( $old->get('cancel') || $self->get('cancel') ) {
1305 dbh->rollback if $oldAutoCommit;
1306 return "Can't unexpire cancelled package $pkgnum";
1307 # or at least it's pointless
1310 unless ( $old->get('expire') && $self->get('expire') ) {
1311 dbh->rollback if $oldAutoCommit;
1312 return ""; # no error
1315 my %hash = $self->hash;
1316 $hash{'expire'} = '';
1317 my $new = new FS::cust_pkg ( \%hash );
1318 $error = $new->replace( $self, options => { $self->options } );
1320 $dbh->rollback if $oldAutoCommit;
1324 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1330 =item suspend [ OPTION => VALUE ... ]
1332 Suspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
1333 package, then suspends the package itself (sets the susp field to now).
1335 Available options are:
1339 =item reason - can be set to a cancellation reason (see L<FS:reason>),
1340 either a reasonnum of an existing reason, or passing a hashref will create
1341 a new reason. The hashref should have the following keys:
1342 - typenum - Reason type (see L<FS::reason_type>
1343 - reason - Text of the new reason.
1345 =item date - can be set to a unix style timestamp to specify when to
1348 =item time - can be set to override the current time, for calculation
1349 of final invoices or unused-time credits
1351 =item resume_date - can be set to a time when the package should be
1352 unsuspended. This may be more convenient than calling C<unsuspend()>
1355 =item from_main - allows a supplemental package to be suspended, rather
1356 than redirecting the method call to its main package. For internal use.
1358 =item from_cancel - used when suspending from the cancel method, forces
1359 this to skip everything besides basic suspension. For internal use.
1363 If there is an error, returns the error, otherwise returns false.
1368 my( $self, %options ) = @_;
1371 # supplemental packages still can't be separately suspended, but silently
1372 # exit instead of failing or passing the action to the main package (so
1373 # that the "Suspend customer" action doesn't trip over the supplemental
1376 if ( $self->main_pkgnum and !$options{'from_main'} ) {
1380 my $oldAutoCommit = $FS::UID::AutoCommit;
1381 local $FS::UID::AutoCommit = 0;
1384 my $old = $self->select_for_update;
1386 my $pkgnum = $old->pkgnum;
1387 if ( $old->get('cancel') || $self->get('cancel') ) {
1388 dbh->rollback if $oldAutoCommit;
1389 return "Can't suspend cancelled package $pkgnum";
1392 if ( $old->get('susp') || $self->get('susp') ) {
1393 dbh->rollback if $oldAutoCommit;
1394 return ""; # no error # complain on adjourn?
1397 my $suspend_time = $options{'time'} || time;
1398 my $date = $options{date} if $options{date}; # adjourn/suspend later
1399 $date = '' if ($date && $date <= $suspend_time); # complain instead?
1401 if ( $date && $old->get('expire') && $old->get('expire') < $date ) {
1402 dbh->rollback if $oldAutoCommit;
1403 return "Package $pkgnum expires before it would be suspended.";
1406 # some false laziness with sub cancel
1407 if ( !$options{nobill} && !$date && !$options{'from_cancel'} &&
1408 $self->part_pkg->option('bill_suspend_as_cancel',1) ) {
1409 # kind of a kludge--'bill_suspend_as_cancel' to avoid having to
1410 # make the entire cust_main->bill path recognize 'suspend' and
1411 # 'cancel' separately.
1412 warn "Billing $pkgnum on suspension (at $suspend_time)\n" if $DEBUG;
1413 my $copy = $self->new({$self->hash});
1415 $copy->cust_main->bill( 'pkg_list' => [ $copy ],
1417 'time' => $suspend_time );
1418 warn "Error billing during suspend, custnum ".
1419 #$self->cust_main->custnum. ": $error"
1424 my $cust_pkg_reason;
1425 if ( $options{'reason'} ) {
1426 $error = $self->insert_reason( 'reason' => $options{'reason'},
1427 'action' => $date ? 'adjourn' : 'suspend',
1428 'date' => $date ? $date : $suspend_time,
1429 'reason_otaker' => $options{'reason_otaker'},
1432 dbh->rollback if $oldAutoCommit;
1433 return "Error inserting cust_pkg_reason: $error";
1435 $cust_pkg_reason = qsearchs('cust_pkg_reason', {
1436 'date' => $date ? $date : $suspend_time,
1437 'action' => $date ? 'A' : 'S',
1438 'pkgnum' => $self->pkgnum,
1442 # if a reasonnum was passed, get the actual reason object so we can check
1444 # (passing a reason hashref is still allowed, but it can't be used with
1445 # the fancy behavioral options.)
1448 if ($options{'reason'} =~ /^\d+$/) {
1449 $reason = FS::reason->by_key($options{'reason'});
1452 my %hash = $self->hash;
1454 $hash{'adjourn'} = $date;
1456 $hash{'susp'} = $suspend_time;
1459 my $resume_date = $options{'resume_date'} || 0;
1460 if ( $resume_date > ($date || $suspend_time) ) {
1461 $hash{'resume'} = $resume_date;
1464 $options{options} ||= {};
1466 my $new = new FS::cust_pkg ( \%hash );
1467 $error = $new->replace( $self, options => { $self->options,
1468 %{ $options{options} },
1472 $dbh->rollback if $oldAutoCommit;
1476 unless ( $date ) { # then we are suspending now
1478 unless ($options{'from_cancel'}) {
1479 # credit remaining time if appropriate
1480 # (if required by the package def, or the suspend reason)
1481 my $unused_credit = $self->part_pkg->option('unused_credit_suspend',1)
1482 || ( defined($reason) && $reason->unused_credit );
1484 if ( $unused_credit ) {
1485 warn "crediting unused time on pkg#".$self->pkgnum."\n" if $DEBUG;
1486 my $error = $self->credit_remaining('suspend', $suspend_time);
1488 $dbh->rollback if $oldAutoCommit;
1494 my @cust_svc = qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } );
1496 #attempt ordering ala cust_svc_suspend_cascade (without infinite-looping
1497 # on the circular dep case)
1498 # (this is too simple for multi-level deps, we need to use something
1499 # to resolve the DAG properly when possible)
1501 $svcpart{$_->svcpart} = 0 foreach @cust_svc;
1502 foreach my $svcpart ( keys %svcpart ) {
1503 foreach my $part_svc_link (
1504 FS::part_svc_link->by_agentnum($self->cust_main->agentnum,
1505 src_svcpart => $svcpart,
1506 link_type => 'cust_svc_suspend_cascade'
1509 $svcpart{$part_svc_link->dst_svcpart} = max(
1510 $svcpart{$part_svc_link->dst_svcpart},
1511 $svcpart{$part_svc_link->src_svcpart} + 1
1515 @cust_svc = sort { $svcpart{ $a->svcpart } <=> $svcpart{ $b->svcpart } }
1519 foreach my $cust_svc ( @cust_svc ) {
1520 $cust_svc->suspend( 'labels_arrayref' => \@labels );
1523 # suspension fees: if there is a feepart, and it's not an unsuspend fee,
1524 # and this is not a suspend-before-cancel
1525 if ( $cust_pkg_reason ) {
1526 my $reason_obj = $cust_pkg_reason->reason;
1527 if ( $reason_obj->feepart and
1528 ! $reason_obj->fee_on_unsuspend and
1529 ! $options{'from_cancel'} ) {
1531 # register the need to charge a fee, cust_main->bill will do the rest
1532 warn "registering suspend fee: pkgnum ".$self->pkgnum.", feepart ".$reason->feepart."\n"
1534 my $cust_pkg_reason_fee = FS::cust_pkg_reason_fee->new({
1535 'pkgreasonnum' => $cust_pkg_reason->num,
1536 'pkgnum' => $self->pkgnum,
1537 'feepart' => $reason->feepart,
1538 'nextbill' => $reason->fee_hold,
1540 $error ||= $cust_pkg_reason_fee->insert;
1544 my $conf = new FS::Conf;
1545 if ( $conf->config('suspend_email_admin') && !$options{'from_cancel'} ) {
1547 my $error = send_email(
1548 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
1549 #invoice_from ??? well as good as any
1550 'to' => $conf->config('suspend_email_admin'),
1551 'subject' => 'FREESIDE NOTIFICATION: Customer package suspended',
1553 "This is an automatic message from your Freeside installation\n",
1554 "informing you that the following customer package has been suspended:\n",
1556 'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
1557 'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
1558 ( map { "Service : $_\n" } @labels ),
1560 'custnum' => $self->custnum,
1561 'msgtype' => 'admin'
1565 warn "WARNING: can't send suspension admin email (suspending anyway): ".
1573 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1574 $error = $supp_pkg->suspend(%options, 'from_main' => 1);
1576 $dbh->rollback if $oldAutoCommit;
1577 return "suspending supplemental pkg#".$supp_pkg->pkgnum.": $error";
1581 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1586 =item credit_remaining MODE TIME
1588 Generate a credit for this package for the time remaining in the current
1589 billing period. MODE is either "suspend" or "cancel" (determines the
1590 credit type). TIME is the time of suspension/cancellation. Both arguments
1595 # Implementation note:
1597 # If you pkgpart-change a package that has been billed, and it's set to give
1598 # credit on package change, then this method gets called and then the new
1599 # package will have no last_bill date. Therefore the customer will be credited
1600 # only once (per billing period) even if there are multiple package changes.
1602 # If you location-change a package that has been billed, this method will NOT
1603 # be called and the new package WILL have the last bill date of the old
1606 # If the new package is then canceled within the same billing cycle,
1607 # credit_remaining needs to run calc_remain on the OLD package to determine
1608 # the amount of unused time to credit.
1610 sub credit_remaining {
1611 # Add a credit for remaining service
1612 my ($self, $mode, $time) = @_;
1613 die 'credit_remaining requires suspend or cancel'
1614 unless $mode eq 'suspend' or $mode eq 'cancel';
1615 die 'no suspend/cancel time' unless $time > 0;
1617 my $conf = FS::Conf->new;
1618 my $reason_type = $conf->config($mode.'_credit_type');
1620 my $last_bill = $self->getfield('last_bill') || 0;
1621 my $next_bill = $self->getfield('bill') || 0;
1622 if ( $last_bill > 0 # the package has been billed
1623 and $next_bill > 0 # the package has a next bill date
1624 and $next_bill >= $time # which is in the future
1626 my @cust_credit_source_bill_pkg = ();
1627 my $remaining_value = 0;
1629 my $remain_pkg = $self;
1630 $remaining_value = $remain_pkg->calc_remain(
1632 'cust_credit_source_bill_pkg' => \@cust_credit_source_bill_pkg,
1635 # we may have to walk back past some package changes to get to the
1636 # one that actually has unused time
1637 while ( $remaining_value == 0 ) {
1638 if ( $remain_pkg->change_pkgnum ) {
1639 $remain_pkg = FS::cust_pkg->by_key($remain_pkg->change_pkgnum);
1641 # the package has really never been billed
1644 $remaining_value = $remain_pkg->calc_remain(
1646 'cust_credit_source_bill_pkg' => \@cust_credit_source_bill_pkg,
1650 if ( $remaining_value > 0 ) {
1651 warn "Crediting for $remaining_value on package ".$self->pkgnum."\n"
1653 my $error = $self->cust_main->credit(
1655 'Credit for unused time on '. $self->part_pkg->pkg,
1656 'reason_type' => $reason_type,
1657 'cust_credit_source_bill_pkg' => \@cust_credit_source_bill_pkg,
1659 return "Error crediting customer \$$remaining_value for unused time".
1660 " on ". $self->part_pkg->pkg. ": $error"
1662 } #if $remaining_value
1663 } #if $last_bill, etc.
1667 =item unsuspend [ OPTION => VALUE ... ]
1669 Unsuspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
1670 package, then unsuspends the package itself (clears the susp field and the
1671 adjourn field if it is in the past). If the suspend reason includes an
1672 unsuspension package, that package will be ordered.
1674 Available options are:
1680 Can be set to a date to unsuspend the package in the future (the 'resume'
1683 =item adjust_next_bill
1685 Can be set true to adjust the next bill date forward by
1686 the amount of time the account was inactive. This was set true by default
1687 in the past (from 1.4.2 and 1.5.0pre6 through 1.7.0), but now needs to be
1688 explicitly requested with this option or in the price plan.
1692 If there is an error, returns the error, otherwise returns false.
1697 my( $self, %opt ) = @_;
1700 # pass all suspend/cancel actions to the main package
1701 if ( $self->main_pkgnum and !$opt{'from_main'} ) {
1702 return $self->main_pkg->unsuspend(%opt);
1705 my $oldAutoCommit = $FS::UID::AutoCommit;
1706 local $FS::UID::AutoCommit = 0;
1709 my $old = $self->select_for_update;
1711 my $pkgnum = $old->pkgnum;
1712 if ( $old->get('cancel') || $self->get('cancel') ) {
1713 $dbh->rollback if $oldAutoCommit;
1714 return "Can't unsuspend cancelled package $pkgnum";
1717 unless ( $old->get('susp') && $self->get('susp') ) {
1718 $dbh->rollback if $oldAutoCommit;
1719 return ""; # no error # complain instead?
1722 # handle the case of setting a future unsuspend (resume) date
1723 # and do not continue to actually unsuspend the package
1724 my $date = $opt{'date'};
1725 if ( $date and $date > time ) { # return an error if $date <= time?
1727 if ( $old->get('expire') && $old->get('expire') < $date ) {
1728 $dbh->rollback if $oldAutoCommit;
1729 return "Package $pkgnum expires before it would be unsuspended.";
1732 my $new = new FS::cust_pkg { $self->hash };
1733 $new->set('resume', $date);
1734 $error = $new->replace($self, options => $self->options);
1737 $dbh->rollback if $oldAutoCommit;
1741 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1747 if (!$self->setup) {
1748 # then this package is being released from on-hold status
1749 $error = $self->set_initial_timers;
1751 $dbh->rollback if $oldAutoCommit;
1758 foreach my $cust_svc (
1759 qsearch('cust_svc',{'pkgnum'=> $self->pkgnum } )
1761 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
1763 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
1764 $dbh->rollback if $oldAutoCommit;
1765 return "Illegal svcdb value in part_svc!";
1768 require "FS/$svcdb.pm";
1770 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
1772 $error = $svc->unsuspend;
1774 $dbh->rollback if $oldAutoCommit;
1777 my( $label, $value ) = $cust_svc->label;
1778 push @labels, "$label: $value";
1783 my $cust_pkg_reason = $self->last_cust_pkg_reason('susp');
1784 my $reason = $cust_pkg_reason ? $cust_pkg_reason->reason : '';
1786 my %hash = $self->hash;
1787 my $inactive = time - $hash{'susp'};
1789 my $conf = new FS::Conf;
1791 #adjust the next bill date forward
1792 # increment next bill date if certain conditions are met:
1793 # - it was due to be billed at some point
1794 # - either the global or local config says to do this
1795 my $adjust_bill = 0;
1798 && ( $hash{'bill'} || $hash{'setup'} )
1799 && ( $opt{'adjust_next_bill'}
1800 || $conf->exists('unsuspend-always_adjust_next_bill_date')
1801 || $self->part_pkg->option('unsuspend_adjust_bill', 1)
1808 # - the package billed during suspension
1809 # - or it was ordered on hold
1810 # - or the customer was credited for the unused time
1812 if ( $self->option('suspend_bill',1)
1813 or ( $self->part_pkg->option('suspend_bill',1)
1814 and ! $self->option('no_suspend_bill',1)
1816 or $hash{'order_date'} == $hash{'susp'}
1821 if ( $adjust_bill ) {
1822 if ( $self->part_pkg->option('unused_credit_suspend')
1823 or ( ref($reason) and $reason->unused_credit ) ) {
1824 # then the customer was credited for the unused time before suspending,
1825 # so their next bill should be immediate
1826 $hash{'bill'} = time;
1828 # add the length of time suspended to the bill date
1829 $hash{'bill'} = ( $hash{'bill'} || $hash{'setup'} ) + $inactive;
1834 $hash{'adjourn'} = '' if $hash{'adjourn'} and $hash{'adjourn'} < time;
1835 $hash{'resume'} = '' if !$hash{'adjourn'};
1836 my $new = new FS::cust_pkg ( \%hash );
1837 $error = $new->replace( $self, options => { $self->options } );
1839 $dbh->rollback if $oldAutoCommit;
1846 if ( $reason->unsuspend_pkgpart ) {
1847 warn "Suspend reason '".$reason->reason."' uses deprecated unsuspend_pkgpart feature.\n";
1848 my $part_pkg = FS::part_pkg->by_key($reason->unsuspend_pkgpart)
1849 or $error = "Unsuspend package definition ".$reason->unsuspend_pkgpart.
1851 my $start_date = $self->cust_main->next_bill_date
1852 if $reason->unsuspend_hold;
1855 $unsusp_pkg = FS::cust_pkg->new({
1856 'custnum' => $self->custnum,
1857 'pkgpart' => $reason->unsuspend_pkgpart,
1858 'start_date' => $start_date,
1859 'locationnum' => $self->locationnum,
1860 # discount? probably not...
1863 $error ||= $self->cust_main->order_pkg( 'cust_pkg' => $unsusp_pkg );
1866 # new way, using fees
1867 if ( $reason->feepart and $reason->fee_on_unsuspend ) {
1868 # register the need to charge a fee, cust_main->bill will do the rest
1869 warn "registering unsuspend fee: pkgnum ".$self->pkgnum.", feepart ".$reason->feepart."\n"
1871 my $cust_pkg_reason_fee = FS::cust_pkg_reason_fee->new({
1872 'pkgreasonnum' => $cust_pkg_reason->num,
1873 'pkgnum' => $self->pkgnum,
1874 'feepart' => $reason->feepart,
1875 'nextbill' => $reason->fee_hold,
1877 $error ||= $cust_pkg_reason_fee->insert;
1881 $dbh->rollback if $oldAutoCommit;
1886 if ( $conf->config('unsuspend_email_admin') ) {
1888 my $error = send_email(
1889 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
1890 #invoice_from ??? well as good as any
1891 'to' => $conf->config('unsuspend_email_admin'),
1892 'subject' => 'FREESIDE NOTIFICATION: Customer package unsuspended', 'body' => [
1893 "This is an automatic message from your Freeside installation\n",
1894 "informing you that the following customer package has been unsuspended:\n",
1896 'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
1897 'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
1898 ( map { "Service : $_\n" } @labels ),
1900 "An unsuspension fee was charged: ".
1901 $unsusp_pkg->part_pkg->pkg_comment."\n"
1905 'custnum' => $self->custnum,
1906 'msgtype' => 'admin',
1910 warn "WARNING: can't send unsuspension admin email (unsuspending anyway): ".
1916 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1917 $error = $supp_pkg->unsuspend(%opt, 'from_main' => 1);
1919 $dbh->rollback if $oldAutoCommit;
1920 return "unsuspending supplemental pkg#".$supp_pkg->pkgnum.": $error";
1924 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1931 Cancels any pending suspension (sets the adjourn field to null).
1933 If there is an error, returns the error, otherwise returns false.
1938 my( $self, %options ) = @_;
1941 my $oldAutoCommit = $FS::UID::AutoCommit;
1942 local $FS::UID::AutoCommit = 0;
1945 my $old = $self->select_for_update;
1947 my $pkgnum = $old->pkgnum;
1948 if ( $old->get('cancel') || $self->get('cancel') ) {
1949 dbh->rollback if $oldAutoCommit;
1950 return "Can't unadjourn cancelled package $pkgnum";
1951 # or at least it's pointless
1954 if ( $old->get('susp') || $self->get('susp') ) {
1955 dbh->rollback if $oldAutoCommit;
1956 return "Can't unadjourn suspended package $pkgnum";
1957 # perhaps this is arbitrary
1960 unless ( $old->get('adjourn') && $self->get('adjourn') ) {
1961 dbh->rollback if $oldAutoCommit;
1962 return ""; # no error
1965 my %hash = $self->hash;
1966 $hash{'adjourn'} = '';
1967 $hash{'resume'} = '';
1968 my $new = new FS::cust_pkg ( \%hash );
1969 $error = $new->replace( $self, options => { $self->options } );
1971 $dbh->rollback if $oldAutoCommit;
1975 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1982 =item change HASHREF | OPTION => VALUE ...
1984 Changes this package: cancels it and creates a new one, with a different
1985 pkgpart or locationnum or both. All services are transferred to the new
1986 package (no change will be made if this is not possible).
1988 Options may be passed as a list of key/value pairs or as a hash reference.
1995 New locationnum, to change the location for this package.
1999 New FS::cust_location object, to create a new location and assign it
2004 New FS::cust_main object, to create a new customer and assign the new package
2009 New pkgpart (see L<FS::part_pkg>).
2013 New refnum (see L<FS::part_referral>).
2017 New quantity; if unspecified, the new package will have the same quantity
2022 "New" (existing) FS::cust_pkg object. The package's services and other
2023 attributes will be transferred to this package.
2027 Set to true to transfer billing dates (start_date, setup, last_bill, bill,
2028 susp, adjourn, cancel, expire, and contract_end) to the new package.
2030 =item unprotect_svcs
2032 Normally, change() will rollback and return an error if some services
2033 can't be transferred (also see the I<cust_pkg-change_svcpart> config option).
2034 If unprotect_svcs is true, this method will transfer as many services as
2035 it can and then unconditionally cancel the old package.
2039 If specified, sets this value for the contract_end date on the new package
2040 (without regard for keep_dates or the usual date-preservation behavior.)
2041 Will throw an error if defined but false; the UI doesn't allow editing
2042 this unless it already exists, making removal impossible to undo.
2046 At least one of locationnum, cust_location, pkgpart, refnum, cust_main, or
2047 cust_pkg must be specified (otherwise, what's the point?)
2049 Returns either the new FS::cust_pkg object or a scalar error.
2053 my $err_or_new_cust_pkg = $old_cust_pkg->change
2057 #used by change and change_later
2058 #didn't put with documented check methods because it depends on change-specific opts
2059 #and it also possibly edits the value of opts
2063 if ( defined($opt->{'contract_end'}) ) {
2064 my $current_contract_end = $self->get('contract_end');
2065 unless ($opt->{'contract_end'}) {
2066 if ($current_contract_end) {
2067 return "Cannot remove contract end date when changing packages";
2069 #shouldn't even pass this option if there's not a current value
2070 #but can be handled gracefully if the option is empty
2071 warn "Contract end date passed unexpectedly";
2072 delete $opt->{'contract_end'};
2076 unless ($current_contract_end) {
2077 #option shouldn't be passed, throw error if it's non-empty
2078 return "Cannot add contract end date when changing packages " . $self->pkgnum;
2084 #some false laziness w/order
2087 my $opt = ref($_[0]) ? shift : { @_ };
2089 my $conf = new FS::Conf;
2091 # handle contract_end on cust_pkg same as passed option
2092 if ( $opt->{'cust_pkg'} ) {
2093 $opt->{'contract_end'} = $opt->{'cust_pkg'}->contract_end;
2094 delete $opt->{'contract_end'} unless $opt->{'contract_end'};
2097 # check contract_end, prevent adding/removing
2098 my $error = $self->_check_change($opt);
2099 return $error if $error;
2101 # Transactionize this whole mess
2102 my $oldAutoCommit = $FS::UID::AutoCommit;
2103 local $FS::UID::AutoCommit = 0;
2106 if ( $opt->{'cust_location'} ) {
2107 $error = $opt->{'cust_location'}->find_or_insert;
2109 $dbh->rollback if $oldAutoCommit;
2110 return "creating location record: $error";
2112 $opt->{'locationnum'} = $opt->{'cust_location'}->locationnum;
2115 # Before going any further here: if the package is still in the pre-setup
2116 # state, it's safe to modify it in place. No need to charge/credit for
2117 # partial period, transfer services, transfer usage pools, copy invoice
2118 # details, or change any dates.
2119 if ( ! $self->setup and ! $opt->{cust_pkg} and ! $opt->{cust_main} ) {
2120 foreach ( qw( locationnum pkgpart quantity refnum salesnum ) ) {
2121 if ( length($opt->{$_}) ) {
2122 $self->set($_, $opt->{$_});
2125 # almost. if the new pkgpart specifies start/adjourn/expire timers,
2127 if ( $opt->{'pkgpart'} and $opt->{'pkgpart'} != $self->pkgpart ) {
2128 $error ||= $self->set_initial_timers;
2130 # but if contract_end was explicitly specified, that overrides all else
2131 $self->set('contract_end', $opt->{'contract_end'})
2132 if $opt->{'contract_end'};
2133 $error ||= $self->replace;
2135 $dbh->rollback if $oldAutoCommit;
2136 return "modifying package: $error";
2138 $dbh->commit if $oldAutoCommit;
2147 $hash{'setup'} = $time if $self->setup;
2149 $hash{'change_date'} = $time;
2150 $hash{"change_$_"} = $self->$_()
2151 foreach qw( pkgnum pkgpart locationnum );
2153 if ( $opt->{'cust_pkg'} ) {
2154 # treat changing to a package with a different pkgpart as a
2155 # pkgpart change (because it is)
2156 $opt->{'pkgpart'} = $opt->{'cust_pkg'}->pkgpart;
2159 # whether to override pkgpart checking on the new package
2160 my $same_pkgpart = 1;
2161 if ( $opt->{'pkgpart'} and ( $opt->{'pkgpart'} != $self->pkgpart ) ) {
2165 my $unused_credit = 0;
2166 my $keep_dates = $opt->{'keep_dates'};
2168 # Special case. If the pkgpart is changing, and the customer is
2169 # going to be credited for remaining time, don't keep setup, bill,
2170 # or last_bill dates, and DO pass the flag to cancel() to credit
2172 if ( $opt->{'pkgpart'}
2173 and $opt->{'pkgpart'} != $self->pkgpart
2174 and $self->part_pkg->option('unused_credit_change', 1) ) {
2177 $hash{$_} = '' foreach qw(setup bill last_bill);
2180 if ( $keep_dates ) {
2181 foreach my $date ( qw(setup bill last_bill) ) {
2182 $hash{$date} = $self->getfield($date);
2185 # always keep the following dates
2186 foreach my $date (qw(order_date susp adjourn cancel expire resume
2187 start_date contract_end)) {
2188 $hash{$date} = $self->getfield($date);
2190 # but if contract_end was explicitly specified, that overrides all else
2191 $hash{'contract_end'} = $opt->{'contract_end'}
2192 if $opt->{'contract_end'};
2194 # allow $opt->{'locationnum'} = '' to specifically set it to null
2195 # (i.e. customer default location)
2196 $opt->{'locationnum'} = $self->locationnum if !exists($opt->{'locationnum'});
2198 # usually this doesn't matter. the two cases where it does are:
2199 # 1. unused_credit_change + pkgpart change + setup fee on the new package
2201 # 2. (more importantly) changing a package before it's billed
2202 $hash{'waive_setup'} = $self->waive_setup;
2204 # if this package is scheduled for a future package change, preserve that
2205 $hash{'change_to_pkgnum'} = $self->change_to_pkgnum;
2207 my $custnum = $self->custnum;
2208 if ( $opt->{cust_main} ) {
2209 my $cust_main = $opt->{cust_main};
2210 unless ( $cust_main->custnum ) {
2211 my $error = $cust_main->insert( @{ $opt->{cust_main_insert_args}||[] } );
2213 $dbh->rollback if $oldAutoCommit;
2214 return "inserting customer record: $error";
2217 $custnum = $cust_main->custnum;
2220 $hash{'contactnum'} = $opt->{'contactnum'} if $opt->{'contactnum'};
2223 if ( $opt->{'cust_pkg'} ) {
2224 # The target package already exists; update it to show that it was
2225 # changed from this package.
2226 $cust_pkg = $opt->{'cust_pkg'};
2228 # follow all the above rules for date changes, etc.
2229 foreach (keys %hash) {
2230 $cust_pkg->set($_, $hash{$_});
2232 # except those that implement the future package change behavior
2233 foreach (qw(change_to_pkgnum start_date expire)) {
2234 $cust_pkg->set($_, '');
2237 $error = $cust_pkg->replace;
2240 # Create the new package.
2241 $cust_pkg = new FS::cust_pkg {
2242 custnum => $custnum,
2243 locationnum => $opt->{'locationnum'},
2244 ( map { $_ => ( $opt->{$_} || $self->$_() ) }
2245 qw( pkgpart quantity refnum salesnum )
2249 $error = $cust_pkg->insert( 'change' => 1,
2250 'allow_pkgpart' => $same_pkgpart );
2253 $dbh->rollback if $oldAutoCommit;
2254 return "inserting new package: $error";
2257 # Transfer services and cancel old package.
2258 # Enforce service limits only if this is a pkgpart change.
2259 local $FS::cust_svc::ignore_quantity;
2260 $FS::cust_svc::ignore_quantity = 1 if $same_pkgpart;
2261 $error = $self->transfer($cust_pkg);
2262 if ($error and $error == 0) {
2263 # $old_pkg->transfer failed.
2264 $dbh->rollback if $oldAutoCommit;
2265 return "transferring $error";
2268 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
2269 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
2270 $error = $self->transfer($cust_pkg, 'change_svcpart'=>1 );
2271 if ($error and $error == 0) {
2272 # $old_pkg->transfer failed.
2273 $dbh->rollback if $oldAutoCommit;
2274 return "converting $error";
2278 # We set unprotect_svcs when executing a "future package change". It's
2279 # not a user-interactive operation, so returning an error means the
2280 # package change will just fail. Rather than have that happen, we'll
2281 # let leftover services be deleted.
2282 if ($error > 0 and !$opt->{'unprotect_svcs'}) {
2283 # Transfers were successful, but we still had services left on the old
2284 # package. We can't change the package under this circumstances, so abort.
2285 $dbh->rollback if $oldAutoCommit;
2286 return "unable to transfer all services";
2289 #reset usage if changing pkgpart
2290 # AND usage rollover is off (otherwise adds twice, now and at package bill)
2291 if ($self->pkgpart != $cust_pkg->pkgpart) {
2292 my $part_pkg = $cust_pkg->part_pkg;
2293 $error = $part_pkg->reset_usage($cust_pkg, $part_pkg->is_prepaid
2297 if $part_pkg->can('reset_usage') && ! $part_pkg->option('usage_rollover',1);
2300 $dbh->rollback if $oldAutoCommit;
2301 return "setting usage values: $error";
2304 # if NOT changing pkgpart, transfer any usage pools over
2305 foreach my $usage ($self->cust_pkg_usage) {
2306 $usage->set('pkgnum', $cust_pkg->pkgnum);
2307 $error = $usage->replace;
2309 $dbh->rollback if $oldAutoCommit;
2310 return "transferring usage pools: $error";
2315 # transfer usage pricing add-ons, if we're not changing pkgpart or if they were specified
2316 if ( $same_pkgpart || $opt->{'cust_pkg_usageprice'}) {
2317 my @old_cust_pkg_usageprice;
2318 if ($opt->{'cust_pkg_usageprice'}) {
2319 @old_cust_pkg_usageprice = @{ $opt->{'cust_pkg_usageprice'} };
2321 @old_cust_pkg_usageprice = $self->cust_pkg_usageprice;
2323 foreach my $old_cust_pkg_usageprice (@old_cust_pkg_usageprice) {
2324 my $new_cust_pkg_usageprice = new FS::cust_pkg_usageprice {
2325 'pkgnum' => $cust_pkg->pkgnum,
2326 'usagepricepart' => $old_cust_pkg_usageprice->usagepricepart,
2327 'quantity' => $old_cust_pkg_usageprice->quantity,
2329 $error = $new_cust_pkg_usageprice->insert;
2331 $dbh->rollback if $oldAutoCommit;
2332 return "Error transferring usage pricing add-on: $error";
2337 # transfer discounts, if we're not changing pkgpart
2338 if ( $same_pkgpart ) {
2339 foreach my $old_discount ($self->cust_pkg_discount_active) {
2340 # don't remove the old discount, we may still need to bill that package.
2341 my $new_discount = new FS::cust_pkg_discount {
2342 'pkgnum' => $cust_pkg->pkgnum,
2343 'discountnum' => $old_discount->discountnum,
2344 'months_used' => $old_discount->months_used,
2346 $error = $new_discount->insert;
2348 $dbh->rollback if $oldAutoCommit;
2349 return "transferring discounts: $error";
2354 # transfer (copy) invoice details
2355 foreach my $detail ($self->cust_pkg_detail) {
2356 my $new_detail = FS::cust_pkg_detail->new({ $detail->hash });
2357 $new_detail->set('pkgdetailnum', '');
2358 $new_detail->set('pkgnum', $cust_pkg->pkgnum);
2359 $error = $new_detail->insert;
2361 $dbh->rollback if $oldAutoCommit;
2362 return "transferring package notes: $error";
2368 if ( !$opt->{'cust_pkg'} ) {
2369 # Order any supplemental packages.
2370 my $part_pkg = $cust_pkg->part_pkg;
2371 my @old_supp_pkgs = $self->supplemental_pkgs;
2372 foreach my $link ($part_pkg->supp_part_pkg_link) {
2374 foreach (@old_supp_pkgs) {
2375 if ($_->pkgpart == $link->dst_pkgpart) {
2377 $_->pkgpart(0); # so that it can't match more than once
2381 # false laziness with FS::cust_main::Packages::order_pkg
2382 my $new = FS::cust_pkg->new({
2383 pkgpart => $link->dst_pkgpart,
2384 pkglinknum => $link->pkglinknum,
2385 custnum => $custnum,
2386 main_pkgnum => $cust_pkg->pkgnum,
2387 locationnum => $cust_pkg->locationnum,
2388 start_date => $cust_pkg->start_date,
2389 order_date => $cust_pkg->order_date,
2390 expire => $cust_pkg->expire,
2391 adjourn => $cust_pkg->adjourn,
2392 contract_end => $cust_pkg->contract_end,
2393 refnum => $cust_pkg->refnum,
2394 discountnum => $cust_pkg->discountnum,
2395 waive_setup => $cust_pkg->waive_setup,
2397 if ( $old and $opt->{'keep_dates'} ) {
2398 foreach (qw(setup bill last_bill)) {
2399 $new->set($_, $old->get($_));
2402 $error = $new->insert( allow_pkgpart => $same_pkgpart );
2405 $error ||= $old->transfer($new);
2407 if ( $error and $error > 0 ) {
2408 # no reason why this should ever fail, but still...
2409 $error = "Unable to transfer all services from supplemental package ".
2413 $dbh->rollback if $oldAutoCommit;
2416 push @new_supp_pkgs, $new;
2418 } # if !$opt->{'cust_pkg'}
2419 # because if there is one, then supplemental packages would already
2420 # have been created for it.
2422 #Good to go, cancel old package. Notify 'cancel' of whether to credit
2424 #Don't allow billing the package (preceding period packages and/or
2425 #outstanding usage) if we are keeping dates (i.e. location changing),
2426 #because the new package will be billed for the same date range.
2427 #Supplemental packages are also canceled here.
2429 # during scheduled changes, avoid canceling the package we just
2431 $self->set('change_to_pkgnum' => '');
2433 $error = $self->cancel(
2435 unused_credit => $unused_credit,
2436 nobill => $keep_dates,
2437 change_custnum => ( $self->custnum != $custnum ? $custnum : '' ),
2438 no_delay_cancel => 1,
2441 $dbh->rollback if $oldAutoCommit;
2442 return "canceling old package: $error";
2445 if ( $conf->exists('cust_pkg-change_pkgpart-bill_now') ) {
2447 my $error = $cust_pkg->cust_main->bill(
2448 'pkg_list' => [ $cust_pkg, @new_supp_pkgs ]
2451 $dbh->rollback if $oldAutoCommit;
2452 return "billing new package: $error";
2456 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2462 =item change_later OPTION => VALUE...
2464 Schedule a package change for a later date. This actually orders the new
2465 package immediately, but sets its start date for a future date, and sets
2466 the current package to expire on the same date.
2468 If the package is already scheduled for a change, this can be called with
2469 'start_date' to change the scheduled date, or with pkgpart and/or
2470 locationnum to modify the package change. To cancel the scheduled change
2471 entirely, see C<abort_change>.
2479 The date for the package change. Required, and must be in the future.
2489 The pkgpart, locationnum, quantity and optional contract_end of the new
2490 package, with the same meaning as in C<change>.
2498 my $opt = ref($_[0]) ? shift : { @_ };
2500 # check contract_end, prevent adding/removing
2501 my $error = $self->_check_change($opt);
2502 return $error if $error;
2504 my $oldAutoCommit = $FS::UID::AutoCommit;
2505 local $FS::UID::AutoCommit = 0;
2508 my $cust_main = $self->cust_main;
2510 my $date = delete $opt->{'start_date'} or return 'start_date required';
2512 if ( $date <= time ) {
2513 $dbh->rollback if $oldAutoCommit;
2514 return "start_date $date is in the past";
2517 if ( $self->change_to_pkgnum ) {
2518 my $change_to = FS::cust_pkg->by_key($self->change_to_pkgnum);
2519 my $new_pkgpart = $opt->{'pkgpart'}
2520 if $opt->{'pkgpart'} and $opt->{'pkgpart'} != $change_to->pkgpart;
2521 my $new_locationnum = $opt->{'locationnum'}
2522 if $opt->{'locationnum'} and $opt->{'locationnum'} != $change_to->locationnum;
2523 my $new_quantity = $opt->{'quantity'}
2524 if $opt->{'quantity'} and $opt->{'quantity'} != $change_to->quantity;
2525 my $new_contract_end = $opt->{'contract_end'}
2526 if $opt->{'contract_end'} and $opt->{'contract_end'} != $change_to->contract_end;
2527 if ( $new_pkgpart or $new_locationnum or $new_quantity or $new_contract_end ) {
2528 # it hasn't been billed yet, so in principle we could just edit
2529 # it in place (w/o a package change), but that's bad form.
2530 # So change the package according to the new options...
2531 my $err_or_pkg = $change_to->change(%$opt);
2532 if ( ref $err_or_pkg ) {
2533 # Then set that package up for a future start.
2534 $self->set('change_to_pkgnum', $err_or_pkg->pkgnum);
2535 $self->set('expire', $date); # in case it's different
2536 $err_or_pkg->set('start_date', $date);
2537 $err_or_pkg->set('change_date', '');
2538 $err_or_pkg->set('change_pkgnum', '');
2540 $error = $self->replace ||
2541 $err_or_pkg->replace ||
2542 #because change() might've edited existing scheduled change in place
2543 (($err_or_pkg->pkgnum == $change_to->pkgnum) ? '' :
2544 $change_to->cancel('no_delay_cancel' => 1) ||
2545 $change_to->delete);
2547 $error = $err_or_pkg;
2549 } else { # change the start date only.
2550 $self->set('expire', $date);
2551 $change_to->set('start_date', $date);
2552 $error = $self->replace || $change_to->replace;
2555 $dbh->rollback if $oldAutoCommit;
2558 $dbh->commit if $oldAutoCommit;
2561 } # if $self->change_to_pkgnum
2563 my $new_pkgpart = $opt->{'pkgpart'}
2564 if $opt->{'pkgpart'} and $opt->{'pkgpart'} != $self->pkgpart;
2565 my $new_locationnum = $opt->{'locationnum'}
2566 if $opt->{'locationnum'} and $opt->{'locationnum'} != $self->locationnum;
2567 my $new_quantity = $opt->{'quantity'}
2568 if $opt->{'quantity'} and $opt->{'quantity'} != $self->quantity;
2569 my $new_contract_end = $opt->{'contract_end'}
2570 if $opt->{'contract_end'} and $opt->{'contract_end'} != $self->contract_end;
2572 return '' unless $new_pkgpart or $new_locationnum or $new_quantity or $new_contract_end; # wouldn't do anything
2574 # allow $opt->{'locationnum'} = '' to specifically set it to null
2575 # (i.e. customer default location)
2576 $opt->{'locationnum'} = $self->locationnum if !exists($opt->{'locationnum'});
2578 my $new = FS::cust_pkg->new( {
2579 custnum => $self->custnum,
2580 locationnum => $opt->{'locationnum'},
2581 start_date => $date,
2582 map { $_ => ( $opt->{$_} || $self->$_() ) }
2583 qw( pkgpart quantity refnum salesnum contract_end )
2585 $error = $new->insert('change' => 1,
2586 'allow_pkgpart' => ($new_pkgpart ? 0 : 1));
2588 $self->set('change_to_pkgnum', $new->pkgnum);
2589 $self->set('expire', $date);
2590 $error = $self->replace;
2593 $dbh->rollback if $oldAutoCommit;
2595 $dbh->commit if $oldAutoCommit;
2603 Cancels a future package change scheduled by C<change_later>.
2609 my $oldAutoCommit = $FS::UID::AutoCommit;
2610 local $FS::UID::AutoCommit = 0;
2612 my $pkgnum = $self->change_to_pkgnum;
2613 my $change_to = FS::cust_pkg->by_key($pkgnum) if $pkgnum;
2615 $self->set('change_to_pkgnum', '');
2616 $self->set('expire', '');
2617 $error = $self->replace;
2619 $error ||= $change_to->cancel || $change_to->delete;
2622 if ( $oldAutoCommit ) {
2633 =item set_quantity QUANTITY
2635 Change the package's quantity field. This is one of the few package properties
2636 that can safely be changed without canceling and reordering the package
2637 (because it doesn't affect tax eligibility). Returns an error or an
2644 $self = $self->replace_old; # just to make sure
2645 $self->quantity(shift);
2649 =item set_salesnum SALESNUM
2651 Change the package's salesnum (sales person) field. This is one of the few
2652 package properties that can safely be changed without canceling and reordering
2653 the package (because it doesn't affect tax eligibility). Returns an error or
2660 $self = $self->replace_old; # just to make sure
2661 $self->salesnum(shift);
2663 # XXX this should probably reassign any credit that's already been given
2666 =item modify_charge OPTIONS
2668 Change the properties of a one-time charge. The following properties can
2669 be changed this way:
2670 - pkg: the package description
2671 - classnum: the package class
2672 - additional: arrayref of additional invoice details to add to this package
2674 and, I<if the charge has not yet been billed>:
2675 - start_date: the date when it will be billed
2676 - amount: the setup fee to be charged
2677 - quantity: the multiplier for the setup fee
2678 - separate_bill: whether to put the charge on a separate invoice
2680 If you pass 'adjust_commission' => 1, and the classnum changes, and there are
2681 commission credits linked to this charge, they will be recalculated.
2688 my $part_pkg = $self->part_pkg;
2689 my $pkgnum = $self->pkgnum;
2692 my $oldAutoCommit = $FS::UID::AutoCommit;
2693 local $FS::UID::AutoCommit = 0;
2695 return "Can't use modify_charge except on one-time charges"
2696 unless $part_pkg->freq eq '0';
2698 if ( length($opt{'pkg'}) and $part_pkg->pkg ne $opt{'pkg'} ) {
2699 $part_pkg->set('pkg', $opt{'pkg'});
2702 my %pkg_opt = $part_pkg->options;
2703 my $pkg_opt_modified = 0;
2705 $opt{'additional'} ||= [];
2708 foreach (grep /^additional/, keys %pkg_opt) {
2709 ($i) = ($_ =~ /^additional_info(\d+)$/);
2710 $old_additional[$i] = $pkg_opt{$_} if $i;
2711 delete $pkg_opt{$_};
2714 for ( $i = 0; exists($opt{'additional'}->[$i]); $i++ ) {
2715 $pkg_opt{ "additional_info$i" } = $opt{'additional'}->[$i];
2716 if (!exists($old_additional[$i])
2717 or $old_additional[$i] ne $opt{'additional'}->[$i])
2719 $pkg_opt_modified = 1;
2722 $pkg_opt_modified = 1 if (scalar(@old_additional) - 1) != $i;
2723 $pkg_opt{'additional_count'} = $i if $i > 0;
2726 if ( exists($opt{'classnum'}) and $part_pkg->classnum ne $opt{'classnum'} )
2729 $old_classnum = $part_pkg->classnum;
2730 $part_pkg->set('classnum', $opt{'classnum'});
2733 if ( !$self->get('setup') ) {
2734 # not yet billed, so allow amount, setup_cost, quantity, start_date,
2737 if ( exists($opt{'amount'})
2738 and $part_pkg->option('setup_fee') != $opt{'amount'}
2739 and $opt{'amount'} > 0 ) {
2741 $pkg_opt{'setup_fee'} = $opt{'amount'};
2742 $pkg_opt_modified = 1;
2745 if ( exists($opt{'setup_cost'})
2746 and $part_pkg->setup_cost != $opt{'setup_cost'}
2747 and $opt{'setup_cost'} > 0 ) {
2749 $part_pkg->set('setup_cost', $opt{'setup_cost'});
2752 if ( exists($opt{'quantity'})
2753 and $opt{'quantity'} != $self->quantity
2754 and $opt{'quantity'} > 0 ) {
2756 $self->set('quantity', $opt{'quantity'});
2759 if ( exists($opt{'start_date'})
2760 and $opt{'start_date'} != $self->start_date ) {
2762 $self->set('start_date', $opt{'start_date'});
2765 if ( exists($opt{'separate_bill'})
2766 and $opt{'separate_bill'} ne $self->separate_bill ) {
2768 $self->set('separate_bill', $opt{'separate_bill'});
2772 } # else simply ignore them; the UI shouldn't allow editing the fields
2775 if ( exists($opt{'taxclass'})
2776 and $part_pkg->taxclass ne $opt{'taxclass'}) {
2778 $part_pkg->set('taxclass', $opt{'taxclass'});
2782 if ( $part_pkg->modified or $pkg_opt_modified ) {
2783 # can we safely modify the package def?
2784 # Yes, if it's not available for purchase, and this is the only instance
2786 if ( $part_pkg->disabled
2787 and FS::cust_pkg->count('pkgpart = '.$part_pkg->pkgpart) == 1
2788 and FS::quotation_pkg->count('pkgpart = '.$part_pkg->pkgpart) == 0
2790 $error = $part_pkg->replace( options => \%pkg_opt );
2793 $part_pkg = $part_pkg->clone;
2794 $part_pkg->set('disabled' => 'Y');
2795 $error = $part_pkg->insert( options => \%pkg_opt );
2796 # and associate this as yet-unbilled package to the new package def
2797 $self->set('pkgpart' => $part_pkg->pkgpart);
2800 $dbh->rollback if $oldAutoCommit;
2805 if ($self->modified) { # for quantity or start_date change, or if we had
2806 # to clone the existing package def
2807 my $error = $self->replace;
2808 return $error if $error;
2810 if (defined $old_classnum) {
2811 # fix invoice grouping records
2812 my $old_catname = $old_classnum
2813 ? FS::pkg_class->by_key($old_classnum)->categoryname
2815 my $new_catname = $opt{'classnum'}
2816 ? $part_pkg->pkg_class->categoryname
2818 if ( $old_catname ne $new_catname ) {
2819 foreach my $cust_bill_pkg ($self->cust_bill_pkg) {
2820 # (there should only be one...)
2821 my @display = qsearch( 'cust_bill_pkg_display', {
2822 'billpkgnum' => $cust_bill_pkg->billpkgnum,
2823 'section' => $old_catname,
2825 foreach (@display) {
2826 $_->set('section', $new_catname);
2827 $error = $_->replace;
2829 $dbh->rollback if $oldAutoCommit;
2833 } # foreach $cust_bill_pkg
2836 if ( $opt{'adjust_commission'} ) {
2837 # fix commission credits...tricky.
2838 foreach my $cust_event ($self->cust_event) {
2839 my $part_event = $cust_event->part_event;
2840 foreach my $table (qw(sales agent)) {
2842 "FS::part_event::Action::Mixin::credit_${table}_pkg_class";
2843 my $credit = qsearchs('cust_credit', {
2844 'eventnum' => $cust_event->eventnum,
2846 if ( $part_event->isa($class) ) {
2847 # Yes, this results in current commission rates being applied
2848 # retroactively to a one-time charge. For accounting purposes
2849 # there ought to be some kind of time limit on doing this.
2850 my $amount = $part_event->_calc_credit($self);
2851 if ( $credit and $credit->amount ne $amount ) {
2852 # Void the old credit.
2853 $error = $credit->void('Package class changed');
2855 $dbh->rollback if $oldAutoCommit;
2856 return "$error (adjusting commission credit)";
2859 # redo the event action to recreate the credit.
2861 eval { $part_event->do_action( $self, $cust_event ) };
2863 $dbh->rollback if $oldAutoCommit;
2866 } # if $part_event->isa($class)
2868 } # foreach $cust_event
2869 } # if $opt{'adjust_commission'}
2870 } # if defined $old_classnum
2872 $dbh->commit if $oldAutoCommit;
2879 sub process_bulk_cust_pkg {
2882 warn Dumper($param) if $DEBUG;
2884 my $old_part_pkg = qsearchs('part_pkg',
2885 { pkgpart => $param->{'old_pkgpart'} });
2886 my $new_part_pkg = qsearchs('part_pkg',
2887 { pkgpart => $param->{'new_pkgpart'} });
2888 die "Must select a new package type\n" unless $new_part_pkg;
2889 #my $keep_dates = $param->{'keep_dates'} || 0;
2890 my $keep_dates = 1; # there is no good reason to turn this off
2892 my $oldAutoCommit = $FS::UID::AutoCommit;
2893 local $FS::UID::AutoCommit = 0;
2896 my @cust_pkgs = qsearch('cust_pkg', { 'pkgpart' => $param->{'old_pkgpart'} } );
2899 foreach my $old_cust_pkg ( @cust_pkgs ) {
2901 $job->update_statustext(int(100*$i/(scalar @cust_pkgs)));
2902 if ( $old_cust_pkg->getfield('cancel') ) {
2903 warn '[process_bulk_cust_pkg ] skipping canceled pkgnum '.
2904 $old_cust_pkg->pkgnum."\n"
2908 warn '[process_bulk_cust_pkg] changing pkgnum '.$old_cust_pkg->pkgnum."\n"
2910 my $error = $old_cust_pkg->change(
2911 'pkgpart' => $param->{'new_pkgpart'},
2912 'keep_dates' => $keep_dates
2914 if ( !ref($error) ) { # change returns the cust_pkg on success
2916 die "Error changing pkgnum ".$old_cust_pkg->pkgnum.": '$error'\n";
2919 $dbh->commit if $oldAutoCommit;
2925 Returns the last bill date, or if there is no last bill date, the setup date.
2926 Useful for billing metered services.
2932 return $self->setfield('last_bill', $_[0]) if @_;
2933 return $self->getfield('last_bill') if $self->getfield('last_bill');
2934 my $cust_bill_pkg = qsearchs('cust_bill_pkg', { 'pkgnum' => $self->pkgnum,
2935 'edate' => $self->bill, } );
2936 $cust_bill_pkg ? $cust_bill_pkg->sdate : $self->setup || 0;
2939 =item last_cust_pkg_reason ACTION
2941 Returns the most recent ACTION FS::cust_pkg_reason associated with the package.
2942 Returns false if there is no reason or the package is not currenly ACTION'd
2943 ACTION is one of adjourn, susp, cancel, or expire.
2947 sub last_cust_pkg_reason {
2948 my ( $self, $action ) = ( shift, shift );
2949 my $date = $self->get($action);
2951 'table' => 'cust_pkg_reason',
2952 'hashref' => { 'pkgnum' => $self->pkgnum,
2953 'action' => substr(uc($action), 0, 1),
2956 'order_by' => 'ORDER BY num DESC LIMIT 1',
2960 =item last_reason ACTION
2962 Returns the most recent ACTION FS::reason associated with the package.
2963 Returns false if there is no reason or the package is not currenly ACTION'd
2964 ACTION is one of adjourn, susp, cancel, or expire.
2969 my $cust_pkg_reason = shift->last_cust_pkg_reason(@_);
2970 $cust_pkg_reason->reason
2971 if $cust_pkg_reason;
2976 Returns the definition for this billing item, as an FS::part_pkg object (see
2983 return $self->{'_pkgpart'} if $self->{'_pkgpart'};
2984 cluck "cust_pkg->part_pkg called" if $DEBUG > 1;
2985 qsearchs( 'part_pkg', { 'pkgpart' => $self->pkgpart } );
2990 Returns the cancelled package this package was changed from, if any.
2996 return '' unless $self->change_pkgnum;
2997 qsearchs('cust_pkg', { 'pkgnum' => $self->change_pkgnum } );
3000 =item change_cust_main
3002 Returns the customter this package was detached to, if any.
3006 sub change_cust_main {
3008 return '' unless $self->change_custnum;
3009 qsearchs('cust_main', { 'custnum' => $self->change_custnum } );
3014 Calls the I<calc_setup> of the FS::part_pkg object associated with this billing
3021 $self->part_pkg->calc_setup($self, @_);
3026 Calls the I<calc_recur> of the FS::part_pkg object associated with this billing
3033 $self->part_pkg->calc_recur($self, @_);
3038 Calls the I<base_setup> of the FS::part_pkg object associated with this billing
3045 $self->part_pkg->base_setup($self, @_);
3050 Calls the I<base_recur> of the FS::part_pkg object associated with this billing
3057 $self->part_pkg->base_recur($self, @_);
3062 Calls the I<calc_remain> of the FS::part_pkg object associated with this
3069 $self->part_pkg->calc_remain($self, @_);
3074 Calls the I<calc_cancel> of the FS::part_pkg object associated with this
3081 $self->part_pkg->calc_cancel($self, @_);
3086 Returns any invoice line items for this package (see L<FS::cust_bill_pkg>).
3092 qsearch( 'cust_bill_pkg', { 'pkgnum' => $self->pkgnum } );
3095 =item cust_pkg_detail [ DETAILTYPE ]
3097 Returns any customer package details for this package (see
3098 L<FS::cust_pkg_detail>).
3100 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
3104 sub cust_pkg_detail {
3106 my %hash = ( 'pkgnum' => $self->pkgnum );
3107 $hash{detailtype} = shift if @_;
3109 'table' => 'cust_pkg_detail',
3110 'hashref' => \%hash,
3111 'order_by' => 'ORDER BY weight, pkgdetailnum',
3115 =item set_cust_pkg_detail DETAILTYPE [ DETAIL, DETAIL, ... ]
3117 Sets customer package details for this package (see L<FS::cust_pkg_detail>).
3119 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
3121 If there is an error, returns the error, otherwise returns false.
3125 sub set_cust_pkg_detail {
3126 my( $self, $detailtype, @details ) = @_;
3128 my $oldAutoCommit = $FS::UID::AutoCommit;
3129 local $FS::UID::AutoCommit = 0;
3132 foreach my $current ( $self->cust_pkg_detail($detailtype) ) {
3133 my $error = $current->delete;
3135 $dbh->rollback if $oldAutoCommit;
3136 return "error removing old detail: $error";
3140 foreach my $detail ( @details ) {
3141 my $cust_pkg_detail = new FS::cust_pkg_detail {
3142 'pkgnum' => $self->pkgnum,
3143 'detailtype' => $detailtype,
3144 'detail' => $detail,
3146 my $error = $cust_pkg_detail->insert;
3148 $dbh->rollback if $oldAutoCommit;
3149 return "error adding new detail: $error";
3154 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3161 Returns the customer billing events (see L<FS::cust_event>) for this invoice.
3165 #false laziness w/cust_bill.pm
3169 'table' => 'cust_event',
3170 'addl_from' => 'JOIN part_event USING ( eventpart )',
3171 'hashref' => { 'tablenum' => $self->pkgnum },
3172 'extra_sql' => " AND eventtable = 'cust_pkg' ",
3176 =item num_cust_event
3178 Returns the number of customer billing events (see L<FS::cust_event>) for this package.
3182 #false laziness w/cust_bill.pm
3183 sub num_cust_event {
3185 my $sql = "SELECT COUNT(*) ". $self->_from_cust_event_where;
3186 $self->_prep_ex($sql, $self->pkgnum)->fetchrow_arrayref->[0];
3189 =item exists_cust_event
3191 Returns true if there are customer billing events (see L<FS::cust_event>) for this package. More efficient than using num_cust_event.
3195 sub exists_cust_event {
3197 my $sql = "SELECT 1 ". $self->_from_cust_event_where. " LIMIT 1";
3198 my $row = $self->_prep_ex($sql, $self->pkgnum)->fetchrow_arrayref;
3199 $row ? $row->[0] : '';
3202 sub _from_cust_event_where {
3204 " FROM cust_event JOIN part_event USING ( eventpart ) ".
3205 " WHERE tablenum = ? AND eventtable = 'cust_pkg' ";
3209 my( $self, $sql, @args ) = @_;
3210 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
3211 $sth->execute(@args) or die $sth->errstr. " executing $sql";
3215 =item part_pkg_currency_option OPTIONNAME
3217 Returns a two item list consisting of the currency of this customer, if any,
3218 and a value for the provided option. If the customer has a currency, the value
3219 is the option value the given name and the currency (see
3220 L<FS::part_pkg_currency>). Otherwise, if the customer has no currency, is the
3221 regular option value for the given name (see L<FS::part_pkg_option>).
3225 sub part_pkg_currency_option {
3226 my( $self, $optionname ) = @_;
3227 my $part_pkg = $self->part_pkg;
3228 if ( my $currency = $self->cust_main->currency ) {
3229 ($currency, $part_pkg->part_pkg_currency_option($currency, $optionname) );
3231 ('', $part_pkg->option($optionname) );
3235 =item cust_svc [ SVCPART ] (old, deprecated usage)
3237 =item cust_svc [ OPTION => VALUE ... ] (current usage)
3239 =item cust_svc_unsorted [ OPTION => VALUE ... ]
3241 Returns the services for this package, as FS::cust_svc objects (see
3242 L<FS::cust_svc>). Available options are svcpart and svcdb. If either is
3243 spcififed, returns only the matching services.
3245 As an optimization, use the cust_svc_unsorted version if you are not displaying
3252 cluck "cust_pkg->cust_svc called" if $DEBUG > 2;
3253 $self->_sort_cust_svc( $self->cust_svc_unsorted_arrayref(@_) );
3256 sub cust_svc_unsorted {
3258 @{ $self->cust_svc_unsorted_arrayref(@_) };
3261 sub cust_svc_unsorted_arrayref {
3264 return [] unless $self->num_cust_svc(@_);
3267 if ( @_ && $_[0] =~ /^\d+/ ) {
3268 $opt{svcpart} = shift;
3269 } elsif ( @_ && ref($_[0]) eq 'HASH' ) {
3276 'table' => 'cust_svc',
3277 'hashref' => { 'pkgnum' => $self->pkgnum },
3279 if ( $opt{svcpart} ) {
3280 $search{hashref}->{svcpart} = $opt{'svcpart'};
3282 if ( $opt{'svcdb'} ) {
3283 $search{addl_from} = ' LEFT JOIN part_svc USING ( svcpart ) ';
3284 $search{extra_sql} = ' AND svcdb = '. dbh->quote( $opt{'svcdb'} );
3287 [ qsearch(\%search) ];
3291 =item overlimit [ SVCPART ]
3293 Returns the services for this package which have exceeded their
3294 usage limit as FS::cust_svc objects (see L<FS::cust_svc>). If a svcpart
3295 is specified, return only the matching services.
3301 return () unless $self->num_cust_svc(@_);
3302 grep { $_->overlimit } $self->cust_svc(@_);
3305 =item h_cust_svc END_TIMESTAMP [ START_TIMESTAMP ] [ MODE ]
3307 Returns historical services for this package created before END TIMESTAMP and
3308 (optionally) not cancelled before START_TIMESTAMP, as FS::h_cust_svc objects
3309 (see L<FS::h_cust_svc>). If MODE is 'I' (for 'invoice'), services with the
3310 I<pkg_svc.hidden> flag will be omitted.
3316 warn "$me _h_cust_svc called on $self\n"
3319 my ($end, $start, $mode) = @_;
3321 local($FS::Record::qsearch_qualify_columns) = 0;
3323 my @cust_svc = $self->_sort_cust_svc(
3324 [ qsearch( 'h_cust_svc',
3325 { 'pkgnum' => $self->pkgnum, },
3326 FS::h_cust_svc->sql_h_search(@_),
3330 if ( defined($mode) && $mode eq 'I' ) {
3331 my %hidden_svcpart = map { $_->svcpart => $_->hidden } $self->part_svc;
3332 return grep { !$hidden_svcpart{$_->svcpart} } @cust_svc;
3338 sub _sort_cust_svc {
3339 my( $self, $arrayref ) = @_;
3342 sub ($$) { my ($a, $b) = @_; $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] };
3344 my %pkg_svc = map { $_->svcpart => $_ }
3345 qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
3350 my $pkg_svc = $pkg_svc{ $_->svcpart } || '';
3352 $pkg_svc ? $pkg_svc->primary_svc : '',
3353 $pkg_svc ? $pkg_svc->quantity : 0,
3360 =item num_cust_svc [ SVCPART ] (old, deprecated usage)
3362 =item num_cust_svc [ OPTION => VALUE ... ] (current usage)
3364 Returns the number of services for this package. Available options are svcpart
3365 and svcdb. If either is spcififed, returns only the matching services.
3372 return $self->{'_num_cust_svc'}
3374 && exists($self->{'_num_cust_svc'})
3375 && $self->{'_num_cust_svc'} =~ /\d/;
3377 cluck "cust_pkg->num_cust_svc called, _num_cust_svc:".$self->{'_num_cust_svc'}
3381 if ( @_ && $_[0] =~ /^\d+/ ) {
3382 $opt{svcpart} = shift;
3383 } elsif ( @_ && ref($_[0]) eq 'HASH' ) {
3389 my $select = 'SELECT COUNT(*) FROM cust_svc ';
3390 my $where = ' WHERE pkgnum = ? ';
3391 my @param = ($self->pkgnum);
3393 if ( $opt{'svcpart'} ) {
3394 $where .= ' AND svcpart = ? ';
3395 push @param, $opt{'svcpart'};
3397 if ( $opt{'svcdb'} ) {
3398 $select .= ' LEFT JOIN part_svc USING ( svcpart ) ';
3399 $where .= ' AND svcdb = ? ';
3400 push @param, $opt{'svcdb'};
3403 my $sth = dbh->prepare("$select $where") or die dbh->errstr;
3404 $sth->execute(@param) or die $sth->errstr;
3405 $sth->fetchrow_arrayref->[0];
3408 =item available_part_svc
3410 Returns a list of FS::part_svc objects representing services included in this
3411 package but not yet provisioned. Each FS::part_svc object also has an extra
3412 field, I<num_avail>, which specifies the number of available services.
3414 Accepts option I<provision_hold>; if true, only returns part_svc for which the
3415 associated pkg_svc has the provision_hold flag set.
3419 sub available_part_svc {
3423 my $pkg_quantity = $self->quantity || 1;
3425 grep { $_->num_avail > 0 }
3427 my $part_svc = $_->part_svc;
3428 $part_svc->{'Hash'}{'num_avail'} = #evil encapsulation-breaking
3429 $pkg_quantity * $_->quantity - $self->num_cust_svc($_->svcpart);
3431 # more evil encapsulation breakage
3432 if ($part_svc->{'Hash'}{'num_avail'} > 0) {
3433 my @exports = $part_svc->part_export_did;
3434 $part_svc->{'Hash'}{'can_get_dids'} = scalar(@exports);
3439 grep { $opt{'provision_hold'} ? $_->provision_hold : 1 }
3440 $self->part_pkg->pkg_svc;
3443 =item part_svc [ OPTION => VALUE ... ]
3445 Returns a list of FS::part_svc objects representing provisioned and available
3446 services included in this package. Each FS::part_svc object also has the
3447 following extra fields:
3461 (services) - array reference containing the provisioned services, as cust_svc objects
3465 Accepts two options:
3469 =item summarize_size
3471 If true, will omit the extra cust_pkg_svc option for objects where num_cust_svc
3472 is this size or greater.
3474 =item hide_discontinued
3476 If true, will omit looking for services that are no longer avaialble in the
3484 #label -> ($cust_svc->label)[1]
3490 my $pkg_quantity = $self->quantity || 1;
3492 #XXX some sort of sort order besides numeric by svcpart...
3493 my @part_svc = sort { $a->svcpart <=> $b->svcpart } map {
3495 my $part_svc = $pkg_svc->part_svc;
3496 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
3497 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #more evil
3498 $part_svc->{'Hash'}{'num_avail'} =
3499 max( 0, $pkg_quantity * $pkg_svc->quantity - $num_cust_svc );
3500 $part_svc->{'Hash'}{'cust_pkg_svc'} =
3501 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : []
3502 unless exists($opt{summarize_size}) && $opt{summarize_size} > 0
3503 && $num_cust_svc >= $opt{summarize_size};
3504 $part_svc->{'Hash'}{'hidden'} = $pkg_svc->hidden;
3506 } $self->part_pkg->pkg_svc;
3508 unless ( $opt{hide_discontinued} ) {
3510 push @part_svc, map {
3512 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
3513 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #speak no evail
3514 $part_svc->{'Hash'}{'num_avail'} = 0; #0-$num_cust_svc ?
3515 $part_svc->{'Hash'}{'cust_pkg_svc'} =
3516 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : [];
3518 } $self->extra_part_svc;
3525 =item extra_part_svc
3527 Returns a list of FS::part_svc objects corresponding to services in this
3528 package which are still provisioned but not (any longer) available in the
3533 sub extra_part_svc {
3536 my $pkgnum = $self->pkgnum;
3537 #my $pkgpart = $self->pkgpart;
3540 # 'table' => 'part_svc',
3543 # "WHERE 0 = ( SELECT COUNT(*) FROM pkg_svc
3544 # WHERE pkg_svc.svcpart = part_svc.svcpart
3545 # AND pkg_svc.pkgpart = ?
3548 # AND 0 < ( SELECT COUNT(*) FROM cust_svc
3549 # LEFT JOIN cust_pkg USING ( pkgnum )
3550 # WHERE cust_svc.svcpart = part_svc.svcpart
3553 # 'extra_param' => [ [$self->pkgpart=>'int'], [$self->pkgnum=>'int'] ],
3556 #seems to benchmark slightly faster... (or did?)
3558 my @pkgparts = map $_->pkgpart, $self->part_pkg->self_and_svc_linked;
3559 my $pkgparts = join(',', @pkgparts);
3562 #'select' => 'DISTINCT ON (svcpart) part_svc.*',
3563 #MySQL doesn't grok DISINCT ON
3564 'select' => 'DISTINCT part_svc.*',
3565 'table' => 'part_svc',
3567 "LEFT JOIN pkg_svc ON ( pkg_svc.svcpart = part_svc.svcpart
3568 AND pkg_svc.pkgpart IN ($pkgparts)
3571 LEFT JOIN cust_svc ON ( cust_svc.svcpart = part_svc.svcpart )
3572 LEFT JOIN cust_pkg USING ( pkgnum )
3575 'extra_sql' => "WHERE pkgsvcnum IS NULL AND cust_pkg.pkgnum = ? ",
3576 'extra_param' => [ [$self->pkgnum=>'int'] ],
3582 Returns a short status string for this package, currently:
3588 =item not yet billed
3590 =item one-time charge
3605 my $freq = length($self->freq) ? $self->freq : $self->part_pkg->freq;
3607 return 'cancelled' if $self->get('cancel');
3608 return 'on hold' if $self->susp && ! $self->setup;
3609 return 'suspended' if $self->susp;
3610 return 'not yet billed' unless $self->setup;
3611 return 'one-time charge' if $freq =~ /^(0|$)/;
3615 =item ucfirst_status
3617 Returns the status with the first character capitalized.
3621 sub ucfirst_status {
3622 ucfirst(shift->status);
3627 Class method that returns the list of possible status strings for packages
3628 (see L<the status method|/status>). For example:
3630 @statuses = FS::cust_pkg->statuses();
3634 tie my %statuscolor, 'Tie::IxHash',
3635 'on hold' => 'FF00F5', #brighter purple!
3636 'not yet billed' => '009999', #teal? cyan?
3637 'one-time charge' => '0000CC', #blue #'000000',
3638 'active' => '00CC00',
3639 'suspended' => 'FF9900',
3640 'cancelled' => 'FF0000',
3644 my $self = shift; #could be class...
3645 #grep { $_ !~ /^(not yet billed)$/ } #this is a dumb status anyway
3646 # # mayble split btw one-time vs. recur
3657 Returns a hex triplet color string for this package's status.
3663 $statuscolor{$self->status};
3666 =item is_status_delay_cancel
3668 Returns true if part_pkg has option delay_cancel,
3669 cust_pkg status is 'suspended' and expire is set
3670 to cancel package within the next day (or however
3671 many days are set in global config part_pkg-delay_cancel-days.
3673 Accepts option I<part_pkg-delay_cancel-days> which should be
3674 the value of the config setting, to avoid looking it up again.
3676 This is not a real status, this only meant for hacking display
3677 values, because otherwise treating the package as suspended is
3678 really the whole point of the delay_cancel option.
3682 sub is_status_delay_cancel {
3683 my ($self,%opt) = @_;
3684 if ( $self->main_pkgnum and $self->pkglinknum ) {
3685 return $self->main_pkg->is_status_delay_cancel;
3687 return 0 unless $self->part_pkg->option('delay_cancel',1);
3688 return 0 unless $self->status eq 'suspended';
3689 return 0 unless $self->expire;
3690 my $expdays = $opt{'part_pkg-delay_cancel-days'};
3692 my $conf = new FS::Conf;
3693 $expdays = $conf->config('part_pkg-delay_cancel-days') || 1;
3695 my $expsecs = 60*60*24*$expdays;
3696 return 0 unless $self->expire < time + $expsecs;
3702 Returns a label for this package. (Currently "pkgnum: pkg - comment" or
3703 "pkg - comment" depending on user preference).
3709 my $label = $self->part_pkg->pkg_comment( cust_pkg=>$self, nopkgpart=>1 );
3710 $label = $self->pkgnum. ": $label"
3711 if $FS::CurrentUser::CurrentUser->option('show_pkgnum');
3715 =item pkg_label_long
3717 Returns a long label for this package, adding the primary service's label to
3722 sub pkg_label_long {
3724 my $label = $self->pkg_label;
3725 my $cust_svc = $self->primary_cust_svc;
3726 $label .= ' ('. ($cust_svc->label)[1]. ')' if $cust_svc;
3732 Returns a customer-localized label for this package.
3738 $self->part_pkg->pkg_locale( $self->cust_main->locale );
3741 =item primary_cust_svc
3743 Returns a primary service (as FS::cust_svc object) if one can be identified.
3747 #for labeling purposes - might not 100% match up with part_pkg->svcpart's idea
3749 sub primary_cust_svc {
3752 my @cust_svc = $self->cust_svc;
3754 return '' unless @cust_svc; #no serivces - irrelevant then
3756 return $cust_svc[0] if scalar(@cust_svc) == 1; #always return a single service
3758 # primary service as specified in the package definition
3759 # or exactly one service definition with quantity one
3760 my $svcpart = $self->part_pkg->svcpart;
3761 @cust_svc = grep { $_->svcpart == $svcpart } @cust_svc;
3762 return $cust_svc[0] if scalar(@cust_svc) == 1;
3764 #couldn't identify one thing..
3770 Returns a list of lists, calling the label method for all services
3771 (see L<FS::cust_svc>) of this billing item.
3777 map { [ $_->label ] } $self->cust_svc;
3780 =item h_labels END_TIMESTAMP [ START_TIMESTAMP ] [ MODE ]
3782 Like the labels method, but returns historical information on services that
3783 were active as of END_TIMESTAMP and (optionally) not cancelled before
3784 START_TIMESTAMP. If MODE is 'I' (for 'invoice'), services with the
3785 I<pkg_svc.hidden> flag will be omitted.
3787 Returns a list of lists, calling the label method for all (historical) services
3788 (see L<FS::h_cust_svc>) of this billing item.
3794 warn "$me _h_labels called on $self\n"
3796 map { [ $_->label(@_) ] } $self->h_cust_svc(@_);
3801 Like labels, except returns a simple flat list, and shortens long
3802 (currently >5 or the cust_bill-max_same_services configuration value) lists of
3803 identical services to one line that lists the service label and the number of
3804 individual services rather than individual items.
3809 shift->_labels_short( 'labels', @_ );
3812 =item h_labels_short END_TIMESTAMP [ START_TIMESTAMP ]
3814 Like h_labels, except returns a simple flat list, and shortens long
3815 (currently >5 or the cust_bill-max_same_services configuration value) lists of
3816 identical services to one line that lists the service label and the number of
3817 individual services rather than individual items.
3821 sub h_labels_short {
3822 shift->_labels_short( 'h_labels', @_ );
3826 my( $self, $method ) = ( shift, shift );
3828 warn "$me _labels_short called on $self with $method method\n"
3831 my $conf = new FS::Conf;
3832 my $max_same_services = $conf->config('cust_bill-max_same_services') || 5;
3834 warn "$me _labels_short populating \%labels\n"
3838 #tie %labels, 'Tie::IxHash';
3839 push @{ $labels{$_->[0]} }, $_->[1]
3840 foreach $self->$method(@_);
3842 warn "$me _labels_short populating \@labels\n"
3846 foreach my $label ( keys %labels ) {
3848 my @values = grep { ! $seen{$_}++ } @{ $labels{$label} };
3849 my $num = scalar(@values);
3850 warn "$me _labels_short $num items for $label\n"
3853 if ( $num > $max_same_services ) {
3854 warn "$me _labels_short more than $max_same_services, so summarizing\n"
3856 push @labels, "$label ($num)";
3858 if ( $conf->exists('cust_bill-consolidate_services') ) {
3859 warn "$me _labels_short consolidating services\n"
3861 # push @labels, "$label: ". join(', ', @values);
3863 my $detail = "$label: ";
3864 $detail .= shift(@values). ', '
3866 && ( length($detail.$values[0]) < 78 || $detail eq "$label: " );
3868 push @labels, $detail;
3870 warn "$me _labels_short done consolidating services\n"
3873 warn "$me _labels_short adding service data\n"
3875 push @labels, map { "$label: $_" } @values;
3886 Returns the parent customer object (see L<FS::cust_main>).
3890 Returns the balance for this specific package, when using
3891 experimental package balance.
3897 $self->cust_main->balance_pkgnum( $self->pkgnum );
3900 #these subs are in location_Mixin.pm now... unfortunately the POD doesn't mixin
3904 Returns the location object, if any (see L<FS::cust_location>).
3906 =item cust_location_or_main
3908 If this package is associated with a location, returns the locaiton (see
3909 L<FS::cust_location>), otherwise returns the customer (see L<FS::cust_main>).
3911 =item location_label [ OPTION => VALUE ... ]
3913 Returns the label of the location object (see L<FS::cust_location>).
3917 #end of subs in location_Mixin.pm now... unfortunately the POD doesn't mixin
3919 =item tax_locationnum
3921 Returns the foreign key to a L<FS::cust_location> object for calculating
3922 tax on this package, as determined by the C<tax-pkg_address> and
3923 C<tax-ship_address> configuration flags.
3927 sub tax_locationnum {
3929 my $conf = FS::Conf->new;
3930 if ( $conf->exists('tax-pkg_address') ) {
3931 return $self->locationnum;
3933 elsif ( $conf->exists('tax-ship_address') ) {
3934 return $self->cust_main->ship_locationnum;
3937 return $self->cust_main->bill_locationnum;
3943 Returns the L<FS::cust_location> object for tax_locationnum.
3949 my $conf = FS::Conf->new;
3950 if ( $conf->exists('tax-pkg_address') and $self->locationnum ) {
3951 return FS::cust_location->by_key($self->locationnum);
3953 elsif ( $conf->exists('tax-ship_address') ) {
3954 return $self->cust_main->ship_location;
3957 return $self->cust_main->bill_location;
3961 =item seconds_since TIMESTAMP
3963 Returns the number of seconds all accounts (see L<FS::svc_acct>) in this
3964 package have been online since TIMESTAMP, according to the session monitor.
3966 TIMESTAMP is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
3967 L<Time::Local> and L<Date::Parse> for conversion functions.
3972 my($self, $since) = @_;
3975 foreach my $cust_svc (
3976 grep { $_->part_svc->svcdb eq 'svc_acct' } $self->cust_svc
3978 $seconds += $cust_svc->seconds_since($since);
3985 =item seconds_since_sqlradacct TIMESTAMP_START TIMESTAMP_END
3987 Returns the numbers of seconds all accounts (see L<FS::svc_acct>) in this
3988 package have been online between TIMESTAMP_START (inclusive) and TIMESTAMP_END
3991 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
3992 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
3998 sub seconds_since_sqlradacct {
3999 my($self, $start, $end) = @_;
4003 foreach my $cust_svc (
4005 my $part_svc = $_->part_svc;
4006 $part_svc->svcdb eq 'svc_acct'
4007 && scalar($part_svc->part_export_usage);
4010 $seconds += $cust_svc->seconds_since_sqlradacct($start, $end);
4017 =item attribute_since_sqlradacct TIMESTAMP_START TIMESTAMP_END ATTRIBUTE
4019 Returns the sum of the given attribute for all accounts (see L<FS::svc_acct>)
4020 in this package for sessions ending between TIMESTAMP_START (inclusive) and
4024 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
4025 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
4030 sub attribute_since_sqlradacct {
4031 my($self, $start, $end, $attrib) = @_;
4035 foreach my $cust_svc (
4037 my $part_svc = $_->part_svc;
4038 scalar($part_svc->part_export_usage);
4041 $sum += $cust_svc->attribute_since_sqlradacct($start, $end, $attrib);
4053 my( $self, $value ) = @_;
4054 if ( defined($value) ) {
4055 $self->setfield('quantity', $value);
4057 $self->getfield('quantity') || 1;
4060 =item transfer DEST_PKGNUM | DEST_CUST_PKG, [ OPTION => VALUE ... ]
4062 Transfers as many services as possible from this package to another package.
4064 The destination package can be specified by pkgnum by passing an FS::cust_pkg
4065 object. The destination package must already exist.
4067 Services are moved only if the destination allows services with the correct
4068 I<svcpart> (not svcdb), unless the B<change_svcpart> option is set true. Use
4069 this option with caution! No provision is made for export differences
4070 between the old and new service definitions. Probably only should be used
4071 when your exports for all service definitions of a given svcdb are identical.
4072 (attempt a transfer without it first, to move all possible svcpart-matching
4075 Any services that can't be moved remain in the original package.
4077 Returns an error, if there is one; otherwise, returns the number of services
4078 that couldn't be moved.
4083 my ($self, $dest_pkgnum, %opt) = @_;
4089 if (ref ($dest_pkgnum) eq 'FS::cust_pkg') {
4090 $dest = $dest_pkgnum;
4091 $dest_pkgnum = $dest->pkgnum;
4093 $dest = qsearchs('cust_pkg', { pkgnum => $dest_pkgnum });
4096 return ('Package does not exist: '.$dest_pkgnum) unless $dest;
4098 foreach my $pkg_svc ( $dest->part_pkg->pkg_svc ) {
4099 $target{$pkg_svc->svcpart} = $pkg_svc->quantity * ( $dest->quantity || 1 );
4102 foreach my $cust_svc ($dest->cust_svc) {
4103 $target{$cust_svc->svcpart}--;
4106 my %svcpart2svcparts = ();
4107 if ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
4108 warn "change_svcpart option received, creating alternates list\n" if $DEBUG;
4109 foreach my $svcpart ( map { $_->svcpart } $self->cust_svc ) {
4110 next if exists $svcpart2svcparts{$svcpart};
4111 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
4112 $svcpart2svcparts{$svcpart} = [
4114 sort { $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] }
4116 my $pkg_svc = qsearchs( 'pkg_svc', { 'pkgpart' => $dest->pkgpart,
4117 'svcpart' => $_ } );
4119 $pkg_svc ? $pkg_svc->primary_svc : '',
4120 $pkg_svc ? $pkg_svc->quantity : 0,
4124 grep { $_ != $svcpart }
4126 qsearch('part_svc', { 'svcdb' => $part_svc->svcdb } )
4128 warn "alternates for svcpart $svcpart: ".
4129 join(', ', @{$svcpart2svcparts{$svcpart}}). "\n"
4135 foreach my $cust_svc ($self->cust_svc) {
4136 my $svcnum = $cust_svc->svcnum;
4137 if($target{$cust_svc->svcpart} > 0
4138 or $FS::cust_svc::ignore_quantity) { # maybe should be a 'force' option
4139 $target{$cust_svc->svcpart}--;
4140 my $new = new FS::cust_svc { $cust_svc->hash };
4141 $new->pkgnum($dest_pkgnum);
4142 $error = $new->replace($cust_svc);
4143 } elsif ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
4145 warn "looking for alternates for svcpart ". $cust_svc->svcpart. "\n";
4146 warn "alternates to consider: ".
4147 join(', ', @{$svcpart2svcparts{$cust_svc->svcpart}}). "\n";
4149 my @alternate = grep {
4150 warn "considering alternate svcpart $_: ".
4151 "$target{$_} available in new package\n"
4154 } @{$svcpart2svcparts{$cust_svc->svcpart}};
4156 warn "alternate(s) found\n" if $DEBUG;
4157 my $change_svcpart = $alternate[0];
4158 $target{$change_svcpart}--;
4159 my $new = new FS::cust_svc { $cust_svc->hash };
4160 $new->svcpart($change_svcpart);
4161 $new->pkgnum($dest_pkgnum);
4162 $error = $new->replace($cust_svc);
4170 my @label = $cust_svc->label;
4171 return "$label[0] $label[1]: $error";
4177 =item grab_svcnums SVCNUM, SVCNUM ...
4179 Change the pkgnum for the provided services to this packages. If there is an
4180 error, returns the error, otherwise returns false.
4188 my $oldAutoCommit = $FS::UID::AutoCommit;
4189 local $FS::UID::AutoCommit = 0;
4192 foreach my $svcnum (@svcnum) {
4193 my $cust_svc = qsearchs('cust_svc', { svcnum=>$svcnum } ) or do {
4194 $dbh->rollback if $oldAutoCommit;
4195 return "unknown svcnum $svcnum";
4197 $cust_svc->pkgnum( $self->pkgnum );
4198 my $error = $cust_svc->replace;
4200 $dbh->rollback if $oldAutoCommit;
4205 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4212 This method is deprecated. See the I<depend_jobnum> option to the insert and
4213 order_pkgs methods in FS::cust_main for a better way to defer provisioning.
4217 #looks like this is still used by the order_pkg and change_pkg methods in
4218 # ClientAPI/MyAccount, need to look into those before removing
4222 my $oldAutoCommit = $FS::UID::AutoCommit;
4223 local $FS::UID::AutoCommit = 0;
4226 foreach my $cust_svc ( $self->cust_svc ) {
4227 #false laziness w/svc_Common::insert
4228 my $svc_x = $cust_svc->svc_x;
4229 foreach my $part_export ( $cust_svc->part_svc->part_export ) {
4230 my $error = $part_export->export_insert($svc_x);
4232 $dbh->rollback if $oldAutoCommit;
4238 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4243 =item export_pkg_change OLD_CUST_PKG
4245 Calls the "pkg_change" export action for all services attached to this package.
4249 sub export_pkg_change {
4250 my( $self, $old ) = ( shift, shift );
4252 my $oldAutoCommit = $FS::UID::AutoCommit;
4253 local $FS::UID::AutoCommit = 0;
4256 foreach my $svc_x ( map $_->svc_x, $self->cust_svc ) {
4257 my $error = $svc_x->export('pkg_change', $self, $old);
4259 $dbh->rollback if $oldAutoCommit;
4264 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4271 Associates this package with a (suspension or cancellation) reason (see
4272 L<FS::cust_pkg_reason>, possibly inserting a new reason on the fly (see
4275 Available options are:
4281 can be set to a cancellation reason (see L<FS:reason>), either a reasonnum of an existing reason, or passing a hashref will create a new reason. The hashref should have the following keys: typenum - Reason type (see L<FS::reason_type>, reason - Text of the new reason.
4285 the access_user (see L<FS::access_user>) providing the reason
4293 the action (cancel, susp, adjourn, expire) associated with the reason
4297 If there is an error, returns the error, otherwise returns false.
4302 my ($self, %options) = @_;
4304 my $otaker = $options{reason_otaker} ||
4305 $FS::CurrentUser::CurrentUser->username;
4308 if ( $options{'reason'} =~ /^(\d+)$/ ) {
4312 } elsif ( ref($options{'reason'}) ) {
4314 return 'Enter a new reason (or select an existing one)'
4315 unless $options{'reason'}->{'reason'} !~ /^\s*$/;
4317 my $reason = new FS::reason({
4318 'reason_type' => $options{'reason'}->{'typenum'},
4319 'reason' => $options{'reason'}->{'reason'},
4321 my $error = $reason->insert;
4322 return $error if $error;
4324 $reasonnum = $reason->reasonnum;
4327 return "Unparseable reason: ". $options{'reason'};
4330 my $cust_pkg_reason =
4331 new FS::cust_pkg_reason({ 'pkgnum' => $self->pkgnum,
4332 'reasonnum' => $reasonnum,
4333 'otaker' => $otaker,
4334 'action' => substr(uc($options{'action'}),0,1),
4335 'date' => $options{'date'}
4340 $cust_pkg_reason->insert;
4343 =item insert_discount
4345 Associates this package with a discount (see L<FS::cust_pkg_discount>, possibly
4346 inserting a new discount on the fly (see L<FS::discount>).
4348 This will look at the cust_pkg for a pseudo-field named "setup_discountnum",
4349 and if present, will create a setup discount. If the discountnum is -1,
4350 a new discount definition will be inserted using the value in
4351 "setup_discountnum_amount" or "setup_discountnum_percent". Likewise for recur.
4353 If there is an error, returns the error, otherwise returns false.
4357 sub insert_discount {
4358 #my ($self, %options) = @_;
4361 foreach my $x (qw(setup recur)) {
4362 if ( my $discountnum = $self->get("${x}_discountnum") ) {
4363 my $cust_pkg_discount = FS::cust_pkg_discount->new( {
4364 'pkgnum' => $self->pkgnum,
4365 'discountnum' => $discountnum,
4368 'end_date' => '', #XXX
4369 #for the create a new discount case
4370 'amount' => $self->get("${x}_discountnum_amount"),
4371 'percent' => $self->get("${x}_discountnum_percent"),
4372 'months' => $self->get("${x}_discountnum_months"),
4374 if ( $x eq 'setup' ) {
4375 $cust_pkg_discount->setup('Y');
4376 $cust_pkg_discount->months('');
4378 my $error = $cust_pkg_discount->insert;
4379 return $error if $error;
4386 =item set_usage USAGE_VALUE_HASHREF
4388 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
4389 to which they should be set (see L<FS::svc_acct>). Currently seconds,
4390 upbytes, downbytes, and totalbytes are appropriate keys.
4392 All svc_accts which are part of this package have their values reset.
4397 my ($self, $valueref, %opt) = @_;
4399 #only svc_acct can set_usage for now
4400 foreach my $cust_svc ( $self->cust_svc( 'svcdb'=>'svc_acct' ) ) {
4401 my $svc_x = $cust_svc->svc_x;
4402 $svc_x->set_usage($valueref, %opt)
4403 if $svc_x->can("set_usage");
4407 =item recharge USAGE_VALUE_HASHREF
4409 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
4410 to which they should be set (see L<FS::svc_acct>). Currently seconds,
4411 upbytes, downbytes, and totalbytes are appropriate keys.
4413 All svc_accts which are part of this package have their values incremented.
4418 my ($self, $valueref) = @_;
4420 #only svc_acct can set_usage for now
4421 foreach my $cust_svc ( $self->cust_svc( 'svcdb'=>'svc_acct' ) ) {
4422 my $svc_x = $cust_svc->svc_x;
4423 $svc_x->recharge($valueref)
4424 if $svc_x->can("recharge");
4428 =item apply_usageprice
4432 sub apply_usageprice {
4435 my $oldAutoCommit = $FS::UID::AutoCommit;
4436 local $FS::UID::AutoCommit = 0;
4441 foreach my $cust_pkg_usageprice ( $self->cust_pkg_usageprice ) {
4442 $error ||= $cust_pkg_usageprice->apply;
4446 $dbh->rollback if $oldAutoCommit;
4447 die "error applying part_pkg_usageprice add-ons, pkgnum ". $self->pkgnum.
4450 $dbh->commit if $oldAutoCommit;
4456 =item cust_pkg_discount
4458 =item cust_pkg_discount_active
4462 sub cust_pkg_discount_active {
4464 grep { $_->status eq 'active' } $self->cust_pkg_discount;
4467 =item cust_pkg_usage
4469 Returns a list of all voice usage counters attached to this package.
4471 =item apply_usage OPTIONS
4473 Takes the following options:
4474 - cdr: a call detail record (L<FS::cdr>)
4475 - rate_detail: the rate determined for this call (L<FS::rate_detail>)
4476 - minutes: the maximum number of minutes to be charged
4478 Finds available usage minutes for a call of this class, and subtracts
4479 up to that many minutes from the usage pool. If the usage pool is empty,
4480 and the C<cdr-minutes_priority> global config option is set, minutes may
4481 be taken from other calls as well. Either way, an allocation record will
4482 be created (L<FS::cdr_cust_pkg_usage>) and this method will return the
4483 number of minutes of usage applied to the call.
4488 my ($self, %opt) = @_;
4489 my $cdr = $opt{cdr};
4490 my $rate_detail = $opt{rate_detail};
4491 my $minutes = $opt{minutes};
4492 my $classnum = $rate_detail->classnum;
4493 my $pkgnum = $self->pkgnum;
4494 my $custnum = $self->custnum;
4496 my $oldAutoCommit = $FS::UID::AutoCommit;
4497 local $FS::UID::AutoCommit = 0;
4500 my $order = FS::Conf->new->config('cdr-minutes_priority');
4504 $is_classnum = ' part_pkg_usage_class.classnum = '.$classnum;
4506 $is_classnum = ' part_pkg_usage_class.classnum IS NULL';
4508 my @usage_recs = qsearch({
4509 'table' => 'cust_pkg_usage',
4510 'addl_from' => ' JOIN part_pkg_usage USING (pkgusagepart)'.
4511 ' JOIN cust_pkg USING (pkgnum)'.
4512 ' JOIN part_pkg_usage_class USING (pkgusagepart)',
4513 'select' => 'cust_pkg_usage.*',
4514 'extra_sql' => " WHERE ( cust_pkg.pkgnum = $pkgnum OR ".
4515 " ( cust_pkg.custnum = $custnum AND ".
4516 " part_pkg_usage.shared IS NOT NULL ) ) AND ".
4517 $is_classnum . ' AND '.
4518 " cust_pkg_usage.minutes > 0",
4519 'order_by' => " ORDER BY priority ASC",
4522 my $orig_minutes = $minutes;
4524 while (!$error and $minutes > 0 and @usage_recs) {
4525 my $cust_pkg_usage = shift @usage_recs;
4526 $cust_pkg_usage->select_for_update;
4527 my $cdr_cust_pkg_usage = FS::cdr_cust_pkg_usage->new({
4528 pkgusagenum => $cust_pkg_usage->pkgusagenum,
4529 acctid => $cdr->acctid,
4530 minutes => min($cust_pkg_usage->minutes, $minutes),
4532 $cust_pkg_usage->set('minutes',
4533 $cust_pkg_usage->minutes - $cdr_cust_pkg_usage->minutes
4535 $error = $cust_pkg_usage->replace || $cdr_cust_pkg_usage->insert;
4536 $minutes -= $cdr_cust_pkg_usage->minutes;
4538 if ( $order and $minutes > 0 and !$error ) {
4539 # then try to steal minutes from another call
4541 'table' => 'cdr_cust_pkg_usage',
4542 'addl_from' => ' JOIN cust_pkg_usage USING (pkgusagenum)'.
4543 ' JOIN part_pkg_usage USING (pkgusagepart)'.
4544 ' JOIN cust_pkg USING (pkgnum)'.
4545 ' JOIN part_pkg_usage_class USING (pkgusagepart)'.
4546 ' JOIN cdr USING (acctid)',
4547 'select' => 'cdr_cust_pkg_usage.*',
4548 'extra_sql' => " WHERE cdr.freesidestatus = 'rated' AND ".
4549 " ( cust_pkg.pkgnum = $pkgnum OR ".
4550 " ( cust_pkg.custnum = $custnum AND ".
4551 " part_pkg_usage.shared IS NOT NULL ) ) AND ".
4552 " part_pkg_usage_class.classnum = $classnum",
4553 'order_by' => ' ORDER BY part_pkg_usage.priority ASC',
4555 if ( $order eq 'time' ) {
4556 # find CDRs that are using minutes, but have a later startdate
4558 my $startdate = $cdr->startdate;
4559 if ($startdate !~ /^\d+$/) {
4560 die "bad cdr startdate '$startdate'";
4562 $search{'extra_sql'} .= " AND cdr.startdate > $startdate";
4563 # minimize needless reshuffling
4564 $search{'order_by'} .= ', cdr.startdate DESC';
4566 # XXX may not work correctly with rate_time schedules. Could
4567 # fix this by storing ratedetailnum in cdr_cust_pkg_usage, I
4569 $search{'addl_from'} .=
4570 ' JOIN rate_detail'.
4571 ' ON (cdr.rated_ratedetailnum = rate_detail.ratedetailnum)';
4572 if ( $order eq 'rate_high' ) {
4573 $search{'extra_sql'} .= ' AND rate_detail.min_charge < '.
4574 $rate_detail->min_charge;
4575 $search{'order_by'} .= ', rate_detail.min_charge ASC';
4576 } elsif ( $order eq 'rate_low' ) {
4577 $search{'extra_sql'} .= ' AND rate_detail.min_charge > '.
4578 $rate_detail->min_charge;
4579 $search{'order_by'} .= ', rate_detail.min_charge DESC';
4581 # this should really never happen
4582 die "invalid cdr-minutes_priority value '$order'\n";
4585 my @cdr_usage_recs = qsearch(\%search);
4587 while (!$error and @cdr_usage_recs and $minutes > 0) {
4588 my $cdr_cust_pkg_usage = shift @cdr_usage_recs;
4589 my $cust_pkg_usage = $cdr_cust_pkg_usage->cust_pkg_usage;
4590 my $old_cdr = $cdr_cust_pkg_usage->cdr;
4591 $reproc_cdrs{$old_cdr->acctid} = $old_cdr;
4592 $cdr_cust_pkg_usage->select_for_update;
4593 $old_cdr->select_for_update;
4594 $cust_pkg_usage->select_for_update;
4595 # in case someone else stole the usage from this CDR
4596 # while waiting for the lock...
4597 next if $old_cdr->acctid != $cdr_cust_pkg_usage->acctid;
4598 # steal the usage allocation and flag the old CDR for reprocessing
4599 $cdr_cust_pkg_usage->set('acctid', $cdr->acctid);
4600 # if the allocation is more minutes than we need, adjust it...
4601 my $delta = $cdr_cust_pkg_usage->minutes - $minutes;
4603 $cdr_cust_pkg_usage->set('minutes', $minutes);
4604 $cust_pkg_usage->set('minutes', $cust_pkg_usage->minutes + $delta);
4605 $error = $cust_pkg_usage->replace;
4607 #warn 'CDR '.$cdr->acctid . ' stealing allocation '.$cdr_cust_pkg_usage->cdrusagenum.' from CDR '.$old_cdr->acctid."\n";
4608 $error ||= $cdr_cust_pkg_usage->replace;
4609 # deduct the stolen minutes
4610 $minutes -= $cdr_cust_pkg_usage->minutes;
4612 # after all minute-stealing is done, reset the affected CDRs
4613 foreach (values %reproc_cdrs) {
4614 $error ||= $_->set_status('');
4615 # XXX or should we just call $cdr->rate right here?
4616 # it's not like we can create a loop this way, since the min_charge
4617 # or call time has to go monotonically in one direction.
4618 # we COULD get some very deep recursions going, though...
4620 } # if $order and $minutes
4623 die "error applying included minutes\npkgnum ".$self->pkgnum.", class $classnum, acctid ".$cdr->acctid."\n$error\n"
4625 $dbh->commit if $oldAutoCommit;
4626 return $orig_minutes - $minutes;
4630 =item supplemental_pkgs
4632 Returns a list of all packages supplemental to this one.
4636 sub supplemental_pkgs {
4638 qsearch('cust_pkg', { 'main_pkgnum' => $self->pkgnum });
4643 Returns the package that this one is supplemental to, if any.
4649 if ( $self->main_pkgnum ) {
4650 return FS::cust_pkg->by_key($self->main_pkgnum);
4657 =head1 CLASS METHODS
4663 Returns an SQL expression identifying recurring packages.
4667 sub recurring_sql { "
4668 '0' != ( select freq from part_pkg
4669 where cust_pkg.pkgpart = part_pkg.pkgpart )
4674 Returns an SQL expression identifying one-time packages.
4679 '0' = ( select freq from part_pkg
4680 where cust_pkg.pkgpart = part_pkg.pkgpart )
4685 Returns an SQL expression identifying ordered packages (recurring packages not
4691 $_[0]->recurring_sql. " AND ". $_[0]->not_yet_billed_sql;
4696 Returns an SQL expression identifying active packages.
4701 $_[0]->recurring_sql. "
4702 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
4703 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4704 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
4707 =item not_yet_billed_sql
4709 Returns an SQL expression identifying packages which have not yet been billed.
4713 sub not_yet_billed_sql { "
4714 ( cust_pkg.setup IS NULL OR cust_pkg.setup = 0 )
4715 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4716 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
4721 Returns an SQL expression identifying inactive packages (one-time packages
4722 that are otherwise unsuspended/uncancelled).
4726 sub inactive_sql { "
4727 ". $_[0]->onetime_sql(). "
4728 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
4729 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4730 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
4735 Returns an SQL expression identifying on-hold packages.
4740 #$_[0]->recurring_sql(). ' AND '.
4742 ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4743 AND cust_pkg.susp IS NOT NULL AND cust_pkg.susp != 0
4744 AND ( cust_pkg.setup IS NULL OR cust_pkg.setup = 0 )
4751 Returns an SQL expression identifying suspended packages.
4755 sub suspended_sql { susp_sql(@_); }
4757 #$_[0]->recurring_sql(). ' AND '.
4759 ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4760 AND cust_pkg.susp IS NOT NULL AND cust_pkg.susp != 0
4761 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
4768 Returns an SQL exprression identifying cancelled packages.
4772 sub cancelled_sql { cancel_sql(@_); }
4774 #$_[0]->recurring_sql(). ' AND '.
4775 "cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0";
4780 Returns an SQL expression to give the package status as a string.
4786 WHEN cust_pkg.cancel IS NOT NULL THEN 'cancelled'
4787 WHEN ( cust_pkg.susp IS NOT NULL AND cust_pkg.setup IS NULL ) THEN 'on hold'
4788 WHEN cust_pkg.susp IS NOT NULL THEN 'suspended'
4789 WHEN cust_pkg.setup IS NULL THEN 'not yet billed'
4790 WHEN ".onetime_sql()." THEN 'one-time charge'
4797 Returns a list of two package counts. The first is a count of packages
4798 based on the supplied criteria and the second is the count of residential
4799 packages with those same criteria. Criteria are specified as in the search
4805 my ($class, $params) = @_;
4807 my $sql_query = $class->search( $params );
4809 my $count_sql = delete($sql_query->{'count_query'});
4810 $count_sql =~ s/ FROM/,count(CASE WHEN cust_main.company IS NULL OR cust_main.company = '' THEN 1 END) FROM/
4811 or die "couldn't parse count_sql";
4813 my $count_sth = dbh->prepare($count_sql)
4814 or die "Error preparing $count_sql: ". dbh->errstr;
4816 or die "Error executing $count_sql: ". $count_sth->errstr;
4817 my $count_arrayref = $count_sth->fetchrow_arrayref;
4819 return ( @$count_arrayref );
4823 =item tax_locationnum_sql
4825 Returns an SQL expression for the tax location for a package, based
4826 on the settings of 'tax-pkg_address' and 'tax-ship_address'.
4830 sub tax_locationnum_sql {
4831 my $conf = FS::Conf->new;
4832 if ( $conf->exists('tax-pkg_address') ) {
4833 'cust_pkg.locationnum';
4835 elsif ( $conf->exists('tax-ship_address') ) {
4836 'cust_main.ship_locationnum';
4839 'cust_main.bill_locationnum';
4845 Returns a list: the first item is an SQL fragment identifying matching
4846 packages/customers via location (taking into account shipping and package
4847 address taxation, if enabled), and subsequent items are the parameters to
4848 substitute for the placeholders in that fragment.
4853 my($class, %opt) = @_;
4854 my $ornull = $opt{'ornull'};
4856 my $conf = new FS::Conf;
4858 # '?' placeholders in _location_sql_where
4859 my $x = $ornull ? 3 : 2;
4870 if ( $conf->exists('tax-ship_address') ) {
4873 ( ( ship_last IS NULL OR ship_last = '' )
4874 AND ". _location_sql_where('cust_main', '', $ornull ). "
4876 OR ( ship_last IS NOT NULL AND ship_last != ''
4877 AND ". _location_sql_where('cust_main', 'ship_', $ornull ). "
4880 # AND payby != 'COMP'
4882 @main_param = ( @bill_param, @bill_param );
4886 $main_where = _location_sql_where('cust_main'); # AND payby != 'COMP'
4887 @main_param = @bill_param;
4893 if ( $conf->exists('tax-pkg_address') ) {
4895 my $loc_where = _location_sql_where( 'cust_location', '', $ornull );
4898 ( cust_pkg.locationnum IS NULL AND $main_where )
4899 OR ( cust_pkg.locationnum IS NOT NULL AND $loc_where )
4902 @param = ( @main_param, @bill_param );
4906 $where = $main_where;
4907 @param = @main_param;
4915 #subroutine, helper for location_sql
4916 sub _location_sql_where {
4918 my $prefix = @_ ? shift : '';
4919 my $ornull = @_ ? shift : '';
4921 # $ornull = $ornull ? " OR ( ? IS NULL AND $table.${prefix}county IS NULL ) " : '';
4923 $ornull = $ornull ? ' OR ? IS NULL ' : '';
4925 my $or_empty_city = " OR ( ? = '' AND $table.${prefix}city IS NULL )";
4926 my $or_empty_county = " OR ( ? = '' AND $table.${prefix}county IS NULL )";
4927 my $or_empty_state = " OR ( ? = '' AND $table.${prefix}state IS NULL )";
4929 my $text = (driver_name =~ /^mysql/i) ? 'char' : 'text';
4931 # ( $table.${prefix}city = ? $or_empty_city $ornull )
4933 ( $table.district = ? OR ? = '' OR CAST(? AS $text) IS NULL )
4934 AND ( $table.${prefix}city = ? OR ? = '' OR CAST(? AS $text) IS NULL )
4935 AND ( $table.${prefix}county = ? $or_empty_county $ornull )
4936 AND ( $table.${prefix}state = ? $or_empty_state $ornull )
4937 AND $table.${prefix}country = ?
4942 my( $self, $what ) = @_;
4944 my $what_show_zero = $what. '_show_zero';
4945 length($self->$what_show_zero())
4946 ? ($self->$what_show_zero() eq 'Y')
4947 : $self->part_pkg->$what_show_zero();
4954 =item order CUSTNUM, PKGPARTS_ARYREF, [ REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF [ REFNUM ] ] ]
4956 Bulk cancel + order subroutine. Perhaps slightly deprecated, only used by the
4957 bulk cancel+order in the web UI and nowhere else (edit/process/cust_pkg.cgi)
4959 CUSTNUM is a customer (see L<FS::cust_main>)
4961 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
4962 L<FS::part_pkg>) to order for this customer. Duplicates are of course
4965 REMOVE_PKGNUMS is an optional list of pkgnums specifying the billing items to
4966 remove for this customer. The services (see L<FS::cust_svc>) are moved to the
4967 new billing items. An error is returned if this is not possible (see
4968 L<FS::pkg_svc>). An empty arrayref is equivalent to not specifying this
4971 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
4972 newly-created cust_pkg objects.
4974 REFNUM, if specified, will specify the FS::pkg_referral record to be created
4975 and inserted. Multiple FS::pkg_referral records can be created by
4976 setting I<refnum> to an array reference of refnums or a hash reference with
4977 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
4978 record will be created corresponding to cust_main.refnum.
4983 my ($custnum, $pkgparts, $remove_pkgnum, $return_cust_pkg, $refnum) = @_;
4985 my $conf = new FS::Conf;
4987 # Transactionize this whole mess
4988 my $oldAutoCommit = $FS::UID::AutoCommit;
4989 local $FS::UID::AutoCommit = 0;
4993 # my $cust_main = qsearchs('cust_main', { custnum => $custnum });
4994 # return "Customer not found: $custnum" unless $cust_main;
4996 warn "$me order: pkgnums to remove: ". join(',', @$remove_pkgnum). "\n"
4999 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
5002 my $change = scalar(@old_cust_pkg) != 0;
5005 if ( scalar(@old_cust_pkg) == 1 && scalar(@$pkgparts) == 1 ) {
5007 warn "$me order: changing pkgnum ". $old_cust_pkg[0]->pkgnum.
5008 " to pkgpart ". $pkgparts->[0]. "\n"
5011 my $err_or_cust_pkg =
5012 $old_cust_pkg[0]->change( 'pkgpart' => $pkgparts->[0],
5013 'refnum' => $refnum,
5016 unless (ref($err_or_cust_pkg)) {
5017 $dbh->rollback if $oldAutoCommit;
5018 return $err_or_cust_pkg;
5021 push @$return_cust_pkg, $err_or_cust_pkg;
5022 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5027 # Create the new packages.
5028 foreach my $pkgpart (@$pkgparts) {
5030 warn "$me order: inserting pkgpart $pkgpart\n" if $DEBUG;
5032 my $cust_pkg = new FS::cust_pkg { custnum => $custnum,
5033 pkgpart => $pkgpart,
5037 $error = $cust_pkg->insert( 'change' => $change );
5038 push @$return_cust_pkg, $cust_pkg;
5040 foreach my $link ($cust_pkg->part_pkg->supp_part_pkg_link) {
5041 my $supp_pkg = FS::cust_pkg->new({
5042 custnum => $custnum,
5043 pkgpart => $link->dst_pkgpart,
5045 main_pkgnum => $cust_pkg->pkgnum,
5048 $error ||= $supp_pkg->insert( 'change' => $change );
5049 push @$return_cust_pkg, $supp_pkg;
5053 $dbh->rollback if $oldAutoCommit;
5058 # $return_cust_pkg now contains refs to all of the newly
5061 # Transfer services and cancel old packages.
5062 foreach my $old_pkg (@old_cust_pkg) {
5064 warn "$me order: transferring services from pkgnum ". $old_pkg->pkgnum. "\n"
5067 foreach my $new_pkg (@$return_cust_pkg) {
5068 $error = $old_pkg->transfer($new_pkg);
5069 if ($error and $error == 0) {
5070 # $old_pkg->transfer failed.
5071 $dbh->rollback if $oldAutoCommit;
5076 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
5077 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
5078 foreach my $new_pkg (@$return_cust_pkg) {
5079 $error = $old_pkg->transfer($new_pkg, 'change_svcpart'=>1 );
5080 if ($error and $error == 0) {
5081 # $old_pkg->transfer failed.
5082 $dbh->rollback if $oldAutoCommit;
5089 # Transfers were successful, but we went through all of the
5090 # new packages and still had services left on the old package.
5091 # We can't cancel the package under the circumstances, so abort.
5092 $dbh->rollback if $oldAutoCommit;
5093 return "Unable to transfer all services from package ".$old_pkg->pkgnum;
5095 $error = $old_pkg->cancel( quiet=>1, 'no_delay_cancel'=>1 );
5101 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5105 =item bulk_change PKGPARTS_ARYREF, REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF ]
5107 A bulk change method to change packages for multiple customers.
5109 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
5110 L<FS::part_pkg>) to order for each customer. Duplicates are of course
5113 REMOVE_PKGNUMS is an list of pkgnums specifying the billing items to
5114 replace. The services (see L<FS::cust_svc>) are moved to the
5115 new billing items. An error is returned if this is not possible (see
5118 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
5119 newly-created cust_pkg objects.
5124 my ($pkgparts, $remove_pkgnum, $return_cust_pkg) = @_;
5126 # Transactionize this whole mess
5127 my $oldAutoCommit = $FS::UID::AutoCommit;
5128 local $FS::UID::AutoCommit = 0;
5132 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
5135 while(scalar(@old_cust_pkg)) {
5137 my $custnum = $old_cust_pkg[0]->custnum;
5138 my (@remove) = map { $_->pkgnum }
5139 grep { $_->custnum == $custnum } @old_cust_pkg;
5140 @old_cust_pkg = grep { $_->custnum != $custnum } @old_cust_pkg;
5142 my $error = order $custnum, $pkgparts, \@remove, \@return;
5144 push @errors, $error
5146 push @$return_cust_pkg, @return;
5149 if (scalar(@errors)) {
5150 $dbh->rollback if $oldAutoCommit;
5151 return join(' / ', @errors);
5154 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5158 =item forward_emails
5160 Returns a hash of svcnums and corresponding email addresses
5161 for svc_acct services that can be used as source or dest
5162 for svc_forward services provisioned in this package.
5164 Accepts options I<svc_forward> OR I<svcnum> for a svc_forward
5165 service; if included, will ensure the current values of the
5166 specified service are included in the list, even if for some
5167 other reason they wouldn't be. If called as a class method
5168 with a specified service, returns only these current values.
5170 Caution: does not actually check if svc_forward services are
5171 available to be provisioned on this package.
5175 sub forward_emails {
5179 #load optional service, thoroughly validated
5180 die "Use svcnum or svc_forward, not both"
5181 if $opt{'svcnum'} && $opt{'svc_forward'};
5182 my $svc_forward = $opt{'svc_forward'};
5183 $svc_forward ||= qsearchs('svc_forward',{ 'svcnum' => $opt{'svcnum'} })
5185 die "Specified service is not a forward service"
5186 if $svc_forward && (ref($svc_forward) ne 'FS::svc_forward');
5187 die "Specified service not found"
5188 if ($opt{'svcnum'} || $opt{'svc_forward'}) && !$svc_forward;
5192 ## everything below was basically copied from httemplate/edit/svc_forward.cgi
5193 ## with minimal refactoring, not sure why we can't just load all svc_accts for this custnum
5195 #add current values from specified service, if there was one
5197 foreach my $method (qw( srcsvc_acct dstsvc_acct )) {
5198 my $svc_acct = $svc_forward->$method();
5199 $email{$svc_acct->svcnum} = $svc_acct->email if $svc_acct;
5203 if (ref($self) eq 'FS::cust_pkg') {
5205 #and including the rest for this customer
5206 my($u_part_svc,@u_acct_svcparts);
5207 foreach $u_part_svc ( qsearch('part_svc',{'svcdb'=>'svc_acct'}) ) {
5208 push @u_acct_svcparts,$u_part_svc->getfield('svcpart');
5211 my $custnum = $self->getfield('custnum');
5212 foreach my $i_cust_pkg ( qsearch('cust_pkg',{'custnum'=>$custnum}) ) {
5213 my $cust_pkgnum = $i_cust_pkg->getfield('pkgnum');
5214 #now find the corresponding record(s) in cust_svc (for this pkgnum!)
5215 foreach my $acct_svcpart (@u_acct_svcparts) {
5216 foreach my $i_cust_svc (
5217 qsearch( 'cust_svc', { 'pkgnum' => $cust_pkgnum,
5218 'svcpart' => $acct_svcpart } )
5220 my $svc_acct = qsearchs( 'svc_acct', { 'svcnum' => $i_cust_svc->svcnum } );
5221 $email{$svc_acct->svcnum} = $svc_acct->email;
5230 # Used by FS::Upgrade to migrate to a new database.
5231 sub _upgrade_data { # class method
5232 my ($class, %opts) = @_;
5233 $class->_upgrade_otaker(%opts);
5235 # RT#10139, bug resulting in contract_end being set when it shouldn't
5236 'UPDATE cust_pkg SET contract_end = NULL WHERE contract_end = -1',
5237 # RT#10830, bad calculation of prorate date near end of year
5238 # the date range for bill is December 2009, and we move it forward
5239 # one year if it's before the previous bill date (which it should
5241 'UPDATE cust_pkg SET bill = bill + (365*24*60*60) WHERE bill < last_bill
5242 AND bill > 1259654400 AND bill < 1262332800 AND (SELECT plan FROM part_pkg
5243 WHERE part_pkg.pkgpart = cust_pkg.pkgpart) = \'prorate\'',
5244 # RT6628, add order_date to cust_pkg
5245 'update cust_pkg set order_date = (select history_date from h_cust_pkg
5246 where h_cust_pkg.pkgnum = cust_pkg.pkgnum and
5247 history_action = \'insert\') where order_date is null',
5249 foreach my $sql (@statements) {
5250 my $sth = dbh->prepare($sql);
5251 $sth->execute or die $sth->errstr;
5254 # RT31194: supplemental package links that are deleted don't clean up
5256 my @pkglinknums = qsearch({
5257 'select' => 'DISTINCT cust_pkg.pkglinknum',
5258 'table' => 'cust_pkg',
5259 'addl_from' => ' LEFT JOIN part_pkg_link USING (pkglinknum) ',
5260 'extra_sql' => ' WHERE cust_pkg.pkglinknum IS NOT NULL
5261 AND part_pkg_link.pkglinknum IS NULL',
5263 foreach (@pkglinknums) {
5264 my $pkglinknum = $_->pkglinknum;
5265 warn "cleaning part_pkg_link #$pkglinknum\n";
5266 my $part_pkg_link = FS::part_pkg_link->new({pkglinknum => $pkglinknum});
5267 my $error = $part_pkg_link->remove_linked;
5268 die $error if $error;
5276 sub order is not OO. Perhaps it should be moved to FS::cust_main and made so?
5278 In sub order, the @pkgparts array (passed by reference) is clobbered.
5280 Also in sub order, no money is adjusted. Once FS::part_pkg defines a standard
5281 method to pass dates to the recur_prog expression, it should do so.
5283 FS::svc_acct, FS::svc_domain, FS::svc_www, FS::svc_ip and FS::svc_forward are
5284 loaded via 'use' at compile time, rather than via 'require' in sub { setup,
5285 suspend, unsuspend, cancel } because they use %FS::UID::callback to load
5286 configuration values. Probably need a subroutine which decides what to do
5287 based on whether or not we've fetched the user yet, rather than a hash. See
5288 FS::UID and the TODO.
5290 Now that things are transactional should the check in the insert method be
5295 L<FS::Record>, L<FS::cust_main>, L<FS::part_pkg>, L<FS::cust_svc>,
5296 L<FS::pkg_svc>, schema.html from the base documentation