4 use vars qw(@ISA $disable_agentcheck $DEBUG);
6 use Scalar::Util qw( blessed );
7 use List::Util qw(max);
10 use FS::UID qw( getotaker dbh );
11 use FS::Misc qw( send_email );
12 use FS::Record qw( qsearch qsearchs );
14 use FS::cust_main_Mixin;
18 use FS::cust_location;
20 use FS::cust_bill_pkg;
21 use FS::cust_pkg_detail;
26 use FS::cust_pkg_reason;
30 # need to 'use' these instead of 'require' in sub { cancel, suspend, unsuspend,
32 # because they load configuration by setting FS::UID::callback (see TODO)
38 # for sending cancel emails in sub cancel
41 @ISA = qw( FS::m2m_Common FS::cust_main_Mixin FS::option_Common FS::Record );
45 $disable_agentcheck = 0;
49 my ( $hashref, $cache ) = @_;
50 #if ( $hashref->{'pkgpart'} ) {
51 if ( $hashref->{'pkg'} ) {
52 # #@{ $self->{'_pkgnum'} } = ();
53 # my $subcache = $cache->subcache('pkgpart', 'part_pkg');
54 # $self->{'_pkgpart'} = $subcache;
55 # #push @{ $self->{'_pkgnum'} },
56 # FS::part_pkg->new_or_cached($hashref, $subcache);
57 $self->{'_pkgpart'} = FS::part_pkg->new($hashref);
59 if ( exists $hashref->{'svcnum'} ) {
60 #@{ $self->{'_pkgnum'} } = ();
61 my $subcache = $cache->subcache('svcnum', 'cust_svc', $hashref->{pkgnum});
62 $self->{'_svcnum'} = $subcache;
63 #push @{ $self->{'_pkgnum'} },
64 FS::cust_svc->new_or_cached($hashref, $subcache) if $hashref->{svcnum};
70 FS::cust_pkg - Object methods for cust_pkg objects
76 $record = new FS::cust_pkg \%hash;
77 $record = new FS::cust_pkg { 'column' => 'value' };
79 $error = $record->insert;
81 $error = $new_record->replace($old_record);
83 $error = $record->delete;
85 $error = $record->check;
87 $error = $record->cancel;
89 $error = $record->suspend;
91 $error = $record->unsuspend;
93 $part_pkg = $record->part_pkg;
95 @labels = $record->labels;
97 $seconds = $record->seconds_since($timestamp);
99 $error = FS::cust_pkg::order( $custnum, \@pkgparts );
100 $error = FS::cust_pkg::order( $custnum, \@pkgparts, \@remove_pkgnums ] );
104 An FS::cust_pkg object represents a customer billing item. FS::cust_pkg
105 inherits from FS::Record. The following fields are currently supported:
111 Primary key (assigned automatically for new billing items)
115 Customer (see L<FS::cust_main>)
119 Billing item definition (see L<FS::part_pkg>)
123 Optional link to package location (see L<FS::location>)
135 date (next bill date)
159 order taker (assigned automatically if null, see L<FS::UID>)
163 If this field is set to 1, disables the automatic
164 unsuspension of this package when using the B<unsuspendauto> config option.
168 If not set, defaults to 1
172 Date of change from previous package
182 =item change_locationnum
188 Note: setup, last_bill, bill, adjourn, susp, expire, cancel and change_date
189 are specified as UNIX timestamps; see L<perlfunc/"time">. Also see
190 L<Time::Local> and L<Date::Parse> for conversion functions.
198 Create a new billing item. To add the item to the database, see L<"insert">.
202 sub table { 'cust_pkg'; }
203 sub cust_linked { $_[0]->cust_main_custnum; }
204 sub cust_unlinked_msg {
206 "WARNING: can't find cust_main.custnum ". $self->custnum.
207 ' (cust_pkg.pkgnum '. $self->pkgnum. ')';
210 =item insert [ OPTION => VALUE ... ]
212 Adds this billing item to the database ("Orders" the item). If there is an
213 error, returns the error, otherwise returns false.
215 If the additional field I<promo_code> is defined instead of I<pkgpart>, it
216 will be used to look up the package definition and agent restrictions will be
219 If the additional field I<refnum> is defined, an FS::pkg_referral record will
220 be created and inserted. Multiple FS::pkg_referral records can be created by
221 setting I<refnum> to an array reference of refnums or a hash reference with
222 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
223 record will be created corresponding to cust_main.refnum.
225 The following options are available:
231 If set true, supresses any referral credit to a referring customer.
235 cust_pkg_option records will be created
239 a ticket will be added to this customer with this subject
243 an optional queue name for ticket additions
250 my( $self, %options ) = @_;
252 local $SIG{HUP} = 'IGNORE';
253 local $SIG{INT} = 'IGNORE';
254 local $SIG{QUIT} = 'IGNORE';
255 local $SIG{TERM} = 'IGNORE';
256 local $SIG{TSTP} = 'IGNORE';
257 local $SIG{PIPE} = 'IGNORE';
259 my $oldAutoCommit = $FS::UID::AutoCommit;
260 local $FS::UID::AutoCommit = 0;
263 my $error = $self->SUPER::insert($options{options} ? %{$options{options}} : ());
265 $dbh->rollback if $oldAutoCommit;
269 $self->refnum($self->cust_main->refnum) unless $self->refnum;
270 $self->refnum( [ $self->refnum ] ) unless ref($self->refnum);
271 $self->process_m2m( 'link_table' => 'pkg_referral',
272 'target_table' => 'part_referral',
273 'params' => $self->refnum,
276 #if ( $self->reg_code ) {
277 # my $reg_code = qsearchs('reg_code', { 'code' => $self->reg_code } );
278 # $error = $reg_code->delete;
280 # $dbh->rollback if $oldAutoCommit;
285 my $conf = new FS::Conf;
287 if ( $conf->config('ticket_system') && $options{ticket_subject} ) {
289 use lib ( "/opt/rt3/local/lib", "/opt/rt3/lib" );
296 my $q = new RT::Queue($RT::SystemUser);
297 $q->Load($options{ticket_queue}) if $options{ticket_queue};
298 my $t = new RT::Ticket($RT::SystemUser);
299 my $mime = new MIME::Entity;
300 $mime->build( Type => 'text/plain', Data => $options{ticket_subject} );
301 $t->Create( $options{ticket_queue} ? (Queue => $q) : (),
302 Subject => $options{ticket_subject},
305 $t->AddLink( Type => 'MemberOf',
306 Target => 'freeside://freeside/cust_main/'. $self->custnum,
310 if ($conf->config('welcome_letter') && $self->cust_main->num_pkgs == 1) {
311 my $queue = new FS::queue {
312 'job' => 'FS::cust_main::queueable_print',
314 $error = $queue->insert(
315 'custnum' => $self->custnum,
316 'template' => 'welcome_letter',
320 warn "can't send welcome letter: $error";
325 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
332 This method now works but you probably shouldn't use it.
334 You don't want to delete billing items, because there would then be no record
335 the customer ever purchased the item. Instead, see the cancel method.
340 # return "Can't delete cust_pkg records!";
343 =item replace [ OLD_RECORD ] [ HASHREF | OPTION => VALUE ... ]
345 Replaces the OLD_RECORD with this one in the database. If there is an error,
346 returns the error, otherwise returns false.
348 Currently, custnum, setup, bill, adjourn, susp, expire, and cancel may be changed.
350 Changing pkgpart may have disasterous effects. See the order subroutine.
352 setup and bill are normally updated by calling the bill method of a customer
353 object (see L<FS::cust_main>).
355 suspend is normally updated by the suspend and unsuspend methods.
357 cancel is normally updated by the cancel method (and also the order subroutine
360 Available options are:
366 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.
370 the access_user (see L<FS::access_user>) providing the reason
374 hashref of keys and values - cust_pkg_option records will be created, updated or removed as appopriate
383 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
388 ( ref($_[0]) eq 'HASH' )
392 #return "Can't (yet?) change pkgpart!" if $old->pkgpart != $new->pkgpart;
393 return "Can't change otaker!" if $old->otaker ne $new->otaker;
396 #return "Can't change setup once it exists!"
397 # if $old->getfield('setup') &&
398 # $old->getfield('setup') != $new->getfield('setup');
400 #some logic for bill, susp, cancel?
402 local($disable_agentcheck) = 1 if $old->pkgpart == $new->pkgpart;
404 local $SIG{HUP} = 'IGNORE';
405 local $SIG{INT} = 'IGNORE';
406 local $SIG{QUIT} = 'IGNORE';
407 local $SIG{TERM} = 'IGNORE';
408 local $SIG{TSTP} = 'IGNORE';
409 local $SIG{PIPE} = 'IGNORE';
411 my $oldAutoCommit = $FS::UID::AutoCommit;
412 local $FS::UID::AutoCommit = 0;
415 foreach my $method ( qw(adjourn expire) ) { # How many reasons?
416 if ($options->{'reason'} && $new->$method && $old->$method ne $new->$method) {
417 my $error = $new->insert_reason(
418 'reason' => $options->{'reason'},
419 'date' => $new->$method,
421 'reason_otaker' => $options->{'reason_otaker'},
424 dbh->rollback if $oldAutoCommit;
425 return "Error inserting cust_pkg_reason: $error";
430 #save off and freeze RADIUS attributes for any associated svc_acct records
432 if ( $old->part_pkg->is_prepaid || $new->part_pkg->is_prepaid ) {
434 #also check for specific exports?
435 # to avoid spurious modify export events
436 @svc_acct = map { $_->svc_x }
437 grep { $_->part_svc->svcdb eq 'svc_acct' }
440 $_->snapshot foreach @svc_acct;
444 my $error = $new->SUPER::replace($old,
445 $options->{options} ? $options->{options} : ()
448 $dbh->rollback if $oldAutoCommit;
452 #for prepaid packages,
453 #trigger export of new RADIUS Expiration attribute when cust_pkg.bill changes
454 foreach my $old_svc_acct ( @svc_acct ) {
455 my $new_svc_acct = new FS::svc_acct { $old_svc_acct->hash };
456 my $s_error = $new_svc_acct->replace($old_svc_acct);
458 $dbh->rollback if $oldAutoCommit;
463 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
470 Checks all fields to make sure this is a valid billing item. If there is an
471 error, returns the error, otherwise returns false. Called by the insert and
479 $self->locationnum('') if !$self->locationnum || $self->locationnum == -1;
482 $self->ut_numbern('pkgnum')
483 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum')
484 || $self->ut_numbern('pkgpart')
485 || $self->ut_foreign_keyn('locationnum', 'cust_location', 'locationnum')
486 || $self->ut_numbern('start_date')
487 || $self->ut_numbern('setup')
488 || $self->ut_numbern('bill')
489 || $self->ut_numbern('susp')
490 || $self->ut_numbern('cancel')
491 || $self->ut_numbern('adjourn')
492 || $self->ut_numbern('expire')
494 return $error if $error;
496 if ( $self->reg_code ) {
498 unless ( grep { $self->pkgpart == $_->pkgpart }
499 map { $_->reg_code_pkg }
500 qsearchs( 'reg_code', { 'code' => $self->reg_code,
501 'agentnum' => $self->cust_main->agentnum })
503 return "Unknown registration code";
506 } elsif ( $self->promo_code ) {
509 qsearchs('part_pkg', {
510 'pkgpart' => $self->pkgpart,
511 'promo_code' => { op=>'ILIKE', value=>$self->promo_code },
513 return 'Unknown promotional code' unless $promo_part_pkg;
517 unless ( $disable_agentcheck ) {
519 qsearchs( 'agent', { 'agentnum' => $self->cust_main->agentnum } );
520 return "agent ". $agent->agentnum. ':'. $agent->agent.
521 " can't purchase pkgpart ". $self->pkgpart
522 unless $agent->pkgpart_hashref->{ $self->pkgpart }
523 || $agent->agentnum == $self->part_pkg->agentnum;
526 $error = $self->ut_foreign_key('pkgpart', 'part_pkg', 'pkgpart' );
527 return $error if $error;
531 $self->otaker(getotaker) unless $self->otaker;
532 $self->otaker =~ /^(\w{1,32})$/ or return "Illegal otaker";
535 if ( $self->dbdef_table->column('manual_flag') ) {
536 $self->manual_flag('') if $self->manual_flag eq ' ';
537 $self->manual_flag =~ /^([01]?)$/
538 or return "Illegal manual_flag ". $self->manual_flag;
539 $self->manual_flag($1);
545 =item cancel [ OPTION => VALUE ... ]
547 Cancels and removes all services (see L<FS::cust_svc> and L<FS::part_svc>)
548 in this package, then cancels the package itself (sets the cancel field to
551 Available options are:
555 =item quiet - can be set true to supress email cancellation notices.
557 =item time - can be set to cancel the package based on a specific future or historical date. Using time ensures that the remaining amount is calculated correctly. Note however that this is an immediate cancel and just changes the date. You are PROBABLY looking to expire the account instead of using this.
559 =item reason - 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.
561 =item date - can be set to a unix style timestamp to specify when to cancel (expire)
563 =item nobill - can be set true to skip billing if it might otherwise be done.
567 If there is an error, returns the error, otherwise returns false.
572 my( $self, %options ) = @_;
575 my $conf = new FS::Conf;
577 warn "cust_pkg::cancel called with options".
578 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
581 local $SIG{HUP} = 'IGNORE';
582 local $SIG{INT} = 'IGNORE';
583 local $SIG{QUIT} = 'IGNORE';
584 local $SIG{TERM} = 'IGNORE';
585 local $SIG{TSTP} = 'IGNORE';
586 local $SIG{PIPE} = 'IGNORE';
588 my $oldAutoCommit = $FS::UID::AutoCommit;
589 local $FS::UID::AutoCommit = 0;
592 my $old = $self->select_for_update;
594 if ( $old->get('cancel') || $self->get('cancel') ) {
595 dbh->rollback if $oldAutoCommit;
596 return ""; # no error
599 my $date = $options{date} if $options{date}; # expire/cancel later
600 $date = '' if ($date && $date <= time); # complain instead?
602 #race condition: usage could be ongoing until unprovisioned
603 #resolved by performing a change package instead (which unprovisions) and
605 if ( !$options{nobill} && !$date && $conf->exists('bill_usage_on_cancel') ) {
606 my $copy = $self->new({$self->hash});
608 $copy->cust_main->bill( pkg_list => [ $copy ], cancel => 1 );
609 warn "Error billing during cancel, custnum ".
610 #$self->cust_main->custnum. ": $error"
616 my $cancel_time = $options{'time'} || time;
618 if ( $options{'reason'} ) {
619 $error = $self->insert_reason( 'reason' => $options{'reason'},
620 'action' => $date ? 'expire' : 'cancel',
621 'date' => $date ? $date : $cancel_time,
622 'reason_otaker' => $options{'reason_otaker'},
625 dbh->rollback if $oldAutoCommit;
626 return "Error inserting cust_pkg_reason: $error";
632 foreach my $cust_svc (
635 sort { $a->[1] <=> $b->[1] }
636 map { [ $_, $_->svc_x->table_info->{'cancel_weight'} ]; }
637 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
640 my $error = $cust_svc->cancel;
643 $dbh->rollback if $oldAutoCommit;
644 return "Error cancelling cust_svc: $error";
648 # Add a credit for remaining service
649 my $remaining_value = $self->calc_remain(time=>$cancel_time);
650 if ( $remaining_value > 0 && !$options{'no_credit'} ) {
651 my $error = $self->cust_main->credit(
653 'Credit for unused time on '. $self->part_pkg->pkg,
654 'reason_type' => $conf->config('cancel_credit_type'),
657 $dbh->rollback if $oldAutoCommit;
658 return "Error crediting customer \$$remaining_value for unused time on".
659 $self->part_pkg->pkg. ": $error";
664 my %hash = $self->hash;
665 $date ? ($hash{'expire'} = $date) : ($hash{'cancel'} = $cancel_time);
666 my $new = new FS::cust_pkg ( \%hash );
667 $error = $new->replace( $self, options => { $self->options } );
669 $dbh->rollback if $oldAutoCommit;
673 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
674 return '' if $date; #no errors
676 my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ } $self->cust_main->invoicing_list;
677 if ( !$options{'quiet'} && $conf->exists('emailcancel') && @invoicing_list ) {
678 my $error = send_email(
679 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
680 'to' => \@invoicing_list,
681 'subject' => ( $conf->config('cancelsubject') || 'Cancellation Notice' ),
682 'body' => [ map "$_\n", $conf->config('cancelmessage') ],
684 #should this do something on errors?
691 =item cancel_if_expired [ NOW_TIMESTAMP ]
693 Cancels this package if its expire date has been reached.
697 sub cancel_if_expired {
699 my $time = shift || time;
700 return '' unless $self->expire && $self->expire <= $time;
701 my $error = $self->cancel;
703 return "Error cancelling expired pkg ". $self->pkgnum. " for custnum ".
704 $self->custnum. ": $error";
711 Cancels any pending expiration (sets the expire field to null).
713 If there is an error, returns the error, otherwise returns false.
718 my( $self, %options ) = @_;
721 local $SIG{HUP} = 'IGNORE';
722 local $SIG{INT} = 'IGNORE';
723 local $SIG{QUIT} = 'IGNORE';
724 local $SIG{TERM} = 'IGNORE';
725 local $SIG{TSTP} = 'IGNORE';
726 local $SIG{PIPE} = 'IGNORE';
728 my $oldAutoCommit = $FS::UID::AutoCommit;
729 local $FS::UID::AutoCommit = 0;
732 my $old = $self->select_for_update;
734 my $pkgnum = $old->pkgnum;
735 if ( $old->get('cancel') || $self->get('cancel') ) {
736 dbh->rollback if $oldAutoCommit;
737 return "Can't unexpire cancelled package $pkgnum";
738 # or at least it's pointless
741 unless ( $old->get('expire') && $self->get('expire') ) {
742 dbh->rollback if $oldAutoCommit;
743 return ""; # no error
746 my %hash = $self->hash;
747 $hash{'expire'} = '';
748 my $new = new FS::cust_pkg ( \%hash );
749 $error = $new->replace( $self, options => { $self->options } );
751 $dbh->rollback if $oldAutoCommit;
755 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
761 =item suspend [ OPTION => VALUE ... ]
763 Suspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
764 package, then suspends the package itself (sets the susp field to now).
766 Available options are:
770 =item reason - 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.
772 =item date - can be set to a unix style timestamp to specify when to suspend (adjourn)
776 If there is an error, returns the error, otherwise returns false.
781 my( $self, %options ) = @_;
784 local $SIG{HUP} = 'IGNORE';
785 local $SIG{INT} = 'IGNORE';
786 local $SIG{QUIT} = 'IGNORE';
787 local $SIG{TERM} = 'IGNORE';
788 local $SIG{TSTP} = 'IGNORE';
789 local $SIG{PIPE} = 'IGNORE';
791 my $oldAutoCommit = $FS::UID::AutoCommit;
792 local $FS::UID::AutoCommit = 0;
795 my $old = $self->select_for_update;
797 my $pkgnum = $old->pkgnum;
798 if ( $old->get('cancel') || $self->get('cancel') ) {
799 dbh->rollback if $oldAutoCommit;
800 return "Can't suspend cancelled package $pkgnum";
803 if ( $old->get('susp') || $self->get('susp') ) {
804 dbh->rollback if $oldAutoCommit;
805 return ""; # no error # complain on adjourn?
808 my $date = $options{date} if $options{date}; # adjourn/suspend later
809 $date = '' if ($date && $date <= time); # complain instead?
811 if ( $date && $old->get('expire') && $old->get('expire') < $date ) {
812 dbh->rollback if $oldAutoCommit;
813 return "Package $pkgnum expires before it would be suspended.";
816 my $suspend_time = $options{'time'} || time;
818 if ( $options{'reason'} ) {
819 $error = $self->insert_reason( 'reason' => $options{'reason'},
820 'action' => $date ? 'adjourn' : 'suspend',
821 'date' => $date ? $date : $suspend_time,
822 'reason_otaker' => $options{'reason_otaker'},
825 dbh->rollback if $oldAutoCommit;
826 return "Error inserting cust_pkg_reason: $error";
834 foreach my $cust_svc (
835 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
837 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
839 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
840 $dbh->rollback if $oldAutoCommit;
841 return "Illegal svcdb value in part_svc!";
844 require "FS/$svcdb.pm";
846 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
848 $error = $svc->suspend;
850 $dbh->rollback if $oldAutoCommit;
853 my( $label, $value ) = $cust_svc->label;
854 push @labels, "$label: $value";
858 my $conf = new FS::Conf;
859 if ( $conf->config('suspend_email_admin') ) {
861 my $error = send_email(
862 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
863 #invoice_from ??? well as good as any
864 'to' => $conf->config('suspend_email_admin'),
865 'subject' => 'FREESIDE NOTIFICATION: Customer package suspended',
867 "This is an automatic message from your Freeside installation\n",
868 "informing you that the following customer package has been suspended:\n",
870 'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
871 'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
872 ( map { "Service : $_\n" } @labels ),
877 warn "WARNING: can't send suspension admin email (suspending anyway): ".
885 my %hash = $self->hash;
887 $hash{'adjourn'} = $date;
889 $hash{'susp'} = $suspend_time;
891 my $new = new FS::cust_pkg ( \%hash );
892 $error = $new->replace( $self, options => { $self->options } );
894 $dbh->rollback if $oldAutoCommit;
898 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
903 =item unsuspend [ OPTION => VALUE ... ]
905 Unsuspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
906 package, then unsuspends the package itself (clears the susp field and the
907 adjourn field if it is in the past).
909 Available options are:
913 =item adjust_next_bill
915 Can be set true to adjust the next bill date forward by
916 the amount of time the account was inactive. This was set true by default
917 since 1.4.2 and 1.5.0pre6; however, starting with 1.7.0 this needs to be
918 explicitly requested. Price plans for which this makes sense (anniversary-date
919 based than prorate or subscription) could have an option to enable this
924 If there is an error, returns the error, otherwise returns false.
929 my( $self, %opt ) = @_;
932 local $SIG{HUP} = 'IGNORE';
933 local $SIG{INT} = 'IGNORE';
934 local $SIG{QUIT} = 'IGNORE';
935 local $SIG{TERM} = 'IGNORE';
936 local $SIG{TSTP} = 'IGNORE';
937 local $SIG{PIPE} = 'IGNORE';
939 my $oldAutoCommit = $FS::UID::AutoCommit;
940 local $FS::UID::AutoCommit = 0;
943 my $old = $self->select_for_update;
945 my $pkgnum = $old->pkgnum;
946 if ( $old->get('cancel') || $self->get('cancel') ) {
947 dbh->rollback if $oldAutoCommit;
948 return "Can't unsuspend cancelled package $pkgnum";
951 unless ( $old->get('susp') && $self->get('susp') ) {
952 dbh->rollback if $oldAutoCommit;
953 return ""; # no error # complain instead?
956 foreach my $cust_svc (
957 qsearch('cust_svc',{'pkgnum'=> $self->pkgnum } )
959 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
961 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
962 $dbh->rollback if $oldAutoCommit;
963 return "Illegal svcdb value in part_svc!";
966 require "FS/$svcdb.pm";
968 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
970 $error = $svc->unsuspend;
972 $dbh->rollback if $oldAutoCommit;
979 my %hash = $self->hash;
980 my $inactive = time - $hash{'susp'};
982 my $conf = new FS::Conf;
984 $hash{'bill'} = ( $hash{'bill'} || $hash{'setup'} ) + $inactive
985 if ( $opt{'adjust_next_bill'}
986 || $conf->exists('unsuspend-always_adjust_next_bill_date') )
987 && $inactive > 0 && ( $hash{'bill'} || $hash{'setup'} );
990 $hash{'adjourn'} = '' if $hash{'adjourn'} < time;
991 my $new = new FS::cust_pkg ( \%hash );
992 $error = $new->replace( $self, options => { $self->options } );
994 $dbh->rollback if $oldAutoCommit;
998 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1005 Cancels any pending suspension (sets the adjourn field to null).
1007 If there is an error, returns the error, otherwise returns false.
1012 my( $self, %options ) = @_;
1015 local $SIG{HUP} = 'IGNORE';
1016 local $SIG{INT} = 'IGNORE';
1017 local $SIG{QUIT} = 'IGNORE';
1018 local $SIG{TERM} = 'IGNORE';
1019 local $SIG{TSTP} = 'IGNORE';
1020 local $SIG{PIPE} = 'IGNORE';
1022 my $oldAutoCommit = $FS::UID::AutoCommit;
1023 local $FS::UID::AutoCommit = 0;
1026 my $old = $self->select_for_update;
1028 my $pkgnum = $old->pkgnum;
1029 if ( $old->get('cancel') || $self->get('cancel') ) {
1030 dbh->rollback if $oldAutoCommit;
1031 return "Can't unadjourn cancelled package $pkgnum";
1032 # or at least it's pointless
1035 if ( $old->get('susp') || $self->get('susp') ) {
1036 dbh->rollback if $oldAutoCommit;
1037 return "Can't unadjourn suspended package $pkgnum";
1038 # perhaps this is arbitrary
1041 unless ( $old->get('adjourn') && $self->get('adjourn') ) {
1042 dbh->rollback if $oldAutoCommit;
1043 return ""; # no error
1046 my %hash = $self->hash;
1047 $hash{'adjourn'} = '';
1048 my $new = new FS::cust_pkg ( \%hash );
1049 $error = $new->replace( $self, options => { $self->options } );
1051 $dbh->rollback if $oldAutoCommit;
1055 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1062 =item change HASHREF | OPTION => VALUE ...
1064 Changes this package: cancels it and creates a new one, with a different
1065 pkgpart or locationnum or both. All services are transferred to the new
1066 package (no change will be made if this is not possible).
1068 Options may be passed as a list of key/value pairs or as a hash reference.
1075 New locationnum, to change the location for this package.
1079 New FS::cust_location object, to create a new location and assign it
1084 New pkgpart (see L<FS::part_pkg>).
1088 New refnum (see L<FS::part_referral>).
1092 At least one option must be specified (otherwise, what's the point?)
1094 Returns either the new FS::cust_pkg object or a scalar error.
1098 my $err_or_new_cust_pkg = $old_cust_pkg->change
1102 #some false laziness w/order
1105 my $opt = ref($_[0]) ? shift : { @_ };
1107 # my ($custnum, $pkgparts, $remove_pkgnum, $return_cust_pkg, $refnum) = @_;
1110 my $conf = new FS::Conf;
1112 # Transactionize this whole mess
1113 local $SIG{HUP} = 'IGNORE';
1114 local $SIG{INT} = 'IGNORE';
1115 local $SIG{QUIT} = 'IGNORE';
1116 local $SIG{TERM} = 'IGNORE';
1117 local $SIG{TSTP} = 'IGNORE';
1118 local $SIG{PIPE} = 'IGNORE';
1120 my $oldAutoCommit = $FS::UID::AutoCommit;
1121 local $FS::UID::AutoCommit = 0;
1130 #$hash{$_} = $self->$_() foreach qw( last_bill bill );
1132 #$hash{$_} = $self->$_() foreach qw( setup );
1134 $hash{'setup'} = $time if $self->setup;
1136 $hash{'change_date'} = $time;
1137 $hash{"change_$_"} = $self->$_()
1138 foreach qw( pkgnum pkgpart locationnum );
1140 if ( $opt->{'cust_location'} &&
1141 ( ! $opt->{'locationnum'} || $opt->{'locationnum'} == -1 ) ) {
1142 $error = $opt->{'cust_location'}->insert;
1144 $dbh->rollback if $oldAutoCommit;
1145 return "inserting cust_location (transaction rolled back): $error";
1147 $opt->{'locationnum'} = $opt->{'cust_location'}->locationnum;
1150 # Create the new package.
1151 my $cust_pkg = new FS::cust_pkg {
1152 custnum => $self->custnum,
1153 pkgpart => ( $opt->{'pkgpart'} || $self->pkgpart ),
1154 refnum => ( $opt->{'refnum'} || $self->refnum ),
1155 locationnum => ( $opt->{'locationnum'} || $self->locationnum ),
1159 $error = $cust_pkg->insert( 'change' => 1 );
1161 $dbh->rollback if $oldAutoCommit;
1165 # Transfer services and cancel old package.
1167 $error = $self->transfer($cust_pkg);
1168 if ($error and $error == 0) {
1169 # $old_pkg->transfer failed.
1170 $dbh->rollback if $oldAutoCommit;
1174 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
1175 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
1176 $error = $self->transfer($cust_pkg, 'change_svcpart'=>1 );
1177 if ($error and $error == 0) {
1178 # $old_pkg->transfer failed.
1179 $dbh->rollback if $oldAutoCommit;
1185 # Transfers were successful, but we still had services left on the old
1186 # package. We can't change the package under this circumstances, so abort.
1187 $dbh->rollback if $oldAutoCommit;
1188 return "Unable to transfer all services from package ". $self->pkgnum;
1191 #reset usage if changing pkgpart
1192 # AND usage rollover is off (otherwise adds twice, now and at package bill)
1193 if ($self->pkgpart != $cust_pkg->pkgpart) {
1194 my $part_pkg = $cust_pkg->part_pkg;
1195 $error = $part_pkg->reset_usage($cust_pkg, $part_pkg->is_prepaid
1199 if $part_pkg->can('reset_usage') && ! $part_pkg->option('usage_rollover');
1202 $dbh->rollback if $oldAutoCommit;
1203 return "Error setting usage values: $error";
1207 #Good to go, cancel old package.
1208 $error = $self->cancel( quiet=>1 );
1210 $dbh->rollback if $oldAutoCommit;
1214 if ( $conf->exists('cust_pkg-change_pkgpart-bill_now') ) {
1216 my $error = $cust_pkg->cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1218 $dbh->rollback if $oldAutoCommit;
1223 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1231 Returns the last bill date, or if there is no last bill date, the setup date.
1232 Useful for billing metered services.
1238 return $self->setfield('last_bill', $_[0]) if @_;
1239 return $self->getfield('last_bill') if $self->getfield('last_bill');
1240 my $cust_bill_pkg = qsearchs('cust_bill_pkg', { 'pkgnum' => $self->pkgnum,
1241 'edate' => $self->bill, } );
1242 $cust_bill_pkg ? $cust_bill_pkg->sdate : $self->setup || 0;
1245 =item last_cust_pkg_reason ACTION
1247 Returns the most recent ACTION FS::cust_pkg_reason associated with the package.
1248 Returns false if there is no reason or the package is not currenly ACTION'd
1249 ACTION is one of adjourn, susp, cancel, or expire.
1253 sub last_cust_pkg_reason {
1254 my ( $self, $action ) = ( shift, shift );
1255 my $date = $self->get($action);
1257 'table' => 'cust_pkg_reason',
1258 'hashref' => { 'pkgnum' => $self->pkgnum,
1259 'action' => substr(uc($action), 0, 1),
1262 'order_by' => 'ORDER BY num DESC LIMIT 1',
1266 =item last_reason ACTION
1268 Returns the most recent ACTION FS::reason associated with the package.
1269 Returns false if there is no reason or the package is not currenly ACTION'd
1270 ACTION is one of adjourn, susp, cancel, or expire.
1275 my $cust_pkg_reason = shift->last_cust_pkg_reason(@_);
1276 $cust_pkg_reason->reason
1277 if $cust_pkg_reason;
1282 Returns the definition for this billing item, as an FS::part_pkg object (see
1289 return $self->{'_pkgpart'} if $self->{'_pkgpart'};
1290 cluck "cust_pkg->part_pkg called" if $DEBUG > 1;
1291 qsearchs( 'part_pkg', { 'pkgpart' => $self->pkgpart } );
1296 Returns the cancelled package this package was changed from, if any.
1302 return '' unless $self->change_pkgnum;
1303 qsearchs('cust_pkg', { 'pkgnum' => $self->change_pkgnum } );
1308 Calls the I<calc_setup> of the FS::part_pkg object associated with this billing
1315 $self->part_pkg->calc_setup($self, @_);
1320 Calls the I<calc_recur> of the FS::part_pkg object associated with this billing
1327 $self->part_pkg->calc_recur($self, @_);
1332 Calls the I<calc_remain> of the FS::part_pkg object associated with this
1339 $self->part_pkg->calc_remain($self, @_);
1344 Calls the I<calc_cancel> of the FS::part_pkg object associated with this
1351 $self->part_pkg->calc_cancel($self, @_);
1356 Returns any invoice line items for this package (see L<FS::cust_bill_pkg>).
1362 qsearch( 'cust_bill_pkg', { 'pkgnum' => $self->pkgnum } );
1365 =item cust_pkg_detail [ DETAILTYPE ]
1367 Returns any customer package details for this package (see
1368 L<FS::cust_pkg_detail>).
1370 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
1374 sub cust_pkg_detail {
1376 my %hash = ( 'pkgnum' => $self->pkgnum );
1377 $hash{detailtype} = shift if @_;
1379 'table' => 'cust_pkg_detail',
1380 'hashref' => \%hash,
1381 'order_by' => 'ORDER BY weight, pkgdetailnum',
1385 =item set_cust_pkg_detail DETAILTYPE [ DETAIL, DETAIL, ... ]
1387 Sets customer package details for this package (see L<FS::cust_pkg_detail>).
1389 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
1391 If there is an error, returns the error, otherwise returns false.
1395 sub set_cust_pkg_detail {
1396 my( $self, $detailtype, @details ) = @_;
1398 local $SIG{HUP} = 'IGNORE';
1399 local $SIG{INT} = 'IGNORE';
1400 local $SIG{QUIT} = 'IGNORE';
1401 local $SIG{TERM} = 'IGNORE';
1402 local $SIG{TSTP} = 'IGNORE';
1403 local $SIG{PIPE} = 'IGNORE';
1405 my $oldAutoCommit = $FS::UID::AutoCommit;
1406 local $FS::UID::AutoCommit = 0;
1409 foreach my $current ( $self->cust_pkg_detail($detailtype) ) {
1410 my $error = $current->delete;
1412 $dbh->rollback if $oldAutoCommit;
1413 return "error removing old detail: $error";
1417 foreach my $detail ( @details ) {
1418 my $cust_pkg_detail = new FS::cust_pkg_detail {
1419 'pkgnum' => $self->pkgnum,
1420 'detailtype' => $detailtype,
1421 'detail' => $detail,
1423 my $error = $cust_pkg_detail->insert;
1425 $dbh->rollback if $oldAutoCommit;
1426 return "error adding new detail: $error";
1431 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1438 Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.
1442 #false laziness w/cust_bill.pm
1446 'table' => 'cust_event',
1447 'addl_from' => 'JOIN part_event USING ( eventpart )',
1448 'hashref' => { 'tablenum' => $self->pkgnum },
1449 'extra_sql' => " AND eventtable = 'cust_pkg' ",
1453 =item num_cust_event
1455 Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.
1459 #false laziness w/cust_bill.pm
1460 sub num_cust_event {
1463 "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
1464 " WHERE tablenum = ? AND eventtable = 'cust_pkg'";
1465 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
1466 $sth->execute($self->pkgnum) or die $sth->errstr. " executing $sql";
1467 $sth->fetchrow_arrayref->[0];
1470 =item cust_svc [ SVCPART ]
1472 Returns the services for this package, as FS::cust_svc objects (see
1473 L<FS::cust_svc>). If a svcpart is specified, return only the matching
1481 return () unless $self->num_cust_svc(@_);
1484 return qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum,
1485 'svcpart' => shift, } );
1488 cluck "cust_pkg->cust_svc called" if $DEBUG > 2;
1490 #if ( $self->{'_svcnum'} ) {
1491 # values %{ $self->{'_svcnum'}->cache };
1493 $self->_sort_cust_svc(
1494 [ qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } ) ]
1500 =item overlimit [ SVCPART ]
1502 Returns the services for this package which have exceeded their
1503 usage limit as FS::cust_svc objects (see L<FS::cust_svc>). If a svcpart
1504 is specified, return only the matching services.
1510 return () unless $self->num_cust_svc(@_);
1511 grep { $_->overlimit } $self->cust_svc(@_);
1514 =item h_cust_svc END_TIMESTAMP [ START_TIMESTAMP ]
1516 Returns historical services for this package created before END TIMESTAMP and
1517 (optionally) not cancelled before START_TIMESTAMP, as FS::h_cust_svc objects
1518 (see L<FS::h_cust_svc>).
1525 $self->_sort_cust_svc(
1526 [ qsearch( 'h_cust_svc',
1527 { 'pkgnum' => $self->pkgnum, },
1528 FS::h_cust_svc->sql_h_search(@_),
1534 sub _sort_cust_svc {
1535 my( $self, $arrayref ) = @_;
1538 sort { $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] }
1540 my $pkg_svc = qsearchs( 'pkg_svc', { 'pkgpart' => $self->pkgpart,
1541 'svcpart' => $_->svcpart } );
1543 $pkg_svc ? $pkg_svc->primary_svc : '',
1544 $pkg_svc ? $pkg_svc->quantity : 0,
1551 =item num_cust_svc [ SVCPART ]
1553 Returns the number of provisioned services for this package. If a svcpart is
1554 specified, counts only the matching services.
1561 return $self->{'_num_cust_svc'}
1563 && exists($self->{'_num_cust_svc'})
1564 && $self->{'_num_cust_svc'} =~ /\d/;
1566 cluck "cust_pkg->num_cust_svc called, _num_cust_svc:".$self->{'_num_cust_svc'}
1569 my $sql = 'SELECT COUNT(*) FROM cust_svc WHERE pkgnum = ?';
1570 $sql .= ' AND svcpart = ?' if @_;
1572 my $sth = dbh->prepare($sql) or die dbh->errstr;
1573 $sth->execute($self->pkgnum, @_) or die $sth->errstr;
1574 $sth->fetchrow_arrayref->[0];
1577 =item available_part_svc
1579 Returns a list of FS::part_svc objects representing services included in this
1580 package but not yet provisioned. Each FS::part_svc object also has an extra
1581 field, I<num_avail>, which specifies the number of available services.
1585 sub available_part_svc {
1587 grep { $_->num_avail > 0 }
1589 my $part_svc = $_->part_svc;
1590 $part_svc->{'Hash'}{'num_avail'} = #evil encapsulation-breaking
1591 $_->quantity - $self->num_cust_svc($_->svcpart);
1594 $self->part_pkg->pkg_svc;
1599 Returns a list of FS::part_svc objects representing provisioned and available
1600 services included in this package. Each FS::part_svc object also has the
1601 following extra fields:
1605 =item num_cust_svc (count)
1607 =item num_avail (quantity - count)
1609 =item cust_pkg_svc (services) - array reference containing the provisioned services, as cust_svc objects
1612 label -> ($cust_svc->label)[1]
1621 #XXX some sort of sort order besides numeric by svcpart...
1622 my @part_svc = sort { $a->svcpart <=> $b->svcpart } map {
1624 my $part_svc = $pkg_svc->part_svc;
1625 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
1626 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #more evil
1627 $part_svc->{'Hash'}{'num_avail'} =
1628 max( 0, $pkg_svc->quantity - $num_cust_svc );
1629 $part_svc->{'Hash'}{'cust_pkg_svc'} =
1630 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : [];
1632 } $self->part_pkg->pkg_svc;
1635 push @part_svc, map {
1637 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
1638 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #speak no evail
1639 $part_svc->{'Hash'}{'num_avail'} = 0; #0-$num_cust_svc ?
1640 $part_svc->{'Hash'}{'cust_pkg_svc'} =
1641 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : [];
1643 } $self->extra_part_svc;
1649 =item extra_part_svc
1651 Returns a list of FS::part_svc objects corresponding to services in this
1652 package which are still provisioned but not (any longer) available in the
1657 sub extra_part_svc {
1660 my $pkgnum = $self->pkgnum;
1661 my $pkgpart = $self->pkgpart;
1664 # 'table' => 'part_svc',
1667 # "WHERE 0 = ( SELECT COUNT(*) FROM pkg_svc
1668 # WHERE pkg_svc.svcpart = part_svc.svcpart
1669 # AND pkg_svc.pkgpart = ?
1672 # AND 0 < ( SELECT COUNT(*) FROM cust_svc
1673 # LEFT JOIN cust_pkg USING ( pkgnum )
1674 # WHERE cust_svc.svcpart = part_svc.svcpart
1677 # 'extra_param' => [ [$self->pkgpart=>'int'], [$self->pkgnum=>'int'] ],
1680 #seems to benchmark slightly faster...
1682 'select' => 'DISTINCT ON (svcpart) part_svc.*',
1683 'table' => 'part_svc',
1685 'LEFT JOIN pkg_svc ON ( pkg_svc.svcpart = part_svc.svcpart
1686 AND pkg_svc.pkgpart = ?
1689 LEFT JOIN cust_svc ON ( cust_svc.svcpart = part_svc.svcpart )
1690 LEFT JOIN cust_pkg USING ( pkgnum )
1693 'extra_sql' => "WHERE pkgsvcnum IS NULL AND cust_pkg.pkgnum = ? ",
1694 'extra_param' => [ [$self->pkgpart=>'int'], [$self->pkgnum=>'int'] ],
1700 Returns a short status string for this package, currently:
1704 =item not yet billed
1706 =item one-time charge
1721 my $freq = length($self->freq) ? $self->freq : $self->part_pkg->freq;
1723 return 'cancelled' if $self->get('cancel');
1724 return 'suspended' if $self->susp;
1725 return 'not yet billed' unless $self->setup;
1726 return 'one-time charge' if $freq =~ /^(0|$)/;
1732 Class method that returns the list of possible status strings for packages
1733 (see L<the status method|/status>). For example:
1735 @statuses = FS::cust_pkg->statuses();
1739 tie my %statuscolor, 'Tie::IxHash',
1740 'not yet billed' => '000000',
1741 'one-time charge' => '000000',
1742 'active' => '00CC00',
1743 'suspended' => 'FF9900',
1744 'cancelled' => 'FF0000',
1748 my $self = shift; #could be class...
1749 #grep { $_ !~ /^(not yet billed)$/ } #this is a dumb status anyway
1750 # # mayble split btw one-time vs. recur
1756 Returns a hex triplet color string for this package's status.
1762 $statuscolor{$self->status};
1767 Returns a label for this package. (Currently "pkgnum: pkg - comment" or
1768 "pkg-comment" depending on user preference).
1774 my $label = $self->part_pkg->pkg_comment( 'nopkgpart' => 1 );
1775 $label = $self->pkgnum. ": $label"
1776 if $FS::CurrentUser::CurrentUser->option('show_pkgnum');
1780 =item pkg_label_long
1782 Returns a long label for this package, adding the primary service's label to
1787 sub pkg_label_long {
1789 my $label = $self->pkg_label;
1790 my $cust_svc = $self->primary_cust_svc;
1791 $label .= ' ('. ($cust_svc->label)[1]. ')' if $cust_svc;
1795 =item primary_cust_svc
1797 Returns a primary service (as FS::cust_svc object) if one can be identified.
1801 #for labeling purposes - might not 100% match up with part_pkg->svcpart's idea
1803 sub primary_cust_svc {
1806 my @cust_svc = $self->cust_svc;
1808 return '' unless @cust_svc; #no serivces - irrelevant then
1810 return $cust_svc[0] if scalar(@cust_svc) == 1; #always return a single service
1812 # primary service as specified in the package definition
1813 # or exactly one service definition with quantity one
1814 my $svcpart = $self->part_pkg->svcpart;
1815 @cust_svc = grep { $_->svcpart == $svcpart } @cust_svc;
1816 return $cust_svc[0] if scalar(@cust_svc) == 1;
1818 #couldn't identify one thing..
1824 Returns a list of lists, calling the label method for all services
1825 (see L<FS::cust_svc>) of this billing item.
1831 map { [ $_->label ] } $self->cust_svc;
1834 =item h_labels END_TIMESTAMP [ START_TIMESTAMP ]
1836 Like the labels method, but returns historical information on services that
1837 were active as of END_TIMESTAMP and (optionally) not cancelled before
1840 Returns a list of lists, calling the label method for all (historical) services
1841 (see L<FS::h_cust_svc>) of this billing item.
1847 map { [ $_->label(@_) ] } $self->h_cust_svc(@_);
1852 Like labels, except returns a simple flat list, and shortens long
1853 (currently >5 or the cust_bill-max_same_services configuration value) lists of
1854 identical services to one line that lists the service label and the number of
1855 individual services rather than individual items.
1860 shift->_labels_short( 'labels', @_ );
1863 =item h_labels_short END_TIMESTAMP [ START_TIMESTAMP ]
1865 Like h_labels, except returns a simple flat list, and shortens long
1866 (currently >5 or the cust_bill-max_same_services configuration value) lists of
1867 identical services to one line that lists the service label and the number of
1868 individual services rather than individual items.
1872 sub h_labels_short {
1873 shift->_labels_short( 'h_labels', @_ );
1877 my( $self, $method ) = ( shift, shift );
1879 my $conf = new FS::Conf;
1880 my $max_same_services = $conf->config('cust_bill-max_same_services') || 5;
1883 #tie %labels, 'Tie::IxHash';
1884 push @{ $labels{$_->[0]} }, $_->[1]
1885 foreach $self->h_labels(@_);
1887 foreach my $label ( keys %labels ) {
1889 my @values = grep { ! $seen{$_}++ } @{ $labels{$label} };
1890 my $num = scalar(@values);
1891 if ( $num > $max_same_services ) {
1892 push @labels, "$label ($num)";
1894 if ( $conf->exists('cust_bill-consolidate_services') ) {
1895 # push @labels, "$label: ". join(', ', @values);
1897 my $detail = "$label: ";
1898 $detail .= shift(@values). ', '
1899 while @values && length($detail.$values[0]) < 78;
1901 push @labels, $detail;
1904 push @labels, map { "$label: $_" } @values;
1915 Returns the parent customer object (see L<FS::cust_main>).
1921 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
1926 Returns the location object, if any (see L<FS::cust_location>).
1932 return '' unless $self->locationnum;
1933 qsearchs( 'cust_location', { 'locationnum' => $self->locationnum } );
1936 =item cust_location_or_main
1938 If this package is associated with a location, returns the locaiton (see
1939 L<FS::cust_location>), otherwise returns the customer (see L<FS::cust_main>).
1943 sub cust_location_or_main {
1945 $self->cust_location || $self->cust_main;
1948 =item seconds_since TIMESTAMP
1950 Returns the number of seconds all accounts (see L<FS::svc_acct>) in this
1951 package have been online since TIMESTAMP, according to the session monitor.
1953 TIMESTAMP is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
1954 L<Time::Local> and L<Date::Parse> for conversion functions.
1959 my($self, $since) = @_;
1962 foreach my $cust_svc (
1963 grep { $_->part_svc->svcdb eq 'svc_acct' } $self->cust_svc
1965 $seconds += $cust_svc->seconds_since($since);
1972 =item seconds_since_sqlradacct TIMESTAMP_START TIMESTAMP_END
1974 Returns the numbers of seconds all accounts (see L<FS::svc_acct>) in this
1975 package have been online between TIMESTAMP_START (inclusive) and TIMESTAMP_END
1978 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
1979 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
1985 sub seconds_since_sqlradacct {
1986 my($self, $start, $end) = @_;
1990 foreach my $cust_svc (
1992 my $part_svc = $_->part_svc;
1993 $part_svc->svcdb eq 'svc_acct'
1994 && scalar($part_svc->part_export('sqlradius'));
1997 $seconds += $cust_svc->seconds_since_sqlradacct($start, $end);
2004 =item attribute_since_sqlradacct TIMESTAMP_START TIMESTAMP_END ATTRIBUTE
2006 Returns the sum of the given attribute for all accounts (see L<FS::svc_acct>)
2007 in this package for sessions ending between TIMESTAMP_START (inclusive) and
2011 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
2012 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
2017 sub attribute_since_sqlradacct {
2018 my($self, $start, $end, $attrib) = @_;
2022 foreach my $cust_svc (
2024 my $part_svc = $_->part_svc;
2025 $part_svc->svcdb eq 'svc_acct'
2026 && scalar($part_svc->part_export('sqlradius'));
2029 $sum += $cust_svc->attribute_since_sqlradacct($start, $end, $attrib);
2041 my( $self, $value ) = @_;
2042 if ( defined($value) ) {
2043 $self->setfield('quantity', $value);
2045 $self->getfield('quantity') || 1;
2048 =item transfer DEST_PKGNUM | DEST_CUST_PKG, [ OPTION => VALUE ... ]
2050 Transfers as many services as possible from this package to another package.
2052 The destination package can be specified by pkgnum by passing an FS::cust_pkg
2053 object. The destination package must already exist.
2055 Services are moved only if the destination allows services with the correct
2056 I<svcpart> (not svcdb), unless the B<change_svcpart> option is set true. Use
2057 this option with caution! No provision is made for export differences
2058 between the old and new service definitions. Probably only should be used
2059 when your exports for all service definitions of a given svcdb are identical.
2060 (attempt a transfer without it first, to move all possible svcpart-matching
2063 Any services that can't be moved remain in the original package.
2065 Returns an error, if there is one; otherwise, returns the number of services
2066 that couldn't be moved.
2071 my ($self, $dest_pkgnum, %opt) = @_;
2077 if (ref ($dest_pkgnum) eq 'FS::cust_pkg') {
2078 $dest = $dest_pkgnum;
2079 $dest_pkgnum = $dest->pkgnum;
2081 $dest = qsearchs('cust_pkg', { pkgnum => $dest_pkgnum });
2084 return ('Package does not exist: '.$dest_pkgnum) unless $dest;
2086 foreach my $pkg_svc ( $dest->part_pkg->pkg_svc ) {
2087 $target{$pkg_svc->svcpart} = $pkg_svc->quantity;
2090 foreach my $cust_svc ($dest->cust_svc) {
2091 $target{$cust_svc->svcpart}--;
2094 my %svcpart2svcparts = ();
2095 if ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
2096 warn "change_svcpart option received, creating alternates list\n" if $DEBUG;
2097 foreach my $svcpart ( map { $_->svcpart } $self->cust_svc ) {
2098 next if exists $svcpart2svcparts{$svcpart};
2099 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2100 $svcpart2svcparts{$svcpart} = [
2102 sort { $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] }
2104 my $pkg_svc = qsearchs( 'pkg_svc', { 'pkgpart' => $dest->pkgpart,
2105 'svcpart' => $_ } );
2107 $pkg_svc ? $pkg_svc->primary_svc : '',
2108 $pkg_svc ? $pkg_svc->quantity : 0,
2112 grep { $_ != $svcpart }
2114 qsearch('part_svc', { 'svcdb' => $part_svc->svcdb } )
2116 warn "alternates for svcpart $svcpart: ".
2117 join(', ', @{$svcpart2svcparts{$svcpart}}). "\n"
2122 foreach my $cust_svc ($self->cust_svc) {
2123 if($target{$cust_svc->svcpart} > 0) {
2124 $target{$cust_svc->svcpart}--;
2125 my $new = new FS::cust_svc { $cust_svc->hash };
2126 $new->pkgnum($dest_pkgnum);
2127 my $error = $new->replace($cust_svc);
2128 return $error if $error;
2129 } elsif ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
2131 warn "looking for alternates for svcpart ". $cust_svc->svcpart. "\n";
2132 warn "alternates to consider: ".
2133 join(', ', @{$svcpart2svcparts{$cust_svc->svcpart}}). "\n";
2135 my @alternate = grep {
2136 warn "considering alternate svcpart $_: ".
2137 "$target{$_} available in new package\n"
2140 } @{$svcpart2svcparts{$cust_svc->svcpart}};
2142 warn "alternate(s) found\n" if $DEBUG;
2143 my $change_svcpart = $alternate[0];
2144 $target{$change_svcpart}--;
2145 my $new = new FS::cust_svc { $cust_svc->hash };
2146 $new->svcpart($change_svcpart);
2147 $new->pkgnum($dest_pkgnum);
2148 my $error = $new->replace($cust_svc);
2149 return $error if $error;
2162 This method is deprecated. See the I<depend_jobnum> option to the insert and
2163 order_pkgs methods in FS::cust_main for a better way to defer provisioning.
2170 local $SIG{HUP} = 'IGNORE';
2171 local $SIG{INT} = 'IGNORE';
2172 local $SIG{QUIT} = 'IGNORE';
2173 local $SIG{TERM} = 'IGNORE';
2174 local $SIG{TSTP} = 'IGNORE';
2175 local $SIG{PIPE} = 'IGNORE';
2177 my $oldAutoCommit = $FS::UID::AutoCommit;
2178 local $FS::UID::AutoCommit = 0;
2181 foreach my $cust_svc ( $self->cust_svc ) {
2182 #false laziness w/svc_Common::insert
2183 my $svc_x = $cust_svc->svc_x;
2184 foreach my $part_export ( $cust_svc->part_svc->part_export ) {
2185 my $error = $part_export->export_insert($svc_x);
2187 $dbh->rollback if $oldAutoCommit;
2193 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2200 =head1 CLASS METHODS
2206 Returns an SQL expression identifying recurring packages.
2210 sub recurring_sql { "
2211 '0' != ( select freq from part_pkg
2212 where cust_pkg.pkgpart = part_pkg.pkgpart )
2217 Returns an SQL expression identifying one-time packages.
2222 '0' = ( select freq from part_pkg
2223 where cust_pkg.pkgpart = part_pkg.pkgpart )
2228 Returns an SQL expression identifying active packages.
2233 ". $_[0]->recurring_sql(). "
2234 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
2235 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
2236 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
2239 =item not_yet_billed_sql
2241 Returns an SQL expression identifying packages which have not yet been billed.
2245 sub not_yet_billed_sql { "
2246 ( cust_pkg.setup IS NULL OR cust_pkg.setup = 0 )
2247 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
2248 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
2253 Returns an SQL expression identifying inactive packages (one-time packages
2254 that are otherwise unsuspended/uncancelled).
2258 sub inactive_sql { "
2259 ". $_[0]->onetime_sql(). "
2260 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
2261 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
2262 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
2268 Returns an SQL expression identifying suspended packages.
2272 sub suspended_sql { susp_sql(@_); }
2274 #$_[0]->recurring_sql(). ' AND '.
2276 ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
2277 AND cust_pkg.susp IS NOT NULL AND cust_pkg.susp != 0
2284 Returns an SQL exprression identifying cancelled packages.
2288 sub cancelled_sql { cancel_sql(@_); }
2290 #$_[0]->recurring_sql(). ' AND '.
2291 "cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0";
2294 =item search HASHREF
2298 Returns a qsearch hash expression to search for parameters specified in HASHREF.
2299 Valid parameters are
2307 active, inactive, suspended, cancel (or cancelled)
2311 active, inactive, suspended, one-time charge, inactive, cancel (or cancelled)
2315 boolean selects custom packages
2321 pkgpart or arrayref or hashref of pkgparts
2325 arrayref of beginning and ending epoch date
2329 arrayref of beginning and ending epoch date
2333 arrayref of beginning and ending epoch date
2337 arrayref of beginning and ending epoch date
2341 arrayref of beginning and ending epoch date
2345 arrayref of beginning and ending epoch date
2349 arrayref of beginning and ending epoch date
2353 pkgnum or APKG_pkgnum
2357 a value suited to passing to FS::UI::Web::cust_header
2361 specifies the user for agent virtualization
2368 my ($class, $params) = @_;
2375 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
2377 "cust_main.agentnum = $1";
2384 if ( $params->{'custnum'} =~ /^(\d+)$/ and $1 ) {
2386 "cust_pkg.custnum = $1";
2393 if ( $params->{'magic'} eq 'active'
2394 || $params->{'status'} eq 'active' ) {
2396 push @where, FS::cust_pkg->active_sql();
2398 } elsif ( $params->{'magic'} =~ /^not[ _]yet[ _]billed$/
2399 || $params->{'status'} =~ /^not[ _]yet[ _]billed$/ ) {
2401 push @where, FS::cust_pkg->not_yet_billed_sql();
2403 } elsif ( $params->{'magic'} =~ /^(one-time charge|inactive)/
2404 || $params->{'status'} =~ /^(one-time charge|inactive)/ ) {
2406 push @where, FS::cust_pkg->inactive_sql();
2408 } elsif ( $params->{'magic'} eq 'suspended'
2409 || $params->{'status'} eq 'suspended' ) {
2411 push @where, FS::cust_pkg->suspended_sql();
2413 } elsif ( $params->{'magic'} =~ /^cancell?ed$/
2414 || $params->{'status'} =~ /^cancell?ed$/ ) {
2416 push @where, FS::cust_pkg->cancelled_sql();
2421 # parse package class
2424 #false lazinessish w/graph/cust_bill_pkg.cgi
2427 if ( exists($params->{'classnum'})
2428 && $params->{'classnum'} =~ /^(\d*)$/
2432 if ( $classnum ) { #a specific class
2433 push @where, "part_pkg.classnum = $classnum";
2435 #@pkg_class = ( qsearchs('pkg_class', { 'classnum' => $classnum } ) );
2436 #die "classnum $classnum not found!" unless $pkg_class[0];
2437 #$title .= $pkg_class[0]->classname.' ';
2439 } elsif ( $classnum eq '' ) { #the empty class
2441 push @where, "part_pkg.classnum IS NULL";
2442 #$title .= 'Empty class ';
2443 #@pkg_class = ( '(empty class)' );
2444 } elsif ( $classnum eq '0' ) {
2445 #@pkg_class = qsearch('pkg_class', {} ); # { 'disabled' => '' } );
2446 #push @pkg_class, '(empty class)';
2448 die "illegal classnum";
2454 # parse package report options
2457 my @report_option = ();
2458 if ( exists($params->{'report_option'})
2459 && $params->{'report_option'} =~ /^([,\d]*)$/
2462 @report_option = split(',', $1);
2465 if (@report_option) {
2466 # this will result in the empty set for the dangling comma case as it should
2468 map{ "0 < ( SELECT count(*) FROM part_pkg_option
2469 WHERE part_pkg_option.pkgpart = part_pkg.pkgpart
2470 AND optionname = 'report_option_$_'
2471 AND optionvalue = '1' )"
2481 push @where, "part_pkg.custom = 'Y'" if $params->{custom};
2487 if ( exists($params->{'censustract'}) ) {
2488 $params->{'censustract'} =~ /^([.\d]*)$/;
2489 my $censustract = "cust_main.censustract = '$1'";
2490 $censustract .= ' OR cust_main.censustract is NULL' unless $1;
2491 push @where, "( $censustract )";
2498 if ( ref($params->{'pkgpart'}) ) {
2501 if ( ref($params->{'pkgpart'}) eq 'HASH' ) {
2502 @pkgpart = grep $params->{'pkgpart'}{$_}, keys %{ $params->{'pkgpart'} };
2503 } elsif ( ref($params->{'pkgpart'}) eq 'ARRAY' ) {
2504 @pkgpart = @{ $params->{'pkgpart'} };
2506 die 'unhandled pkgpart ref '. $params->{'pkgpart'};
2509 @pkgpart = grep /^(\d+)$/, @pkgpart;
2511 push @where, 'pkgpart IN ('. join(',', @pkgpart). ')' if scalar(@pkgpart);
2513 } elsif ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
2514 push @where, "pkgpart = $1";
2523 #false laziness w/report_cust_pkg.html
2526 'one-time charge' => { 'last_bill'=>1, 'bill'=>1, 'adjourn'=>1, 'susp'=>1, 'expire'=>1, 'cancel'=>1, },
2527 'active' => { 'susp'=>1, 'cancel'=>1 },
2528 'suspended' => { 'cancel' => 1 },
2533 foreach my $field (qw( setup last_bill bill adjourn susp expire cancel )) {
2535 next unless exists($params->{$field});
2537 my($beginning, $ending) = @{$params->{$field}};
2539 next if $beginning == 0 && $ending == 4294967295;
2542 "cust_pkg.$field IS NOT NULL",
2543 "cust_pkg.$field >= $beginning",
2544 "cust_pkg.$field <= $ending";
2546 $orderby ||= "ORDER BY cust_pkg.$field";
2550 $orderby ||= 'ORDER BY bill';
2553 # parse magic, legacy, etc.
2556 if ( $params->{'magic'} &&
2557 $params->{'magic'} =~ /^(active|inactive|suspended|cancell?ed)$/
2560 $orderby = 'ORDER BY pkgnum';
2562 if ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
2563 push @where, "pkgpart = $1";
2566 } elsif ( $params->{'query'} eq 'pkgnum' ) {
2568 $orderby = 'ORDER BY pkgnum';
2570 } elsif ( $params->{'query'} eq 'APKG_pkgnum' ) {
2572 $orderby = 'ORDER BY pkgnum';
2575 SELECT count(*) FROM pkg_svc
2576 WHERE pkg_svc.pkgpart = cust_pkg.pkgpart
2577 AND pkg_svc.quantity > ( SELECT count(*) FROM cust_svc
2578 WHERE cust_svc.pkgnum = cust_pkg.pkgnum
2579 AND cust_svc.svcpart = pkg_svc.svcpart
2586 # setup queries, links, subs, etc. for the search
2589 # here is the agent virtualization
2590 if ($params->{CurrentUser}) {
2592 qsearchs('access_user', { username => $params->{CurrentUser} });
2595 push @where, $access_user->agentnums_sql('table'=>'cust_main');
2600 push @where, $FS::CurrentUser::CurrentUser->agentnums_sql('table'=>'cust_main');
2603 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
2605 my $addl_from = 'LEFT JOIN part_pkg USING ( pkgpart ) '.
2606 'LEFT JOIN pkg_class USING ( classnum ) '.
2607 'LEFT JOIN cust_main USING ( custnum ) ';
2609 my $count_query = "SELECT COUNT(*) FROM cust_pkg $addl_from $extra_sql";
2612 'table' => 'cust_pkg',
2614 'select' => join(', ',
2616 ( map "part_pkg.$_", qw( pkg freq ) ),
2617 'pkg_class.classname',
2618 'cust_main.custnum as cust_main_custnum',
2619 FS::UI::Web::cust_sql_fields(
2620 $params->{'cust_fields'}
2623 'extra_sql' => "$extra_sql $orderby",
2624 'addl_from' => $addl_from,
2625 'count_query' => $count_query,
2632 Returns a list: the first item is an SQL fragment identifying matching
2633 packages/customers via location (taking into account shipping and package
2634 address taxation, if enabled), and subsequent items are the parameters to
2635 substitute for the placeholders in that fragment.
2640 my($class, %opt) = @_;
2641 my $ornull = $opt{'ornull'};
2643 my $conf = new FS::Conf;
2645 # '?' placeholders in _location_sql_where
2648 @bill_param = qw( county county state state state country );
2650 @bill_param = qw( county state state country );
2652 unshift @bill_param, 'county'; # unless $nec;
2656 if ( $conf->exists('tax-ship_address') ) {
2659 ( ( ship_last IS NULL OR ship_last = '' )
2660 AND ". _location_sql_where('cust_main', '', $ornull ). "
2662 OR ( ship_last IS NOT NULL AND ship_last != ''
2663 AND ". _location_sql_where('cust_main', 'ship_', $ornull ). "
2666 # AND payby != 'COMP'
2668 @main_param = ( @bill_param, @bill_param );
2672 $main_where = _location_sql_where('cust_main'); # AND payby != 'COMP'
2673 @main_param = @bill_param;
2679 if ( $conf->exists('tax-pkg_address') ) {
2681 my $loc_where = _location_sql_where( 'cust_location', '', $ornull );
2684 ( cust_pkg.locationnum IS NULL AND $main_where )
2685 OR ( cust_pkg.locationnum IS NOT NULL AND $loc_where )
2688 @param = ( @main_param, @bill_param );
2692 $where = $main_where;
2693 @param = @main_param;
2701 #subroutine, helper for location_sql
2702 sub _location_sql_where {
2704 my $prefix = @_ ? shift : '';
2705 my $ornull = @_ ? shift : '';
2707 # $ornull = $ornull ? " OR ( ? IS NULL AND $table.${prefix}county IS NULL ) " : '';
2709 $ornull = $ornull ? ' OR ? IS NULL ' : '';
2711 my $or_empty_county = " OR ( ? = '' AND $table.${prefix}county IS NULL ) ";
2712 my $or_empty_state = " OR ( ? = '' AND $table.${prefix}state IS NULL ) ";
2715 ( $table.${prefix}county = ? $or_empty_county $ornull )
2716 AND ( $table.${prefix}state = ? $or_empty_state $ornull )
2717 AND $table.${prefix}country = ?
2725 =item order CUSTNUM, PKGPARTS_ARYREF, [ REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF [ REFNUM ] ] ]
2727 CUSTNUM is a customer (see L<FS::cust_main>)
2729 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
2730 L<FS::part_pkg>) to order for this customer. Duplicates are of course
2733 REMOVE_PKGNUMS is an optional list of pkgnums specifying the billing items to
2734 remove for this customer. The services (see L<FS::cust_svc>) are moved to the
2735 new billing items. An error is returned if this is not possible (see
2736 L<FS::pkg_svc>). An empty arrayref is equivalent to not specifying this
2739 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
2740 newly-created cust_pkg objects.
2742 REFNUM, if specified, will specify the FS::pkg_referral record to be created
2743 and inserted. Multiple FS::pkg_referral records can be created by
2744 setting I<refnum> to an array reference of refnums or a hash reference with
2745 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
2746 record will be created corresponding to cust_main.refnum.
2751 my ($custnum, $pkgparts, $remove_pkgnum, $return_cust_pkg, $refnum) = @_;
2753 my $conf = new FS::Conf;
2755 # Transactionize this whole mess
2756 local $SIG{HUP} = 'IGNORE';
2757 local $SIG{INT} = 'IGNORE';
2758 local $SIG{QUIT} = 'IGNORE';
2759 local $SIG{TERM} = 'IGNORE';
2760 local $SIG{TSTP} = 'IGNORE';
2761 local $SIG{PIPE} = 'IGNORE';
2763 my $oldAutoCommit = $FS::UID::AutoCommit;
2764 local $FS::UID::AutoCommit = 0;
2768 # my $cust_main = qsearchs('cust_main', { custnum => $custnum });
2769 # return "Customer not found: $custnum" unless $cust_main;
2771 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
2774 my $change = scalar(@old_cust_pkg) != 0;
2777 if ( scalar(@old_cust_pkg) == 1 && scalar(@$pkgparts) == 1 ) {
2779 my $err_or_cust_pkg =
2780 $old_cust_pkg[0]->change( 'pkgpart' => $pkgparts->[0],
2781 'refnum' => $refnum,
2784 unless (ref($err_or_cust_pkg)) {
2785 $dbh->rollback if $oldAutoCommit;
2786 return $err_or_cust_pkg;
2789 push @$return_cust_pkg, $err_or_cust_pkg;
2794 # Create the new packages.
2795 foreach my $pkgpart (@$pkgparts) {
2796 my $cust_pkg = new FS::cust_pkg { custnum => $custnum,
2797 pkgpart => $pkgpart,
2801 $error = $cust_pkg->insert( 'change' => $change );
2803 $dbh->rollback if $oldAutoCommit;
2806 push @$return_cust_pkg, $cust_pkg;
2808 # $return_cust_pkg now contains refs to all of the newly
2811 # Transfer services and cancel old packages.
2812 foreach my $old_pkg (@old_cust_pkg) {
2814 foreach my $new_pkg (@$return_cust_pkg) {
2815 $error = $old_pkg->transfer($new_pkg);
2816 if ($error and $error == 0) {
2817 # $old_pkg->transfer failed.
2818 $dbh->rollback if $oldAutoCommit;
2823 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
2824 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
2825 foreach my $new_pkg (@$return_cust_pkg) {
2826 $error = $old_pkg->transfer($new_pkg, 'change_svcpart'=>1 );
2827 if ($error and $error == 0) {
2828 # $old_pkg->transfer failed.
2829 $dbh->rollback if $oldAutoCommit;
2836 # Transfers were successful, but we went through all of the
2837 # new packages and still had services left on the old package.
2838 # We can't cancel the package under the circumstances, so abort.
2839 $dbh->rollback if $oldAutoCommit;
2840 return "Unable to transfer all services from package ".$old_pkg->pkgnum;
2842 $error = $old_pkg->cancel( quiet=>1 );
2848 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2852 =item bulk_change PKGPARTS_ARYREF, REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF ]
2854 A bulk change method to change packages for multiple customers.
2856 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
2857 L<FS::part_pkg>) to order for each customer. Duplicates are of course
2860 REMOVE_PKGNUMS is an list of pkgnums specifying the billing items to
2861 replace. The services (see L<FS::cust_svc>) are moved to the
2862 new billing items. An error is returned if this is not possible (see
2865 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
2866 newly-created cust_pkg objects.
2871 my ($pkgparts, $remove_pkgnum, $return_cust_pkg) = @_;
2873 # Transactionize this whole mess
2874 local $SIG{HUP} = 'IGNORE';
2875 local $SIG{INT} = 'IGNORE';
2876 local $SIG{QUIT} = 'IGNORE';
2877 local $SIG{TERM} = 'IGNORE';
2878 local $SIG{TSTP} = 'IGNORE';
2879 local $SIG{PIPE} = 'IGNORE';
2881 my $oldAutoCommit = $FS::UID::AutoCommit;
2882 local $FS::UID::AutoCommit = 0;
2886 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
2889 while(scalar(@old_cust_pkg)) {
2891 my $custnum = $old_cust_pkg[0]->custnum;
2892 my (@remove) = map { $_->pkgnum }
2893 grep { $_->custnum == $custnum } @old_cust_pkg;
2894 @old_cust_pkg = grep { $_->custnum != $custnum } @old_cust_pkg;
2896 my $error = order $custnum, $pkgparts, \@remove, \@return;
2898 push @errors, $error
2900 push @$return_cust_pkg, @return;
2903 if (scalar(@errors)) {
2904 $dbh->rollback if $oldAutoCommit;
2905 return join(' / ', @errors);
2908 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2914 Associates this package with a (suspension or cancellation) reason (see
2915 L<FS::cust_pkg_reason>, possibly inserting a new reason on the fly (see
2918 Available options are:
2924 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.
2928 the access_user (see L<FS::access_user>) providing the reason
2936 the action (cancel, susp, adjourn, expire) associated with the reason
2940 If there is an error, returns the error, otherwise returns false.
2945 my ($self, %options) = @_;
2947 my $otaker = $options{reason_otaker} ||
2948 $FS::CurrentUser::CurrentUser->username;
2951 if ( $options{'reason'} =~ /^(\d+)$/ ) {
2955 } elsif ( ref($options{'reason'}) ) {
2957 return 'Enter a new reason (or select an existing one)'
2958 unless $options{'reason'}->{'reason'} !~ /^\s*$/;
2960 my $reason = new FS::reason({
2961 'reason_type' => $options{'reason'}->{'typenum'},
2962 'reason' => $options{'reason'}->{'reason'},
2964 my $error = $reason->insert;
2965 return $error if $error;
2967 $reasonnum = $reason->reasonnum;
2970 return "Unparsable reason: ". $options{'reason'};
2973 my $cust_pkg_reason =
2974 new FS::cust_pkg_reason({ 'pkgnum' => $self->pkgnum,
2975 'reasonnum' => $reasonnum,
2976 'otaker' => $otaker,
2977 'action' => substr(uc($options{'action'}),0,1),
2978 'date' => $options{'date'}
2983 $cust_pkg_reason->insert;
2986 =item set_usage USAGE_VALUE_HASHREF
2988 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
2989 to which they should be set (see L<FS::svc_acct>). Currently seconds,
2990 upbytes, downbytes, and totalbytes are appropriate keys.
2992 All svc_accts which are part of this package have their values reset.
2997 my ($self, $valueref, %opt) = @_;
2999 foreach my $cust_svc ($self->cust_svc){
3000 my $svc_x = $cust_svc->svc_x;
3001 $svc_x->set_usage($valueref, %opt)
3002 if $svc_x->can("set_usage");
3006 =item recharge USAGE_VALUE_HASHREF
3008 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
3009 to which they should be set (see L<FS::svc_acct>). Currently seconds,
3010 upbytes, downbytes, and totalbytes are appropriate keys.
3012 All svc_accts which are part of this package have their values incremented.
3017 my ($self, $valueref) = @_;
3019 foreach my $cust_svc ($self->cust_svc){
3020 my $svc_x = $cust_svc->svc_x;
3021 $svc_x->recharge($valueref)
3022 if $svc_x->can("recharge");
3030 sub order is not OO. Perhaps it should be moved to FS::cust_main and made so?
3032 In sub order, the @pkgparts array (passed by reference) is clobbered.
3034 Also in sub order, no money is adjusted. Once FS::part_pkg defines a standard
3035 method to pass dates to the recur_prog expression, it should do so.
3037 FS::svc_acct, FS::svc_domain, FS::svc_www, FS::svc_ip and FS::svc_forward are
3038 loaded via 'use' at compile time, rather than via 'require' in sub { setup,
3039 suspend, unsuspend, cancel } because they use %FS::UID::callback to load
3040 configuration values. Probably need a subroutine which decides what to do
3041 based on whether or not we've fetched the user yet, rather than a hash. See
3042 FS::UID and the TODO.
3044 Now that things are transactional should the check in the insert method be
3049 L<FS::Record>, L<FS::cust_main>, L<FS::part_pkg>, L<FS::cust_svc>,
3050 L<FS::pkg_svc>, schema.html from the base documentation