4 use base qw( FS::otaker_Mixin FS::cust_main_Mixin FS::location_Mixin
5 FS::m2m_Common FS::option_Common );
6 use vars qw($disable_agentcheck $DEBUG $me);
8 use Scalar::Util qw( blessed );
9 use List::Util qw(max);
11 use Time::Local qw( timelocal_nocheck );
13 use FS::UID qw( getotaker dbh );
14 use FS::Misc qw( send_email );
15 use FS::Record qw( qsearch qsearchs );
20 use FS::cust_location;
22 use FS::cust_bill_pkg;
23 use FS::cust_pkg_detail;
28 use FS::cust_pkg_reason;
30 use FS::cust_pkg_discount;
34 # need to 'use' these instead of 'require' in sub { cancel, suspend, unsuspend,
36 # because they load configuration by setting FS::UID::callback (see TODO)
42 # for sending cancel emails in sub cancel
46 $me = '[FS::cust_pkg]';
48 $disable_agentcheck = 0;
52 my ( $hashref, $cache ) = @_;
53 #if ( $hashref->{'pkgpart'} ) {
54 if ( $hashref->{'pkg'} ) {
55 # #@{ $self->{'_pkgnum'} } = ();
56 # my $subcache = $cache->subcache('pkgpart', 'part_pkg');
57 # $self->{'_pkgpart'} = $subcache;
58 # #push @{ $self->{'_pkgnum'} },
59 # FS::part_pkg->new_or_cached($hashref, $subcache);
60 $self->{'_pkgpart'} = FS::part_pkg->new($hashref);
62 if ( exists $hashref->{'svcnum'} ) {
63 #@{ $self->{'_pkgnum'} } = ();
64 my $subcache = $cache->subcache('svcnum', 'cust_svc', $hashref->{pkgnum});
65 $self->{'_svcnum'} = $subcache;
66 #push @{ $self->{'_pkgnum'} },
67 FS::cust_svc->new_or_cached($hashref, $subcache) if $hashref->{svcnum};
73 FS::cust_pkg - Object methods for cust_pkg objects
79 $record = new FS::cust_pkg \%hash;
80 $record = new FS::cust_pkg { 'column' => 'value' };
82 $error = $record->insert;
84 $error = $new_record->replace($old_record);
86 $error = $record->delete;
88 $error = $record->check;
90 $error = $record->cancel;
92 $error = $record->suspend;
94 $error = $record->unsuspend;
96 $part_pkg = $record->part_pkg;
98 @labels = $record->labels;
100 $seconds = $record->seconds_since($timestamp);
102 $error = FS::cust_pkg::order( $custnum, \@pkgparts );
103 $error = FS::cust_pkg::order( $custnum, \@pkgparts, \@remove_pkgnums ] );
107 An FS::cust_pkg object represents a customer billing item. FS::cust_pkg
108 inherits from FS::Record. The following fields are currently supported:
114 Primary key (assigned automatically for new billing items)
118 Customer (see L<FS::cust_main>)
122 Billing item definition (see L<FS::part_pkg>)
126 Optional link to package location (see L<FS::location>)
130 date package was ordered (also remains same on changes)
142 date (next bill date)
170 order taker (see L<FS::access_user>)
174 If this field is set to 1, disables the automatic
175 unsuspension of this package when using the B<unsuspendauto> config option.
179 If not set, defaults to 1
183 Date of change from previous package
193 =item change_locationnum
199 Note: setup, last_bill, bill, adjourn, susp, expire, cancel and change_date
200 are specified as UNIX timestamps; see L<perlfunc/"time">. Also see
201 L<Time::Local> and L<Date::Parse> for conversion functions.
209 Create a new billing item. To add the item to the database, see L<"insert">.
213 sub table { 'cust_pkg'; }
214 sub cust_linked { $_[0]->cust_main_custnum; }
215 sub cust_unlinked_msg {
217 "WARNING: can't find cust_main.custnum ". $self->custnum.
218 ' (cust_pkg.pkgnum '. $self->pkgnum. ')';
221 =item insert [ OPTION => VALUE ... ]
223 Adds this billing item to the database ("Orders" the item). If there is an
224 error, returns the error, otherwise returns false.
226 If the additional field I<promo_code> is defined instead of I<pkgpart>, it
227 will be used to look up the package definition and agent restrictions will be
230 If the additional field I<refnum> is defined, an FS::pkg_referral record will
231 be created and inserted. Multiple FS::pkg_referral records can be created by
232 setting I<refnum> to an array reference of refnums or a hash reference with
233 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
234 record will be created corresponding to cust_main.refnum.
236 The following options are available:
242 If set true, supresses any referral credit to a referring customer.
246 cust_pkg_option records will be created
250 a ticket will be added to this customer with this subject
254 an optional queue name for ticket additions
261 my( $self, %options ) = @_;
263 if ( $self->part_pkg->option('start_1st', 1) && !$self->start_date ) {
264 my ($sec,$min,$hour,$mday,$mon,$year) = (localtime(time) )[0,1,2,3,4,5];
265 $mon += 1 unless $mday == 1;
266 until ( $mon < 12 ) { $mon -= 12; $year++; }
267 $self->start_date( timelocal_nocheck(0,0,0,1,$mon,$year) );
270 foreach my $action ( qw(expire adjourn contract_end) ) {
271 my $months = $self->part_pkg->option("${action}_months",1);
272 if($months and !$self->$action) {
273 my $start = $self->start_date || $self->setup || time;
274 $self->$action( $self->part_pkg->add_freq($start, $months) );
278 $self->order_date(time);
280 local $SIG{HUP} = 'IGNORE';
281 local $SIG{INT} = 'IGNORE';
282 local $SIG{QUIT} = 'IGNORE';
283 local $SIG{TERM} = 'IGNORE';
284 local $SIG{TSTP} = 'IGNORE';
285 local $SIG{PIPE} = 'IGNORE';
287 my $oldAutoCommit = $FS::UID::AutoCommit;
288 local $FS::UID::AutoCommit = 0;
291 my $error = $self->SUPER::insert($options{options} ? %{$options{options}} : ());
293 $dbh->rollback if $oldAutoCommit;
297 $self->refnum($self->cust_main->refnum) unless $self->refnum;
298 $self->refnum( [ $self->refnum ] ) unless ref($self->refnum);
299 $self->process_m2m( 'link_table' => 'pkg_referral',
300 'target_table' => 'part_referral',
301 'params' => $self->refnum,
304 if ( $self->discountnum ) {
305 my $error = $self->insert_discount();
307 $dbh->rollback if $oldAutoCommit;
312 #if ( $self->reg_code ) {
313 # my $reg_code = qsearchs('reg_code', { 'code' => $self->reg_code } );
314 # $error = $reg_code->delete;
316 # $dbh->rollback if $oldAutoCommit;
321 my $conf = new FS::Conf;
323 if ( $conf->config('ticket_system') && $options{ticket_subject} ) {
326 # use lib ( "/opt/rt3/local/lib", "/opt/rt3/lib" );
333 use FS::TicketSystem;
334 FS::TicketSystem->init();
336 my $q = new RT::Queue($RT::SystemUser);
337 $q->Load($options{ticket_queue}) if $options{ticket_queue};
338 my $t = new RT::Ticket($RT::SystemUser);
339 my $mime = new MIME::Entity;
340 $mime->build( Type => 'text/plain', Data => $options{ticket_subject} );
341 $t->Create( $options{ticket_queue} ? (Queue => $q) : (),
342 Subject => $options{ticket_subject},
345 $t->AddLink( Type => 'MemberOf',
346 Target => 'freeside://freeside/cust_main/'. $self->custnum,
350 if ($conf->config('welcome_letter') && $self->cust_main->num_pkgs == 1) {
351 my $queue = new FS::queue {
352 'job' => 'FS::cust_main::queueable_print',
354 $error = $queue->insert(
355 'custnum' => $self->custnum,
356 'template' => 'welcome_letter',
360 warn "can't send welcome letter: $error";
365 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
372 This method now works but you probably shouldn't use it.
374 You don't want to delete billing items, because there would then be no record
375 the customer ever purchased the item. Instead, see the cancel method.
380 # return "Can't delete cust_pkg records!";
383 =item replace [ OLD_RECORD ] [ HASHREF | OPTION => VALUE ... ]
385 Replaces the OLD_RECORD with this one in the database. If there is an error,
386 returns the error, otherwise returns false.
388 Currently, custnum, setup, bill, adjourn, susp, expire, and cancel may be changed.
390 Changing pkgpart may have disasterous effects. See the order subroutine.
392 setup and bill are normally updated by calling the bill method of a customer
393 object (see L<FS::cust_main>).
395 suspend is normally updated by the suspend and unsuspend methods.
397 cancel is normally updated by the cancel method (and also the order subroutine
400 Available options are:
406 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.
410 the access_user (see L<FS::access_user>) providing the reason
414 hashref of keys and values - cust_pkg_option records will be created, updated or removed as appopriate
423 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
428 ( ref($_[0]) eq 'HASH' )
432 #return "Can't (yet?) change pkgpart!" if $old->pkgpart != $new->pkgpart;
433 #return "Can't change otaker!" if $old->otaker ne $new->otaker;
436 #return "Can't change setup once it exists!"
437 # if $old->getfield('setup') &&
438 # $old->getfield('setup') != $new->getfield('setup');
440 #some logic for bill, susp, cancel?
442 local($disable_agentcheck) = 1 if $old->pkgpart == $new->pkgpart;
444 local $SIG{HUP} = 'IGNORE';
445 local $SIG{INT} = 'IGNORE';
446 local $SIG{QUIT} = 'IGNORE';
447 local $SIG{TERM} = 'IGNORE';
448 local $SIG{TSTP} = 'IGNORE';
449 local $SIG{PIPE} = 'IGNORE';
451 my $oldAutoCommit = $FS::UID::AutoCommit;
452 local $FS::UID::AutoCommit = 0;
455 foreach my $method ( qw(adjourn expire) ) { # How many reasons?
456 if ($options->{'reason'} && $new->$method && $old->$method ne $new->$method) {
457 my $error = $new->insert_reason(
458 'reason' => $options->{'reason'},
459 'date' => $new->$method,
461 'reason_otaker' => $options->{'reason_otaker'},
464 dbh->rollback if $oldAutoCommit;
465 return "Error inserting cust_pkg_reason: $error";
470 #save off and freeze RADIUS attributes for any associated svc_acct records
472 if ( $old->part_pkg->is_prepaid || $new->part_pkg->is_prepaid ) {
474 #also check for specific exports?
475 # to avoid spurious modify export events
476 @svc_acct = map { $_->svc_x }
477 grep { $_->part_svc->svcdb eq 'svc_acct' }
480 $_->snapshot foreach @svc_acct;
484 my $error = $new->SUPER::replace($old,
485 $options->{options} ? $options->{options} : ()
488 $dbh->rollback if $oldAutoCommit;
492 #for prepaid packages,
493 #trigger export of new RADIUS Expiration attribute when cust_pkg.bill changes
494 foreach my $old_svc_acct ( @svc_acct ) {
495 my $new_svc_acct = new FS::svc_acct { $old_svc_acct->hash };
496 my $s_error = $new_svc_acct->replace($old_svc_acct);
498 $dbh->rollback if $oldAutoCommit;
503 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
510 Checks all fields to make sure this is a valid billing item. If there is an
511 error, returns the error, otherwise returns false. Called by the insert and
519 $self->locationnum('') if !$self->locationnum || $self->locationnum == -1;
522 $self->ut_numbern('pkgnum')
523 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum')
524 || $self->ut_numbern('pkgpart')
525 || $self->ut_foreign_keyn('locationnum', 'cust_location', 'locationnum')
526 || $self->ut_numbern('start_date')
527 || $self->ut_numbern('setup')
528 || $self->ut_numbern('bill')
529 || $self->ut_numbern('susp')
530 || $self->ut_numbern('cancel')
531 || $self->ut_numbern('adjourn')
532 || $self->ut_numbern('expire')
533 || $self->ut_enum('no_auto', [ '', 'Y' ])
535 return $error if $error;
537 if ( $self->reg_code ) {
539 unless ( grep { $self->pkgpart == $_->pkgpart }
540 map { $_->reg_code_pkg }
541 qsearchs( 'reg_code', { 'code' => $self->reg_code,
542 'agentnum' => $self->cust_main->agentnum })
544 return "Unknown registration code";
547 } elsif ( $self->promo_code ) {
550 qsearchs('part_pkg', {
551 'pkgpart' => $self->pkgpart,
552 'promo_code' => { op=>'ILIKE', value=>$self->promo_code },
554 return 'Unknown promotional code' unless $promo_part_pkg;
558 unless ( $disable_agentcheck ) {
560 qsearchs( 'agent', { 'agentnum' => $self->cust_main->agentnum } );
561 return "agent ". $agent->agentnum. ':'. $agent->agent.
562 " can't purchase pkgpart ". $self->pkgpart
563 unless $agent->pkgpart_hashref->{ $self->pkgpart }
564 || $agent->agentnum == $self->part_pkg->agentnum;
567 $error = $self->ut_foreign_key('pkgpart', 'part_pkg', 'pkgpart' );
568 return $error if $error;
572 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
574 if ( $self->dbdef_table->column('manual_flag') ) {
575 $self->manual_flag('') if $self->manual_flag eq ' ';
576 $self->manual_flag =~ /^([01]?)$/
577 or return "Illegal manual_flag ". $self->manual_flag;
578 $self->manual_flag($1);
584 =item cancel [ OPTION => VALUE ... ]
586 Cancels and removes all services (see L<FS::cust_svc> and L<FS::part_svc>)
587 in this package, then cancels the package itself (sets the cancel field to
590 Available options are:
594 =item quiet - can be set true to supress email cancellation notices.
596 =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.
598 =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.
600 =item date - can be set to a unix style timestamp to specify when to cancel (expire)
602 =item nobill - can be set true to skip billing if it might otherwise be done.
604 =item unused_credit - can be set to 1 to credit the remaining time, or 0 to
605 not credit it. This must be set (by change()) when changing the package
606 to a different pkgpart or location, and probably shouldn't be in any other
607 case. If it's not set, the 'unused_credit_cancel' part_pkg option will
612 If there is an error, returns the error, otherwise returns false.
617 my( $self, %options ) = @_;
620 my $conf = new FS::Conf;
622 warn "cust_pkg::cancel called with options".
623 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
626 local $SIG{HUP} = 'IGNORE';
627 local $SIG{INT} = 'IGNORE';
628 local $SIG{QUIT} = 'IGNORE';
629 local $SIG{TERM} = 'IGNORE';
630 local $SIG{TSTP} = 'IGNORE';
631 local $SIG{PIPE} = 'IGNORE';
633 my $oldAutoCommit = $FS::UID::AutoCommit;
634 local $FS::UID::AutoCommit = 0;
637 my $old = $self->select_for_update;
639 if ( $old->get('cancel') || $self->get('cancel') ) {
640 dbh->rollback if $oldAutoCommit;
641 return ""; # no error
644 my $date = $options{date} if $options{date}; # expire/cancel later
645 $date = '' if ($date && $date <= time); # complain instead?
647 #race condition: usage could be ongoing until unprovisioned
648 #resolved by performing a change package instead (which unprovisions) and
650 if ( !$options{nobill} && !$date && $conf->exists('bill_usage_on_cancel') ) {
651 my $copy = $self->new({$self->hash});
653 $copy->cust_main->bill( pkg_list => [ $copy ], cancel => 1 );
654 warn "Error billing during cancel, custnum ".
655 #$self->cust_main->custnum. ": $error"
660 my $cancel_time = $options{'time'} || time;
662 if ( $options{'reason'} ) {
663 $error = $self->insert_reason( 'reason' => $options{'reason'},
664 'action' => $date ? 'expire' : 'cancel',
665 'date' => $date ? $date : $cancel_time,
666 'reason_otaker' => $options{'reason_otaker'},
669 dbh->rollback if $oldAutoCommit;
670 return "Error inserting cust_pkg_reason: $error";
677 foreach my $cust_svc (
680 sort { $a->[1] <=> $b->[1] }
681 map { [ $_, $_->svc_x->table_info->{'cancel_weight'} ]; }
682 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
684 my $error = $cust_svc->cancel( ('date' => $date) );
687 $dbh->rollback if $oldAutoCommit;
688 return "Error expiring cust_svc: $error";
692 foreach my $cust_svc (
695 sort { $a->[1] <=> $b->[1] }
696 map { [ $_, $_->svc_x->table_info->{'cancel_weight'} ]; }
697 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
699 my $error = $cust_svc->cancel;
702 $dbh->rollback if $oldAutoCommit;
703 return "Error cancelling cust_svc: $error";
708 # Add a credit for remaining service
709 my $last_bill = $self->getfield('last_bill') || 0;
710 my $next_bill = $self->getfield('bill') || 0;
712 if ( exists($options{'unused_credit'}) ) {
713 $do_credit = $options{'unused_credit'};
716 $do_credit = $self->part_pkg->option('unused_credit_cancel', 1);
719 and $last_bill > 0 # the package has been billed
720 and $next_bill > 0 # the package has a next bill date
721 and $next_bill >= $cancel_time # which is in the future
723 my $remaining_value = $self->calc_remain('time' => $cancel_time);
724 if ( $remaining_value > 0 ) {
725 # && !$options{'no_credit'} ) {
726 # Undocumented, unused option.
727 # part_pkg configuration should decide this anyway.
728 my $error = $self->cust_main->credit(
730 'Credit for unused time on '. $self->part_pkg->pkg,
731 'reason_type' => $conf->config('cancel_credit_type'),
734 $dbh->rollback if $oldAutoCommit;
735 return "Error crediting customer \$$remaining_value for unused time on".
736 $self->part_pkg->pkg. ": $error";
738 } #if $remaining_value
741 my %hash = $self->hash;
742 $date ? ($hash{'expire'} = $date) : ($hash{'cancel'} = $cancel_time);
743 my $new = new FS::cust_pkg ( \%hash );
744 $error = $new->replace( $self, options => { $self->options } );
746 $dbh->rollback if $oldAutoCommit;
750 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
751 return '' if $date; #no errors
753 my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ } $self->cust_main->invoicing_list;
754 if ( !$options{'quiet'} &&
755 $conf->exists('emailcancel', $self->cust_main->agentnum) &&
757 my $msgnum = $conf->config('cancel_msgnum', $self->cust_main->agentnum);
760 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum });
761 $error = $msg_template->send( 'cust_main' => $self->cust_main,
766 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
767 'to' => \@invoicing_list,
768 'subject' => ( $conf->config('cancelsubject') || 'Cancellation Notice' ),
769 'body' => [ map "$_\n", $conf->config('cancelmessage') ],
772 #should this do something on errors?
779 =item cancel_if_expired [ NOW_TIMESTAMP ]
781 Cancels this package if its expire date has been reached.
785 sub cancel_if_expired {
787 my $time = shift || time;
788 return '' unless $self->expire && $self->expire <= $time;
789 my $error = $self->cancel;
791 return "Error cancelling expired pkg ". $self->pkgnum. " for custnum ".
792 $self->custnum. ": $error";
799 Cancels any pending expiration (sets the expire field to null).
801 If there is an error, returns the error, otherwise returns false.
806 my( $self, %options ) = @_;
809 local $SIG{HUP} = 'IGNORE';
810 local $SIG{INT} = 'IGNORE';
811 local $SIG{QUIT} = 'IGNORE';
812 local $SIG{TERM} = 'IGNORE';
813 local $SIG{TSTP} = 'IGNORE';
814 local $SIG{PIPE} = 'IGNORE';
816 my $oldAutoCommit = $FS::UID::AutoCommit;
817 local $FS::UID::AutoCommit = 0;
820 my $old = $self->select_for_update;
822 my $pkgnum = $old->pkgnum;
823 if ( $old->get('cancel') || $self->get('cancel') ) {
824 dbh->rollback if $oldAutoCommit;
825 return "Can't unexpire cancelled package $pkgnum";
826 # or at least it's pointless
829 unless ( $old->get('expire') && $self->get('expire') ) {
830 dbh->rollback if $oldAutoCommit;
831 return ""; # no error
834 my %hash = $self->hash;
835 $hash{'expire'} = '';
836 my $new = new FS::cust_pkg ( \%hash );
837 $error = $new->replace( $self, options => { $self->options } );
839 $dbh->rollback if $oldAutoCommit;
843 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
849 =item suspend [ OPTION => VALUE ... ]
851 Suspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
852 package, then suspends the package itself (sets the susp field to now).
854 Available options are:
858 =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.
860 =item date - can be set to a unix style timestamp to specify when to suspend (adjourn)
864 If there is an error, returns the error, otherwise returns false.
869 my( $self, %options ) = @_;
872 local $SIG{HUP} = 'IGNORE';
873 local $SIG{INT} = 'IGNORE';
874 local $SIG{QUIT} = 'IGNORE';
875 local $SIG{TERM} = 'IGNORE';
876 local $SIG{TSTP} = 'IGNORE';
877 local $SIG{PIPE} = 'IGNORE';
879 my $oldAutoCommit = $FS::UID::AutoCommit;
880 local $FS::UID::AutoCommit = 0;
883 my $old = $self->select_for_update;
885 my $pkgnum = $old->pkgnum;
886 if ( $old->get('cancel') || $self->get('cancel') ) {
887 dbh->rollback if $oldAutoCommit;
888 return "Can't suspend cancelled package $pkgnum";
891 if ( $old->get('susp') || $self->get('susp') ) {
892 dbh->rollback if $oldAutoCommit;
893 return ""; # no error # complain on adjourn?
896 my $date = $options{date} if $options{date}; # adjourn/suspend later
897 $date = '' if ($date && $date <= time); # complain instead?
899 if ( $date && $old->get('expire') && $old->get('expire') < $date ) {
900 dbh->rollback if $oldAutoCommit;
901 return "Package $pkgnum expires before it would be suspended.";
904 my $suspend_time = $options{'time'} || time;
906 if ( $options{'reason'} ) {
907 $error = $self->insert_reason( 'reason' => $options{'reason'},
908 'action' => $date ? 'adjourn' : 'suspend',
909 'date' => $date ? $date : $suspend_time,
910 'reason_otaker' => $options{'reason_otaker'},
913 dbh->rollback if $oldAutoCommit;
914 return "Error inserting cust_pkg_reason: $error";
922 foreach my $cust_svc (
923 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
925 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
927 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
928 $dbh->rollback if $oldAutoCommit;
929 return "Illegal svcdb value in part_svc!";
932 require "FS/$svcdb.pm";
934 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
936 $error = $svc->suspend;
938 $dbh->rollback if $oldAutoCommit;
941 my( $label, $value ) = $cust_svc->label;
942 push @labels, "$label: $value";
946 my $conf = new FS::Conf;
947 if ( $conf->config('suspend_email_admin') ) {
949 my $error = send_email(
950 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
951 #invoice_from ??? well as good as any
952 'to' => $conf->config('suspend_email_admin'),
953 'subject' => 'FREESIDE NOTIFICATION: Customer package suspended',
955 "This is an automatic message from your Freeside installation\n",
956 "informing you that the following customer package has been suspended:\n",
958 'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
959 'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
960 ( map { "Service : $_\n" } @labels ),
965 warn "WARNING: can't send suspension admin email (suspending anyway): ".
973 my %hash = $self->hash;
975 $hash{'adjourn'} = $date;
977 $hash{'susp'} = $suspend_time;
979 my $new = new FS::cust_pkg ( \%hash );
980 $error = $new->replace( $self, options => { $self->options } );
982 $dbh->rollback if $oldAutoCommit;
986 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
991 =item unsuspend [ OPTION => VALUE ... ]
993 Unsuspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
994 package, then unsuspends the package itself (clears the susp field and the
995 adjourn field if it is in the past).
997 Available options are:
1001 =item adjust_next_bill
1003 Can be set true to adjust the next bill date forward by
1004 the amount of time the account was inactive. This was set true by default
1005 since 1.4.2 and 1.5.0pre6; however, starting with 1.7.0 this needs to be
1006 explicitly requested. Price plans for which this makes sense (anniversary-date
1007 based than prorate or subscription) could have an option to enable this
1012 If there is an error, returns the error, otherwise returns false.
1017 my( $self, %opt ) = @_;
1020 local $SIG{HUP} = 'IGNORE';
1021 local $SIG{INT} = 'IGNORE';
1022 local $SIG{QUIT} = 'IGNORE';
1023 local $SIG{TERM} = 'IGNORE';
1024 local $SIG{TSTP} = 'IGNORE';
1025 local $SIG{PIPE} = 'IGNORE';
1027 my $oldAutoCommit = $FS::UID::AutoCommit;
1028 local $FS::UID::AutoCommit = 0;
1031 my $old = $self->select_for_update;
1033 my $pkgnum = $old->pkgnum;
1034 if ( $old->get('cancel') || $self->get('cancel') ) {
1035 dbh->rollback if $oldAutoCommit;
1036 return "Can't unsuspend cancelled package $pkgnum";
1039 unless ( $old->get('susp') && $self->get('susp') ) {
1040 dbh->rollback if $oldAutoCommit;
1041 return ""; # no error # complain instead?
1044 foreach my $cust_svc (
1045 qsearch('cust_svc',{'pkgnum'=> $self->pkgnum } )
1047 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
1049 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
1050 $dbh->rollback if $oldAutoCommit;
1051 return "Illegal svcdb value in part_svc!";
1054 require "FS/$svcdb.pm";
1056 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
1058 $error = $svc->unsuspend;
1060 $dbh->rollback if $oldAutoCommit;
1067 my %hash = $self->hash;
1068 my $inactive = time - $hash{'susp'};
1070 my $conf = new FS::Conf;
1072 if ( $inactive > 0 &&
1073 ( $hash{'bill'} || $hash{'setup'} ) &&
1074 ( $opt{'adjust_next_bill'} ||
1075 $conf->exists('unsuspend-always_adjust_next_bill_date') ||
1076 $self->part_pkg->option('unsuspend_adjust_bill', 1) )
1079 $hash{'bill'} = ( $hash{'bill'} || $hash{'setup'} ) + $inactive;
1084 $hash{'adjourn'} = '' if $hash{'adjourn'} < time;
1085 my $new = new FS::cust_pkg ( \%hash );
1086 $error = $new->replace( $self, options => { $self->options } );
1088 $dbh->rollback if $oldAutoCommit;
1092 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1099 Cancels any pending suspension (sets the adjourn field to null).
1101 If there is an error, returns the error, otherwise returns false.
1106 my( $self, %options ) = @_;
1109 local $SIG{HUP} = 'IGNORE';
1110 local $SIG{INT} = 'IGNORE';
1111 local $SIG{QUIT} = 'IGNORE';
1112 local $SIG{TERM} = 'IGNORE';
1113 local $SIG{TSTP} = 'IGNORE';
1114 local $SIG{PIPE} = 'IGNORE';
1116 my $oldAutoCommit = $FS::UID::AutoCommit;
1117 local $FS::UID::AutoCommit = 0;
1120 my $old = $self->select_for_update;
1122 my $pkgnum = $old->pkgnum;
1123 if ( $old->get('cancel') || $self->get('cancel') ) {
1124 dbh->rollback if $oldAutoCommit;
1125 return "Can't unadjourn cancelled package $pkgnum";
1126 # or at least it's pointless
1129 if ( $old->get('susp') || $self->get('susp') ) {
1130 dbh->rollback if $oldAutoCommit;
1131 return "Can't unadjourn suspended package $pkgnum";
1132 # perhaps this is arbitrary
1135 unless ( $old->get('adjourn') && $self->get('adjourn') ) {
1136 dbh->rollback if $oldAutoCommit;
1137 return ""; # no error
1140 my %hash = $self->hash;
1141 $hash{'adjourn'} = '';
1142 my $new = new FS::cust_pkg ( \%hash );
1143 $error = $new->replace( $self, options => { $self->options } );
1145 $dbh->rollback if $oldAutoCommit;
1149 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1156 =item change HASHREF | OPTION => VALUE ...
1158 Changes this package: cancels it and creates a new one, with a different
1159 pkgpart or locationnum or both. All services are transferred to the new
1160 package (no change will be made if this is not possible).
1162 Options may be passed as a list of key/value pairs or as a hash reference.
1169 New locationnum, to change the location for this package.
1173 New FS::cust_location object, to create a new location and assign it
1178 New pkgpart (see L<FS::part_pkg>).
1182 New refnum (see L<FS::part_referral>).
1186 Set to true to transfer billing dates (start_date, setup, last_bill, bill,
1187 susp, adjourn, cancel, expire, and contract_end) to the new package.
1191 At least one of locationnum, cust_location, pkgpart, refnum must be specified
1192 (otherwise, what's the point?)
1194 Returns either the new FS::cust_pkg object or a scalar error.
1198 my $err_or_new_cust_pkg = $old_cust_pkg->change
1202 #some false laziness w/order
1205 my $opt = ref($_[0]) ? shift : { @_ };
1207 # my ($custnum, $pkgparts, $remove_pkgnum, $return_cust_pkg, $refnum) = @_;
1210 my $conf = new FS::Conf;
1212 # Transactionize this whole mess
1213 local $SIG{HUP} = 'IGNORE';
1214 local $SIG{INT} = 'IGNORE';
1215 local $SIG{QUIT} = 'IGNORE';
1216 local $SIG{TERM} = 'IGNORE';
1217 local $SIG{TSTP} = 'IGNORE';
1218 local $SIG{PIPE} = 'IGNORE';
1220 my $oldAutoCommit = $FS::UID::AutoCommit;
1221 local $FS::UID::AutoCommit = 0;
1230 #$hash{$_} = $self->$_() foreach qw( last_bill bill );
1232 #$hash{$_} = $self->$_() foreach qw( setup );
1234 $hash{'setup'} = $time if $self->setup;
1236 $hash{'change_date'} = $time;
1237 $hash{"change_$_"} = $self->$_()
1238 foreach qw( pkgnum pkgpart locationnum );
1240 if ( $opt->{'cust_location'} &&
1241 ( ! $opt->{'locationnum'} || $opt->{'locationnum'} == -1 ) ) {
1242 $error = $opt->{'cust_location'}->insert;
1244 $dbh->rollback if $oldAutoCommit;
1245 return "inserting cust_location (transaction rolled back): $error";
1247 $opt->{'locationnum'} = $opt->{'cust_location'}->locationnum;
1250 my $unused_credit = 0;
1251 if ( $opt->{'keep_dates'} ) {
1252 foreach my $date ( qw(setup bill last_bill susp adjourn cancel expire
1253 start_date contract_end ) ) {
1254 $hash{$date} = $self->getfield($date);
1257 # Special case. If the pkgpart is changing, and the customer is
1258 # going to be credited for remaining time, don't keep setup, bill,
1259 # or last_bill dates, and DO pass the flag to cancel() to credit
1261 if ( $opt->{'pkgpart'}
1262 and $opt->{'pkgpart'} != $self->pkgpart
1263 and $self->part_pkg->option('unused_credit_change', 1) ) {
1265 $hash{$_} = '' foreach qw(setup bill last_bill);
1268 # Create the new package.
1269 my $cust_pkg = new FS::cust_pkg {
1270 custnum => $self->custnum,
1271 pkgpart => ( $opt->{'pkgpart'} || $self->pkgpart ),
1272 refnum => ( $opt->{'refnum'} || $self->refnum ),
1273 locationnum => ( $opt->{'locationnum'} || $self->locationnum ),
1277 $error = $cust_pkg->insert( 'change' => 1 );
1279 $dbh->rollback if $oldAutoCommit;
1283 # Transfer services and cancel old package.
1285 $error = $self->transfer($cust_pkg);
1286 if ($error and $error == 0) {
1287 # $old_pkg->transfer failed.
1288 $dbh->rollback if $oldAutoCommit;
1292 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
1293 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
1294 $error = $self->transfer($cust_pkg, 'change_svcpart'=>1 );
1295 if ($error and $error == 0) {
1296 # $old_pkg->transfer failed.
1297 $dbh->rollback if $oldAutoCommit;
1303 # Transfers were successful, but we still had services left on the old
1304 # package. We can't change the package under this circumstances, so abort.
1305 $dbh->rollback if $oldAutoCommit;
1306 return "Unable to transfer all services from package ". $self->pkgnum;
1309 #reset usage if changing pkgpart
1310 # AND usage rollover is off (otherwise adds twice, now and at package bill)
1311 if ($self->pkgpart != $cust_pkg->pkgpart) {
1312 my $part_pkg = $cust_pkg->part_pkg;
1313 $error = $part_pkg->reset_usage($cust_pkg, $part_pkg->is_prepaid
1317 if $part_pkg->can('reset_usage') && ! $part_pkg->option('usage_rollover',1);
1320 $dbh->rollback if $oldAutoCommit;
1321 return "Error setting usage values: $error";
1325 #Good to go, cancel old package. Notify 'cancel' of whether to credit
1327 $error = $self->cancel( quiet=>1, unused_credit => $unused_credit );
1329 $dbh->rollback if $oldAutoCommit;
1333 if ( $conf->exists('cust_pkg-change_pkgpart-bill_now') ) {
1335 my $error = $cust_pkg->cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1337 $dbh->rollback if $oldAutoCommit;
1342 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1349 use Storable 'thaw';
1351 sub process_bulk_cust_pkg {
1353 my $param = thaw(decode_base64(shift));
1354 warn Dumper($param) if $DEBUG;
1356 my $old_part_pkg = qsearchs('part_pkg',
1357 { pkgpart => $param->{'old_pkgpart'} });
1358 my $new_part_pkg = qsearchs('part_pkg',
1359 { pkgpart => $param->{'new_pkgpart'} });
1360 die "Must select a new package type\n" unless $new_part_pkg;
1361 #my $keep_dates = $param->{'keep_dates'} || 0;
1362 my $keep_dates = 1; # there is no good reason to turn this off
1364 local $SIG{HUP} = 'IGNORE';
1365 local $SIG{INT} = 'IGNORE';
1366 local $SIG{QUIT} = 'IGNORE';
1367 local $SIG{TERM} = 'IGNORE';
1368 local $SIG{TSTP} = 'IGNORE';
1369 local $SIG{PIPE} = 'IGNORE';
1371 my $oldAutoCommit = $FS::UID::AutoCommit;
1372 local $FS::UID::AutoCommit = 0;
1375 my @cust_pkgs = qsearch('cust_pkg', { 'pkgpart' => $param->{'old_pkgpart'} } );
1378 foreach my $old_cust_pkg ( @cust_pkgs ) {
1380 $job->update_statustext(int(100*$i/(scalar @cust_pkgs)));
1381 if ( $old_cust_pkg->getfield('cancel') ) {
1382 warn '[process_bulk_cust_pkg ] skipping canceled pkgnum '.
1383 $old_cust_pkg->pkgnum."\n"
1387 warn '[process_bulk_cust_pkg] changing pkgnum '.$old_cust_pkg->pkgnum."\n"
1389 my $error = $old_cust_pkg->change(
1390 'pkgpart' => $param->{'new_pkgpart'},
1391 'keep_dates' => $keep_dates
1393 if ( !ref($error) ) { # change returns the cust_pkg on success
1395 die "Error changing pkgnum ".$old_cust_pkg->pkgnum.": '$error'\n";
1398 $dbh->commit if $oldAutoCommit;
1404 Returns the last bill date, or if there is no last bill date, the setup date.
1405 Useful for billing metered services.
1411 return $self->setfield('last_bill', $_[0]) if @_;
1412 return $self->getfield('last_bill') if $self->getfield('last_bill');
1413 my $cust_bill_pkg = qsearchs('cust_bill_pkg', { 'pkgnum' => $self->pkgnum,
1414 'edate' => $self->bill, } );
1415 $cust_bill_pkg ? $cust_bill_pkg->sdate : $self->setup || 0;
1418 =item last_cust_pkg_reason ACTION
1420 Returns the most recent ACTION FS::cust_pkg_reason associated with the package.
1421 Returns false if there is no reason or the package is not currenly ACTION'd
1422 ACTION is one of adjourn, susp, cancel, or expire.
1426 sub last_cust_pkg_reason {
1427 my ( $self, $action ) = ( shift, shift );
1428 my $date = $self->get($action);
1430 'table' => 'cust_pkg_reason',
1431 'hashref' => { 'pkgnum' => $self->pkgnum,
1432 'action' => substr(uc($action), 0, 1),
1435 'order_by' => 'ORDER BY num DESC LIMIT 1',
1439 =item last_reason ACTION
1441 Returns the most recent ACTION FS::reason associated with the package.
1442 Returns false if there is no reason or the package is not currenly ACTION'd
1443 ACTION is one of adjourn, susp, cancel, or expire.
1448 my $cust_pkg_reason = shift->last_cust_pkg_reason(@_);
1449 $cust_pkg_reason->reason
1450 if $cust_pkg_reason;
1455 Returns the definition for this billing item, as an FS::part_pkg object (see
1462 return $self->{'_pkgpart'} if $self->{'_pkgpart'};
1463 cluck "cust_pkg->part_pkg called" if $DEBUG > 1;
1464 qsearchs( 'part_pkg', { 'pkgpart' => $self->pkgpart } );
1469 Returns the cancelled package this package was changed from, if any.
1475 return '' unless $self->change_pkgnum;
1476 qsearchs('cust_pkg', { 'pkgnum' => $self->change_pkgnum } );
1481 Calls the I<calc_setup> of the FS::part_pkg object associated with this billing
1488 $self->part_pkg->calc_setup($self, @_);
1493 Calls the I<calc_recur> of the FS::part_pkg object associated with this billing
1500 $self->part_pkg->calc_recur($self, @_);
1505 Calls the I<base_recur> of the FS::part_pkg object associated with this billing
1512 $self->part_pkg->base_recur($self, @_);
1517 Calls the I<calc_remain> of the FS::part_pkg object associated with this
1524 $self->part_pkg->calc_remain($self, @_);
1529 Calls the I<calc_cancel> of the FS::part_pkg object associated with this
1536 $self->part_pkg->calc_cancel($self, @_);
1541 Returns any invoice line items for this package (see L<FS::cust_bill_pkg>).
1547 qsearch( 'cust_bill_pkg', { 'pkgnum' => $self->pkgnum } );
1550 =item cust_pkg_detail [ DETAILTYPE ]
1552 Returns any customer package details for this package (see
1553 L<FS::cust_pkg_detail>).
1555 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
1559 sub cust_pkg_detail {
1561 my %hash = ( 'pkgnum' => $self->pkgnum );
1562 $hash{detailtype} = shift if @_;
1564 'table' => 'cust_pkg_detail',
1565 'hashref' => \%hash,
1566 'order_by' => 'ORDER BY weight, pkgdetailnum',
1570 =item set_cust_pkg_detail DETAILTYPE [ DETAIL, DETAIL, ... ]
1572 Sets customer package details for this package (see L<FS::cust_pkg_detail>).
1574 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
1576 If there is an error, returns the error, otherwise returns false.
1580 sub set_cust_pkg_detail {
1581 my( $self, $detailtype, @details ) = @_;
1583 local $SIG{HUP} = 'IGNORE';
1584 local $SIG{INT} = 'IGNORE';
1585 local $SIG{QUIT} = 'IGNORE';
1586 local $SIG{TERM} = 'IGNORE';
1587 local $SIG{TSTP} = 'IGNORE';
1588 local $SIG{PIPE} = 'IGNORE';
1590 my $oldAutoCommit = $FS::UID::AutoCommit;
1591 local $FS::UID::AutoCommit = 0;
1594 foreach my $current ( $self->cust_pkg_detail($detailtype) ) {
1595 my $error = $current->delete;
1597 $dbh->rollback if $oldAutoCommit;
1598 return "error removing old detail: $error";
1602 foreach my $detail ( @details ) {
1603 my $cust_pkg_detail = new FS::cust_pkg_detail {
1604 'pkgnum' => $self->pkgnum,
1605 'detailtype' => $detailtype,
1606 'detail' => $detail,
1608 my $error = $cust_pkg_detail->insert;
1610 $dbh->rollback if $oldAutoCommit;
1611 return "error adding new detail: $error";
1616 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1623 Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.
1627 #false laziness w/cust_bill.pm
1631 'table' => 'cust_event',
1632 'addl_from' => 'JOIN part_event USING ( eventpart )',
1633 'hashref' => { 'tablenum' => $self->pkgnum },
1634 'extra_sql' => " AND eventtable = 'cust_pkg' ",
1638 =item num_cust_event
1640 Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.
1644 #false laziness w/cust_bill.pm
1645 sub num_cust_event {
1648 "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
1649 " WHERE tablenum = ? AND eventtable = 'cust_pkg'";
1650 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
1651 $sth->execute($self->pkgnum) or die $sth->errstr. " executing $sql";
1652 $sth->fetchrow_arrayref->[0];
1655 =item cust_svc [ SVCPART ]
1657 Returns the services for this package, as FS::cust_svc objects (see
1658 L<FS::cust_svc>). If a svcpart is specified, return only the matching
1666 return () unless $self->num_cust_svc(@_);
1669 return qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum,
1670 'svcpart' => shift, } );
1673 cluck "cust_pkg->cust_svc called" if $DEBUG > 2;
1675 #if ( $self->{'_svcnum'} ) {
1676 # values %{ $self->{'_svcnum'}->cache };
1678 $self->_sort_cust_svc(
1679 [ qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } ) ]
1685 =item overlimit [ SVCPART ]
1687 Returns the services for this package which have exceeded their
1688 usage limit as FS::cust_svc objects (see L<FS::cust_svc>). If a svcpart
1689 is specified, return only the matching services.
1695 return () unless $self->num_cust_svc(@_);
1696 grep { $_->overlimit } $self->cust_svc(@_);
1699 =item h_cust_svc END_TIMESTAMP [ START_TIMESTAMP ] [ MODE ]
1701 Returns historical services for this package created before END TIMESTAMP and
1702 (optionally) not cancelled before START_TIMESTAMP, as FS::h_cust_svc objects
1703 (see L<FS::h_cust_svc>). If MODE is 'I' (for 'invoice'), services with the
1704 I<pkg_svc.hidden> flag will be omitted.
1710 my ($end, $start, $mode) = @_;
1711 my @cust_svc = $self->_sort_cust_svc(
1712 [ qsearch( 'h_cust_svc',
1713 { 'pkgnum' => $self->pkgnum, },
1714 FS::h_cust_svc->sql_h_search(@_),
1717 if ( $mode eq 'I' ) {
1718 my %hidden_svcpart = map { $_->svcpart => $_->hidden } $self->part_svc;
1719 return grep { !$hidden_svcpart{$_->svcpart} } @cust_svc;
1726 sub _sort_cust_svc {
1727 my( $self, $arrayref ) = @_;
1730 sub ($$) { my ($a, $b) = @_; $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] };
1735 my $pkg_svc = qsearchs( 'pkg_svc', { 'pkgpart' => $self->pkgpart,
1736 'svcpart' => $_->svcpart } );
1738 $pkg_svc ? $pkg_svc->primary_svc : '',
1739 $pkg_svc ? $pkg_svc->quantity : 0,
1746 =item num_cust_svc [ SVCPART ]
1748 Returns the number of provisioned services for this package. If a svcpart is
1749 specified, counts only the matching services.
1756 return $self->{'_num_cust_svc'}
1758 && exists($self->{'_num_cust_svc'})
1759 && $self->{'_num_cust_svc'} =~ /\d/;
1761 cluck "cust_pkg->num_cust_svc called, _num_cust_svc:".$self->{'_num_cust_svc'}
1764 my $sql = 'SELECT COUNT(*) FROM cust_svc WHERE pkgnum = ?';
1765 $sql .= ' AND svcpart = ?' if @_;
1767 my $sth = dbh->prepare($sql) or die dbh->errstr;
1768 $sth->execute($self->pkgnum, @_) or die $sth->errstr;
1769 $sth->fetchrow_arrayref->[0];
1772 =item available_part_svc
1774 Returns a list of FS::part_svc objects representing services included in this
1775 package but not yet provisioned. Each FS::part_svc object also has an extra
1776 field, I<num_avail>, which specifies the number of available services.
1780 sub available_part_svc {
1782 grep { $_->num_avail > 0 }
1784 my $part_svc = $_->part_svc;
1785 $part_svc->{'Hash'}{'num_avail'} = #evil encapsulation-breaking
1786 $_->quantity - $self->num_cust_svc($_->svcpart);
1788 # more evil encapsulation breakage
1789 if($part_svc->{'Hash'}{'num_avail'} > 0) {
1790 my @exports = $part_svc->part_export_did;
1791 $part_svc->{'Hash'}{'can_get_dids'} = scalar(@exports);
1796 $self->part_pkg->pkg_svc;
1801 Returns a list of FS::part_svc objects representing provisioned and available
1802 services included in this package. Each FS::part_svc object also has the
1803 following extra fields:
1807 =item num_cust_svc (count)
1809 =item num_avail (quantity - count)
1811 =item cust_pkg_svc (services) - array reference containing the provisioned services, as cust_svc objects
1814 label -> ($cust_svc->label)[1]
1823 #XXX some sort of sort order besides numeric by svcpart...
1824 my @part_svc = sort { $a->svcpart <=> $b->svcpart } map {
1826 my $part_svc = $pkg_svc->part_svc;
1827 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
1828 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #more evil
1829 $part_svc->{'Hash'}{'num_avail'} =
1830 max( 0, $pkg_svc->quantity - $num_cust_svc );
1831 $part_svc->{'Hash'}{'cust_pkg_svc'} =
1832 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : [];
1833 $part_svc->{'Hash'}{'hidden'} = $pkg_svc->hidden;
1835 } $self->part_pkg->pkg_svc;
1838 push @part_svc, map {
1840 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
1841 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #speak no evail
1842 $part_svc->{'Hash'}{'num_avail'} = 0; #0-$num_cust_svc ?
1843 $part_svc->{'Hash'}{'cust_pkg_svc'} =
1844 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : [];
1846 } $self->extra_part_svc;
1852 =item extra_part_svc
1854 Returns a list of FS::part_svc objects corresponding to services in this
1855 package which are still provisioned but not (any longer) available in the
1860 sub extra_part_svc {
1863 my $pkgnum = $self->pkgnum;
1864 my $pkgpart = $self->pkgpart;
1867 # 'table' => 'part_svc',
1870 # "WHERE 0 = ( SELECT COUNT(*) FROM pkg_svc
1871 # WHERE pkg_svc.svcpart = part_svc.svcpart
1872 # AND pkg_svc.pkgpart = ?
1875 # AND 0 < ( SELECT COUNT(*) FROM cust_svc
1876 # LEFT JOIN cust_pkg USING ( pkgnum )
1877 # WHERE cust_svc.svcpart = part_svc.svcpart
1880 # 'extra_param' => [ [$self->pkgpart=>'int'], [$self->pkgnum=>'int'] ],
1883 #seems to benchmark slightly faster...
1885 #'select' => 'DISTINCT ON (svcpart) part_svc.*',
1886 #MySQL doesn't grok DISINCT ON
1887 'select' => 'DISTINCT part_svc.*',
1888 'table' => 'part_svc',
1890 'LEFT JOIN pkg_svc ON ( pkg_svc.svcpart = part_svc.svcpart
1891 AND pkg_svc.pkgpart = ?
1894 LEFT JOIN cust_svc ON ( cust_svc.svcpart = part_svc.svcpart )
1895 LEFT JOIN cust_pkg USING ( pkgnum )
1898 'extra_sql' => "WHERE pkgsvcnum IS NULL AND cust_pkg.pkgnum = ? ",
1899 'extra_param' => [ [$self->pkgpart=>'int'], [$self->pkgnum=>'int'] ],
1905 Returns a short status string for this package, currently:
1909 =item not yet billed
1911 =item one-time charge
1926 my $freq = length($self->freq) ? $self->freq : $self->part_pkg->freq;
1928 return 'cancelled' if $self->get('cancel');
1929 return 'suspended' if $self->susp;
1930 return 'not yet billed' unless $self->setup;
1931 return 'one-time charge' if $freq =~ /^(0|$)/;
1935 =item ucfirst_status
1937 Returns the status with the first character capitalized.
1941 sub ucfirst_status {
1942 ucfirst(shift->status);
1947 Class method that returns the list of possible status strings for packages
1948 (see L<the status method|/status>). For example:
1950 @statuses = FS::cust_pkg->statuses();
1954 tie my %statuscolor, 'Tie::IxHash',
1955 'not yet billed' => '009999', #teal? cyan?
1956 'one-time charge' => '000000',
1957 'active' => '00CC00',
1958 'suspended' => 'FF9900',
1959 'cancelled' => 'FF0000',
1963 my $self = shift; #could be class...
1964 #grep { $_ !~ /^(not yet billed)$/ } #this is a dumb status anyway
1965 # # mayble split btw one-time vs. recur
1971 Returns a hex triplet color string for this package's status.
1977 $statuscolor{$self->status};
1982 Returns a label for this package. (Currently "pkgnum: pkg - comment" or
1983 "pkg-comment" depending on user preference).
1989 my $label = $self->part_pkg->pkg_comment( 'nopkgpart' => 1 );
1990 $label = $self->pkgnum. ": $label"
1991 if $FS::CurrentUser::CurrentUser->option('show_pkgnum');
1995 =item pkg_label_long
1997 Returns a long label for this package, adding the primary service's label to
2002 sub pkg_label_long {
2004 my $label = $self->pkg_label;
2005 my $cust_svc = $self->primary_cust_svc;
2006 $label .= ' ('. ($cust_svc->label)[1]. ')' if $cust_svc;
2010 =item primary_cust_svc
2012 Returns a primary service (as FS::cust_svc object) if one can be identified.
2016 #for labeling purposes - might not 100% match up with part_pkg->svcpart's idea
2018 sub primary_cust_svc {
2021 my @cust_svc = $self->cust_svc;
2023 return '' unless @cust_svc; #no serivces - irrelevant then
2025 return $cust_svc[0] if scalar(@cust_svc) == 1; #always return a single service
2027 # primary service as specified in the package definition
2028 # or exactly one service definition with quantity one
2029 my $svcpart = $self->part_pkg->svcpart;
2030 @cust_svc = grep { $_->svcpart == $svcpart } @cust_svc;
2031 return $cust_svc[0] if scalar(@cust_svc) == 1;
2033 #couldn't identify one thing..
2039 Returns a list of lists, calling the label method for all services
2040 (see L<FS::cust_svc>) of this billing item.
2046 map { [ $_->label ] } $self->cust_svc;
2049 =item h_labels END_TIMESTAMP [ START_TIMESTAMP ] [ MODE ]
2051 Like the labels method, but returns historical information on services that
2052 were active as of END_TIMESTAMP and (optionally) not cancelled before
2053 START_TIMESTAMP. If MODE is 'I' (for 'invoice'), services with the
2054 I<pkg_svc.hidden> flag will be omitted.
2056 Returns a list of lists, calling the label method for all (historical) services
2057 (see L<FS::h_cust_svc>) of this billing item.
2063 map { [ $_->label(@_) ] } $self->h_cust_svc(@_);
2068 Like labels, except returns a simple flat list, and shortens long
2069 (currently >5 or the cust_bill-max_same_services configuration value) lists of
2070 identical services to one line that lists the service label and the number of
2071 individual services rather than individual items.
2076 shift->_labels_short( 'labels', @_ );
2079 =item h_labels_short END_TIMESTAMP [ START_TIMESTAMP ]
2081 Like h_labels, except returns a simple flat list, and shortens long
2082 (currently >5 or the cust_bill-max_same_services configuration value) lists of
2083 identical services to one line that lists the service label and the number of
2084 individual services rather than individual items.
2088 sub h_labels_short {
2089 shift->_labels_short( 'h_labels', @_ );
2093 my( $self, $method ) = ( shift, shift );
2095 my $conf = new FS::Conf;
2096 my $max_same_services = $conf->config('cust_bill-max_same_services') || 5;
2099 #tie %labels, 'Tie::IxHash';
2100 push @{ $labels{$_->[0]} }, $_->[1]
2101 foreach $self->$method(@_);
2103 foreach my $label ( keys %labels ) {
2105 my @values = grep { ! $seen{$_}++ } @{ $labels{$label} };
2106 my $num = scalar(@values);
2107 if ( $num > $max_same_services ) {
2108 push @labels, "$label ($num)";
2110 if ( $conf->exists('cust_bill-consolidate_services') ) {
2111 # push @labels, "$label: ". join(', ', @values);
2113 my $detail = "$label: ";
2114 $detail .= shift(@values). ', '
2115 while @values && length($detail.$values[0]) < 78;
2117 push @labels, $detail;
2120 push @labels, map { "$label: $_" } @values;
2131 Returns the parent customer object (see L<FS::cust_main>).
2137 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
2140 #these subs are in location_Mixin.pm now... unfortunately the POD doesn't mixin
2144 Returns the location object, if any (see L<FS::cust_location>).
2146 =item cust_location_or_main
2148 If this package is associated with a location, returns the locaiton (see
2149 L<FS::cust_location>), otherwise returns the customer (see L<FS::cust_main>).
2151 =item location_label [ OPTION => VALUE ... ]
2153 Returns the label of the location object (see L<FS::cust_location>).
2157 #end of subs in location_Mixin.pm now... unfortunately the POD doesn't mixin
2159 =item seconds_since TIMESTAMP
2161 Returns the number of seconds all accounts (see L<FS::svc_acct>) in this
2162 package have been online since TIMESTAMP, according to the session monitor.
2164 TIMESTAMP is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
2165 L<Time::Local> and L<Date::Parse> for conversion functions.
2170 my($self, $since) = @_;
2173 foreach my $cust_svc (
2174 grep { $_->part_svc->svcdb eq 'svc_acct' } $self->cust_svc
2176 $seconds += $cust_svc->seconds_since($since);
2183 =item seconds_since_sqlradacct TIMESTAMP_START TIMESTAMP_END
2185 Returns the numbers of seconds all accounts (see L<FS::svc_acct>) in this
2186 package have been online between TIMESTAMP_START (inclusive) and TIMESTAMP_END
2189 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
2190 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
2196 sub seconds_since_sqlradacct {
2197 my($self, $start, $end) = @_;
2201 foreach my $cust_svc (
2203 my $part_svc = $_->part_svc;
2204 $part_svc->svcdb eq 'svc_acct'
2205 && scalar($part_svc->part_export('sqlradius'));
2208 $seconds += $cust_svc->seconds_since_sqlradacct($start, $end);
2215 =item attribute_since_sqlradacct TIMESTAMP_START TIMESTAMP_END ATTRIBUTE
2217 Returns the sum of the given attribute for all accounts (see L<FS::svc_acct>)
2218 in this package for sessions ending between TIMESTAMP_START (inclusive) and
2222 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
2223 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
2228 sub attribute_since_sqlradacct {
2229 my($self, $start, $end, $attrib) = @_;
2233 foreach my $cust_svc (
2235 my $part_svc = $_->part_svc;
2236 $part_svc->svcdb eq 'svc_acct'
2237 && scalar($part_svc->part_export('sqlradius'));
2240 $sum += $cust_svc->attribute_since_sqlradacct($start, $end, $attrib);
2252 my( $self, $value ) = @_;
2253 if ( defined($value) ) {
2254 $self->setfield('quantity', $value);
2256 $self->getfield('quantity') || 1;
2259 =item transfer DEST_PKGNUM | DEST_CUST_PKG, [ OPTION => VALUE ... ]
2261 Transfers as many services as possible from this package to another package.
2263 The destination package can be specified by pkgnum by passing an FS::cust_pkg
2264 object. The destination package must already exist.
2266 Services are moved only if the destination allows services with the correct
2267 I<svcpart> (not svcdb), unless the B<change_svcpart> option is set true. Use
2268 this option with caution! No provision is made for export differences
2269 between the old and new service definitions. Probably only should be used
2270 when your exports for all service definitions of a given svcdb are identical.
2271 (attempt a transfer without it first, to move all possible svcpart-matching
2274 Any services that can't be moved remain in the original package.
2276 Returns an error, if there is one; otherwise, returns the number of services
2277 that couldn't be moved.
2282 my ($self, $dest_pkgnum, %opt) = @_;
2288 if (ref ($dest_pkgnum) eq 'FS::cust_pkg') {
2289 $dest = $dest_pkgnum;
2290 $dest_pkgnum = $dest->pkgnum;
2292 $dest = qsearchs('cust_pkg', { pkgnum => $dest_pkgnum });
2295 return ('Package does not exist: '.$dest_pkgnum) unless $dest;
2297 foreach my $pkg_svc ( $dest->part_pkg->pkg_svc ) {
2298 $target{$pkg_svc->svcpart} = $pkg_svc->quantity;
2301 foreach my $cust_svc ($dest->cust_svc) {
2302 $target{$cust_svc->svcpart}--;
2305 my %svcpart2svcparts = ();
2306 if ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
2307 warn "change_svcpart option received, creating alternates list\n" if $DEBUG;
2308 foreach my $svcpart ( map { $_->svcpart } $self->cust_svc ) {
2309 next if exists $svcpart2svcparts{$svcpart};
2310 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2311 $svcpart2svcparts{$svcpart} = [
2313 sort { $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] }
2315 my $pkg_svc = qsearchs( 'pkg_svc', { 'pkgpart' => $dest->pkgpart,
2316 'svcpart' => $_ } );
2318 $pkg_svc ? $pkg_svc->primary_svc : '',
2319 $pkg_svc ? $pkg_svc->quantity : 0,
2323 grep { $_ != $svcpart }
2325 qsearch('part_svc', { 'svcdb' => $part_svc->svcdb } )
2327 warn "alternates for svcpart $svcpart: ".
2328 join(', ', @{$svcpart2svcparts{$svcpart}}). "\n"
2333 foreach my $cust_svc ($self->cust_svc) {
2334 if($target{$cust_svc->svcpart} > 0) {
2335 $target{$cust_svc->svcpart}--;
2336 my $new = new FS::cust_svc { $cust_svc->hash };
2337 $new->pkgnum($dest_pkgnum);
2338 my $error = $new->replace($cust_svc);
2339 return $error if $error;
2340 } elsif ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
2342 warn "looking for alternates for svcpart ". $cust_svc->svcpart. "\n";
2343 warn "alternates to consider: ".
2344 join(', ', @{$svcpart2svcparts{$cust_svc->svcpart}}). "\n";
2346 my @alternate = grep {
2347 warn "considering alternate svcpart $_: ".
2348 "$target{$_} available in new package\n"
2351 } @{$svcpart2svcparts{$cust_svc->svcpart}};
2353 warn "alternate(s) found\n" if $DEBUG;
2354 my $change_svcpart = $alternate[0];
2355 $target{$change_svcpart}--;
2356 my $new = new FS::cust_svc { $cust_svc->hash };
2357 $new->svcpart($change_svcpart);
2358 $new->pkgnum($dest_pkgnum);
2359 my $error = $new->replace($cust_svc);
2360 return $error if $error;
2373 This method is deprecated. See the I<depend_jobnum> option to the insert and
2374 order_pkgs methods in FS::cust_main for a better way to defer provisioning.
2381 local $SIG{HUP} = 'IGNORE';
2382 local $SIG{INT} = 'IGNORE';
2383 local $SIG{QUIT} = 'IGNORE';
2384 local $SIG{TERM} = 'IGNORE';
2385 local $SIG{TSTP} = 'IGNORE';
2386 local $SIG{PIPE} = 'IGNORE';
2388 my $oldAutoCommit = $FS::UID::AutoCommit;
2389 local $FS::UID::AutoCommit = 0;
2392 foreach my $cust_svc ( $self->cust_svc ) {
2393 #false laziness w/svc_Common::insert
2394 my $svc_x = $cust_svc->svc_x;
2395 foreach my $part_export ( $cust_svc->part_svc->part_export ) {
2396 my $error = $part_export->export_insert($svc_x);
2398 $dbh->rollback if $oldAutoCommit;
2404 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2411 Associates this package with a (suspension or cancellation) reason (see
2412 L<FS::cust_pkg_reason>, possibly inserting a new reason on the fly (see
2415 Available options are:
2421 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.
2425 the access_user (see L<FS::access_user>) providing the reason
2433 the action (cancel, susp, adjourn, expire) associated with the reason
2437 If there is an error, returns the error, otherwise returns false.
2442 my ($self, %options) = @_;
2444 my $otaker = $options{reason_otaker} ||
2445 $FS::CurrentUser::CurrentUser->username;
2448 if ( $options{'reason'} =~ /^(\d+)$/ ) {
2452 } elsif ( ref($options{'reason'}) ) {
2454 return 'Enter a new reason (or select an existing one)'
2455 unless $options{'reason'}->{'reason'} !~ /^\s*$/;
2457 my $reason = new FS::reason({
2458 'reason_type' => $options{'reason'}->{'typenum'},
2459 'reason' => $options{'reason'}->{'reason'},
2461 my $error = $reason->insert;
2462 return $error if $error;
2464 $reasonnum = $reason->reasonnum;
2467 return "Unparsable reason: ". $options{'reason'};
2470 my $cust_pkg_reason =
2471 new FS::cust_pkg_reason({ 'pkgnum' => $self->pkgnum,
2472 'reasonnum' => $reasonnum,
2473 'otaker' => $otaker,
2474 'action' => substr(uc($options{'action'}),0,1),
2475 'date' => $options{'date'}
2480 $cust_pkg_reason->insert;
2483 =item insert_discount
2485 Associates this package with a discount (see L<FS::cust_pkg_discount>, possibly
2486 inserting a new discount on the fly (see L<FS::discount>).
2488 Available options are:
2496 If there is an error, returns the error, otherwise returns false.
2500 sub insert_discount {
2501 #my ($self, %options) = @_;
2504 my $cust_pkg_discount = new FS::cust_pkg_discount {
2505 'pkgnum' => $self->pkgnum,
2506 'discountnum' => $self->discountnum,
2508 'end_date' => '', #XXX
2509 #for the create a new discount case
2510 '_type' => $self->discountnum__type,
2511 'amount' => $self->discountnum_amount,
2512 'percent' => $self->discountnum_percent,
2513 'months' => $self->discountnum_months,
2514 #'disabled' => $self->discountnum_disabled,
2517 $cust_pkg_discount->insert;
2520 =item set_usage USAGE_VALUE_HASHREF
2522 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
2523 to which they should be set (see L<FS::svc_acct>). Currently seconds,
2524 upbytes, downbytes, and totalbytes are appropriate keys.
2526 All svc_accts which are part of this package have their values reset.
2531 my ($self, $valueref, %opt) = @_;
2533 foreach my $cust_svc ($self->cust_svc){
2534 my $svc_x = $cust_svc->svc_x;
2535 $svc_x->set_usage($valueref, %opt)
2536 if $svc_x->can("set_usage");
2540 =item recharge USAGE_VALUE_HASHREF
2542 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
2543 to which they should be set (see L<FS::svc_acct>). Currently seconds,
2544 upbytes, downbytes, and totalbytes are appropriate keys.
2546 All svc_accts which are part of this package have their values incremented.
2551 my ($self, $valueref) = @_;
2553 foreach my $cust_svc ($self->cust_svc){
2554 my $svc_x = $cust_svc->svc_x;
2555 $svc_x->recharge($valueref)
2556 if $svc_x->can("recharge");
2560 =item cust_pkg_discount
2564 sub cust_pkg_discount {
2566 qsearch('cust_pkg_discount', { 'pkgnum' => $self->pkgnum } );
2569 =item cust_pkg_discount_active
2573 sub cust_pkg_discount_active {
2575 grep { $_->status eq 'active' } $self->cust_pkg_discount;
2580 =head1 CLASS METHODS
2586 Returns an SQL expression identifying recurring packages.
2590 sub recurring_sql { "
2591 '0' != ( select freq from part_pkg
2592 where cust_pkg.pkgpart = part_pkg.pkgpart )
2597 Returns an SQL expression identifying one-time packages.
2602 '0' = ( select freq from part_pkg
2603 where cust_pkg.pkgpart = part_pkg.pkgpart )
2608 Returns an SQL expression identifying ordered packages (recurring packages not
2614 $_[0]->recurring_sql. " AND ". $_[0]->not_yet_billed_sql;
2619 Returns an SQL expression identifying active packages.
2624 $_[0]->recurring_sql. "
2625 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
2626 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
2627 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
2630 =item not_yet_billed_sql
2632 Returns an SQL expression identifying packages which have not yet been billed.
2636 sub not_yet_billed_sql { "
2637 ( cust_pkg.setup IS NULL OR cust_pkg.setup = 0 )
2638 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
2639 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
2644 Returns an SQL expression identifying inactive packages (one-time packages
2645 that are otherwise unsuspended/uncancelled).
2649 sub inactive_sql { "
2650 ". $_[0]->onetime_sql(). "
2651 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
2652 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
2653 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
2659 Returns an SQL expression identifying suspended packages.
2663 sub suspended_sql { susp_sql(@_); }
2665 #$_[0]->recurring_sql(). ' AND '.
2667 ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
2668 AND cust_pkg.susp IS NOT NULL AND cust_pkg.susp != 0
2675 Returns an SQL exprression identifying cancelled packages.
2679 sub cancelled_sql { cancel_sql(@_); }
2681 #$_[0]->recurring_sql(). ' AND '.
2682 "cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0";
2687 Returns an SQL expression to give the package status as a string.
2693 WHEN cust_pkg.cancel IS NOT NULL THEN 'cancelled'
2694 WHEN cust_pkg.susp IS NOT NULL THEN 'suspended'
2695 WHEN cust_pkg.setup IS NULL THEN 'not yet billed'
2696 WHEN ".onetime_sql()." THEN 'one-time charge'
2701 =item search HASHREF
2705 Returns a qsearch hash expression to search for parameters specified in HASHREF.
2706 Valid parameters are
2714 active, inactive, suspended, cancel (or cancelled)
2718 active, inactive, suspended, one-time charge, inactive, cancel (or cancelled)
2722 boolean selects custom packages
2728 pkgpart or arrayref or hashref of pkgparts
2732 arrayref of beginning and ending epoch date
2736 arrayref of beginning and ending epoch date
2740 arrayref of beginning and ending epoch date
2744 arrayref of beginning and ending epoch date
2748 arrayref of beginning and ending epoch date
2752 arrayref of beginning and ending epoch date
2756 arrayref of beginning and ending epoch date
2760 pkgnum or APKG_pkgnum
2764 a value suited to passing to FS::UI::Web::cust_header
2768 specifies the user for agent virtualization
2772 boolean selects packages containing fcc form 477 telco lines
2779 my ($class, $params) = @_;
2786 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
2788 "cust_main.agentnum = $1";
2795 if ( $params->{'custnum'} =~ /^(\d+)$/ and $1 ) {
2797 "cust_pkg.custnum = $1";
2804 if ( $params->{'pkgbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
2806 "cust_pkg.pkgbatch = '$1'";
2813 if ( $params->{'magic'} eq 'active'
2814 || $params->{'status'} eq 'active' ) {
2816 push @where, FS::cust_pkg->active_sql();
2818 } elsif ( $params->{'magic'} =~ /^not[ _]yet[ _]billed$/
2819 || $params->{'status'} =~ /^not[ _]yet[ _]billed$/ ) {
2821 push @where, FS::cust_pkg->not_yet_billed_sql();
2823 } elsif ( $params->{'magic'} =~ /^(one-time charge|inactive)/
2824 || $params->{'status'} =~ /^(one-time charge|inactive)/ ) {
2826 push @where, FS::cust_pkg->inactive_sql();
2828 } elsif ( $params->{'magic'} eq 'suspended'
2829 || $params->{'status'} eq 'suspended' ) {
2831 push @where, FS::cust_pkg->suspended_sql();
2833 } elsif ( $params->{'magic'} =~ /^cancell?ed$/
2834 || $params->{'status'} =~ /^cancell?ed$/ ) {
2836 push @where, FS::cust_pkg->cancelled_sql();
2841 # parse package class
2844 #false lazinessish w/graph/cust_bill_pkg.cgi
2847 if ( exists($params->{'classnum'})
2848 && $params->{'classnum'} =~ /^(\d*)$/
2852 if ( $classnum ) { #a specific class
2853 push @where, "part_pkg.classnum = $classnum";
2855 #@pkg_class = ( qsearchs('pkg_class', { 'classnum' => $classnum } ) );
2856 #die "classnum $classnum not found!" unless $pkg_class[0];
2857 #$title .= $pkg_class[0]->classname.' ';
2859 } elsif ( $classnum eq '' ) { #the empty class
2861 push @where, "part_pkg.classnum IS NULL";
2862 #$title .= 'Empty class ';
2863 #@pkg_class = ( '(empty class)' );
2864 } elsif ( $classnum eq '0' ) {
2865 #@pkg_class = qsearch('pkg_class', {} ); # { 'disabled' => '' } );
2866 #push @pkg_class, '(empty class)';
2868 die "illegal classnum";
2874 # parse package report options
2877 my @report_option = ();
2878 if ( exists($params->{'report_option'})
2879 && $params->{'report_option'} =~ /^([,\d]*)$/
2882 @report_option = split(',', $1);
2885 if (@report_option) {
2886 # this will result in the empty set for the dangling comma case as it should
2888 map{ "0 < ( SELECT count(*) FROM part_pkg_option
2889 WHERE part_pkg_option.pkgpart = part_pkg.pkgpart
2890 AND optionname = 'report_option_$_'
2891 AND optionvalue = '1' )"
2901 push @where, "part_pkg.custom = 'Y'" if $params->{custom};
2907 push @where, "part_pkg.fcc_ds0s > 0" if $params->{fcc_line};
2913 if ( exists($params->{'censustract'}) ) {
2914 $params->{'censustract'} =~ /^([.\d]*)$/;
2915 my $censustract = "cust_main.censustract = '$1'";
2916 $censustract .= ' OR cust_main.censustract is NULL' unless $1;
2917 push @where, "( $censustract )";
2924 if ( ref($params->{'pkgpart'}) ) {
2927 if ( ref($params->{'pkgpart'}) eq 'HASH' ) {
2928 @pkgpart = grep $params->{'pkgpart'}{$_}, keys %{ $params->{'pkgpart'} };
2929 } elsif ( ref($params->{'pkgpart'}) eq 'ARRAY' ) {
2930 @pkgpart = @{ $params->{'pkgpart'} };
2932 die 'unhandled pkgpart ref '. $params->{'pkgpart'};
2935 @pkgpart = grep /^(\d+)$/, @pkgpart;
2937 push @where, 'pkgpart IN ('. join(',', @pkgpart). ')' if scalar(@pkgpart);
2939 } elsif ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
2940 push @where, "pkgpart = $1";
2949 #false laziness w/report_cust_pkg.html
2952 'one-time charge' => { 'last_bill'=>1, 'bill'=>1, 'adjourn'=>1, 'susp'=>1, 'expire'=>1, 'cancel'=>1, },
2953 'active' => { 'susp'=>1, 'cancel'=>1 },
2954 'suspended' => { 'cancel' => 1 },
2959 if( exists($params->{'active'} ) ) {
2960 # This overrides all the other date-related fields
2961 my($beginning, $ending) = @{$params->{'active'}};
2963 "cust_pkg.setup IS NOT NULL",
2964 "cust_pkg.setup <= $ending",
2965 "(cust_pkg.cancel IS NULL OR cust_pkg.cancel >= $beginning )",
2966 "NOT (".FS::cust_pkg->onetime_sql . ")";
2969 foreach my $field (qw( setup last_bill bill adjourn susp expire contract_end cancel )) {
2971 next unless exists($params->{$field});
2973 my($beginning, $ending) = @{$params->{$field}};
2975 next if $beginning == 0 && $ending == 4294967295;
2978 "cust_pkg.$field IS NOT NULL",
2979 "cust_pkg.$field >= $beginning",
2980 "cust_pkg.$field <= $ending";
2982 $orderby ||= "ORDER BY cust_pkg.$field";
2987 $orderby ||= 'ORDER BY bill';
2990 # parse magic, legacy, etc.
2993 if ( $params->{'magic'} &&
2994 $params->{'magic'} =~ /^(active|inactive|suspended|cancell?ed)$/
2997 $orderby = 'ORDER BY pkgnum';
2999 if ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
3000 push @where, "pkgpart = $1";
3003 } elsif ( $params->{'query'} eq 'pkgnum' ) {
3005 $orderby = 'ORDER BY pkgnum';
3007 } elsif ( $params->{'query'} eq 'APKG_pkgnum' ) {
3009 $orderby = 'ORDER BY pkgnum';
3012 SELECT count(*) FROM pkg_svc
3013 WHERE pkg_svc.pkgpart = cust_pkg.pkgpart
3014 AND pkg_svc.quantity > ( SELECT count(*) FROM cust_svc
3015 WHERE cust_svc.pkgnum = cust_pkg.pkgnum
3016 AND cust_svc.svcpart = pkg_svc.svcpart
3023 # setup queries, links, subs, etc. for the search
3026 # here is the agent virtualization
3027 if ($params->{CurrentUser}) {
3029 qsearchs('access_user', { username => $params->{CurrentUser} });
3032 push @where, $access_user->agentnums_sql('table'=>'cust_main');
3037 push @where, $FS::CurrentUser::CurrentUser->agentnums_sql('table'=>'cust_main');
3040 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
3042 my $addl_from = 'LEFT JOIN cust_main USING ( custnum ) '.
3043 'LEFT JOIN part_pkg USING ( pkgpart ) '.
3044 'LEFT JOIN pkg_class ON ( part_pkg.classnum = pkg_class.classnum ) ';
3046 my $count_query = "SELECT COUNT(*) FROM cust_pkg $addl_from $extra_sql";
3049 'table' => 'cust_pkg',
3051 'select' => join(', ',
3053 ( map "part_pkg.$_", qw( pkg freq ) ),
3054 'pkg_class.classname',
3055 'cust_main.custnum AS cust_main_custnum',
3056 FS::UI::Web::cust_sql_fields(
3057 $params->{'cust_fields'}
3060 'extra_sql' => "$extra_sql $orderby",
3061 'addl_from' => $addl_from,
3062 'count_query' => $count_query,
3069 Returns a list of two package counts. The first is a count of packages
3070 based on the supplied criteria and the second is the count of residential
3071 packages with those same criteria. Criteria are specified as in the search
3077 my ($class, $params) = @_;
3079 my $sql_query = $class->search( $params );
3081 my $count_sql = delete($sql_query->{'count_query'});
3082 $count_sql =~ s/ FROM/,count(CASE WHEN cust_main.company IS NULL OR cust_main.company = '' THEN 1 END) FROM/
3083 or die "couldn't parse count_sql";
3085 my $count_sth = dbh->prepare($count_sql)
3086 or die "Error preparing $count_sql: ". dbh->errstr;
3088 or die "Error executing $count_sql: ". $count_sth->errstr;
3089 my $count_arrayref = $count_sth->fetchrow_arrayref;
3091 return ( @$count_arrayref );
3098 Returns a list: the first item is an SQL fragment identifying matching
3099 packages/customers via location (taking into account shipping and package
3100 address taxation, if enabled), and subsequent items are the parameters to
3101 substitute for the placeholders in that fragment.
3106 my($class, %opt) = @_;
3107 my $ornull = $opt{'ornull'};
3109 my $conf = new FS::Conf;
3111 # '?' placeholders in _location_sql_where
3112 my $x = $ornull ? 3 : 2;
3113 my @bill_param = ( ('city')x3, ('county')x$x, ('state')x$x, 'country' );
3117 if ( $conf->exists('tax-ship_address') ) {
3120 ( ( ship_last IS NULL OR ship_last = '' )
3121 AND ". _location_sql_where('cust_main', '', $ornull ). "
3123 OR ( ship_last IS NOT NULL AND ship_last != ''
3124 AND ". _location_sql_where('cust_main', 'ship_', $ornull ). "
3127 # AND payby != 'COMP'
3129 @main_param = ( @bill_param, @bill_param );
3133 $main_where = _location_sql_where('cust_main'); # AND payby != 'COMP'
3134 @main_param = @bill_param;
3140 if ( $conf->exists('tax-pkg_address') ) {
3142 my $loc_where = _location_sql_where( 'cust_location', '', $ornull );
3145 ( cust_pkg.locationnum IS NULL AND $main_where )
3146 OR ( cust_pkg.locationnum IS NOT NULL AND $loc_where )
3149 @param = ( @main_param, @bill_param );
3153 $where = $main_where;
3154 @param = @main_param;
3162 #subroutine, helper for location_sql
3163 sub _location_sql_where {
3165 my $prefix = @_ ? shift : '';
3166 my $ornull = @_ ? shift : '';
3168 # $ornull = $ornull ? " OR ( ? IS NULL AND $table.${prefix}county IS NULL ) " : '';
3170 $ornull = $ornull ? ' OR ? IS NULL ' : '';
3172 my $or_empty_city = " OR ( ? = '' AND $table.${prefix}city IS NULL ) ";
3173 my $or_empty_county = " OR ( ? = '' AND $table.${prefix}county IS NULL ) ";
3174 my $or_empty_state = " OR ( ? = '' AND $table.${prefix}state IS NULL ) ";
3176 # ( $table.${prefix}city = ? $or_empty_city $ornull )
3178 ( $table.${prefix}city = ? OR ? = '' OR CAST(? AS text) IS NULL )
3179 AND ( $table.${prefix}county = ? $or_empty_county $ornull )
3180 AND ( $table.${prefix}state = ? $or_empty_state $ornull )
3181 AND $table.${prefix}country = ?
3189 =item order CUSTNUM, PKGPARTS_ARYREF, [ REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF [ REFNUM ] ] ]
3191 CUSTNUM is a customer (see L<FS::cust_main>)
3193 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
3194 L<FS::part_pkg>) to order for this customer. Duplicates are of course
3197 REMOVE_PKGNUMS is an optional list of pkgnums specifying the billing items to
3198 remove for this customer. The services (see L<FS::cust_svc>) are moved to the
3199 new billing items. An error is returned if this is not possible (see
3200 L<FS::pkg_svc>). An empty arrayref is equivalent to not specifying this
3203 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
3204 newly-created cust_pkg objects.
3206 REFNUM, if specified, will specify the FS::pkg_referral record to be created
3207 and inserted. Multiple FS::pkg_referral records can be created by
3208 setting I<refnum> to an array reference of refnums or a hash reference with
3209 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
3210 record will be created corresponding to cust_main.refnum.
3215 my ($custnum, $pkgparts, $remove_pkgnum, $return_cust_pkg, $refnum) = @_;
3217 my $conf = new FS::Conf;
3219 # Transactionize this whole mess
3220 local $SIG{HUP} = 'IGNORE';
3221 local $SIG{INT} = 'IGNORE';
3222 local $SIG{QUIT} = 'IGNORE';
3223 local $SIG{TERM} = 'IGNORE';
3224 local $SIG{TSTP} = 'IGNORE';
3225 local $SIG{PIPE} = 'IGNORE';
3227 my $oldAutoCommit = $FS::UID::AutoCommit;
3228 local $FS::UID::AutoCommit = 0;
3232 # my $cust_main = qsearchs('cust_main', { custnum => $custnum });
3233 # return "Customer not found: $custnum" unless $cust_main;
3235 warn "$me order: pkgnums to remove: ". join(',', @$remove_pkgnum). "\n"
3238 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
3241 my $change = scalar(@old_cust_pkg) != 0;
3244 if ( scalar(@old_cust_pkg) == 1 && scalar(@$pkgparts) == 1 ) {
3246 warn "$me order: changing pkgnum ". $old_cust_pkg[0]->pkgnum.
3247 " to pkgpart ". $pkgparts->[0]. "\n"
3250 my $err_or_cust_pkg =
3251 $old_cust_pkg[0]->change( 'pkgpart' => $pkgparts->[0],
3252 'refnum' => $refnum,
3255 unless (ref($err_or_cust_pkg)) {
3256 $dbh->rollback if $oldAutoCommit;
3257 return $err_or_cust_pkg;
3260 push @$return_cust_pkg, $err_or_cust_pkg;
3261 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3266 # Create the new packages.
3267 foreach my $pkgpart (@$pkgparts) {
3269 warn "$me order: inserting pkgpart $pkgpart\n" if $DEBUG;
3271 my $cust_pkg = new FS::cust_pkg { custnum => $custnum,
3272 pkgpart => $pkgpart,
3276 $error = $cust_pkg->insert( 'change' => $change );
3278 $dbh->rollback if $oldAutoCommit;
3281 push @$return_cust_pkg, $cust_pkg;
3283 # $return_cust_pkg now contains refs to all of the newly
3286 # Transfer services and cancel old packages.
3287 foreach my $old_pkg (@old_cust_pkg) {
3289 warn "$me order: transferring services from pkgnum ". $old_pkg->pkgnum. "\n"
3292 foreach my $new_pkg (@$return_cust_pkg) {
3293 $error = $old_pkg->transfer($new_pkg);
3294 if ($error and $error == 0) {
3295 # $old_pkg->transfer failed.
3296 $dbh->rollback if $oldAutoCommit;
3301 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
3302 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
3303 foreach my $new_pkg (@$return_cust_pkg) {
3304 $error = $old_pkg->transfer($new_pkg, 'change_svcpart'=>1 );
3305 if ($error and $error == 0) {
3306 # $old_pkg->transfer failed.
3307 $dbh->rollback if $oldAutoCommit;
3314 # Transfers were successful, but we went through all of the
3315 # new packages and still had services left on the old package.
3316 # We can't cancel the package under the circumstances, so abort.
3317 $dbh->rollback if $oldAutoCommit;
3318 return "Unable to transfer all services from package ".$old_pkg->pkgnum;
3320 $error = $old_pkg->cancel( quiet=>1 );
3326 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3330 =item bulk_change PKGPARTS_ARYREF, REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF ]
3332 A bulk change method to change packages for multiple customers.
3334 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
3335 L<FS::part_pkg>) to order for each customer. Duplicates are of course
3338 REMOVE_PKGNUMS is an list of pkgnums specifying the billing items to
3339 replace. The services (see L<FS::cust_svc>) are moved to the
3340 new billing items. An error is returned if this is not possible (see
3343 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
3344 newly-created cust_pkg objects.
3349 my ($pkgparts, $remove_pkgnum, $return_cust_pkg) = @_;
3351 # Transactionize this whole mess
3352 local $SIG{HUP} = 'IGNORE';
3353 local $SIG{INT} = 'IGNORE';
3354 local $SIG{QUIT} = 'IGNORE';
3355 local $SIG{TERM} = 'IGNORE';
3356 local $SIG{TSTP} = 'IGNORE';
3357 local $SIG{PIPE} = 'IGNORE';
3359 my $oldAutoCommit = $FS::UID::AutoCommit;
3360 local $FS::UID::AutoCommit = 0;
3364 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
3367 while(scalar(@old_cust_pkg)) {
3369 my $custnum = $old_cust_pkg[0]->custnum;
3370 my (@remove) = map { $_->pkgnum }
3371 grep { $_->custnum == $custnum } @old_cust_pkg;
3372 @old_cust_pkg = grep { $_->custnum != $custnum } @old_cust_pkg;
3374 my $error = order $custnum, $pkgparts, \@remove, \@return;
3376 push @errors, $error
3378 push @$return_cust_pkg, @return;
3381 if (scalar(@errors)) {
3382 $dbh->rollback if $oldAutoCommit;
3383 return join(' / ', @errors);
3386 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3390 # Used by FS::Upgrade to migrate to a new database.
3391 sub _upgrade_data { # class method
3392 my ($class, %opts) = @_;
3393 $class->_upgrade_otaker(%opts);
3395 # RT#10139, bug resulting in contract_end being set when it shouldn't
3396 'UPDATE cust_pkg SET contract_end = NULL WHERE contract_end = -1',
3397 # RT#10830, bad calculation of prorate date near end of year
3398 # the date range for bill is December 2009, and we move it forward
3399 # one year if it's before the previous bill date (which it should
3401 'UPDATE cust_pkg SET bill = bill + (365*24*60*60) WHERE bill < last_bill
3402 AND bill > 1259654400 AND bill < 1262332800 AND (SELECT plan FROM part_pkg
3403 WHERE part_pkg.pkgpart = cust_pkg.pkgpart) = \'prorate\'',
3404 # RT6628, add order_date to cust_pkg
3405 'update cust_pkg set order_date = (select history_date from h_cust_pkg
3406 where h_cust_pkg.pkgnum = cust_pkg.pkgnum and
3407 history_action = \'insert\') where order_date is null',
3409 foreach my $sql (@statements) {
3410 my $sth = dbh->prepare($sql);
3411 $sth->execute or die $sth->errstr;
3419 sub order is not OO. Perhaps it should be moved to FS::cust_main and made so?
3421 In sub order, the @pkgparts array (passed by reference) is clobbered.
3423 Also in sub order, no money is adjusted. Once FS::part_pkg defines a standard
3424 method to pass dates to the recur_prog expression, it should do so.
3426 FS::svc_acct, FS::svc_domain, FS::svc_www, FS::svc_ip and FS::svc_forward are
3427 loaded via 'use' at compile time, rather than via 'require' in sub { setup,
3428 suspend, unsuspend, cancel } because they use %FS::UID::callback to load
3429 configuration values. Probably need a subroutine which decides what to do
3430 based on whether or not we've fetched the user yet, rather than a hash. See
3431 FS::UID and the TODO.
3433 Now that things are transactional should the check in the insert method be
3438 L<FS::Record>, L<FS::cust_main>, L<FS::part_pkg>, L<FS::cust_svc>,
3439 L<FS::pkg_svc>, schema.html from the base documentation