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 my $error = $self->check_pkgpart;
264 return $error if $error;
266 if ( $self->part_pkg->option('start_1st', 1) && !$self->start_date ) {
267 my ($sec,$min,$hour,$mday,$mon,$year) = (localtime(time) )[0,1,2,3,4,5];
268 $mon += 1 unless $mday == 1;
269 until ( $mon < 12 ) { $mon -= 12; $year++; }
270 $self->start_date( timelocal_nocheck(0,0,0,1,$mon,$year) );
273 foreach my $action ( qw(expire adjourn contract_end) ) {
274 my $months = $self->part_pkg->option("${action}_months",1);
275 if($months and !$self->$action) {
276 my $start = $self->start_date || $self->setup || time;
277 $self->$action( $self->part_pkg->add_freq($start, $months) );
281 $self->order_date(time);
283 local $SIG{HUP} = 'IGNORE';
284 local $SIG{INT} = 'IGNORE';
285 local $SIG{QUIT} = 'IGNORE';
286 local $SIG{TERM} = 'IGNORE';
287 local $SIG{TSTP} = 'IGNORE';
288 local $SIG{PIPE} = 'IGNORE';
290 my $oldAutoCommit = $FS::UID::AutoCommit;
291 local $FS::UID::AutoCommit = 0;
294 $error = $self->SUPER::insert($options{options} ? %{$options{options}} : ());
296 $dbh->rollback if $oldAutoCommit;
300 $self->refnum($self->cust_main->refnum) unless $self->refnum;
301 $self->refnum( [ $self->refnum ] ) unless ref($self->refnum);
302 $self->process_m2m( 'link_table' => 'pkg_referral',
303 'target_table' => 'part_referral',
304 'params' => $self->refnum,
307 if ( $self->discountnum ) {
308 my $error = $self->insert_discount();
310 $dbh->rollback if $oldAutoCommit;
315 #if ( $self->reg_code ) {
316 # my $reg_code = qsearchs('reg_code', { 'code' => $self->reg_code } );
317 # $error = $reg_code->delete;
319 # $dbh->rollback if $oldAutoCommit;
324 my $conf = new FS::Conf;
326 if ( $conf->config('ticket_system') && $options{ticket_subject} ) {
329 # use lib ( "/opt/rt3/local/lib", "/opt/rt3/lib" );
336 use FS::TicketSystem;
337 FS::TicketSystem->init();
339 my $q = new RT::Queue($RT::SystemUser);
340 $q->Load($options{ticket_queue}) if $options{ticket_queue};
341 my $t = new RT::Ticket($RT::SystemUser);
342 my $mime = new MIME::Entity;
343 $mime->build( Type => 'text/plain', Data => $options{ticket_subject} );
344 $t->Create( $options{ticket_queue} ? (Queue => $q) : (),
345 Subject => $options{ticket_subject},
348 $t->AddLink( Type => 'MemberOf',
349 Target => 'freeside://freeside/cust_main/'. $self->custnum,
353 if ($conf->config('welcome_letter') && $self->cust_main->num_pkgs == 1) {
354 my $queue = new FS::queue {
355 'job' => 'FS::cust_main::queueable_print',
357 $error = $queue->insert(
358 'custnum' => $self->custnum,
359 'template' => 'welcome_letter',
363 warn "can't send welcome letter: $error";
368 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
375 This method now works but you probably shouldn't use it.
377 You don't want to delete packages, because there would then be no record
378 the customer ever purchased the package. Instead, see the cancel method and
379 hide cancelled packages.
386 local $SIG{HUP} = 'IGNORE';
387 local $SIG{INT} = 'IGNORE';
388 local $SIG{QUIT} = 'IGNORE';
389 local $SIG{TERM} = 'IGNORE';
390 local $SIG{TSTP} = 'IGNORE';
391 local $SIG{PIPE} = 'IGNORE';
393 my $oldAutoCommit = $FS::UID::AutoCommit;
394 local $FS::UID::AutoCommit = 0;
397 foreach my $cust_pkg_discount ($self->cust_pkg_discount) {
398 my $error = $cust_pkg_discount->delete;
400 $dbh->rollback if $oldAutoCommit;
404 #cust_bill_pkg_discount?
406 foreach my $cust_pkg_detail ($self->cust_pkg_detail) {
407 my $error = $cust_pkg_detail->delete;
409 $dbh->rollback if $oldAutoCommit;
414 foreach my $cust_pkg_reason (
416 'table' => 'cust_pkg_reason',
417 'hashref' => { 'pkgnum' => $self->pkgnum },
421 my $error = $cust_pkg_reason->delete;
423 $dbh->rollback if $oldAutoCommit;
430 my $error = $self->SUPER::delete(@_);
432 $dbh->rollback if $oldAutoCommit;
436 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
442 =item replace [ OLD_RECORD ] [ HASHREF | OPTION => VALUE ... ]
444 Replaces the OLD_RECORD with this one in the database. If there is an error,
445 returns the error, otherwise returns false.
447 Currently, custnum, setup, bill, adjourn, susp, expire, and cancel may be changed.
449 Changing pkgpart may have disasterous effects. See the order subroutine.
451 setup and bill are normally updated by calling the bill method of a customer
452 object (see L<FS::cust_main>).
454 suspend is normally updated by the suspend and unsuspend methods.
456 cancel is normally updated by the cancel method (and also the order subroutine
459 Available options are:
465 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.
469 the access_user (see L<FS::access_user>) providing the reason
473 hashref of keys and values - cust_pkg_option records will be created, updated or removed as appopriate
482 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
487 ( ref($_[0]) eq 'HASH' )
491 #return "Can't (yet?) change pkgpart!" if $old->pkgpart != $new->pkgpart;
492 #return "Can't change otaker!" if $old->otaker ne $new->otaker;
495 #return "Can't change setup once it exists!"
496 # if $old->getfield('setup') &&
497 # $old->getfield('setup') != $new->getfield('setup');
499 #some logic for bill, susp, cancel?
501 local($disable_agentcheck) = 1 if $old->pkgpart == $new->pkgpart;
503 local $SIG{HUP} = 'IGNORE';
504 local $SIG{INT} = 'IGNORE';
505 local $SIG{QUIT} = 'IGNORE';
506 local $SIG{TERM} = 'IGNORE';
507 local $SIG{TSTP} = 'IGNORE';
508 local $SIG{PIPE} = 'IGNORE';
510 my $oldAutoCommit = $FS::UID::AutoCommit;
511 local $FS::UID::AutoCommit = 0;
514 foreach my $method ( qw(adjourn expire) ) { # How many reasons?
515 if ($options->{'reason'} && $new->$method && $old->$method ne $new->$method) {
516 my $error = $new->insert_reason(
517 'reason' => $options->{'reason'},
518 'date' => $new->$method,
520 'reason_otaker' => $options->{'reason_otaker'},
523 dbh->rollback if $oldAutoCommit;
524 return "Error inserting cust_pkg_reason: $error";
529 #save off and freeze RADIUS attributes for any associated svc_acct records
531 if ( $old->part_pkg->is_prepaid || $new->part_pkg->is_prepaid ) {
533 #also check for specific exports?
534 # to avoid spurious modify export events
535 @svc_acct = map { $_->svc_x }
536 grep { $_->part_svc->svcdb eq 'svc_acct' }
539 $_->snapshot foreach @svc_acct;
543 my $error = $new->SUPER::replace($old,
544 $options->{options} ? $options->{options} : ()
547 $dbh->rollback if $oldAutoCommit;
551 #for prepaid packages,
552 #trigger export of new RADIUS Expiration attribute when cust_pkg.bill changes
553 foreach my $old_svc_acct ( @svc_acct ) {
554 my $new_svc_acct = new FS::svc_acct { $old_svc_acct->hash };
556 $new_svc_acct->replace( $old_svc_acct,
557 'depend_jobnum' => $options->{depend_jobnum},
560 $dbh->rollback if $oldAutoCommit;
565 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
572 Checks all fields to make sure this is a valid billing item. If there is an
573 error, returns the error, otherwise returns false. Called by the insert and
581 $self->locationnum('') if !$self->locationnum || $self->locationnum == -1;
584 $self->ut_numbern('pkgnum')
585 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum')
586 || $self->ut_numbern('pkgpart')
587 || $self->check_pkgpart
588 || $self->ut_foreign_keyn('locationnum', 'cust_location', 'locationnum')
589 || $self->ut_numbern('start_date')
590 || $self->ut_numbern('setup')
591 || $self->ut_numbern('bill')
592 || $self->ut_numbern('susp')
593 || $self->ut_numbern('cancel')
594 || $self->ut_numbern('adjourn')
595 || $self->ut_numbern('expire')
596 || $self->ut_enum('no_auto', [ '', 'Y' ])
597 || $self->ut_numbern('agent_pkgid')
599 return $error if $error;
601 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
603 if ( $self->dbdef_table->column('manual_flag') ) {
604 $self->manual_flag('') if $self->manual_flag eq ' ';
605 $self->manual_flag =~ /^([01]?)$/
606 or return "Illegal manual_flag ". $self->manual_flag;
607 $self->manual_flag($1);
620 my $error = $self->ut_numbern('pkgpart');
621 return $error if $error;
623 if ( $self->reg_code ) {
625 unless ( grep { $self->pkgpart == $_->pkgpart }
626 map { $_->reg_code_pkg }
627 qsearchs( 'reg_code', { 'code' => $self->reg_code,
628 'agentnum' => $self->cust_main->agentnum })
630 return "Unknown registration code";
633 } elsif ( $self->promo_code ) {
636 qsearchs('part_pkg', {
637 'pkgpart' => $self->pkgpart,
638 'promo_code' => { op=>'ILIKE', value=>$self->promo_code },
640 return 'Unknown promotional code' unless $promo_part_pkg;
644 unless ( $disable_agentcheck ) {
646 qsearchs( 'agent', { 'agentnum' => $self->cust_main->agentnum } );
647 return "agent ". $agent->agentnum. ':'. $agent->agent.
648 " can't purchase pkgpart ". $self->pkgpart
649 unless $agent->pkgpart_hashref->{ $self->pkgpart }
650 || $agent->agentnum == $self->part_pkg->agentnum;
653 $error = $self->ut_foreign_key('pkgpart', 'part_pkg', 'pkgpart' );
654 return $error if $error;
662 =item cancel [ OPTION => VALUE ... ]
664 Cancels and removes all services (see L<FS::cust_svc> and L<FS::part_svc>)
665 in this package, then cancels the package itself (sets the cancel field to
668 Available options are:
672 =item quiet - can be set true to supress email cancellation notices.
674 =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.
676 =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.
678 =item date - can be set to a unix style timestamp to specify when to cancel (expire)
680 =item nobill - can be set true to skip billing if it might otherwise be done.
682 =item unused_credit - can be set to 1 to credit the remaining time, or 0 to
683 not credit it. This must be set (by change()) when changing the package
684 to a different pkgpart or location, and probably shouldn't be in any other
685 case. If it's not set, the 'unused_credit_cancel' part_pkg option will
690 If there is an error, returns the error, otherwise returns false.
695 my( $self, %options ) = @_;
698 my $conf = new FS::Conf;
700 warn "cust_pkg::cancel called with options".
701 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
704 local $SIG{HUP} = 'IGNORE';
705 local $SIG{INT} = 'IGNORE';
706 local $SIG{QUIT} = 'IGNORE';
707 local $SIG{TERM} = 'IGNORE';
708 local $SIG{TSTP} = 'IGNORE';
709 local $SIG{PIPE} = 'IGNORE';
711 my $oldAutoCommit = $FS::UID::AutoCommit;
712 local $FS::UID::AutoCommit = 0;
715 my $old = $self->select_for_update;
717 if ( $old->get('cancel') || $self->get('cancel') ) {
718 dbh->rollback if $oldAutoCommit;
719 return ""; # no error
722 my $date = $options{date} if $options{date}; # expire/cancel later
723 $date = '' if ($date && $date <= time); # complain instead?
725 #race condition: usage could be ongoing until unprovisioned
726 #resolved by performing a change package instead (which unprovisions) and
728 if ( !$options{nobill} && !$date && $conf->exists('bill_usage_on_cancel') ) {
729 my $copy = $self->new({$self->hash});
731 $copy->cust_main->bill( pkg_list => [ $copy ], cancel => 1 );
732 warn "Error billing during cancel, custnum ".
733 #$self->cust_main->custnum. ": $error"
738 my $cancel_time = $options{'time'} || time;
740 if ( $options{'reason'} ) {
741 $error = $self->insert_reason( 'reason' => $options{'reason'},
742 'action' => $date ? 'expire' : 'cancel',
743 'date' => $date ? $date : $cancel_time,
744 'reason_otaker' => $options{'reason_otaker'},
747 dbh->rollback if $oldAutoCommit;
748 return "Error inserting cust_pkg_reason: $error";
754 foreach my $cust_svc (
757 sort { $a->[1] <=> $b->[1] }
758 map { [ $_, $_->svc_x->table_info->{'cancel_weight'} ]; }
759 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
761 my $error = $cust_svc->cancel;
764 $dbh->rollback if $oldAutoCommit;
765 return "Error cancelling cust_svc: $error";
769 # Add a credit for remaining service
770 my $last_bill = $self->getfield('last_bill') || 0;
771 my $next_bill = $self->getfield('bill') || 0;
773 if ( exists($options{'unused_credit'}) ) {
774 $do_credit = $options{'unused_credit'};
777 $do_credit = $self->part_pkg->option('unused_credit_cancel', 1);
780 and $last_bill > 0 # the package has been billed
781 and $next_bill > 0 # the package has a next bill date
782 and $next_bill >= $cancel_time # which is in the future
784 my $remaining_value = $self->calc_remain('time' => $cancel_time);
785 if ( $remaining_value > 0 ) {
786 my $error = $self->cust_main->credit(
788 'Credit for unused time on '. $self->part_pkg->pkg,
789 'reason_type' => $conf->config('cancel_credit_type'),
792 $dbh->rollback if $oldAutoCommit;
793 return "Error crediting customer \$$remaining_value for unused time".
794 " on ". $self->part_pkg->pkg. ": $error";
796 } #if $remaining_value
801 my %hash = $self->hash;
802 $date ? ($hash{'expire'} = $date) : ($hash{'cancel'} = $cancel_time);
803 my $new = new FS::cust_pkg ( \%hash );
804 $error = $new->replace( $self, options => { $self->options } );
806 $dbh->rollback if $oldAutoCommit;
810 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
811 return '' if $date; #no errors
813 my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ } $self->cust_main->invoicing_list;
814 if ( !$options{'quiet'} &&
815 $conf->exists('emailcancel', $self->cust_main->agentnum) &&
817 my $msgnum = $conf->config('cancel_msgnum', $self->cust_main->agentnum);
820 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum });
821 $error = $msg_template->send( 'cust_main' => $self->cust_main,
826 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
827 'to' => \@invoicing_list,
828 'subject' => ( $conf->config('cancelsubject') || 'Cancellation Notice' ),
829 'body' => [ map "$_\n", $conf->config('cancelmessage') ],
832 #should this do something on errors?
839 =item cancel_if_expired [ NOW_TIMESTAMP ]
841 Cancels this package if its expire date has been reached.
845 sub cancel_if_expired {
847 my $time = shift || time;
848 return '' unless $self->expire && $self->expire <= $time;
849 my $error = $self->cancel;
851 return "Error cancelling expired pkg ". $self->pkgnum. " for custnum ".
852 $self->custnum. ": $error";
859 Cancels any pending expiration (sets the expire field to null).
861 If there is an error, returns the error, otherwise returns false.
866 my( $self, %options ) = @_;
869 local $SIG{HUP} = 'IGNORE';
870 local $SIG{INT} = 'IGNORE';
871 local $SIG{QUIT} = 'IGNORE';
872 local $SIG{TERM} = 'IGNORE';
873 local $SIG{TSTP} = 'IGNORE';
874 local $SIG{PIPE} = 'IGNORE';
876 my $oldAutoCommit = $FS::UID::AutoCommit;
877 local $FS::UID::AutoCommit = 0;
880 my $old = $self->select_for_update;
882 my $pkgnum = $old->pkgnum;
883 if ( $old->get('cancel') || $self->get('cancel') ) {
884 dbh->rollback if $oldAutoCommit;
885 return "Can't unexpire cancelled package $pkgnum";
886 # or at least it's pointless
889 unless ( $old->get('expire') && $self->get('expire') ) {
890 dbh->rollback if $oldAutoCommit;
891 return ""; # no error
894 my %hash = $self->hash;
895 $hash{'expire'} = '';
896 my $new = new FS::cust_pkg ( \%hash );
897 $error = $new->replace( $self, options => { $self->options } );
899 $dbh->rollback if $oldAutoCommit;
903 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
909 =item suspend [ OPTION => VALUE ... ]
911 Suspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
912 package, then suspends the package itself (sets the susp field to now).
914 Available options are:
918 =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.
920 =item date - can be set to a unix style timestamp to specify when to suspend (adjourn)
924 If there is an error, returns the error, otherwise returns false.
929 my( $self, %options ) = @_;
932 local $SIG{HUP} = 'IGNORE';
933 local $SIG{INT} = 'IGNORE';
934 local $SIG{QUIT} = 'IGNORE';
935 local $SIG{TERM} = 'IGNORE';
936 local $SIG{TSTP} = 'IGNORE';
937 local $SIG{PIPE} = 'IGNORE';
939 my $oldAutoCommit = $FS::UID::AutoCommit;
940 local $FS::UID::AutoCommit = 0;
943 my $old = $self->select_for_update;
945 my $pkgnum = $old->pkgnum;
946 if ( $old->get('cancel') || $self->get('cancel') ) {
947 dbh->rollback if $oldAutoCommit;
948 return "Can't suspend cancelled package $pkgnum";
951 if ( $old->get('susp') || $self->get('susp') ) {
952 dbh->rollback if $oldAutoCommit;
953 return ""; # no error # complain on adjourn?
956 my $date = $options{date} if $options{date}; # adjourn/suspend later
957 $date = '' if ($date && $date <= time); # complain instead?
959 if ( $date && $old->get('expire') && $old->get('expire') < $date ) {
960 dbh->rollback if $oldAutoCommit;
961 return "Package $pkgnum expires before it would be suspended.";
964 my $suspend_time = $options{'time'} || time;
966 if ( $options{'reason'} ) {
967 $error = $self->insert_reason( 'reason' => $options{'reason'},
968 'action' => $date ? 'adjourn' : 'suspend',
969 'date' => $date ? $date : $suspend_time,
970 'reason_otaker' => $options{'reason_otaker'},
973 dbh->rollback if $oldAutoCommit;
974 return "Error inserting cust_pkg_reason: $error";
982 foreach my $cust_svc (
983 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
985 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
987 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
988 $dbh->rollback if $oldAutoCommit;
989 return "Illegal svcdb value in part_svc!";
992 require "FS/$svcdb.pm";
994 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
996 $error = $svc->suspend;
998 $dbh->rollback if $oldAutoCommit;
1001 my( $label, $value ) = $cust_svc->label;
1002 push @labels, "$label: $value";
1006 my $conf = new FS::Conf;
1007 if ( $conf->config('suspend_email_admin') ) {
1009 my $error = send_email(
1010 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
1011 #invoice_from ??? well as good as any
1012 'to' => $conf->config('suspend_email_admin'),
1013 'subject' => 'FREESIDE NOTIFICATION: Customer package suspended',
1015 "This is an automatic message from your Freeside installation\n",
1016 "informing you that the following customer package has been suspended:\n",
1018 'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
1019 'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
1020 ( map { "Service : $_\n" } @labels ),
1025 warn "WARNING: can't send suspension admin email (suspending anyway): ".
1033 my %hash = $self->hash;
1035 $hash{'adjourn'} = $date;
1037 $hash{'susp'} = $suspend_time;
1039 my $new = new FS::cust_pkg ( \%hash );
1040 $error = $new->replace( $self, options => { $self->options } );
1042 $dbh->rollback if $oldAutoCommit;
1046 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1051 =item unsuspend [ OPTION => VALUE ... ]
1053 Unsuspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
1054 package, then unsuspends the package itself (clears the susp field and the
1055 adjourn field if it is in the past).
1057 Available options are:
1061 =item adjust_next_bill
1063 Can be set true to adjust the next bill date forward by
1064 the amount of time the account was inactive. This was set true by default
1065 since 1.4.2 and 1.5.0pre6; however, starting with 1.7.0 this needs to be
1066 explicitly requested. Price plans for which this makes sense (anniversary-date
1067 based than prorate or subscription) could have an option to enable this
1072 If there is an error, returns the error, otherwise returns false.
1077 my( $self, %opt ) = @_;
1080 local $SIG{HUP} = 'IGNORE';
1081 local $SIG{INT} = 'IGNORE';
1082 local $SIG{QUIT} = 'IGNORE';
1083 local $SIG{TERM} = 'IGNORE';
1084 local $SIG{TSTP} = 'IGNORE';
1085 local $SIG{PIPE} = 'IGNORE';
1087 my $oldAutoCommit = $FS::UID::AutoCommit;
1088 local $FS::UID::AutoCommit = 0;
1091 my $old = $self->select_for_update;
1093 my $pkgnum = $old->pkgnum;
1094 if ( $old->get('cancel') || $self->get('cancel') ) {
1095 dbh->rollback if $oldAutoCommit;
1096 return "Can't unsuspend cancelled package $pkgnum";
1099 unless ( $old->get('susp') && $self->get('susp') ) {
1100 dbh->rollback if $oldAutoCommit;
1101 return ""; # no error # complain instead?
1104 foreach my $cust_svc (
1105 qsearch('cust_svc',{'pkgnum'=> $self->pkgnum } )
1107 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
1109 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
1110 $dbh->rollback if $oldAutoCommit;
1111 return "Illegal svcdb value in part_svc!";
1114 require "FS/$svcdb.pm";
1116 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
1118 $error = $svc->unsuspend;
1120 $dbh->rollback if $oldAutoCommit;
1127 my %hash = $self->hash;
1128 my $inactive = time - $hash{'susp'};
1130 my $conf = new FS::Conf;
1132 if ( $inactive > 0 &&
1133 ( $hash{'bill'} || $hash{'setup'} ) &&
1134 ( $opt{'adjust_next_bill'} ||
1135 $conf->exists('unsuspend-always_adjust_next_bill_date') ||
1136 $self->part_pkg->option('unsuspend_adjust_bill', 1) )
1139 $hash{'bill'} = ( $hash{'bill'} || $hash{'setup'} ) + $inactive;
1144 $hash{'adjourn'} = '' if $hash{'adjourn'} < time;
1145 my $new = new FS::cust_pkg ( \%hash );
1146 $error = $new->replace( $self, options => { $self->options } );
1148 $dbh->rollback if $oldAutoCommit;
1152 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1159 Cancels any pending suspension (sets the adjourn field to null).
1161 If there is an error, returns the error, otherwise returns false.
1166 my( $self, %options ) = @_;
1169 local $SIG{HUP} = 'IGNORE';
1170 local $SIG{INT} = 'IGNORE';
1171 local $SIG{QUIT} = 'IGNORE';
1172 local $SIG{TERM} = 'IGNORE';
1173 local $SIG{TSTP} = 'IGNORE';
1174 local $SIG{PIPE} = 'IGNORE';
1176 my $oldAutoCommit = $FS::UID::AutoCommit;
1177 local $FS::UID::AutoCommit = 0;
1180 my $old = $self->select_for_update;
1182 my $pkgnum = $old->pkgnum;
1183 if ( $old->get('cancel') || $self->get('cancel') ) {
1184 dbh->rollback if $oldAutoCommit;
1185 return "Can't unadjourn cancelled package $pkgnum";
1186 # or at least it's pointless
1189 if ( $old->get('susp') || $self->get('susp') ) {
1190 dbh->rollback if $oldAutoCommit;
1191 return "Can't unadjourn suspended package $pkgnum";
1192 # perhaps this is arbitrary
1195 unless ( $old->get('adjourn') && $self->get('adjourn') ) {
1196 dbh->rollback if $oldAutoCommit;
1197 return ""; # no error
1200 my %hash = $self->hash;
1201 $hash{'adjourn'} = '';
1202 my $new = new FS::cust_pkg ( \%hash );
1203 $error = $new->replace( $self, options => { $self->options } );
1205 $dbh->rollback if $oldAutoCommit;
1209 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1216 =item change HASHREF | OPTION => VALUE ...
1218 Changes this package: cancels it and creates a new one, with a different
1219 pkgpart or locationnum or both. All services are transferred to the new
1220 package (no change will be made if this is not possible).
1222 Options may be passed as a list of key/value pairs or as a hash reference.
1229 New locationnum, to change the location for this package.
1233 New FS::cust_location object, to create a new location and assign it
1238 New pkgpart (see L<FS::part_pkg>).
1242 New refnum (see L<FS::part_referral>).
1246 Set to true to transfer billing dates (start_date, setup, last_bill, bill,
1247 susp, adjourn, cancel, expire, and contract_end) to the new package.
1251 At least one of locationnum, cust_location, pkgpart, refnum must be specified
1252 (otherwise, what's the point?)
1254 Returns either the new FS::cust_pkg object or a scalar error.
1258 my $err_or_new_cust_pkg = $old_cust_pkg->change
1262 #some false laziness w/order
1265 my $opt = ref($_[0]) ? shift : { @_ };
1267 # my ($custnum, $pkgparts, $remove_pkgnum, $return_cust_pkg, $refnum) = @_;
1270 my $conf = new FS::Conf;
1272 # Transactionize this whole mess
1273 local $SIG{HUP} = 'IGNORE';
1274 local $SIG{INT} = 'IGNORE';
1275 local $SIG{QUIT} = 'IGNORE';
1276 local $SIG{TERM} = 'IGNORE';
1277 local $SIG{TSTP} = 'IGNORE';
1278 local $SIG{PIPE} = 'IGNORE';
1280 my $oldAutoCommit = $FS::UID::AutoCommit;
1281 local $FS::UID::AutoCommit = 0;
1290 #$hash{$_} = $self->$_() foreach qw( last_bill bill );
1292 #$hash{$_} = $self->$_() foreach qw( setup );
1294 $hash{'setup'} = $time if $self->setup;
1296 $hash{'change_date'} = $time;
1297 $hash{"change_$_"} = $self->$_()
1298 foreach qw( pkgnum pkgpart locationnum );
1300 if ( $opt->{'cust_location'} &&
1301 ( ! $opt->{'locationnum'} || $opt->{'locationnum'} == -1 ) ) {
1302 $error = $opt->{'cust_location'}->insert;
1304 $dbh->rollback if $oldAutoCommit;
1305 return "inserting cust_location (transaction rolled back): $error";
1307 $opt->{'locationnum'} = $opt->{'cust_location'}->locationnum;
1310 my $unused_credit = 0;
1311 if ( $opt->{'keep_dates'} ) {
1312 foreach my $date ( qw(setup bill last_bill susp adjourn cancel expire
1313 start_date contract_end ) ) {
1314 $hash{$date} = $self->getfield($date);
1317 # Special case. If the pkgpart is changing, and the customer is
1318 # going to be credited for remaining time, don't keep setup, bill,
1319 # or last_bill dates, and DO pass the flag to cancel() to credit
1321 if ( $opt->{'pkgpart'}
1322 and $opt->{'pkgpart'} != $self->pkgpart
1323 and $self->part_pkg->option('unused_credit_change', 1) ) {
1325 $hash{$_} = '' foreach qw(setup bill last_bill);
1328 # Create the new package.
1329 my $cust_pkg = new FS::cust_pkg {
1330 custnum => $self->custnum,
1331 pkgpart => ( $opt->{'pkgpart'} || $self->pkgpart ),
1332 refnum => ( $opt->{'refnum'} || $self->refnum ),
1333 locationnum => ( $opt->{'locationnum'} || $self->locationnum ),
1337 $error = $cust_pkg->insert( 'change' => 1 );
1339 $dbh->rollback if $oldAutoCommit;
1343 # Transfer services and cancel old package.
1345 $error = $self->transfer($cust_pkg);
1346 if ($error and $error == 0) {
1347 # $old_pkg->transfer failed.
1348 $dbh->rollback if $oldAutoCommit;
1352 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
1353 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
1354 $error = $self->transfer($cust_pkg, 'change_svcpart'=>1 );
1355 if ($error and $error == 0) {
1356 # $old_pkg->transfer failed.
1357 $dbh->rollback if $oldAutoCommit;
1363 # Transfers were successful, but we still had services left on the old
1364 # package. We can't change the package under this circumstances, so abort.
1365 $dbh->rollback if $oldAutoCommit;
1366 return "Unable to transfer all services from package ". $self->pkgnum;
1369 #reset usage if changing pkgpart
1370 # AND usage rollover is off (otherwise adds twice, now and at package bill)
1371 if ($self->pkgpart != $cust_pkg->pkgpart) {
1372 my $part_pkg = $cust_pkg->part_pkg;
1373 $error = $part_pkg->reset_usage($cust_pkg, $part_pkg->is_prepaid
1377 if $part_pkg->can('reset_usage') && ! $part_pkg->option('usage_rollover',1);
1380 $dbh->rollback if $oldAutoCommit;
1381 return "Error setting usage values: $error";
1385 #Good to go, cancel old package. Notify 'cancel' of whether to credit
1387 $error = $self->cancel( quiet=>1, unused_credit => $unused_credit );
1389 $dbh->rollback if $oldAutoCommit;
1393 if ( $conf->exists('cust_pkg-change_pkgpart-bill_now') ) {
1395 my $error = $cust_pkg->cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1397 $dbh->rollback if $oldAutoCommit;
1402 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1409 use Storable 'thaw';
1411 sub process_bulk_cust_pkg {
1413 my $param = thaw(decode_base64(shift));
1414 warn Dumper($param) if $DEBUG;
1416 my $old_part_pkg = qsearchs('part_pkg',
1417 { pkgpart => $param->{'old_pkgpart'} });
1418 my $new_part_pkg = qsearchs('part_pkg',
1419 { pkgpart => $param->{'new_pkgpart'} });
1420 die "Must select a new package type\n" unless $new_part_pkg;
1421 #my $keep_dates = $param->{'keep_dates'} || 0;
1422 my $keep_dates = 1; # there is no good reason to turn this off
1424 local $SIG{HUP} = 'IGNORE';
1425 local $SIG{INT} = 'IGNORE';
1426 local $SIG{QUIT} = 'IGNORE';
1427 local $SIG{TERM} = 'IGNORE';
1428 local $SIG{TSTP} = 'IGNORE';
1429 local $SIG{PIPE} = 'IGNORE';
1431 my $oldAutoCommit = $FS::UID::AutoCommit;
1432 local $FS::UID::AutoCommit = 0;
1435 my @cust_pkgs = qsearch('cust_pkg', { 'pkgpart' => $param->{'old_pkgpart'} } );
1438 foreach my $old_cust_pkg ( @cust_pkgs ) {
1440 $job->update_statustext(int(100*$i/(scalar @cust_pkgs)));
1441 if ( $old_cust_pkg->getfield('cancel') ) {
1442 warn '[process_bulk_cust_pkg ] skipping canceled pkgnum '.
1443 $old_cust_pkg->pkgnum."\n"
1447 warn '[process_bulk_cust_pkg] changing pkgnum '.$old_cust_pkg->pkgnum."\n"
1449 my $error = $old_cust_pkg->change(
1450 'pkgpart' => $param->{'new_pkgpart'},
1451 'keep_dates' => $keep_dates
1453 if ( !ref($error) ) { # change returns the cust_pkg on success
1455 die "Error changing pkgnum ".$old_cust_pkg->pkgnum.": '$error'\n";
1458 $dbh->commit if $oldAutoCommit;
1464 Returns the last bill date, or if there is no last bill date, the setup date.
1465 Useful for billing metered services.
1471 return $self->setfield('last_bill', $_[0]) if @_;
1472 return $self->getfield('last_bill') if $self->getfield('last_bill');
1473 my $cust_bill_pkg = qsearchs('cust_bill_pkg', { 'pkgnum' => $self->pkgnum,
1474 'edate' => $self->bill, } );
1475 $cust_bill_pkg ? $cust_bill_pkg->sdate : $self->setup || 0;
1478 =item last_cust_pkg_reason ACTION
1480 Returns the most recent ACTION FS::cust_pkg_reason associated with the package.
1481 Returns false if there is no reason or the package is not currenly ACTION'd
1482 ACTION is one of adjourn, susp, cancel, or expire.
1486 sub last_cust_pkg_reason {
1487 my ( $self, $action ) = ( shift, shift );
1488 my $date = $self->get($action);
1490 'table' => 'cust_pkg_reason',
1491 'hashref' => { 'pkgnum' => $self->pkgnum,
1492 'action' => substr(uc($action), 0, 1),
1495 'order_by' => 'ORDER BY num DESC LIMIT 1',
1499 =item last_reason ACTION
1501 Returns the most recent ACTION FS::reason associated with the package.
1502 Returns false if there is no reason or the package is not currenly ACTION'd
1503 ACTION is one of adjourn, susp, cancel, or expire.
1508 my $cust_pkg_reason = shift->last_cust_pkg_reason(@_);
1509 $cust_pkg_reason->reason
1510 if $cust_pkg_reason;
1515 Returns the definition for this billing item, as an FS::part_pkg object (see
1522 return $self->{'_pkgpart'} if $self->{'_pkgpart'};
1523 cluck "cust_pkg->part_pkg called" if $DEBUG > 1;
1524 qsearchs( 'part_pkg', { 'pkgpart' => $self->pkgpart } );
1529 Returns the cancelled package this package was changed from, if any.
1535 return '' unless $self->change_pkgnum;
1536 qsearchs('cust_pkg', { 'pkgnum' => $self->change_pkgnum } );
1541 Calls the I<calc_setup> of the FS::part_pkg object associated with this billing
1548 $self->part_pkg->calc_setup($self, @_);
1553 Calls the I<calc_recur> of the FS::part_pkg object associated with this billing
1560 $self->part_pkg->calc_recur($self, @_);
1565 Calls the I<base_recur> of the FS::part_pkg object associated with this billing
1572 $self->part_pkg->base_recur($self, @_);
1577 Calls the I<calc_remain> of the FS::part_pkg object associated with this
1584 $self->part_pkg->calc_remain($self, @_);
1589 Calls the I<calc_cancel> of the FS::part_pkg object associated with this
1596 $self->part_pkg->calc_cancel($self, @_);
1601 Returns any invoice line items for this package (see L<FS::cust_bill_pkg>).
1607 qsearch( 'cust_bill_pkg', { 'pkgnum' => $self->pkgnum } );
1610 =item cust_pkg_detail [ DETAILTYPE ]
1612 Returns any customer package details for this package (see
1613 L<FS::cust_pkg_detail>).
1615 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
1619 sub cust_pkg_detail {
1621 my %hash = ( 'pkgnum' => $self->pkgnum );
1622 $hash{detailtype} = shift if @_;
1624 'table' => 'cust_pkg_detail',
1625 'hashref' => \%hash,
1626 'order_by' => 'ORDER BY weight, pkgdetailnum',
1630 =item set_cust_pkg_detail DETAILTYPE [ DETAIL, DETAIL, ... ]
1632 Sets customer package details for this package (see L<FS::cust_pkg_detail>).
1634 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
1636 If there is an error, returns the error, otherwise returns false.
1640 sub set_cust_pkg_detail {
1641 my( $self, $detailtype, @details ) = @_;
1643 local $SIG{HUP} = 'IGNORE';
1644 local $SIG{INT} = 'IGNORE';
1645 local $SIG{QUIT} = 'IGNORE';
1646 local $SIG{TERM} = 'IGNORE';
1647 local $SIG{TSTP} = 'IGNORE';
1648 local $SIG{PIPE} = 'IGNORE';
1650 my $oldAutoCommit = $FS::UID::AutoCommit;
1651 local $FS::UID::AutoCommit = 0;
1654 foreach my $current ( $self->cust_pkg_detail($detailtype) ) {
1655 my $error = $current->delete;
1657 $dbh->rollback if $oldAutoCommit;
1658 return "error removing old detail: $error";
1662 foreach my $detail ( @details ) {
1663 my $cust_pkg_detail = new FS::cust_pkg_detail {
1664 'pkgnum' => $self->pkgnum,
1665 'detailtype' => $detailtype,
1666 'detail' => $detail,
1668 my $error = $cust_pkg_detail->insert;
1670 $dbh->rollback if $oldAutoCommit;
1671 return "error adding new detail: $error";
1676 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1683 Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.
1687 #false laziness w/cust_bill.pm
1691 'table' => 'cust_event',
1692 'addl_from' => 'JOIN part_event USING ( eventpart )',
1693 'hashref' => { 'tablenum' => $self->pkgnum },
1694 'extra_sql' => " AND eventtable = 'cust_pkg' ",
1698 =item num_cust_event
1700 Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.
1704 #false laziness w/cust_bill.pm
1705 sub num_cust_event {
1708 "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
1709 " WHERE tablenum = ? AND eventtable = 'cust_pkg'";
1710 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
1711 $sth->execute($self->pkgnum) or die $sth->errstr. " executing $sql";
1712 $sth->fetchrow_arrayref->[0];
1715 =item cust_svc [ SVCPART ]
1717 Returns the services for this package, as FS::cust_svc objects (see
1718 L<FS::cust_svc>). If a svcpart is specified, return only the matching
1726 return () unless $self->num_cust_svc(@_);
1729 return qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum,
1730 'svcpart' => shift, } );
1733 cluck "cust_pkg->cust_svc called" if $DEBUG > 2;
1735 #if ( $self->{'_svcnum'} ) {
1736 # values %{ $self->{'_svcnum'}->cache };
1738 $self->_sort_cust_svc(
1739 [ qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } ) ]
1745 =item overlimit [ SVCPART ]
1747 Returns the services for this package which have exceeded their
1748 usage limit as FS::cust_svc objects (see L<FS::cust_svc>). If a svcpart
1749 is specified, return only the matching services.
1755 return () unless $self->num_cust_svc(@_);
1756 grep { $_->overlimit } $self->cust_svc(@_);
1759 =item h_cust_svc END_TIMESTAMP [ START_TIMESTAMP ] [ MODE ]
1761 Returns historical services for this package created before END TIMESTAMP and
1762 (optionally) not cancelled before START_TIMESTAMP, as FS::h_cust_svc objects
1763 (see L<FS::h_cust_svc>). If MODE is 'I' (for 'invoice'), services with the
1764 I<pkg_svc.hidden> flag will be omitted.
1770 warn "$me _h_cust_svc called on $self\n"
1773 my ($end, $start, $mode) = @_;
1774 my @cust_svc = $self->_sort_cust_svc(
1775 [ qsearch( 'h_cust_svc',
1776 { 'pkgnum' => $self->pkgnum, },
1777 FS::h_cust_svc->sql_h_search(@_),
1780 if ( $mode eq 'I' ) {
1781 my %hidden_svcpart = map { $_->svcpart => $_->hidden } $self->part_svc;
1782 return grep { !$hidden_svcpart{$_->svcpart} } @cust_svc;
1788 sub _sort_cust_svc {
1789 my( $self, $arrayref ) = @_;
1792 sub ($$) { my ($a, $b) = @_; $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] };
1797 my $pkg_svc = qsearchs( 'pkg_svc', { 'pkgpart' => $self->pkgpart,
1798 'svcpart' => $_->svcpart } );
1800 $pkg_svc ? $pkg_svc->primary_svc : '',
1801 $pkg_svc ? $pkg_svc->quantity : 0,
1808 =item num_cust_svc [ SVCPART ]
1810 Returns the number of provisioned services for this package. If a svcpart is
1811 specified, counts only the matching services.
1818 return $self->{'_num_cust_svc'}
1820 && exists($self->{'_num_cust_svc'})
1821 && $self->{'_num_cust_svc'} =~ /\d/;
1823 cluck "cust_pkg->num_cust_svc called, _num_cust_svc:".$self->{'_num_cust_svc'}
1826 my $sql = 'SELECT COUNT(*) FROM cust_svc WHERE pkgnum = ?';
1827 $sql .= ' AND svcpart = ?' if @_;
1829 my $sth = dbh->prepare($sql) or die dbh->errstr;
1830 $sth->execute($self->pkgnum, @_) or die $sth->errstr;
1831 $sth->fetchrow_arrayref->[0];
1834 =item available_part_svc
1836 Returns a list of FS::part_svc objects representing services included in this
1837 package but not yet provisioned. Each FS::part_svc object also has an extra
1838 field, I<num_avail>, which specifies the number of available services.
1842 sub available_part_svc {
1844 grep { $_->num_avail > 0 }
1846 my $part_svc = $_->part_svc;
1847 $part_svc->{'Hash'}{'num_avail'} = #evil encapsulation-breaking
1848 $_->quantity - $self->num_cust_svc($_->svcpart);
1850 # more evil encapsulation breakage
1851 if($part_svc->{'Hash'}{'num_avail'} > 0) {
1852 my @exports = $part_svc->part_export_did;
1853 $part_svc->{'Hash'}{'can_get_dids'} = scalar(@exports);
1858 $self->part_pkg->pkg_svc;
1863 Returns a list of FS::part_svc objects representing provisioned and available
1864 services included in this package. Each FS::part_svc object also has the
1865 following extra fields:
1869 =item num_cust_svc (count)
1871 =item num_avail (quantity - count)
1873 =item cust_pkg_svc (services) - array reference containing the provisioned services, as cust_svc objects
1876 label -> ($cust_svc->label)[1]
1885 #XXX some sort of sort order besides numeric by svcpart...
1886 my @part_svc = sort { $a->svcpart <=> $b->svcpart } map {
1888 my $part_svc = $pkg_svc->part_svc;
1889 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
1890 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #more evil
1891 $part_svc->{'Hash'}{'num_avail'} =
1892 max( 0, $pkg_svc->quantity - $num_cust_svc );
1893 $part_svc->{'Hash'}{'cust_pkg_svc'} =
1894 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : [];
1895 $part_svc->{'Hash'}{'hidden'} = $pkg_svc->hidden;
1897 } $self->part_pkg->pkg_svc;
1900 push @part_svc, map {
1902 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
1903 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #speak no evail
1904 $part_svc->{'Hash'}{'num_avail'} = 0; #0-$num_cust_svc ?
1905 $part_svc->{'Hash'}{'cust_pkg_svc'} =
1906 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : [];
1908 } $self->extra_part_svc;
1914 =item extra_part_svc
1916 Returns a list of FS::part_svc objects corresponding to services in this
1917 package which are still provisioned but not (any longer) available in the
1922 sub extra_part_svc {
1925 my $pkgnum = $self->pkgnum;
1926 my $pkgpart = $self->pkgpart;
1929 # 'table' => 'part_svc',
1932 # "WHERE 0 = ( SELECT COUNT(*) FROM pkg_svc
1933 # WHERE pkg_svc.svcpart = part_svc.svcpart
1934 # AND pkg_svc.pkgpart = ?
1937 # AND 0 < ( SELECT COUNT(*) FROM cust_svc
1938 # LEFT JOIN cust_pkg USING ( pkgnum )
1939 # WHERE cust_svc.svcpart = part_svc.svcpart
1942 # 'extra_param' => [ [$self->pkgpart=>'int'], [$self->pkgnum=>'int'] ],
1945 #seems to benchmark slightly faster...
1947 #'select' => 'DISTINCT ON (svcpart) part_svc.*',
1948 #MySQL doesn't grok DISINCT ON
1949 'select' => 'DISTINCT part_svc.*',
1950 'table' => 'part_svc',
1952 'LEFT JOIN pkg_svc ON ( pkg_svc.svcpart = part_svc.svcpart
1953 AND pkg_svc.pkgpart = ?
1956 LEFT JOIN cust_svc ON ( cust_svc.svcpart = part_svc.svcpart )
1957 LEFT JOIN cust_pkg USING ( pkgnum )
1960 'extra_sql' => "WHERE pkgsvcnum IS NULL AND cust_pkg.pkgnum = ? ",
1961 'extra_param' => [ [$self->pkgpart=>'int'], [$self->pkgnum=>'int'] ],
1967 Returns a short status string for this package, currently:
1971 =item not yet billed
1973 =item one-time charge
1988 my $freq = length($self->freq) ? $self->freq : $self->part_pkg->freq;
1990 return 'cancelled' if $self->get('cancel');
1991 return 'suspended' if $self->susp;
1992 return 'not yet billed' unless $self->setup;
1993 return 'one-time charge' if $freq =~ /^(0|$)/;
1997 =item ucfirst_status
1999 Returns the status with the first character capitalized.
2003 sub ucfirst_status {
2004 ucfirst(shift->status);
2009 Class method that returns the list of possible status strings for packages
2010 (see L<the status method|/status>). For example:
2012 @statuses = FS::cust_pkg->statuses();
2016 tie my %statuscolor, 'Tie::IxHash',
2017 'not yet billed' => '009999', #teal? cyan?
2018 'one-time charge' => '000000',
2019 'active' => '00CC00',
2020 'suspended' => 'FF9900',
2021 'cancelled' => 'FF0000',
2025 my $self = shift; #could be class...
2026 #grep { $_ !~ /^(not yet billed)$/ } #this is a dumb status anyway
2027 # # mayble split btw one-time vs. recur
2033 Returns a hex triplet color string for this package's status.
2039 $statuscolor{$self->status};
2044 Returns a label for this package. (Currently "pkgnum: pkg - comment" or
2045 "pkg-comment" depending on user preference).
2051 my $label = $self->part_pkg->pkg_comment( 'nopkgpart' => 1 );
2052 $label = $self->pkgnum. ": $label"
2053 if $FS::CurrentUser::CurrentUser->option('show_pkgnum');
2057 =item pkg_label_long
2059 Returns a long label for this package, adding the primary service's label to
2064 sub pkg_label_long {
2066 my $label = $self->pkg_label;
2067 my $cust_svc = $self->primary_cust_svc;
2068 $label .= ' ('. ($cust_svc->label)[1]. ')' if $cust_svc;
2072 =item primary_cust_svc
2074 Returns a primary service (as FS::cust_svc object) if one can be identified.
2078 #for labeling purposes - might not 100% match up with part_pkg->svcpart's idea
2080 sub primary_cust_svc {
2083 my @cust_svc = $self->cust_svc;
2085 return '' unless @cust_svc; #no serivces - irrelevant then
2087 return $cust_svc[0] if scalar(@cust_svc) == 1; #always return a single service
2089 # primary service as specified in the package definition
2090 # or exactly one service definition with quantity one
2091 my $svcpart = $self->part_pkg->svcpart;
2092 @cust_svc = grep { $_->svcpart == $svcpart } @cust_svc;
2093 return $cust_svc[0] if scalar(@cust_svc) == 1;
2095 #couldn't identify one thing..
2101 Returns a list of lists, calling the label method for all services
2102 (see L<FS::cust_svc>) of this billing item.
2108 map { [ $_->label ] } $self->cust_svc;
2111 =item h_labels END_TIMESTAMP [ START_TIMESTAMP ] [ MODE ]
2113 Like the labels method, but returns historical information on services that
2114 were active as of END_TIMESTAMP and (optionally) not cancelled before
2115 START_TIMESTAMP. If MODE is 'I' (for 'invoice'), services with the
2116 I<pkg_svc.hidden> flag will be omitted.
2118 Returns a list of lists, calling the label method for all (historical) services
2119 (see L<FS::h_cust_svc>) of this billing item.
2125 warn "$me _h_labels called on $self\n"
2127 map { [ $_->label(@_) ] } $self->h_cust_svc(@_);
2132 Like labels, except returns a simple flat list, and shortens long
2133 (currently >5 or the cust_bill-max_same_services configuration value) lists of
2134 identical services to one line that lists the service label and the number of
2135 individual services rather than individual items.
2140 shift->_labels_short( 'labels', @_ );
2143 =item h_labels_short END_TIMESTAMP [ START_TIMESTAMP ]
2145 Like h_labels, except returns a simple flat list, and shortens long
2146 (currently >5 or the cust_bill-max_same_services configuration value) lists of
2147 identical services to one line that lists the service label and the number of
2148 individual services rather than individual items.
2152 sub h_labels_short {
2153 shift->_labels_short( 'h_labels', @_ );
2157 my( $self, $method ) = ( shift, shift );
2159 warn "$me _labels_short called on $self with $method method\n"
2162 my $conf = new FS::Conf;
2163 my $max_same_services = $conf->config('cust_bill-max_same_services') || 5;
2165 warn "$me _labels_short populating \%labels\n"
2169 #tie %labels, 'Tie::IxHash';
2170 push @{ $labels{$_->[0]} }, $_->[1]
2171 foreach $self->$method(@_);
2173 warn "$me _labels_short populating \@labels\n"
2177 foreach my $label ( keys %labels ) {
2179 my @values = grep { ! $seen{$_}++ } @{ $labels{$label} };
2180 my $num = scalar(@values);
2181 warn "$me _labels_short $num items for $label\n"
2184 if ( $num > $max_same_services ) {
2185 warn "$me _labels_short more than $max_same_services, so summarizing\n"
2187 push @labels, "$label ($num)";
2189 if ( $conf->exists('cust_bill-consolidate_services') ) {
2190 warn "$me _labels_short consolidating services\n"
2192 # push @labels, "$label: ". join(', ', @values);
2194 my $detail = "$label: ";
2195 $detail .= shift(@values). ', '
2197 && ( length($detail.$values[0]) < 78 || $detail eq "$label: " );
2199 push @labels, $detail;
2201 warn "$me _labels_short done consolidating services\n"
2204 warn "$me _labels_short adding service data\n"
2206 push @labels, map { "$label: $_" } @values;
2217 Returns the parent customer object (see L<FS::cust_main>).
2223 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
2226 #these subs are in location_Mixin.pm now... unfortunately the POD doesn't mixin
2230 Returns the location object, if any (see L<FS::cust_location>).
2232 =item cust_location_or_main
2234 If this package is associated with a location, returns the locaiton (see
2235 L<FS::cust_location>), otherwise returns the customer (see L<FS::cust_main>).
2237 =item location_label [ OPTION => VALUE ... ]
2239 Returns the label of the location object (see L<FS::cust_location>).
2243 #end of subs in location_Mixin.pm now... unfortunately the POD doesn't mixin
2245 =item seconds_since TIMESTAMP
2247 Returns the number of seconds all accounts (see L<FS::svc_acct>) in this
2248 package have been online since TIMESTAMP, according to the session monitor.
2250 TIMESTAMP is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
2251 L<Time::Local> and L<Date::Parse> for conversion functions.
2256 my($self, $since) = @_;
2259 foreach my $cust_svc (
2260 grep { $_->part_svc->svcdb eq 'svc_acct' } $self->cust_svc
2262 $seconds += $cust_svc->seconds_since($since);
2269 =item seconds_since_sqlradacct TIMESTAMP_START TIMESTAMP_END
2271 Returns the numbers of seconds all accounts (see L<FS::svc_acct>) in this
2272 package have been online between TIMESTAMP_START (inclusive) and TIMESTAMP_END
2275 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
2276 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
2282 sub seconds_since_sqlradacct {
2283 my($self, $start, $end) = @_;
2287 foreach my $cust_svc (
2289 my $part_svc = $_->part_svc;
2290 $part_svc->svcdb eq 'svc_acct'
2291 && scalar($part_svc->part_export('sqlradius'));
2294 $seconds += $cust_svc->seconds_since_sqlradacct($start, $end);
2301 =item attribute_since_sqlradacct TIMESTAMP_START TIMESTAMP_END ATTRIBUTE
2303 Returns the sum of the given attribute for all accounts (see L<FS::svc_acct>)
2304 in this package for sessions ending between TIMESTAMP_START (inclusive) and
2308 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
2309 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
2314 sub attribute_since_sqlradacct {
2315 my($self, $start, $end, $attrib) = @_;
2319 foreach my $cust_svc (
2321 my $part_svc = $_->part_svc;
2322 $part_svc->svcdb eq 'svc_acct'
2323 && scalar($part_svc->part_export('sqlradius'));
2326 $sum += $cust_svc->attribute_since_sqlradacct($start, $end, $attrib);
2338 my( $self, $value ) = @_;
2339 if ( defined($value) ) {
2340 $self->setfield('quantity', $value);
2342 $self->getfield('quantity') || 1;
2345 =item transfer DEST_PKGNUM | DEST_CUST_PKG, [ OPTION => VALUE ... ]
2347 Transfers as many services as possible from this package to another package.
2349 The destination package can be specified by pkgnum by passing an FS::cust_pkg
2350 object. The destination package must already exist.
2352 Services are moved only if the destination allows services with the correct
2353 I<svcpart> (not svcdb), unless the B<change_svcpart> option is set true. Use
2354 this option with caution! No provision is made for export differences
2355 between the old and new service definitions. Probably only should be used
2356 when your exports for all service definitions of a given svcdb are identical.
2357 (attempt a transfer without it first, to move all possible svcpart-matching
2360 Any services that can't be moved remain in the original package.
2362 Returns an error, if there is one; otherwise, returns the number of services
2363 that couldn't be moved.
2368 my ($self, $dest_pkgnum, %opt) = @_;
2374 if (ref ($dest_pkgnum) eq 'FS::cust_pkg') {
2375 $dest = $dest_pkgnum;
2376 $dest_pkgnum = $dest->pkgnum;
2378 $dest = qsearchs('cust_pkg', { pkgnum => $dest_pkgnum });
2381 return ('Package does not exist: '.$dest_pkgnum) unless $dest;
2383 foreach my $pkg_svc ( $dest->part_pkg->pkg_svc ) {
2384 $target{$pkg_svc->svcpart} = $pkg_svc->quantity;
2387 foreach my $cust_svc ($dest->cust_svc) {
2388 $target{$cust_svc->svcpart}--;
2391 my %svcpart2svcparts = ();
2392 if ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
2393 warn "change_svcpart option received, creating alternates list\n" if $DEBUG;
2394 foreach my $svcpart ( map { $_->svcpart } $self->cust_svc ) {
2395 next if exists $svcpart2svcparts{$svcpart};
2396 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2397 $svcpart2svcparts{$svcpart} = [
2399 sort { $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] }
2401 my $pkg_svc = qsearchs( 'pkg_svc', { 'pkgpart' => $dest->pkgpart,
2402 'svcpart' => $_ } );
2404 $pkg_svc ? $pkg_svc->primary_svc : '',
2405 $pkg_svc ? $pkg_svc->quantity : 0,
2409 grep { $_ != $svcpart }
2411 qsearch('part_svc', { 'svcdb' => $part_svc->svcdb } )
2413 warn "alternates for svcpart $svcpart: ".
2414 join(', ', @{$svcpart2svcparts{$svcpart}}). "\n"
2419 foreach my $cust_svc ($self->cust_svc) {
2420 if($target{$cust_svc->svcpart} > 0) {
2421 $target{$cust_svc->svcpart}--;
2422 my $new = new FS::cust_svc { $cust_svc->hash };
2423 $new->pkgnum($dest_pkgnum);
2424 my $error = $new->replace($cust_svc);
2425 return $error if $error;
2426 } elsif ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
2428 warn "looking for alternates for svcpart ". $cust_svc->svcpart. "\n";
2429 warn "alternates to consider: ".
2430 join(', ', @{$svcpart2svcparts{$cust_svc->svcpart}}). "\n";
2432 my @alternate = grep {
2433 warn "considering alternate svcpart $_: ".
2434 "$target{$_} available in new package\n"
2437 } @{$svcpart2svcparts{$cust_svc->svcpart}};
2439 warn "alternate(s) found\n" if $DEBUG;
2440 my $change_svcpart = $alternate[0];
2441 $target{$change_svcpart}--;
2442 my $new = new FS::cust_svc { $cust_svc->hash };
2443 $new->svcpart($change_svcpart);
2444 $new->pkgnum($dest_pkgnum);
2445 my $error = $new->replace($cust_svc);
2446 return $error if $error;
2459 This method is deprecated. See the I<depend_jobnum> option to the insert and
2460 order_pkgs methods in FS::cust_main for a better way to defer provisioning.
2467 local $SIG{HUP} = 'IGNORE';
2468 local $SIG{INT} = 'IGNORE';
2469 local $SIG{QUIT} = 'IGNORE';
2470 local $SIG{TERM} = 'IGNORE';
2471 local $SIG{TSTP} = 'IGNORE';
2472 local $SIG{PIPE} = 'IGNORE';
2474 my $oldAutoCommit = $FS::UID::AutoCommit;
2475 local $FS::UID::AutoCommit = 0;
2478 foreach my $cust_svc ( $self->cust_svc ) {
2479 #false laziness w/svc_Common::insert
2480 my $svc_x = $cust_svc->svc_x;
2481 foreach my $part_export ( $cust_svc->part_svc->part_export ) {
2482 my $error = $part_export->export_insert($svc_x);
2484 $dbh->rollback if $oldAutoCommit;
2490 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2497 Associates this package with a (suspension or cancellation) reason (see
2498 L<FS::cust_pkg_reason>, possibly inserting a new reason on the fly (see
2501 Available options are:
2507 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.
2511 the access_user (see L<FS::access_user>) providing the reason
2519 the action (cancel, susp, adjourn, expire) associated with the reason
2523 If there is an error, returns the error, otherwise returns false.
2528 my ($self, %options) = @_;
2530 my $otaker = $options{reason_otaker} ||
2531 $FS::CurrentUser::CurrentUser->username;
2534 if ( $options{'reason'} =~ /^(\d+)$/ ) {
2538 } elsif ( ref($options{'reason'}) ) {
2540 return 'Enter a new reason (or select an existing one)'
2541 unless $options{'reason'}->{'reason'} !~ /^\s*$/;
2543 my $reason = new FS::reason({
2544 'reason_type' => $options{'reason'}->{'typenum'},
2545 'reason' => $options{'reason'}->{'reason'},
2547 my $error = $reason->insert;
2548 return $error if $error;
2550 $reasonnum = $reason->reasonnum;
2553 return "Unparsable reason: ". $options{'reason'};
2556 my $cust_pkg_reason =
2557 new FS::cust_pkg_reason({ 'pkgnum' => $self->pkgnum,
2558 'reasonnum' => $reasonnum,
2559 'otaker' => $otaker,
2560 'action' => substr(uc($options{'action'}),0,1),
2561 'date' => $options{'date'}
2566 $cust_pkg_reason->insert;
2569 =item insert_discount
2571 Associates this package with a discount (see L<FS::cust_pkg_discount>, possibly
2572 inserting a new discount on the fly (see L<FS::discount>).
2574 Available options are:
2582 If there is an error, returns the error, otherwise returns false.
2586 sub insert_discount {
2587 #my ($self, %options) = @_;
2590 my $cust_pkg_discount = new FS::cust_pkg_discount {
2591 'pkgnum' => $self->pkgnum,
2592 'discountnum' => $self->discountnum,
2594 'end_date' => '', #XXX
2595 #for the create a new discount case
2596 '_type' => $self->discountnum__type,
2597 'amount' => $self->discountnum_amount,
2598 'percent' => $self->discountnum_percent,
2599 'months' => $self->discountnum_months,
2600 #'disabled' => $self->discountnum_disabled,
2603 $cust_pkg_discount->insert;
2606 =item set_usage USAGE_VALUE_HASHREF
2608 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
2609 to which they should be set (see L<FS::svc_acct>). Currently seconds,
2610 upbytes, downbytes, and totalbytes are appropriate keys.
2612 All svc_accts which are part of this package have their values reset.
2617 my ($self, $valueref, %opt) = @_;
2619 foreach my $cust_svc ($self->cust_svc){
2620 my $svc_x = $cust_svc->svc_x;
2621 $svc_x->set_usage($valueref, %opt)
2622 if $svc_x->can("set_usage");
2626 =item recharge USAGE_VALUE_HASHREF
2628 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
2629 to which they should be set (see L<FS::svc_acct>). Currently seconds,
2630 upbytes, downbytes, and totalbytes are appropriate keys.
2632 All svc_accts which are part of this package have their values incremented.
2637 my ($self, $valueref) = @_;
2639 foreach my $cust_svc ($self->cust_svc){
2640 my $svc_x = $cust_svc->svc_x;
2641 $svc_x->recharge($valueref)
2642 if $svc_x->can("recharge");
2646 =item cust_pkg_discount
2650 sub cust_pkg_discount {
2652 qsearch('cust_pkg_discount', { 'pkgnum' => $self->pkgnum } );
2655 =item cust_pkg_discount_active
2659 sub cust_pkg_discount_active {
2661 grep { $_->status eq 'active' } $self->cust_pkg_discount;
2666 =head1 CLASS METHODS
2672 Returns an SQL expression identifying recurring packages.
2676 sub recurring_sql { "
2677 '0' != ( select freq from part_pkg
2678 where cust_pkg.pkgpart = part_pkg.pkgpart )
2683 Returns an SQL expression identifying one-time packages.
2688 '0' = ( select freq from part_pkg
2689 where cust_pkg.pkgpart = part_pkg.pkgpart )
2694 Returns an SQL expression identifying ordered packages (recurring packages not
2700 $_[0]->recurring_sql. " AND ". $_[0]->not_yet_billed_sql;
2705 Returns an SQL expression identifying active packages.
2710 $_[0]->recurring_sql. "
2711 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
2712 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
2713 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
2716 =item not_yet_billed_sql
2718 Returns an SQL expression identifying packages which have not yet been billed.
2722 sub not_yet_billed_sql { "
2723 ( cust_pkg.setup IS NULL OR cust_pkg.setup = 0 )
2724 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
2725 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
2730 Returns an SQL expression identifying inactive packages (one-time packages
2731 that are otherwise unsuspended/uncancelled).
2735 sub inactive_sql { "
2736 ". $_[0]->onetime_sql(). "
2737 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
2738 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
2739 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
2745 Returns an SQL expression identifying suspended packages.
2749 sub suspended_sql { susp_sql(@_); }
2751 #$_[0]->recurring_sql(). ' AND '.
2753 ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
2754 AND cust_pkg.susp IS NOT NULL AND cust_pkg.susp != 0
2761 Returns an SQL exprression identifying cancelled packages.
2765 sub cancelled_sql { cancel_sql(@_); }
2767 #$_[0]->recurring_sql(). ' AND '.
2768 "cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0";
2773 Returns an SQL expression to give the package status as a string.
2779 WHEN cust_pkg.cancel IS NOT NULL THEN 'cancelled'
2780 WHEN cust_pkg.susp IS NOT NULL THEN 'suspended'
2781 WHEN cust_pkg.setup IS NULL THEN 'not yet billed'
2782 WHEN ".onetime_sql()." THEN 'one-time charge'
2787 =item search HASHREF
2791 Returns a qsearch hash expression to search for parameters specified in HASHREF.
2792 Valid parameters are
2800 active, inactive, suspended, cancel (or cancelled)
2804 active, inactive, suspended, one-time charge, inactive, cancel (or cancelled)
2808 boolean selects custom packages
2814 pkgpart or arrayref or hashref of pkgparts
2818 arrayref of beginning and ending epoch date
2822 arrayref of beginning and ending epoch date
2826 arrayref of beginning and ending epoch date
2830 arrayref of beginning and ending epoch date
2834 arrayref of beginning and ending epoch date
2838 arrayref of beginning and ending epoch date
2842 arrayref of beginning and ending epoch date
2846 pkgnum or APKG_pkgnum
2850 a value suited to passing to FS::UI::Web::cust_header
2854 specifies the user for agent virtualization
2858 boolean selects packages containing fcc form 477 telco lines
2865 my ($class, $params) = @_;
2872 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
2874 "cust_main.agentnum = $1";
2881 if ( $params->{'custnum'} =~ /^(\d+)$/ and $1 ) {
2883 "cust_pkg.custnum = $1";
2890 if ( $params->{'pkgbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
2892 "cust_pkg.pkgbatch = '$1'";
2899 if ( $params->{'magic'} eq 'active'
2900 || $params->{'status'} eq 'active' ) {
2902 push @where, FS::cust_pkg->active_sql();
2904 } elsif ( $params->{'magic'} =~ /^not[ _]yet[ _]billed$/
2905 || $params->{'status'} =~ /^not[ _]yet[ _]billed$/ ) {
2907 push @where, FS::cust_pkg->not_yet_billed_sql();
2909 } elsif ( $params->{'magic'} =~ /^(one-time charge|inactive)/
2910 || $params->{'status'} =~ /^(one-time charge|inactive)/ ) {
2912 push @where, FS::cust_pkg->inactive_sql();
2914 } elsif ( $params->{'magic'} eq 'suspended'
2915 || $params->{'status'} eq 'suspended' ) {
2917 push @where, FS::cust_pkg->suspended_sql();
2919 } elsif ( $params->{'magic'} =~ /^cancell?ed$/
2920 || $params->{'status'} =~ /^cancell?ed$/ ) {
2922 push @where, FS::cust_pkg->cancelled_sql();
2927 # parse package class
2930 #false lazinessish w/graph/cust_bill_pkg.cgi
2933 if ( exists($params->{'classnum'})
2934 && $params->{'classnum'} =~ /^(\d*)$/
2938 if ( $classnum ) { #a specific class
2939 push @where, "part_pkg.classnum = $classnum";
2941 #@pkg_class = ( qsearchs('pkg_class', { 'classnum' => $classnum } ) );
2942 #die "classnum $classnum not found!" unless $pkg_class[0];
2943 #$title .= $pkg_class[0]->classname.' ';
2945 } elsif ( $classnum eq '' ) { #the empty class
2947 push @where, "part_pkg.classnum IS NULL";
2948 #$title .= 'Empty class ';
2949 #@pkg_class = ( '(empty class)' );
2950 } elsif ( $classnum eq '0' ) {
2951 #@pkg_class = qsearch('pkg_class', {} ); # { 'disabled' => '' } );
2952 #push @pkg_class, '(empty class)';
2954 die "illegal classnum";
2960 # parse package report options
2963 my @report_option = ();
2964 if ( exists($params->{'report_option'})
2965 && $params->{'report_option'} =~ /^([,\d]*)$/
2968 @report_option = split(',', $1);
2971 if (@report_option) {
2972 # this will result in the empty set for the dangling comma case as it should
2974 map{ "0 < ( SELECT count(*) FROM part_pkg_option
2975 WHERE part_pkg_option.pkgpart = part_pkg.pkgpart
2976 AND optionname = 'report_option_$_'
2977 AND optionvalue = '1' )"
2987 push @where, "part_pkg.custom = 'Y'" if $params->{custom};
2993 push @where, "part_pkg.fcc_ds0s > 0" if $params->{fcc_line};
2999 if ( exists($params->{'censustract'}) ) {
3000 $params->{'censustract'} =~ /^([.\d]*)$/;
3001 my $censustract = "cust_main.censustract = '$1'";
3002 $censustract .= ' OR cust_main.censustract is NULL' unless $1;
3003 push @where, "( $censustract )";
3010 if ( ref($params->{'pkgpart'}) ) {
3013 if ( ref($params->{'pkgpart'}) eq 'HASH' ) {
3014 @pkgpart = grep $params->{'pkgpart'}{$_}, keys %{ $params->{'pkgpart'} };
3015 } elsif ( ref($params->{'pkgpart'}) eq 'ARRAY' ) {
3016 @pkgpart = @{ $params->{'pkgpart'} };
3018 die 'unhandled pkgpart ref '. $params->{'pkgpart'};
3021 @pkgpart = grep /^(\d+)$/, @pkgpart;
3023 push @where, 'pkgpart IN ('. join(',', @pkgpart). ')' if scalar(@pkgpart);
3025 } elsif ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
3026 push @where, "pkgpart = $1";
3035 #false laziness w/report_cust_pkg.html
3038 'one-time charge' => { 'last_bill'=>1, 'bill'=>1, 'adjourn'=>1, 'susp'=>1, 'expire'=>1, 'cancel'=>1, },
3039 'active' => { 'susp'=>1, 'cancel'=>1 },
3040 'suspended' => { 'cancel' => 1 },
3045 if( exists($params->{'active'} ) ) {
3046 # This overrides all the other date-related fields
3047 my($beginning, $ending) = @{$params->{'active'}};
3049 "cust_pkg.setup IS NOT NULL",
3050 "cust_pkg.setup <= $ending",
3051 "(cust_pkg.cancel IS NULL OR cust_pkg.cancel >= $beginning )",
3052 "NOT (".FS::cust_pkg->onetime_sql . ")";
3055 foreach my $field (qw( setup last_bill bill adjourn susp expire contract_end cancel )) {
3057 next unless exists($params->{$field});
3059 my($beginning, $ending) = @{$params->{$field}};
3061 next if $beginning == 0 && $ending == 4294967295;
3064 "cust_pkg.$field IS NOT NULL",
3065 "cust_pkg.$field >= $beginning",
3066 "cust_pkg.$field <= $ending";
3068 $orderby ||= "ORDER BY cust_pkg.$field";
3073 $orderby ||= 'ORDER BY bill';
3076 # parse magic, legacy, etc.
3079 if ( $params->{'magic'} &&
3080 $params->{'magic'} =~ /^(active|inactive|suspended|cancell?ed)$/
3083 $orderby = 'ORDER BY pkgnum';
3085 if ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
3086 push @where, "pkgpart = $1";
3089 } elsif ( $params->{'query'} eq 'pkgnum' ) {
3091 $orderby = 'ORDER BY pkgnum';
3093 } elsif ( $params->{'query'} eq 'APKG_pkgnum' ) {
3095 $orderby = 'ORDER BY pkgnum';
3098 SELECT count(*) FROM pkg_svc
3099 WHERE pkg_svc.pkgpart = cust_pkg.pkgpart
3100 AND pkg_svc.quantity > ( SELECT count(*) FROM cust_svc
3101 WHERE cust_svc.pkgnum = cust_pkg.pkgnum
3102 AND cust_svc.svcpart = pkg_svc.svcpart
3109 # setup queries, links, subs, etc. for the search
3112 # here is the agent virtualization
3113 if ($params->{CurrentUser}) {
3115 qsearchs('access_user', { username => $params->{CurrentUser} });
3118 push @where, $access_user->agentnums_sql('table'=>'cust_main');
3123 push @where, $FS::CurrentUser::CurrentUser->agentnums_sql('table'=>'cust_main');
3126 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
3128 my $addl_from = 'LEFT JOIN cust_main USING ( custnum ) '.
3129 'LEFT JOIN part_pkg USING ( pkgpart ) '.
3130 'LEFT JOIN pkg_class ON ( part_pkg.classnum = pkg_class.classnum ) ';
3132 my $count_query = "SELECT COUNT(*) FROM cust_pkg $addl_from $extra_sql";
3135 'table' => 'cust_pkg',
3137 'select' => join(', ',
3139 ( map "part_pkg.$_", qw( pkg freq ) ),
3140 'pkg_class.classname',
3141 'cust_main.custnum AS cust_main_custnum',
3142 FS::UI::Web::cust_sql_fields(
3143 $params->{'cust_fields'}
3146 'extra_sql' => "$extra_sql $orderby",
3147 'addl_from' => $addl_from,
3148 'count_query' => $count_query,
3155 Returns a list of two package counts. The first is a count of packages
3156 based on the supplied criteria and the second is the count of residential
3157 packages with those same criteria. Criteria are specified as in the search
3163 my ($class, $params) = @_;
3165 my $sql_query = $class->search( $params );
3167 my $count_sql = delete($sql_query->{'count_query'});
3168 $count_sql =~ s/ FROM/,count(CASE WHEN cust_main.company IS NULL OR cust_main.company = '' THEN 1 END) FROM/
3169 or die "couldn't parse count_sql";
3171 my $count_sth = dbh->prepare($count_sql)
3172 or die "Error preparing $count_sql: ". dbh->errstr;
3174 or die "Error executing $count_sql: ". $count_sth->errstr;
3175 my $count_arrayref = $count_sth->fetchrow_arrayref;
3177 return ( @$count_arrayref );
3184 Returns a list: the first item is an SQL fragment identifying matching
3185 packages/customers via location (taking into account shipping and package
3186 address taxation, if enabled), and subsequent items are the parameters to
3187 substitute for the placeholders in that fragment.
3192 my($class, %opt) = @_;
3193 my $ornull = $opt{'ornull'};
3195 my $conf = new FS::Conf;
3197 # '?' placeholders in _location_sql_where
3198 my $x = $ornull ? 3 : 2;
3199 my @bill_param = ( ('city')x3, ('county')x$x, ('state')x$x, 'country' );
3203 if ( $conf->exists('tax-ship_address') ) {
3206 ( ( ship_last IS NULL OR ship_last = '' )
3207 AND ". _location_sql_where('cust_main', '', $ornull ). "
3209 OR ( ship_last IS NOT NULL AND ship_last != ''
3210 AND ". _location_sql_where('cust_main', 'ship_', $ornull ). "
3213 # AND payby != 'COMP'
3215 @main_param = ( @bill_param, @bill_param );
3219 $main_where = _location_sql_where('cust_main'); # AND payby != 'COMP'
3220 @main_param = @bill_param;
3226 if ( $conf->exists('tax-pkg_address') ) {
3228 my $loc_where = _location_sql_where( 'cust_location', '', $ornull );
3231 ( cust_pkg.locationnum IS NULL AND $main_where )
3232 OR ( cust_pkg.locationnum IS NOT NULL AND $loc_where )
3235 @param = ( @main_param, @bill_param );
3239 $where = $main_where;
3240 @param = @main_param;
3248 #subroutine, helper for location_sql
3249 sub _location_sql_where {
3251 my $prefix = @_ ? shift : '';
3252 my $ornull = @_ ? shift : '';
3254 # $ornull = $ornull ? " OR ( ? IS NULL AND $table.${prefix}county IS NULL ) " : '';
3256 $ornull = $ornull ? ' OR ? IS NULL ' : '';
3258 my $or_empty_city = " OR ( ? = '' AND $table.${prefix}city IS NULL ) ";
3259 my $or_empty_county = " OR ( ? = '' AND $table.${prefix}county IS NULL ) ";
3260 my $or_empty_state = " OR ( ? = '' AND $table.${prefix}state IS NULL ) ";
3262 # ( $table.${prefix}city = ? $or_empty_city $ornull )
3264 ( $table.${prefix}city = ? OR ? = '' OR CAST(? AS text) IS NULL )
3265 AND ( $table.${prefix}county = ? $or_empty_county $ornull )
3266 AND ( $table.${prefix}state = ? $or_empty_state $ornull )
3267 AND $table.${prefix}country = ?
3275 =item order CUSTNUM, PKGPARTS_ARYREF, [ REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF [ REFNUM ] ] ]
3277 CUSTNUM is a customer (see L<FS::cust_main>)
3279 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
3280 L<FS::part_pkg>) to order for this customer. Duplicates are of course
3283 REMOVE_PKGNUMS is an optional list of pkgnums specifying the billing items to
3284 remove for this customer. The services (see L<FS::cust_svc>) are moved to the
3285 new billing items. An error is returned if this is not possible (see
3286 L<FS::pkg_svc>). An empty arrayref is equivalent to not specifying this
3289 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
3290 newly-created cust_pkg objects.
3292 REFNUM, if specified, will specify the FS::pkg_referral record to be created
3293 and inserted. Multiple FS::pkg_referral records can be created by
3294 setting I<refnum> to an array reference of refnums or a hash reference with
3295 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
3296 record will be created corresponding to cust_main.refnum.
3301 my ($custnum, $pkgparts, $remove_pkgnum, $return_cust_pkg, $refnum) = @_;
3303 my $conf = new FS::Conf;
3305 # Transactionize this whole mess
3306 local $SIG{HUP} = 'IGNORE';
3307 local $SIG{INT} = 'IGNORE';
3308 local $SIG{QUIT} = 'IGNORE';
3309 local $SIG{TERM} = 'IGNORE';
3310 local $SIG{TSTP} = 'IGNORE';
3311 local $SIG{PIPE} = 'IGNORE';
3313 my $oldAutoCommit = $FS::UID::AutoCommit;
3314 local $FS::UID::AutoCommit = 0;
3318 # my $cust_main = qsearchs('cust_main', { custnum => $custnum });
3319 # return "Customer not found: $custnum" unless $cust_main;
3321 warn "$me order: pkgnums to remove: ". join(',', @$remove_pkgnum). "\n"
3324 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
3327 my $change = scalar(@old_cust_pkg) != 0;
3330 if ( scalar(@old_cust_pkg) == 1 && scalar(@$pkgparts) == 1 ) {
3332 warn "$me order: changing pkgnum ". $old_cust_pkg[0]->pkgnum.
3333 " to pkgpart ". $pkgparts->[0]. "\n"
3336 my $err_or_cust_pkg =
3337 $old_cust_pkg[0]->change( 'pkgpart' => $pkgparts->[0],
3338 'refnum' => $refnum,
3341 unless (ref($err_or_cust_pkg)) {
3342 $dbh->rollback if $oldAutoCommit;
3343 return $err_or_cust_pkg;
3346 push @$return_cust_pkg, $err_or_cust_pkg;
3347 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3352 # Create the new packages.
3353 foreach my $pkgpart (@$pkgparts) {
3355 warn "$me order: inserting pkgpart $pkgpart\n" if $DEBUG;
3357 my $cust_pkg = new FS::cust_pkg { custnum => $custnum,
3358 pkgpart => $pkgpart,
3362 $error = $cust_pkg->insert( 'change' => $change );
3364 $dbh->rollback if $oldAutoCommit;
3367 push @$return_cust_pkg, $cust_pkg;
3369 # $return_cust_pkg now contains refs to all of the newly
3372 # Transfer services and cancel old packages.
3373 foreach my $old_pkg (@old_cust_pkg) {
3375 warn "$me order: transferring services from pkgnum ". $old_pkg->pkgnum. "\n"
3378 foreach my $new_pkg (@$return_cust_pkg) {
3379 $error = $old_pkg->transfer($new_pkg);
3380 if ($error and $error == 0) {
3381 # $old_pkg->transfer failed.
3382 $dbh->rollback if $oldAutoCommit;
3387 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
3388 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
3389 foreach my $new_pkg (@$return_cust_pkg) {
3390 $error = $old_pkg->transfer($new_pkg, 'change_svcpart'=>1 );
3391 if ($error and $error == 0) {
3392 # $old_pkg->transfer failed.
3393 $dbh->rollback if $oldAutoCommit;
3400 # Transfers were successful, but we went through all of the
3401 # new packages and still had services left on the old package.
3402 # We can't cancel the package under the circumstances, so abort.
3403 $dbh->rollback if $oldAutoCommit;
3404 return "Unable to transfer all services from package ".$old_pkg->pkgnum;
3406 $error = $old_pkg->cancel( quiet=>1 );
3412 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3416 =item bulk_change PKGPARTS_ARYREF, REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF ]
3418 A bulk change method to change packages for multiple customers.
3420 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
3421 L<FS::part_pkg>) to order for each customer. Duplicates are of course
3424 REMOVE_PKGNUMS is an list of pkgnums specifying the billing items to
3425 replace. The services (see L<FS::cust_svc>) are moved to the
3426 new billing items. An error is returned if this is not possible (see
3429 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
3430 newly-created cust_pkg objects.
3435 my ($pkgparts, $remove_pkgnum, $return_cust_pkg) = @_;
3437 # Transactionize this whole mess
3438 local $SIG{HUP} = 'IGNORE';
3439 local $SIG{INT} = 'IGNORE';
3440 local $SIG{QUIT} = 'IGNORE';
3441 local $SIG{TERM} = 'IGNORE';
3442 local $SIG{TSTP} = 'IGNORE';
3443 local $SIG{PIPE} = 'IGNORE';
3445 my $oldAutoCommit = $FS::UID::AutoCommit;
3446 local $FS::UID::AutoCommit = 0;
3450 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
3453 while(scalar(@old_cust_pkg)) {
3455 my $custnum = $old_cust_pkg[0]->custnum;
3456 my (@remove) = map { $_->pkgnum }
3457 grep { $_->custnum == $custnum } @old_cust_pkg;
3458 @old_cust_pkg = grep { $_->custnum != $custnum } @old_cust_pkg;
3460 my $error = order $custnum, $pkgparts, \@remove, \@return;
3462 push @errors, $error
3464 push @$return_cust_pkg, @return;
3467 if (scalar(@errors)) {
3468 $dbh->rollback if $oldAutoCommit;
3469 return join(' / ', @errors);
3472 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3476 # Used by FS::Upgrade to migrate to a new database.
3477 sub _upgrade_data { # class method
3478 my ($class, %opts) = @_;
3479 $class->_upgrade_otaker(%opts);
3481 # RT#10139, bug resulting in contract_end being set when it shouldn't
3482 'UPDATE cust_pkg SET contract_end = NULL WHERE contract_end = -1',
3483 # RT#10830, bad calculation of prorate date near end of year
3484 # the date range for bill is December 2009, and we move it forward
3485 # one year if it's before the previous bill date (which it should
3487 'UPDATE cust_pkg SET bill = bill + (365*24*60*60) WHERE bill < last_bill
3488 AND bill > 1259654400 AND bill < 1262332800 AND (SELECT plan FROM part_pkg
3489 WHERE part_pkg.pkgpart = cust_pkg.pkgpart) = \'prorate\'',
3490 # RT6628, add order_date to cust_pkg
3491 'update cust_pkg set order_date = (select history_date from h_cust_pkg
3492 where h_cust_pkg.pkgnum = cust_pkg.pkgnum and
3493 history_action = \'insert\') where order_date is null',
3495 foreach my $sql (@statements) {
3496 my $sth = dbh->prepare($sql);
3497 $sth->execute or die $sth->errstr;
3505 sub order is not OO. Perhaps it should be moved to FS::cust_main and made so?
3507 In sub order, the @pkgparts array (passed by reference) is clobbered.
3509 Also in sub order, no money is adjusted. Once FS::part_pkg defines a standard
3510 method to pass dates to the recur_prog expression, it should do so.
3512 FS::svc_acct, FS::svc_domain, FS::svc_www, FS::svc_ip and FS::svc_forward are
3513 loaded via 'use' at compile time, rather than via 'require' in sub { setup,
3514 suspend, unsuspend, cancel } because they use %FS::UID::callback to load
3515 configuration values. Probably need a subroutine which decides what to do
3516 based on whether or not we've fetched the user yet, rather than a hash. See
3517 FS::UID and the TODO.
3519 Now that things are transactional should the check in the insert method be
3524 L<FS::Record>, L<FS::cust_main>, L<FS::part_pkg>, L<FS::cust_svc>,
3525 L<FS::pkg_svc>, schema.html from the base documentation