4 use vars qw(@ISA $disable_agentcheck $DEBUG);
5 use Scalar::Util qw( blessed );
6 use List::Util qw(max);
8 use FS::UID qw( getotaker dbh );
9 use FS::Misc qw( send_email );
10 use FS::Record qw( qsearch qsearchs );
12 use FS::cust_main_Mixin;
18 use FS::cust_bill_pkg;
19 use FS::cust_pkg_detail;
24 use FS::cust_pkg_reason;
28 # need to 'use' these instead of 'require' in sub { cancel, suspend, unsuspend,
30 # because they load configuration by setting FS::UID::callback (see TODO)
36 # for sending cancel emails in sub cancel
39 @ISA = qw( FS::m2m_Common FS::cust_main_Mixin FS::option_Common FS::Record );
43 $disable_agentcheck = 0;
47 my ( $hashref, $cache ) = @_;
48 #if ( $hashref->{'pkgpart'} ) {
49 if ( $hashref->{'pkg'} ) {
50 # #@{ $self->{'_pkgnum'} } = ();
51 # my $subcache = $cache->subcache('pkgpart', 'part_pkg');
52 # $self->{'_pkgpart'} = $subcache;
53 # #push @{ $self->{'_pkgnum'} },
54 # FS::part_pkg->new_or_cached($hashref, $subcache);
55 $self->{'_pkgpart'} = FS::part_pkg->new($hashref);
57 if ( exists $hashref->{'svcnum'} ) {
58 #@{ $self->{'_pkgnum'} } = ();
59 my $subcache = $cache->subcache('svcnum', 'cust_svc', $hashref->{pkgnum});
60 $self->{'_svcnum'} = $subcache;
61 #push @{ $self->{'_pkgnum'} },
62 FS::cust_svc->new_or_cached($hashref, $subcache) if $hashref->{svcnum};
68 FS::cust_pkg - Object methods for cust_pkg objects
74 $record = new FS::cust_pkg \%hash;
75 $record = new FS::cust_pkg { 'column' => 'value' };
77 $error = $record->insert;
79 $error = $new_record->replace($old_record);
81 $error = $record->delete;
83 $error = $record->check;
85 $error = $record->cancel;
87 $error = $record->suspend;
89 $error = $record->unsuspend;
91 $part_pkg = $record->part_pkg;
93 @labels = $record->labels;
95 $seconds = $record->seconds_since($timestamp);
97 $error = FS::cust_pkg::order( $custnum, \@pkgparts );
98 $error = FS::cust_pkg::order( $custnum, \@pkgparts, \@remove_pkgnums ] );
102 An FS::cust_pkg object represents a customer billing item. FS::cust_pkg
103 inherits from FS::Record. The following fields are currently supported:
107 =item pkgnum - primary key (assigned automatically for new billing items)
109 =item custnum - Customer (see L<FS::cust_main>)
111 =item pkgpart - Billing item definition (see L<FS::part_pkg>)
115 =item bill - date (next bill date)
117 =item last_bill - last bill date
127 =item otaker - order taker (assigned automatically if null, see L<FS::UID>)
129 =item manual_flag - If this field is set to 1, disables the automatic
130 unsuspension of this package when using the B<unsuspendauto> config file.
132 =item quantity - If not set, defaults to 1
136 Note: setup, bill, adjourn, susp, expire and cancel are specified as UNIX timestamps;
137 see L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for
138 conversion functions.
146 Create a new billing item. To add the item to the database, see L<"insert">.
150 sub table { 'cust_pkg'; }
151 sub cust_linked { $_[0]->cust_main_custnum; }
152 sub cust_unlinked_msg {
154 "WARNING: can't find cust_main.custnum ". $self->custnum.
155 ' (cust_pkg.pkgnum '. $self->pkgnum. ')';
158 =item insert [ OPTION => VALUE ... ]
160 Adds this billing item to the database ("Orders" the item). If there is an
161 error, returns the error, otherwise returns false.
163 If the additional field I<promo_code> is defined instead of I<pkgpart>, it
164 will be used to look up the package definition and agent restrictions will be
167 If the additional field I<refnum> is defined, an FS::pkg_referral record will
168 be created and inserted. Multiple FS::pkg_referral records can be created by
169 setting I<refnum> to an array reference of refnums or a hash reference with
170 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
171 record will be created corresponding to cust_main.refnum.
173 The following options are available:
179 If set true, supresses any referral credit to a referring customer.
183 cust_pkg_option records will be created
190 my( $self, %options ) = @_;
192 local $SIG{HUP} = 'IGNORE';
193 local $SIG{INT} = 'IGNORE';
194 local $SIG{QUIT} = 'IGNORE';
195 local $SIG{TERM} = 'IGNORE';
196 local $SIG{TSTP} = 'IGNORE';
197 local $SIG{PIPE} = 'IGNORE';
199 my $oldAutoCommit = $FS::UID::AutoCommit;
200 local $FS::UID::AutoCommit = 0;
203 my $error = $self->SUPER::insert($options{options} ? %{$options{options}} : ());
205 $dbh->rollback if $oldAutoCommit;
209 $self->refnum($self->cust_main->refnum) unless $self->refnum;
210 $self->refnum( [ $self->refnum ] ) unless ref($self->refnum);
211 $self->process_m2m( 'link_table' => 'pkg_referral',
212 'target_table' => 'part_referral',
213 'params' => $self->refnum,
216 #if ( $self->reg_code ) {
217 # my $reg_code = qsearchs('reg_code', { 'code' => $self->reg_code } );
218 # $error = $reg_code->delete;
220 # $dbh->rollback if $oldAutoCommit;
225 my $conf = new FS::Conf;
226 my $cust_main = $self->cust_main;
227 my $part_pkg = $self->part_pkg;
228 if ( $conf->exists('referral_credit')
229 && $cust_main->referral_custnum
230 && ! $options{'change'}
231 && $part_pkg->freq !~ /^0\D?$/
234 my $referring_cust_main = $cust_main->referring_cust_main;
235 if ( $referring_cust_main->status ne 'cancelled' ) {
237 if ( $part_pkg->freq !~ /^\d+$/ ) {
238 warn 'WARNING: Not crediting customer '. $cust_main->referral_custnum.
239 ' for package '. $self->pkgnum.
240 ' ( customer '. $self->custnum. ')'.
241 ' - One-time referral credits not (yet) available for '.
242 ' packages with '. $part_pkg->freq_pretty. ' frequency';
245 my $amount = sprintf( "%.2f", $part_pkg->base_recur / $part_pkg->freq );
247 $referring_cust_main->
249 'Referral credit for '.$cust_main->name,
250 'reason_type' => $conf->config('referral_credit_type')
253 $dbh->rollback if $oldAutoCommit;
254 return "Error crediting customer ". $cust_main->referral_custnum.
255 " for referral: $error";
263 if ($conf->config('welcome_letter') && $self->cust_main->num_pkgs == 1) {
264 my $queue = new FS::queue {
265 'job' => 'FS::cust_main::queueable_print',
267 $error = $queue->insert(
268 'custnum' => $self->custnum,
269 'template' => 'welcome_letter',
273 warn "can't send welcome letter: $error";
278 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
285 This method now works but you probably shouldn't use it.
287 You don't want to delete billing items, because there would then be no record
288 the customer ever purchased the item. Instead, see the cancel method.
293 # return "Can't delete cust_pkg records!";
296 =item replace [ OLD_RECORD ] [ HASHREF | OPTION => VALUE ... ]
298 Replaces the OLD_RECORD with this one in the database. If there is an error,
299 returns the error, otherwise returns false.
301 Currently, custnum, setup, bill, adjourn, susp, expire, and cancel may be changed.
303 Changing pkgpart may have disasterous effects. See the order subroutine.
305 setup and bill are normally updated by calling the bill method of a customer
306 object (see L<FS::cust_main>).
308 suspend is normally updated by the suspend and unsuspend methods.
310 cancel is normally updated by the cancel method (and also the order subroutine
313 Available options are:
319 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.
323 the access_user (see L<FS::access_user>) providing the reason
327 hashref of keys and values - cust_pkg_option records will be created, updated or removed as appopriate
336 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
341 ( ref($_[0]) eq 'HASH' )
345 #return "Can't (yet?) change pkgpart!" if $old->pkgpart != $new->pkgpart;
346 return "Can't change otaker!" if $old->otaker ne $new->otaker;
349 #return "Can't change setup once it exists!"
350 # if $old->getfield('setup') &&
351 # $old->getfield('setup') != $new->getfield('setup');
353 #some logic for bill, susp, cancel?
355 local($disable_agentcheck) = 1 if $old->pkgpart == $new->pkgpart;
357 local $SIG{HUP} = 'IGNORE';
358 local $SIG{INT} = 'IGNORE';
359 local $SIG{QUIT} = 'IGNORE';
360 local $SIG{TERM} = 'IGNORE';
361 local $SIG{TSTP} = 'IGNORE';
362 local $SIG{PIPE} = 'IGNORE';
364 my $oldAutoCommit = $FS::UID::AutoCommit;
365 local $FS::UID::AutoCommit = 0;
368 foreach my $method ( qw(adjourn expire) ) { # How many reasons?
369 if ($options->{'reason'} && $new->$method && $old->$method ne $new->$method) {
370 my $error = $new->insert_reason(
371 'reason' => $options->{'reason'},
372 'date' => $new->$method,
374 'reason_otaker' => $options->{'reason_otaker'},
377 dbh->rollback if $oldAutoCommit;
378 return "Error inserting cust_pkg_reason: $error";
383 #save off and freeze RADIUS attributes for any associated svc_acct records
385 if ( $old->part_pkg->is_prepaid || $new->part_pkg->is_prepaid ) {
387 #also check for specific exports?
388 # to avoid spurious modify export events
389 @svc_acct = map { $_->svc_x }
390 grep { $_->part_svc->svcdb eq 'svc_acct' }
393 $_->snapshot foreach @svc_acct;
397 my $error = $new->SUPER::replace($old,
398 $options->{options} ? $options->{options} : ()
401 $dbh->rollback if $oldAutoCommit;
405 #for prepaid packages,
406 #trigger export of new RADIUS Expiration attribute when cust_pkg.bill changes
407 foreach my $old_svc_acct ( @svc_acct ) {
408 my $new_svc_acct = new FS::svc_acct { $old_svc_acct->hash };
409 my $s_error = $new_svc_acct->replace($old_svc_acct);
411 $dbh->rollback if $oldAutoCommit;
416 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
423 Checks all fields to make sure this is a valid billing item. If there is an
424 error, returns the error, otherwise returns false. Called by the insert and
433 $self->ut_numbern('pkgnum')
434 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum')
435 || $self->ut_numbern('pkgpart')
436 || $self->ut_numbern('setup')
437 || $self->ut_numbern('bill')
438 || $self->ut_numbern('susp')
439 || $self->ut_numbern('cancel')
440 || $self->ut_numbern('adjourn')
441 || $self->ut_numbern('expire')
443 return $error if $error;
445 if ( $self->reg_code ) {
447 unless ( grep { $self->pkgpart == $_->pkgpart }
448 map { $_->reg_code_pkg }
449 qsearchs( 'reg_code', { 'code' => $self->reg_code,
450 'agentnum' => $self->cust_main->agentnum })
452 return "Unknown registration code";
455 } elsif ( $self->promo_code ) {
458 qsearchs('part_pkg', {
459 'pkgpart' => $self->pkgpart,
460 'promo_code' => { op=>'ILIKE', value=>$self->promo_code },
462 return 'Unknown promotional code' unless $promo_part_pkg;
466 unless ( $disable_agentcheck ) {
468 qsearchs( 'agent', { 'agentnum' => $self->cust_main->agentnum } );
469 my $pkgpart_href = $agent->pkgpart_hashref;
470 return "agent ". $agent->agentnum.
471 " can't purchase pkgpart ". $self->pkgpart
472 unless $pkgpart_href->{ $self->pkgpart };
475 $error = $self->ut_foreign_key('pkgpart', 'part_pkg', 'pkgpart' );
476 return $error if $error;
480 $self->otaker(getotaker) unless $self->otaker;
481 $self->otaker =~ /^(\w{1,32})$/ or return "Illegal otaker";
484 if ( $self->dbdef_table->column('manual_flag') ) {
485 $self->manual_flag('') if $self->manual_flag eq ' ';
486 $self->manual_flag =~ /^([01]?)$/
487 or return "Illegal manual_flag ". $self->manual_flag;
488 $self->manual_flag($1);
494 =item cancel [ OPTION => VALUE ... ]
496 Cancels and removes all services (see L<FS::cust_svc> and L<FS::part_svc>)
497 in this package, then cancels the package itself (sets the cancel field to
500 Available options are:
504 =item quiet - can be set true to supress email cancellation notices.
506 =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.
508 =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.
510 =item date - can be set to a unix style timestamp to specify when to cancel (expire)
514 If there is an error, returns the error, otherwise returns false.
519 my( $self, %options ) = @_;
522 warn "cust_pkg::cancel called with options".
523 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
526 local $SIG{HUP} = 'IGNORE';
527 local $SIG{INT} = 'IGNORE';
528 local $SIG{QUIT} = 'IGNORE';
529 local $SIG{TERM} = 'IGNORE';
530 local $SIG{TSTP} = 'IGNORE';
531 local $SIG{PIPE} = 'IGNORE';
533 my $oldAutoCommit = $FS::UID::AutoCommit;
534 local $FS::UID::AutoCommit = 0;
537 my $old = $self->select_for_update;
539 if ( $old->get('cancel') || $self->get('cancel') ) {
540 dbh->rollback if $oldAutoCommit;
541 return ""; # no error
544 my $date = $options{date} if $options{date}; # expire/cancel later
545 $date = '' if ($date && $date <= time); # complain instead?
547 my $cancel_time = $options{'time'} || time;
549 if ( $options{'reason'} ) {
550 $error = $self->insert_reason( 'reason' => $options{'reason'},
551 'action' => $date ? 'expire' : 'cancel',
552 'reason_otaker' => $options{'reason_otaker'},
555 dbh->rollback if $oldAutoCommit;
556 return "Error inserting cust_pkg_reason: $error";
562 foreach my $cust_svc (
565 sort { $a->[1] <=> $b->[1] }
566 map { [ $_, $_->svc_x->table_info->{'cancel_weight'} ]; }
567 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
570 my $error = $cust_svc->cancel;
573 $dbh->rollback if $oldAutoCommit;
574 return "Error cancelling cust_svc: $error";
578 # Add a credit for remaining service
579 my $remaining_value = $self->calc_remain(time=>$cancel_time);
580 if ( $remaining_value > 0 && !$options{'no_credit'} ) {
581 my $conf = new FS::Conf;
582 my $error = $self->cust_main->credit(
584 'Credit for unused time on '. $self->part_pkg->pkg,
585 'reason_type' => $conf->config('cancel_credit_type'),
588 $dbh->rollback if $oldAutoCommit;
589 return "Error crediting customer \$$remaining_value for unused time on".
590 $self->part_pkg->pkg. ": $error";
595 my %hash = $self->hash;
596 $date ? ($hash{'expire'} = $date) : ($hash{'cancel'} = $cancel_time);
597 my $new = new FS::cust_pkg ( \%hash );
598 $error = $new->replace( $self, options => { $self->options } );
600 $dbh->rollback if $oldAutoCommit;
604 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
605 return '' if $date; #no errors
607 my $conf = new FS::Conf;
608 my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ } $self->cust_main->invoicing_list;
609 if ( !$options{'quiet'} && $conf->exists('emailcancel') && @invoicing_list ) {
610 my $conf = new FS::Conf;
611 my $error = send_email(
612 'from' => $conf->config('invoice_from'),
613 'to' => \@invoicing_list,
614 'subject' => ( $conf->config('cancelsubject') || 'Cancellation Notice' ),
615 'body' => [ map "$_\n", $conf->config('cancelmessage') ],
617 #should this do something on errors?
624 =item cancel_if_expired [ NOW_TIMESTAMP ]
626 Cancels this package if its expire date has been reached.
630 sub cancel_if_expired {
632 my $time = shift || time;
633 return '' unless $self->expire && $self->expire <= $time;
634 my $error = $self->cancel;
636 return "Error cancelling expired pkg ". $self->pkgnum. " for custnum ".
637 $self->custnum. ": $error";
644 Cancels any pending expiration (sets the expire field to null).
646 If there is an error, returns the error, otherwise returns false.
651 my( $self, %options ) = @_;
654 local $SIG{HUP} = 'IGNORE';
655 local $SIG{INT} = 'IGNORE';
656 local $SIG{QUIT} = 'IGNORE';
657 local $SIG{TERM} = 'IGNORE';
658 local $SIG{TSTP} = 'IGNORE';
659 local $SIG{PIPE} = 'IGNORE';
661 my $oldAutoCommit = $FS::UID::AutoCommit;
662 local $FS::UID::AutoCommit = 0;
665 my $old = $self->select_for_update;
667 my $pkgnum = $old->pkgnum;
668 if ( $old->get('cancel') || $self->get('cancel') ) {
669 dbh->rollback if $oldAutoCommit;
670 return "Can't unexpire cancelled package $pkgnum";
671 # or at least it's pointless
674 unless ( $old->get('expire') && $self->get('expire') ) {
675 dbh->rollback if $oldAutoCommit;
676 return ""; # no error
679 my %hash = $self->hash;
680 $hash{'expire'} = '';
681 my $new = new FS::cust_pkg ( \%hash );
682 $error = $new->replace( $self, options => { $self->options } );
684 $dbh->rollback if $oldAutoCommit;
688 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
694 =item suspend [ OPTION => VALUE ... ]
696 Suspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
697 package, then suspends the package itself (sets the susp field to now).
699 Available options are:
703 =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.
705 =item date - can be set to a unix style timestamp to specify when to suspend (adjourn)
709 If there is an error, returns the error, otherwise returns false.
714 my( $self, %options ) = @_;
717 local $SIG{HUP} = 'IGNORE';
718 local $SIG{INT} = 'IGNORE';
719 local $SIG{QUIT} = 'IGNORE';
720 local $SIG{TERM} = 'IGNORE';
721 local $SIG{TSTP} = 'IGNORE';
722 local $SIG{PIPE} = 'IGNORE';
724 my $oldAutoCommit = $FS::UID::AutoCommit;
725 local $FS::UID::AutoCommit = 0;
728 my $old = $self->select_for_update;
730 my $pkgnum = $old->pkgnum;
731 if ( $old->get('cancel') || $self->get('cancel') ) {
732 dbh->rollback if $oldAutoCommit;
733 return "Can't suspend cancelled package $pkgnum";
736 if ( $old->get('susp') || $self->get('susp') ) {
737 dbh->rollback if $oldAutoCommit;
738 return ""; # no error # complain on adjourn?
741 my $date = $options{date} if $options{date}; # adjourn/suspend later
742 $date = '' if ($date && $date <= time); # complain instead?
744 if ( $date && $old->get('expire') && $old->get('expire') < $date ) {
745 dbh->rollback if $oldAutoCommit;
746 return "Package $pkgnum expires before it would be suspended.";
749 if ( $options{'reason'} ) {
750 $error = $self->insert_reason( 'reason' => $options{'reason'},
751 'action' => $date ? 'adjourn' : 'suspend',
752 'reason_otaker' => $options{'reason_otaker'},
755 dbh->rollback if $oldAutoCommit;
756 return "Error inserting cust_pkg_reason: $error";
761 foreach my $cust_svc (
762 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
764 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
766 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
767 $dbh->rollback if $oldAutoCommit;
768 return "Illegal svcdb value in part_svc!";
771 require "FS/$svcdb.pm";
773 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
775 $error = $svc->suspend;
777 $dbh->rollback if $oldAutoCommit;
784 my %hash = $self->hash;
785 $date ? ($hash{'adjourn'} = $date) : ($hash{'susp'} = time);
786 my $new = new FS::cust_pkg ( \%hash );
787 $error = $new->replace( $self, options => { $self->options } );
789 $dbh->rollback if $oldAutoCommit;
793 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
798 =item unsuspend [ OPTION => VALUE ... ]
800 Unsuspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
801 package, then unsuspends the package itself (clears the susp field and the
802 adjourn field if it is in the past).
804 Available options are:
808 =item adjust_next_bill
810 Can be set true to adjust the next bill date forward by
811 the amount of time the account was inactive. This was set true by default
812 since 1.4.2 and 1.5.0pre6; however, starting with 1.7.0 this needs to be
813 explicitly requested. Price plans for which this makes sense (anniversary-date
814 based than prorate or subscription) could have an option to enable this
819 If there is an error, returns the error, otherwise returns false.
824 my( $self, %opt ) = @_;
827 local $SIG{HUP} = 'IGNORE';
828 local $SIG{INT} = 'IGNORE';
829 local $SIG{QUIT} = 'IGNORE';
830 local $SIG{TERM} = 'IGNORE';
831 local $SIG{TSTP} = 'IGNORE';
832 local $SIG{PIPE} = 'IGNORE';
834 my $oldAutoCommit = $FS::UID::AutoCommit;
835 local $FS::UID::AutoCommit = 0;
838 my $old = $self->select_for_update;
840 my $pkgnum = $old->pkgnum;
841 if ( $old->get('cancel') || $self->get('cancel') ) {
842 dbh->rollback if $oldAutoCommit;
843 return "Can't unsuspend cancelled package $pkgnum";
846 unless ( $old->get('susp') && $self->get('susp') ) {
847 dbh->rollback if $oldAutoCommit;
848 return ""; # no error # complain instead?
851 foreach my $cust_svc (
852 qsearch('cust_svc',{'pkgnum'=> $self->pkgnum } )
854 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
856 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
857 $dbh->rollback if $oldAutoCommit;
858 return "Illegal svcdb value in part_svc!";
861 require "FS/$svcdb.pm";
863 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
865 $error = $svc->unsuspend;
867 $dbh->rollback if $oldAutoCommit;
874 my %hash = $self->hash;
875 my $inactive = time - $hash{'susp'};
877 my $conf = new FS::Conf;
879 $hash{'bill'} = ( $hash{'bill'} || $hash{'setup'} ) + $inactive
880 if ( $opt{'adjust_next_bill'}
881 || $conf->config('unsuspend-always_adjust_next_bill_date') )
882 && $inactive > 0 && ( $hash{'bill'} || $hash{'setup'} );
885 $hash{'adjourn'} = '' if $hash{'adjourn'} < time;
886 my $new = new FS::cust_pkg ( \%hash );
887 $error = $new->replace( $self, options => { $self->options } );
889 $dbh->rollback if $oldAutoCommit;
893 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
900 Cancels any pending suspension (sets the adjourn field to null).
902 If there is an error, returns the error, otherwise returns false.
907 my( $self, %options ) = @_;
910 local $SIG{HUP} = 'IGNORE';
911 local $SIG{INT} = 'IGNORE';
912 local $SIG{QUIT} = 'IGNORE';
913 local $SIG{TERM} = 'IGNORE';
914 local $SIG{TSTP} = 'IGNORE';
915 local $SIG{PIPE} = 'IGNORE';
917 my $oldAutoCommit = $FS::UID::AutoCommit;
918 local $FS::UID::AutoCommit = 0;
921 my $old = $self->select_for_update;
923 my $pkgnum = $old->pkgnum;
924 if ( $old->get('cancel') || $self->get('cancel') ) {
925 dbh->rollback if $oldAutoCommit;
926 return "Can't unadjourn cancelled package $pkgnum";
927 # or at least it's pointless
930 if ( $old->get('susp') || $self->get('susp') ) {
931 dbh->rollback if $oldAutoCommit;
932 return "Can't unadjourn suspended package $pkgnum";
933 # perhaps this is arbitrary
936 unless ( $old->get('adjourn') && $self->get('adjourn') ) {
937 dbh->rollback if $oldAutoCommit;
938 return ""; # no error
941 my %hash = $self->hash;
942 $hash{'adjourn'} = '';
943 my $new = new FS::cust_pkg ( \%hash );
944 $error = $new->replace( $self, options => { $self->options } );
946 $dbh->rollback if $oldAutoCommit;
950 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
958 Returns the last bill date, or if there is no last bill date, the setup date.
959 Useful for billing metered services.
965 return $self->setfield('last_bill', $_[0]) if @_;
966 return $self->getfield('last_bill') if $self->getfield('last_bill');
967 my $cust_bill_pkg = qsearchs('cust_bill_pkg', { 'pkgnum' => $self->pkgnum,
968 'edate' => $self->bill, } );
969 $cust_bill_pkg ? $cust_bill_pkg->sdate : $self->setup || 0;
972 =item last_cust_pkg_reason ACTION
974 Returns the most recent ACTION FS::cust_pkg_reason associated with the package.
975 Returns false if there is no reason or the package is not currenly ACTION'd
976 ACTION is one of adjourn, susp, cancel, or expire.
980 sub last_cust_pkg_reason {
981 my ( $self, $action ) = ( shift, shift );
982 my $date = $self->get($action);
984 'table' => 'cust_pkg_reason',
985 'hashref' => { 'pkgnum' => $self->pkgnum,
986 'action' => substr(uc($action), 0, 1),
989 'order_by' => 'ORDER BY num DESC LIMIT 1',
993 =item last_reason ACTION
995 Returns the most recent ACTION FS::reason associated with the package.
996 Returns false if there is no reason or the package is not currenly ACTION'd
997 ACTION is one of adjourn, susp, cancel, or expire.
1002 my $cust_pkg_reason = shift->last_cust_pkg_reason(@_);
1003 $cust_pkg_reason->reason
1004 if $cust_pkg_reason;
1009 Returns the definition for this billing item, as an FS::part_pkg object (see
1016 #exists( $self->{'_pkgpart'} )
1018 ? $self->{'_pkgpart'}
1019 : qsearchs( 'part_pkg', { 'pkgpart' => $self->pkgpart } );
1024 Returns the cancelled package this package was changed from, if any.
1030 return '' unless $self->change_pkgnum;
1031 qsearchs('cust_pkg', { 'pkgnum' => $self->change_pkgnum } );
1036 Calls the I<calc_setup> of the FS::part_pkg object associated with this billing
1043 $self->part_pkg->calc_setup($self, @_);
1048 Calls the I<calc_recur> of the FS::part_pkg object associated with this billing
1055 $self->part_pkg->calc_recur($self, @_);
1060 Calls the I<calc_remain> of the FS::part_pkg object associated with this
1067 $self->part_pkg->calc_remain($self, @_);
1072 Calls the I<calc_cancel> of the FS::part_pkg object associated with this
1079 $self->part_pkg->calc_cancel($self, @_);
1084 Returns any invoice line items for this package (see L<FS::cust_bill_pkg>).
1090 qsearch( 'cust_bill_pkg', { 'pkgnum' => $self->pkgnum } );
1093 =item cust_pkg_detail [ DETAILTYPE ]
1095 Returns any customer package details for this package (see
1096 L<FS::cust_pkg_detail>).
1098 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
1102 sub cust_pkg_detail {
1104 my %hash = ( 'pkgnum' => $self->pkgnum );
1105 $hash{detailtype} = shift if @_;
1107 'table' => 'cust_pkg_detail',
1108 'hashref' => \%hash,
1109 'order_by' => 'ORDER BY weight, pkgdetailnum',
1113 =item set_cust_pkg_detail DETAILTYPE [ DETAIL, DETAIL, ... ]
1115 Sets customer package details for this package (see L<FS::cust_pkg_detail>).
1117 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
1119 If there is an error, returns the error, otherwise returns false.
1123 sub set_cust_pkg_detail {
1124 my( $self, $detailtype, @details ) = @_;
1126 local $SIG{HUP} = 'IGNORE';
1127 local $SIG{INT} = 'IGNORE';
1128 local $SIG{QUIT} = 'IGNORE';
1129 local $SIG{TERM} = 'IGNORE';
1130 local $SIG{TSTP} = 'IGNORE';
1131 local $SIG{PIPE} = 'IGNORE';
1133 my $oldAutoCommit = $FS::UID::AutoCommit;
1134 local $FS::UID::AutoCommit = 0;
1137 foreach my $current ( $self->cust_pkg_detail($detailtype) ) {
1138 my $error = $current->delete;
1140 $dbh->rollback if $oldAutoCommit;
1141 return "error removing old detail: $error";
1145 foreach my $detail ( @details ) {
1146 my $cust_pkg_detail = new FS::cust_pkg_detail {
1147 'pkgnum' => $self->pkgnum,
1148 'detailtype' => $detailtype,
1149 'detail' => $detail,
1151 my $error = $cust_pkg_detail->insert;
1153 $dbh->rollback if $oldAutoCommit;
1154 return "error adding new detail: $error";
1159 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1166 Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.
1170 #false laziness w/cust_bill.pm
1174 'table' => 'cust_event',
1175 'addl_from' => 'JOIN part_event USING ( eventpart )',
1176 'hashref' => { 'tablenum' => $self->pkgnum },
1177 'extra_sql' => " AND eventtable = 'cust_pkg' ",
1181 =item num_cust_event
1183 Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.
1187 #false laziness w/cust_bill.pm
1188 sub num_cust_event {
1191 "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
1192 " WHERE tablenum = ? AND eventtable = 'cust_pkg'";
1193 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
1194 $sth->execute($self->pkgnum) or die $sth->errstr. " executing $sql";
1195 $sth->fetchrow_arrayref->[0];
1198 =item cust_svc [ SVCPART ]
1200 Returns the services for this package, as FS::cust_svc objects (see
1201 L<FS::cust_svc>). If a svcpart is specified, return only the matching
1210 return qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum,
1211 'svcpart' => shift, } );
1214 #if ( $self->{'_svcnum'} ) {
1215 # values %{ $self->{'_svcnum'}->cache };
1217 $self->_sort_cust_svc(
1218 [ qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } ) ]
1224 =item overlimit [ SVCPART ]
1226 Returns the services for this package which have exceeded their
1227 usage limit as FS::cust_svc objects (see L<FS::cust_svc>). If a svcpart
1228 is specified, return only the matching services.
1234 grep { $_->overlimit } $self->cust_svc;
1237 =item h_cust_svc END_TIMESTAMP [ START_TIMESTAMP ]
1239 Returns historical services for this package created before END TIMESTAMP and
1240 (optionally) not cancelled before START_TIMESTAMP, as FS::h_cust_svc objects
1241 (see L<FS::h_cust_svc>).
1248 $self->_sort_cust_svc(
1249 [ qsearch( 'h_cust_svc',
1250 { 'pkgnum' => $self->pkgnum, },
1251 FS::h_cust_svc->sql_h_search(@_),
1257 sub _sort_cust_svc {
1258 my( $self, $arrayref ) = @_;
1261 sort { $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] }
1263 my $pkg_svc = qsearchs( 'pkg_svc', { 'pkgpart' => $self->pkgpart,
1264 'svcpart' => $_->svcpart } );
1266 $pkg_svc ? $pkg_svc->primary_svc : '',
1267 $pkg_svc ? $pkg_svc->quantity : 0,
1274 =item num_cust_svc [ SVCPART ]
1276 Returns the number of provisioned services for this package. If a svcpart is
1277 specified, counts only the matching services.
1283 my $sql = 'SELECT COUNT(*) FROM cust_svc WHERE pkgnum = ?';
1284 $sql .= ' AND svcpart = ?' if @_;
1285 my $sth = dbh->prepare($sql) or die dbh->errstr;
1286 $sth->execute($self->pkgnum, @_) or die $sth->errstr;
1287 $sth->fetchrow_arrayref->[0];
1290 =item available_part_svc
1292 Returns a list of FS::part_svc objects representing services included in this
1293 package but not yet provisioned. Each FS::part_svc object also has an extra
1294 field, I<num_avail>, which specifies the number of available services.
1298 sub available_part_svc {
1300 grep { $_->num_avail > 0 }
1302 my $part_svc = $_->part_svc;
1303 $part_svc->{'Hash'}{'num_avail'} = #evil encapsulation-breaking
1304 $_->quantity - $self->num_cust_svc($_->svcpart);
1307 $self->part_pkg->pkg_svc;
1312 Returns a list of FS::part_svc objects representing provisioned and available
1313 services included in this package. Each FS::part_svc object also has the
1314 following extra fields:
1318 =item num_cust_svc (count)
1320 =item num_avail (quantity - count)
1322 =item cust_pkg_svc (services) - array reference containing the provisioned services, as cust_svc objects
1325 label -> ($cust_svc->label)[1]
1334 #XXX some sort of sort order besides numeric by svcpart...
1335 my @part_svc = sort { $a->svcpart <=> $b->svcpart } map {
1337 my $part_svc = $pkg_svc->part_svc;
1338 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
1339 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #more evil
1340 $part_svc->{'Hash'}{'num_avail'} =
1341 max( 0, $pkg_svc->quantity - $num_cust_svc );
1342 $part_svc->{'Hash'}{'cust_pkg_svc'} = [ $self->cust_svc($part_svc->svcpart) ];
1344 } $self->part_pkg->pkg_svc;
1347 push @part_svc, map {
1349 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
1350 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #speak no evail
1351 $part_svc->{'Hash'}{'num_avail'} = 0; #0-$num_cust_svc ?
1352 $part_svc->{'Hash'}{'cust_pkg_svc'} = [ $self->cust_svc($part_svc->svcpart) ];
1354 } $self->extra_part_svc;
1360 =item extra_part_svc
1362 Returns a list of FS::part_svc objects corresponding to services in this
1363 package which are still provisioned but not (any longer) available in the
1368 sub extra_part_svc {
1371 my $pkgnum = $self->pkgnum;
1372 my $pkgpart = $self->pkgpart;
1375 'table' => 'part_svc',
1377 'extra_sql' => "WHERE 0 = ( SELECT COUNT(*) FROM pkg_svc
1378 WHERE pkg_svc.svcpart = part_svc.svcpart
1379 AND pkg_svc.pkgpart = $pkgpart
1382 AND 0 < ( SELECT count(*)
1384 LEFT JOIN cust_pkg using ( pkgnum )
1385 WHERE cust_svc.svcpart = part_svc.svcpart
1386 AND pkgnum = $pkgnum
1393 Returns a short status string for this package, currently:
1397 =item not yet billed
1399 =item one-time charge
1414 my $freq = length($self->freq) ? $self->freq : $self->part_pkg->freq;
1416 return 'cancelled' if $self->get('cancel');
1417 return 'suspended' if $self->susp;
1418 return 'not yet billed' unless $self->setup;
1419 return 'one-time charge' if $freq =~ /^(0|$)/;
1425 Class method that returns the list of possible status strings for packages
1426 (see L<the status method|/status>). For example:
1428 @statuses = FS::cust_pkg->statuses();
1432 tie my %statuscolor, 'Tie::IxHash',
1433 'not yet billed' => '000000',
1434 'one-time charge' => '000000',
1435 'active' => '00CC00',
1436 'suspended' => 'FF9900',
1437 'cancelled' => 'FF0000',
1441 my $self = shift; #could be class...
1442 grep { $_ !~ /^(not yet billed)$/ } #this is a dumb status anyway
1443 # mayble split btw one-time vs. recur
1449 Returns a hex triplet color string for this package's status.
1455 $statuscolor{$self->status};
1460 Returns a list of lists, calling the label method for all services
1461 (see L<FS::cust_svc>) of this billing item.
1467 map { [ $_->label ] } $self->cust_svc;
1470 =item h_labels END_TIMESTAMP [ START_TIMESTAMP ]
1472 Like the labels method, but returns historical information on services that
1473 were active as of END_TIMESTAMP and (optionally) not cancelled before
1476 Returns a list of lists, calling the label method for all (historical) services
1477 (see L<FS::h_cust_svc>) of this billing item.
1483 map { [ $_->label(@_) ] } $self->h_cust_svc(@_);
1486 =item h_labels_short END_TIMESTAMP [ START_TIMESTAMP ]
1488 Like h_labels, except returns a simple flat list, and shortens long
1489 (currently >5 or the cust_bill-max_same_services configuration value) lists of
1490 identical services to one line that lists the service label and the number of
1491 individual services rather than individual items.
1495 sub h_labels_short {
1498 my $conf = new FS::Conf;
1499 my $max_same_services = $conf->config('cust_bill-max_same_services') || 5;
1502 #tie %labels, 'Tie::IxHash';
1503 push @{ $labels{$_->[0]} }, $_->[1]
1504 foreach $self->h_labels(@_);
1506 foreach my $label ( keys %labels ) {
1507 my @values = @{ $labels{$label} };
1508 my $num = scalar(@values);
1509 if ( $num > $max_same_services ) {
1510 push @labels, "$label ($num)";
1512 push @labels, map { "$label: $_" } @values;
1522 Returns the parent customer object (see L<FS::cust_main>).
1528 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
1531 =item seconds_since TIMESTAMP
1533 Returns the number of seconds all accounts (see L<FS::svc_acct>) in this
1534 package have been online since TIMESTAMP, according to the session monitor.
1536 TIMESTAMP is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
1537 L<Time::Local> and L<Date::Parse> for conversion functions.
1542 my($self, $since) = @_;
1545 foreach my $cust_svc (
1546 grep { $_->part_svc->svcdb eq 'svc_acct' } $self->cust_svc
1548 $seconds += $cust_svc->seconds_since($since);
1555 =item seconds_since_sqlradacct TIMESTAMP_START TIMESTAMP_END
1557 Returns the numbers of seconds all accounts (see L<FS::svc_acct>) in this
1558 package have been online between TIMESTAMP_START (inclusive) and TIMESTAMP_END
1561 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
1562 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
1568 sub seconds_since_sqlradacct {
1569 my($self, $start, $end) = @_;
1573 foreach my $cust_svc (
1575 my $part_svc = $_->part_svc;
1576 $part_svc->svcdb eq 'svc_acct'
1577 && scalar($part_svc->part_export('sqlradius'));
1580 $seconds += $cust_svc->seconds_since_sqlradacct($start, $end);
1587 =item attribute_since_sqlradacct TIMESTAMP_START TIMESTAMP_END ATTRIBUTE
1589 Returns the sum of the given attribute for all accounts (see L<FS::svc_acct>)
1590 in this package for sessions ending between TIMESTAMP_START (inclusive) and
1594 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
1595 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
1600 sub attribute_since_sqlradacct {
1601 my($self, $start, $end, $attrib) = @_;
1605 foreach my $cust_svc (
1607 my $part_svc = $_->part_svc;
1608 $part_svc->svcdb eq 'svc_acct'
1609 && scalar($part_svc->part_export('sqlradius'));
1612 $sum += $cust_svc->attribute_since_sqlradacct($start, $end, $attrib);
1624 my( $self, $value ) = @_;
1625 if ( defined($value) ) {
1626 $self->setfield('quantity', $value);
1628 $self->getfield('quantity') || 1;
1631 =item transfer DEST_PKGNUM | DEST_CUST_PKG, [ OPTION => VALUE ... ]
1633 Transfers as many services as possible from this package to another package.
1635 The destination package can be specified by pkgnum by passing an FS::cust_pkg
1636 object. The destination package must already exist.
1638 Services are moved only if the destination allows services with the correct
1639 I<svcpart> (not svcdb), unless the B<change_svcpart> option is set true. Use
1640 this option with caution! No provision is made for export differences
1641 between the old and new service definitions. Probably only should be used
1642 when your exports for all service definitions of a given svcdb are identical.
1643 (attempt a transfer without it first, to move all possible svcpart-matching
1646 Any services that can't be moved remain in the original package.
1648 Returns an error, if there is one; otherwise, returns the number of services
1649 that couldn't be moved.
1654 my ($self, $dest_pkgnum, %opt) = @_;
1660 if (ref ($dest_pkgnum) eq 'FS::cust_pkg') {
1661 $dest = $dest_pkgnum;
1662 $dest_pkgnum = $dest->pkgnum;
1664 $dest = qsearchs('cust_pkg', { pkgnum => $dest_pkgnum });
1667 return ('Package does not exist: '.$dest_pkgnum) unless $dest;
1669 foreach my $pkg_svc ( $dest->part_pkg->pkg_svc ) {
1670 $target{$pkg_svc->svcpart} = $pkg_svc->quantity;
1673 foreach my $cust_svc ($dest->cust_svc) {
1674 $target{$cust_svc->svcpart}--;
1677 my %svcpart2svcparts = ();
1678 if ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
1679 warn "change_svcpart option received, creating alternates list\n" if $DEBUG;
1680 foreach my $svcpart ( map { $_->svcpart } $self->cust_svc ) {
1681 next if exists $svcpart2svcparts{$svcpart};
1682 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
1683 $svcpart2svcparts{$svcpart} = [
1685 sort { $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] }
1687 my $pkg_svc = qsearchs( 'pkg_svc', { 'pkgpart' => $dest->pkgpart,
1688 'svcpart' => $_ } );
1690 $pkg_svc ? $pkg_svc->primary_svc : '',
1691 $pkg_svc ? $pkg_svc->quantity : 0,
1695 grep { $_ != $svcpart }
1697 qsearch('part_svc', { 'svcdb' => $part_svc->svcdb } )
1699 warn "alternates for svcpart $svcpart: ".
1700 join(', ', @{$svcpart2svcparts{$svcpart}}). "\n"
1705 foreach my $cust_svc ($self->cust_svc) {
1706 if($target{$cust_svc->svcpart} > 0) {
1707 $target{$cust_svc->svcpart}--;
1708 my $new = new FS::cust_svc { $cust_svc->hash };
1709 $new->pkgnum($dest_pkgnum);
1710 my $error = $new->replace($cust_svc);
1711 return $error if $error;
1712 } elsif ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
1714 warn "looking for alternates for svcpart ". $cust_svc->svcpart. "\n";
1715 warn "alternates to consider: ".
1716 join(', ', @{$svcpart2svcparts{$cust_svc->svcpart}}). "\n";
1718 my @alternate = grep {
1719 warn "considering alternate svcpart $_: ".
1720 "$target{$_} available in new package\n"
1723 } @{$svcpart2svcparts{$cust_svc->svcpart}};
1725 warn "alternate(s) found\n" if $DEBUG;
1726 my $change_svcpart = $alternate[0];
1727 $target{$change_svcpart}--;
1728 my $new = new FS::cust_svc { $cust_svc->hash };
1729 $new->svcpart($change_svcpart);
1730 $new->pkgnum($dest_pkgnum);
1731 my $error = $new->replace($cust_svc);
1732 return $error if $error;
1745 This method is deprecated. See the I<depend_jobnum> option to the insert and
1746 order_pkgs methods in FS::cust_main for a better way to defer provisioning.
1753 local $SIG{HUP} = 'IGNORE';
1754 local $SIG{INT} = 'IGNORE';
1755 local $SIG{QUIT} = 'IGNORE';
1756 local $SIG{TERM} = 'IGNORE';
1757 local $SIG{TSTP} = 'IGNORE';
1758 local $SIG{PIPE} = 'IGNORE';
1760 my $oldAutoCommit = $FS::UID::AutoCommit;
1761 local $FS::UID::AutoCommit = 0;
1764 foreach my $cust_svc ( $self->cust_svc ) {
1765 #false laziness w/svc_Common::insert
1766 my $svc_x = $cust_svc->svc_x;
1767 foreach my $part_export ( $cust_svc->part_svc->part_export ) {
1768 my $error = $part_export->export_insert($svc_x);
1770 $dbh->rollback if $oldAutoCommit;
1776 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1783 =head1 CLASS METHODS
1789 Returns an SQL expression identifying recurring packages.
1793 sub recurring_sql { "
1794 '0' != ( select freq from part_pkg
1795 where cust_pkg.pkgpart = part_pkg.pkgpart )
1800 Returns an SQL expression identifying one-time packages.
1805 '0' = ( select freq from part_pkg
1806 where cust_pkg.pkgpart = part_pkg.pkgpart )
1811 Returns an SQL expression identifying active packages.
1816 ". $_[0]->recurring_sql(). "
1817 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
1818 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
1823 Returns an SQL expression identifying inactive packages (one-time packages
1824 that are otherwise unsuspended/uncancelled).
1828 sub inactive_sql { "
1829 ". $_[0]->onetime_sql(). "
1830 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
1831 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
1837 Returns an SQL expression identifying suspended packages.
1841 sub suspended_sql { susp_sql(@_); }
1843 #$_[0]->recurring_sql(). ' AND '.
1845 ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
1846 AND cust_pkg.susp IS NOT NULL AND cust_pkg.susp != 0
1853 Returns an SQL exprression identifying cancelled packages.
1857 sub cancelled_sql { cancel_sql(@_); }
1859 #$_[0]->recurring_sql(). ' AND '.
1860 "cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0";
1863 =item search_sql HASHREF
1867 Returns a qsearch hash expression to search for parameters specified in HASHREF.
1868 Valid parameters are
1876 active, inactive, suspended, cancel (or cancelled)
1880 active, inactive, suspended, one-time charge, inactive, cancel (or cancelled)
1890 arrayref of beginning and ending epoch date
1894 arrayref of beginning and ending epoch date
1898 arrayref of beginning and ending epoch date
1902 arrayref of beginning and ending epoch date
1906 arrayref of beginning and ending epoch date
1910 arrayref of beginning and ending epoch date
1914 arrayref of beginning and ending epoch date
1918 pkgnum or APKG_pkgnum
1922 a value suited to passing to FS::UI::Web::cust_header
1926 specifies the user for agent virtualization
1933 my ($class, $params) = @_;
1940 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
1942 "cust_main.agentnum = $1";
1949 if ( $params->{'magic'} eq 'active'
1950 || $params->{'status'} eq 'active' ) {
1952 push @where, FS::cust_pkg->active_sql();
1954 } elsif ( $params->{'magic'} eq 'inactive'
1955 || $params->{'status'} eq 'inactive' ) {
1957 push @where, FS::cust_pkg->inactive_sql();
1959 } elsif ( $params->{'magic'} eq 'suspended'
1960 || $params->{'status'} eq 'suspended' ) {
1962 push @where, FS::cust_pkg->suspended_sql();
1964 } elsif ( $params->{'magic'} =~ /^cancell?ed$/
1965 || $params->{'status'} =~ /^cancell?ed$/ ) {
1967 push @where, FS::cust_pkg->cancelled_sql();
1969 } elsif ( $params->{'status'} =~ /^(one-time charge|inactive)$/ ) {
1971 push @where, FS::cust_pkg->inactive_sql();
1976 # parse package class
1979 #false lazinessish w/graph/cust_bill_pkg.cgi
1982 if ( exists($params->{'classnum'})
1983 && $params->{'classnum'} =~ /^(\d*)$/
1987 if ( $classnum ) { #a specific class
1988 push @where, "classnum = $classnum";
1990 #@pkg_class = ( qsearchs('pkg_class', { 'classnum' => $classnum } ) );
1991 #die "classnum $classnum not found!" unless $pkg_class[0];
1992 #$title .= $pkg_class[0]->classname.' ';
1994 } elsif ( $classnum eq '' ) { #the empty class
1996 push @where, "classnum IS NULL";
1997 #$title .= 'Empty class ';
1998 #@pkg_class = ( '(empty class)' );
1999 } elsif ( $classnum eq '0' ) {
2000 #@pkg_class = qsearch('pkg_class', {} ); # { 'disabled' => '' } );
2001 #push @pkg_class, '(empty class)';
2003 die "illegal classnum";
2012 my $pkgpart = join (' OR pkgpart=',
2013 grep {$_} map { /^(\d+)$/; } ($params->{'pkgpart'}));
2014 push @where, '(pkgpart=' . $pkgpart . ')' if $pkgpart;
2022 #false laziness w/report_cust_pkg.html
2025 'one-time charge' => { 'last_bill'=>1, 'bill'=>1, 'adjourn'=>1, 'susp'=>1, 'expire'=>1, 'cancel'=>1, },
2026 'active' => { 'susp'=>1, 'cancel'=>1 },
2027 'suspended' => { 'cancel' => 1 },
2032 foreach my $field (qw( setup last_bill bill adjourn susp expire cancel )) {
2034 next unless exists($params->{$field});
2036 my($beginning, $ending) = @{$params->{$field}};
2038 next if $beginning == 0 && $ending == 4294967295;
2041 "cust_pkg.$field IS NOT NULL",
2042 "cust_pkg.$field >= $beginning",
2043 "cust_pkg.$field <= $ending";
2045 $orderby ||= "ORDER BY cust_pkg.$field";
2049 $orderby ||= 'ORDER BY bill';
2052 # parse magic, legacy, etc.
2055 if ( $params->{'magic'} &&
2056 $params->{'magic'} =~ /^(active|inactive|suspended|cancell?ed)$/
2059 $orderby = 'ORDER BY pkgnum';
2061 if ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
2062 push @where, "pkgpart = $1";
2065 } elsif ( $params->{'query'} eq 'pkgnum' ) {
2067 $orderby = 'ORDER BY pkgnum';
2069 } elsif ( $params->{'query'} eq 'APKG_pkgnum' ) {
2071 $orderby = 'ORDER BY pkgnum';
2074 SELECT count(*) FROM pkg_svc
2075 WHERE pkg_svc.pkgpart = cust_pkg.pkgpart
2076 AND pkg_svc.quantity > ( SELECT count(*) FROM cust_svc
2077 WHERE cust_svc.pkgnum = cust_pkg.pkgnum
2078 AND cust_svc.svcpart = pkg_svc.svcpart
2085 # setup queries, links, subs, etc. for the search
2088 # here is the agent virtualization
2089 if ($params->{CurrentUser}) {
2091 qsearchs('access_user', { username => $params->{CurrentUser} });
2094 push @where, $access_user->agentnums_sql('table'=>'cust_main');
2099 push @where, $FS::CurrentUser::CurrentUser->agentnums_sql('table'=>'cust_main');
2102 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
2104 my $addl_from = 'LEFT JOIN cust_main USING ( custnum ) '.
2105 'LEFT JOIN part_pkg USING ( pkgpart ) '.
2106 'LEFT JOIN pkg_class USING ( classnum ) ';
2108 my $count_query = "SELECT COUNT(*) FROM cust_pkg $addl_from $extra_sql";
2111 'table' => 'cust_pkg',
2113 'select' => join(', ',
2115 ( map "part_pkg.$_", qw( pkg freq ) ),
2116 'pkg_class.classname',
2117 'cust_main.custnum as cust_main_custnum',
2118 FS::UI::Web::cust_sql_fields(
2119 $params->{'cust_fields'}
2122 'extra_sql' => "$extra_sql $orderby",
2123 'addl_from' => $addl_from,
2124 'count_query' => $count_query,
2133 =item order CUSTNUM, PKGPARTS_ARYREF, [ REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF [ REFNUM ] ] ]
2135 CUSTNUM is a customer (see L<FS::cust_main>)
2137 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
2138 L<FS::part_pkg>) to order for this customer. Duplicates are of course
2141 REMOVE_PKGNUMS is an optional list of pkgnums specifying the billing items to
2142 remove for this customer. The services (see L<FS::cust_svc>) are moved to the
2143 new billing items. An error is returned if this is not possible (see
2144 L<FS::pkg_svc>). An empty arrayref is equivalent to not specifying this
2147 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
2148 newly-created cust_pkg objects.
2150 REFNUM, if specified, will specify the FS::pkg_referral record to be created
2151 and inserted. Multiple FS::pkg_referral records can be created by
2152 setting I<refnum> to an array reference of refnums or a hash reference with
2153 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
2154 record will be created corresponding to cust_main.refnum.
2159 my ($custnum, $pkgparts, $remove_pkgnum, $return_cust_pkg, $refnum) = @_;
2161 my $conf = new FS::Conf;
2163 # Transactionize this whole mess
2164 local $SIG{HUP} = 'IGNORE';
2165 local $SIG{INT} = 'IGNORE';
2166 local $SIG{QUIT} = 'IGNORE';
2167 local $SIG{TERM} = 'IGNORE';
2168 local $SIG{TSTP} = 'IGNORE';
2169 local $SIG{PIPE} = 'IGNORE';
2171 my $oldAutoCommit = $FS::UID::AutoCommit;
2172 local $FS::UID::AutoCommit = 0;
2176 my $cust_main = qsearchs('cust_main', { custnum => $custnum });
2177 return "Customer not found: $custnum" unless $cust_main;
2179 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
2182 my $change = scalar(@old_cust_pkg) != 0;
2185 if ( scalar(@old_cust_pkg) == 1 && scalar(@$pkgparts) == 1 ) {
2189 #$hash{$_} = $old_cust_pkg[0]->$_() foreach qw( last_bill bill );
2191 #$hash{$_} = $old_cust_pkg[0]->$_() foreach qw( setup );
2192 $hash{'setup'} = $time if $old_cust_pkg[0]->setup;
2194 $hash{'change_date'} = $time;
2195 $hash{"change_$_"} = $old_cust_pkg[0]->$_() foreach qw( pkgnum pkgpart );
2198 # Create the new packages.
2199 foreach my $pkgpart (@$pkgparts) {
2200 my $cust_pkg = new FS::cust_pkg { custnum => $custnum,
2201 pkgpart => $pkgpart,
2205 $error = $cust_pkg->insert( 'change' => $change );
2207 $dbh->rollback if $oldAutoCommit;
2210 push @$return_cust_pkg, $cust_pkg;
2212 # $return_cust_pkg now contains refs to all of the newly
2215 # Transfer services and cancel old packages.
2216 foreach my $old_pkg (@old_cust_pkg) {
2218 foreach my $new_pkg (@$return_cust_pkg) {
2219 $error = $old_pkg->transfer($new_pkg);
2220 if ($error and $error == 0) {
2221 # $old_pkg->transfer failed.
2222 $dbh->rollback if $oldAutoCommit;
2227 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
2228 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
2229 foreach my $new_pkg (@$return_cust_pkg) {
2230 $error = $old_pkg->transfer($new_pkg, 'change_svcpart'=>1 );
2231 if ($error and $error == 0) {
2232 # $old_pkg->transfer failed.
2233 $dbh->rollback if $oldAutoCommit;
2240 # Transfers were successful, but we went through all of the
2241 # new packages and still had services left on the old package.
2242 # We can't cancel the package under the circumstances, so abort.
2243 $dbh->rollback if $oldAutoCommit;
2244 return "Unable to transfer all services from package ".$old_pkg->pkgnum;
2246 $error = $old_pkg->cancel( quiet=>1 );
2252 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2256 =item bulk_change PKGPARTS_ARYREF, REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF ]
2258 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
2259 L<FS::part_pkg>) to order for this customer. Duplicates are of course
2262 REMOVE_PKGNUMS is an list of pkgnums specifying the billing items to
2263 replace. The services (see L<FS::cust_svc>) are moved to the
2264 new billing items. An error is returned if this is not possible (see
2267 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
2268 newly-created cust_pkg objects.
2273 my ($pkgparts, $remove_pkgnum, $return_cust_pkg) = @_;
2275 # Transactionize this whole mess
2276 local $SIG{HUP} = 'IGNORE';
2277 local $SIG{INT} = 'IGNORE';
2278 local $SIG{QUIT} = 'IGNORE';
2279 local $SIG{TERM} = 'IGNORE';
2280 local $SIG{TSTP} = 'IGNORE';
2281 local $SIG{PIPE} = 'IGNORE';
2283 my $oldAutoCommit = $FS::UID::AutoCommit;
2284 local $FS::UID::AutoCommit = 0;
2288 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
2291 while(scalar(@old_cust_pkg)) {
2293 my $custnum = $old_cust_pkg[0]->custnum;
2294 my (@remove) = map { $_->pkgnum }
2295 grep { $_->custnum == $custnum } @old_cust_pkg;
2296 @old_cust_pkg = grep { $_->custnum != $custnum } @old_cust_pkg;
2298 my $error = order $custnum, $pkgparts, \@remove, \@return;
2300 push @errors, $error
2302 push @$return_cust_pkg, @return;
2305 if (scalar(@errors)) {
2306 $dbh->rollback if $oldAutoCommit;
2307 return join(' / ', @errors);
2310 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2316 Associates this package with a (suspension or cancellation) reason (see
2317 L<FS::cust_pkg_reason>, possibly inserting a new reason on the fly (see
2320 Available options are:
2326 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.
2330 the access_user (see L<FS::access_user>) providing the reason
2338 the action (cancel, susp, adjourn, expire) associated with the reason
2342 If there is an error, returns the error, otherwise returns false.
2347 my ($self, %options) = @_;
2349 my $otaker = $options{reason_otaker} ||
2350 $FS::CurrentUser::CurrentUser->username;
2353 if ( $options{'reason'} =~ /^(\d+)$/ ) {
2357 } elsif ( ref($options{'reason'}) ) {
2359 return 'Enter a new reason (or select an existing one)'
2360 unless $options{'reason'}->{'reason'} !~ /^\s*$/;
2362 my $reason = new FS::reason({
2363 'reason_type' => $options{'reason'}->{'typenum'},
2364 'reason' => $options{'reason'}->{'reason'},
2366 my $error = $reason->insert;
2367 return $error if $error;
2369 $reasonnum = $reason->reasonnum;
2372 return "Unparsable reason: ". $options{'reason'};
2375 my $cust_pkg_reason =
2376 new FS::cust_pkg_reason({ 'pkgnum' => $self->pkgnum,
2377 'reasonnum' => $reasonnum,
2378 'otaker' => $otaker,
2379 'action' => substr(uc($options{'action'}),0,1),
2380 'date' => $options{'date'}
2385 $cust_pkg_reason->insert;
2388 =item set_usage USAGE_VALUE_HASHREF
2390 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
2391 to which they should be set (see L<FS::svc_acct>). Currently seconds,
2392 upbytes, downbytes, and totalbytes are appropriate keys.
2394 All svc_accts which are part of this package have their values reset.
2399 my ($self, $valueref) = @_;
2401 foreach my $cust_svc ($self->cust_svc){
2402 my $svc_x = $cust_svc->svc_x;
2403 $svc_x->set_usage($valueref)
2404 if $svc_x->can("set_usage");
2408 =item recharge USAGE_VALUE_HASHREF
2410 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
2411 to which they should be set (see L<FS::svc_acct>). Currently seconds,
2412 upbytes, downbytes, and totalbytes are appropriate keys.
2414 All svc_accts which are part of this package have their values incremented.
2419 my ($self, $valueref) = @_;
2421 foreach my $cust_svc ($self->cust_svc){
2422 my $svc_x = $cust_svc->svc_x;
2423 $svc_x->recharge($valueref)
2424 if $svc_x->can("recharge");
2432 sub order is not OO. Perhaps it should be moved to FS::cust_main and made so?
2434 In sub order, the @pkgparts array (passed by reference) is clobbered.
2436 Also in sub order, no money is adjusted. Once FS::part_pkg defines a standard
2437 method to pass dates to the recur_prog expression, it should do so.
2439 FS::svc_acct, FS::svc_domain, FS::svc_www, FS::svc_ip and FS::svc_forward are
2440 loaded via 'use' at compile time, rather than via 'require' in sub { setup,
2441 suspend, unsuspend, cancel } because they use %FS::UID::callback to load
2442 configuration values. Probably need a subroutine which decides what to do
2443 based on whether or not we've fetched the user yet, rather than a hash. See
2444 FS::UID and the TODO.
2446 Now that things are transactional should the check in the insert method be
2451 L<FS::Record>, L<FS::cust_main>, L<FS::part_pkg>, L<FS::cust_svc>,
2452 L<FS::pkg_svc>, schema.html from the base documentation