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>)
138 date (next bill date)
166 order taker (see L<FS::access_user>)
170 If this field is set to 1, disables the automatic
171 unsuspension of this package when using the B<unsuspendauto> config option.
175 If not set, defaults to 1
179 Date of change from previous package
189 =item change_locationnum
195 Note: setup, last_bill, bill, adjourn, susp, expire, cancel and change_date
196 are specified as UNIX timestamps; see L<perlfunc/"time">. Also see
197 L<Time::Local> and L<Date::Parse> for conversion functions.
205 Create a new billing item. To add the item to the database, see L<"insert">.
209 sub table { 'cust_pkg'; }
210 sub cust_linked { $_[0]->cust_main_custnum; }
211 sub cust_unlinked_msg {
213 "WARNING: can't find cust_main.custnum ". $self->custnum.
214 ' (cust_pkg.pkgnum '. $self->pkgnum. ')';
217 =item insert [ OPTION => VALUE ... ]
219 Adds this billing item to the database ("Orders" the item). If there is an
220 error, returns the error, otherwise returns false.
222 If the additional field I<promo_code> is defined instead of I<pkgpart>, it
223 will be used to look up the package definition and agent restrictions will be
226 If the additional field I<refnum> is defined, an FS::pkg_referral record will
227 be created and inserted. Multiple FS::pkg_referral records can be created by
228 setting I<refnum> to an array reference of refnums or a hash reference with
229 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
230 record will be created corresponding to cust_main.refnum.
232 The following options are available:
238 If set true, supresses any referral credit to a referring customer.
242 cust_pkg_option records will be created
246 a ticket will be added to this customer with this subject
250 an optional queue name for ticket additions
257 my( $self, %options ) = @_;
259 if ( $self->part_pkg->option('start_1st', 1) && !$self->start_date ) {
260 my ($sec,$min,$hour,$mday,$mon,$year) = (localtime(time) )[0,1,2,3,4,5];
261 $mon += 1 unless $mday == 1;
262 until ( $mon < 12 ) { $mon -= 12; $year++; }
263 $self->start_date( timelocal_nocheck(0,0,0,1,$mon,$year) );
266 foreach my $action ( qw(expire adjourn contract_end) ) {
267 my $months = $self->part_pkg->option("${action}_months",1);
268 if($months and !$self->$action) {
269 my $start = $self->start_date || $self->setup || time;
270 $self->$action( $self->part_pkg->add_freq($start, $months) );
274 local $SIG{HUP} = 'IGNORE';
275 local $SIG{INT} = 'IGNORE';
276 local $SIG{QUIT} = 'IGNORE';
277 local $SIG{TERM} = 'IGNORE';
278 local $SIG{TSTP} = 'IGNORE';
279 local $SIG{PIPE} = 'IGNORE';
281 my $oldAutoCommit = $FS::UID::AutoCommit;
282 local $FS::UID::AutoCommit = 0;
285 my $error = $self->SUPER::insert($options{options} ? %{$options{options}} : ());
287 $dbh->rollback if $oldAutoCommit;
291 $self->refnum($self->cust_main->refnum) unless $self->refnum;
292 $self->refnum( [ $self->refnum ] ) unless ref($self->refnum);
293 $self->process_m2m( 'link_table' => 'pkg_referral',
294 'target_table' => 'part_referral',
295 'params' => $self->refnum,
298 if ( $self->discountnum ) {
299 my $error = $self->insert_discount();
301 $dbh->rollback if $oldAutoCommit;
306 #if ( $self->reg_code ) {
307 # my $reg_code = qsearchs('reg_code', { 'code' => $self->reg_code } );
308 # $error = $reg_code->delete;
310 # $dbh->rollback if $oldAutoCommit;
315 my $conf = new FS::Conf;
317 if ( $conf->config('ticket_system') && $options{ticket_subject} ) {
320 # use lib ( "/opt/rt3/local/lib", "/opt/rt3/lib" );
327 use FS::TicketSystem;
328 FS::TicketSystem->init();
330 my $q = new RT::Queue($RT::SystemUser);
331 $q->Load($options{ticket_queue}) if $options{ticket_queue};
332 my $t = new RT::Ticket($RT::SystemUser);
333 my $mime = new MIME::Entity;
334 $mime->build( Type => 'text/plain', Data => $options{ticket_subject} );
335 $t->Create( $options{ticket_queue} ? (Queue => $q) : (),
336 Subject => $options{ticket_subject},
339 $t->AddLink( Type => 'MemberOf',
340 Target => 'freeside://freeside/cust_main/'. $self->custnum,
344 if ($conf->config('welcome_letter') && $self->cust_main->num_pkgs == 1) {
345 my $queue = new FS::queue {
346 'job' => 'FS::cust_main::queueable_print',
348 $error = $queue->insert(
349 'custnum' => $self->custnum,
350 'template' => 'welcome_letter',
354 warn "can't send welcome letter: $error";
359 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
366 This method now works but you probably shouldn't use it.
368 You don't want to delete billing items, because there would then be no record
369 the customer ever purchased the item. Instead, see the cancel method.
374 # return "Can't delete cust_pkg records!";
377 =item replace [ OLD_RECORD ] [ HASHREF | OPTION => VALUE ... ]
379 Replaces the OLD_RECORD with this one in the database. If there is an error,
380 returns the error, otherwise returns false.
382 Currently, custnum, setup, bill, adjourn, susp, expire, and cancel may be changed.
384 Changing pkgpart may have disasterous effects. See the order subroutine.
386 setup and bill are normally updated by calling the bill method of a customer
387 object (see L<FS::cust_main>).
389 suspend is normally updated by the suspend and unsuspend methods.
391 cancel is normally updated by the cancel method (and also the order subroutine
394 Available options are:
400 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.
404 the access_user (see L<FS::access_user>) providing the reason
408 hashref of keys and values - cust_pkg_option records will be created, updated or removed as appopriate
417 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
422 ( ref($_[0]) eq 'HASH' )
426 #return "Can't (yet?) change pkgpart!" if $old->pkgpart != $new->pkgpart;
427 #return "Can't change otaker!" if $old->otaker ne $new->otaker;
430 #return "Can't change setup once it exists!"
431 # if $old->getfield('setup') &&
432 # $old->getfield('setup') != $new->getfield('setup');
434 #some logic for bill, susp, cancel?
436 local($disable_agentcheck) = 1 if $old->pkgpart == $new->pkgpart;
438 local $SIG{HUP} = 'IGNORE';
439 local $SIG{INT} = 'IGNORE';
440 local $SIG{QUIT} = 'IGNORE';
441 local $SIG{TERM} = 'IGNORE';
442 local $SIG{TSTP} = 'IGNORE';
443 local $SIG{PIPE} = 'IGNORE';
445 my $oldAutoCommit = $FS::UID::AutoCommit;
446 local $FS::UID::AutoCommit = 0;
449 foreach my $method ( qw(adjourn expire) ) { # How many reasons?
450 if ($options->{'reason'} && $new->$method && $old->$method ne $new->$method) {
451 my $error = $new->insert_reason(
452 'reason' => $options->{'reason'},
453 'date' => $new->$method,
455 'reason_otaker' => $options->{'reason_otaker'},
458 dbh->rollback if $oldAutoCommit;
459 return "Error inserting cust_pkg_reason: $error";
464 #save off and freeze RADIUS attributes for any associated svc_acct records
466 if ( $old->part_pkg->is_prepaid || $new->part_pkg->is_prepaid ) {
468 #also check for specific exports?
469 # to avoid spurious modify export events
470 @svc_acct = map { $_->svc_x }
471 grep { $_->part_svc->svcdb eq 'svc_acct' }
474 $_->snapshot foreach @svc_acct;
478 my $error = $new->SUPER::replace($old,
479 $options->{options} ? $options->{options} : ()
482 $dbh->rollback if $oldAutoCommit;
486 #for prepaid packages,
487 #trigger export of new RADIUS Expiration attribute when cust_pkg.bill changes
488 foreach my $old_svc_acct ( @svc_acct ) {
489 my $new_svc_acct = new FS::svc_acct { $old_svc_acct->hash };
490 my $s_error = $new_svc_acct->replace($old_svc_acct);
492 $dbh->rollback if $oldAutoCommit;
497 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
504 Checks all fields to make sure this is a valid billing item. If there is an
505 error, returns the error, otherwise returns false. Called by the insert and
513 $self->locationnum('') if !$self->locationnum || $self->locationnum == -1;
516 $self->ut_numbern('pkgnum')
517 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum')
518 || $self->ut_numbern('pkgpart')
519 || $self->ut_foreign_keyn('locationnum', 'cust_location', 'locationnum')
520 || $self->ut_numbern('start_date')
521 || $self->ut_numbern('setup')
522 || $self->ut_numbern('bill')
523 || $self->ut_numbern('susp')
524 || $self->ut_numbern('cancel')
525 || $self->ut_numbern('adjourn')
526 || $self->ut_numbern('expire')
527 || $self->ut_enum('no_auto', [ '', 'Y' ])
529 return $error if $error;
531 if ( $self->reg_code ) {
533 unless ( grep { $self->pkgpart == $_->pkgpart }
534 map { $_->reg_code_pkg }
535 qsearchs( 'reg_code', { 'code' => $self->reg_code,
536 'agentnum' => $self->cust_main->agentnum })
538 return "Unknown registration code";
541 } elsif ( $self->promo_code ) {
544 qsearchs('part_pkg', {
545 'pkgpart' => $self->pkgpart,
546 'promo_code' => { op=>'ILIKE', value=>$self->promo_code },
548 return 'Unknown promotional code' unless $promo_part_pkg;
552 unless ( $disable_agentcheck ) {
554 qsearchs( 'agent', { 'agentnum' => $self->cust_main->agentnum } );
555 return "agent ". $agent->agentnum. ':'. $agent->agent.
556 " can't purchase pkgpart ". $self->pkgpart
557 unless $agent->pkgpart_hashref->{ $self->pkgpart }
558 || $agent->agentnum == $self->part_pkg->agentnum;
561 $error = $self->ut_foreign_key('pkgpart', 'part_pkg', 'pkgpart' );
562 return $error if $error;
566 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
568 if ( $self->dbdef_table->column('manual_flag') ) {
569 $self->manual_flag('') if $self->manual_flag eq ' ';
570 $self->manual_flag =~ /^([01]?)$/
571 or return "Illegal manual_flag ". $self->manual_flag;
572 $self->manual_flag($1);
578 =item cancel [ OPTION => VALUE ... ]
580 Cancels and removes all services (see L<FS::cust_svc> and L<FS::part_svc>)
581 in this package, then cancels the package itself (sets the cancel field to
584 Available options are:
588 =item quiet - can be set true to supress email cancellation notices.
590 =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.
592 =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.
594 =item date - can be set to a unix style timestamp to specify when to cancel (expire)
596 =item nobill - can be set true to skip billing if it might otherwise be done.
600 If there is an error, returns the error, otherwise returns false.
605 my( $self, %options ) = @_;
608 my $conf = new FS::Conf;
610 warn "cust_pkg::cancel called with options".
611 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
614 local $SIG{HUP} = 'IGNORE';
615 local $SIG{INT} = 'IGNORE';
616 local $SIG{QUIT} = 'IGNORE';
617 local $SIG{TERM} = 'IGNORE';
618 local $SIG{TSTP} = 'IGNORE';
619 local $SIG{PIPE} = 'IGNORE';
621 my $oldAutoCommit = $FS::UID::AutoCommit;
622 local $FS::UID::AutoCommit = 0;
625 my $old = $self->select_for_update;
627 if ( $old->get('cancel') || $self->get('cancel') ) {
628 dbh->rollback if $oldAutoCommit;
629 return ""; # no error
632 my $date = $options{date} if $options{date}; # expire/cancel later
633 $date = '' if ($date && $date <= time); # complain instead?
635 #race condition: usage could be ongoing until unprovisioned
636 #resolved by performing a change package instead (which unprovisions) and
638 if ( !$options{nobill} && !$date && $conf->exists('bill_usage_on_cancel') ) {
639 my $copy = $self->new({$self->hash});
641 $copy->cust_main->bill( pkg_list => [ $copy ], cancel => 1 );
642 warn "Error billing during cancel, custnum ".
643 #$self->cust_main->custnum. ": $error"
649 my $cancel_time = $options{'time'} || time;
651 if ( $options{'reason'} ) {
652 $error = $self->insert_reason( 'reason' => $options{'reason'},
653 'action' => $date ? 'expire' : 'cancel',
654 'date' => $date ? $date : $cancel_time,
655 'reason_otaker' => $options{'reason_otaker'},
658 dbh->rollback if $oldAutoCommit;
659 return "Error inserting cust_pkg_reason: $error";
665 foreach my $cust_svc (
668 sort { $a->[1] <=> $b->[1] }
669 map { [ $_, $_->svc_x->table_info->{'cancel_weight'} ]; }
670 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
673 my $error = $cust_svc->cancel;
676 $dbh->rollback if $oldAutoCommit;
677 return "Error cancelling cust_svc: $error";
681 # Add a credit for remaining service
682 my $remaining_value = $self->calc_remain(time=>$cancel_time);
683 if ( $remaining_value > 0 && !$options{'no_credit'} ) {
684 my $error = $self->cust_main->credit(
686 'Credit for unused time on '. $self->part_pkg->pkg,
687 'reason_type' => $conf->config('cancel_credit_type'),
690 $dbh->rollback if $oldAutoCommit;
691 return "Error crediting customer \$$remaining_value for unused time on".
692 $self->part_pkg->pkg. ": $error";
697 my %hash = $self->hash;
698 $date ? ($hash{'expire'} = $date) : ($hash{'cancel'} = $cancel_time);
699 my $new = new FS::cust_pkg ( \%hash );
700 $error = $new->replace( $self, options => { $self->options } );
702 $dbh->rollback if $oldAutoCommit;
706 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
707 return '' if $date; #no errors
709 my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ } $self->cust_main->invoicing_list;
710 if ( !$options{'quiet'} && $conf->exists('emailcancel') && @invoicing_list ) {
711 my $msgnum = $conf->config('cancel_msgnum', $self->cust_main->agentnum);
714 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum });
715 $error = $msg_template->send( 'cust_main' => $self->cust_main,
720 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
721 'to' => \@invoicing_list,
722 'subject' => ( $conf->config('cancelsubject') || 'Cancellation Notice' ),
723 'body' => [ map "$_\n", $conf->config('cancelmessage') ],
726 #should this do something on errors?
733 =item cancel_if_expired [ NOW_TIMESTAMP ]
735 Cancels this package if its expire date has been reached.
739 sub cancel_if_expired {
741 my $time = shift || time;
742 return '' unless $self->expire && $self->expire <= $time;
743 my $error = $self->cancel;
745 return "Error cancelling expired pkg ". $self->pkgnum. " for custnum ".
746 $self->custnum. ": $error";
753 Cancels any pending expiration (sets the expire field to null).
755 If there is an error, returns the error, otherwise returns false.
760 my( $self, %options ) = @_;
763 local $SIG{HUP} = 'IGNORE';
764 local $SIG{INT} = 'IGNORE';
765 local $SIG{QUIT} = 'IGNORE';
766 local $SIG{TERM} = 'IGNORE';
767 local $SIG{TSTP} = 'IGNORE';
768 local $SIG{PIPE} = 'IGNORE';
770 my $oldAutoCommit = $FS::UID::AutoCommit;
771 local $FS::UID::AutoCommit = 0;
774 my $old = $self->select_for_update;
776 my $pkgnum = $old->pkgnum;
777 if ( $old->get('cancel') || $self->get('cancel') ) {
778 dbh->rollback if $oldAutoCommit;
779 return "Can't unexpire cancelled package $pkgnum";
780 # or at least it's pointless
783 unless ( $old->get('expire') && $self->get('expire') ) {
784 dbh->rollback if $oldAutoCommit;
785 return ""; # no error
788 my %hash = $self->hash;
789 $hash{'expire'} = '';
790 my $new = new FS::cust_pkg ( \%hash );
791 $error = $new->replace( $self, options => { $self->options } );
793 $dbh->rollback if $oldAutoCommit;
797 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
803 =item suspend [ OPTION => VALUE ... ]
805 Suspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
806 package, then suspends the package itself (sets the susp field to now).
808 Available options are:
812 =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.
814 =item date - can be set to a unix style timestamp to specify when to suspend (adjourn)
818 If there is an error, returns the error, otherwise returns false.
823 my( $self, %options ) = @_;
826 local $SIG{HUP} = 'IGNORE';
827 local $SIG{INT} = 'IGNORE';
828 local $SIG{QUIT} = 'IGNORE';
829 local $SIG{TERM} = 'IGNORE';
830 local $SIG{TSTP} = 'IGNORE';
831 local $SIG{PIPE} = 'IGNORE';
833 my $oldAutoCommit = $FS::UID::AutoCommit;
834 local $FS::UID::AutoCommit = 0;
837 my $old = $self->select_for_update;
839 my $pkgnum = $old->pkgnum;
840 if ( $old->get('cancel') || $self->get('cancel') ) {
841 dbh->rollback if $oldAutoCommit;
842 return "Can't suspend cancelled package $pkgnum";
845 if ( $old->get('susp') || $self->get('susp') ) {
846 dbh->rollback if $oldAutoCommit;
847 return ""; # no error # complain on adjourn?
850 my $date = $options{date} if $options{date}; # adjourn/suspend later
851 $date = '' if ($date && $date <= time); # complain instead?
853 if ( $date && $old->get('expire') && $old->get('expire') < $date ) {
854 dbh->rollback if $oldAutoCommit;
855 return "Package $pkgnum expires before it would be suspended.";
858 my $suspend_time = $options{'time'} || time;
860 if ( $options{'reason'} ) {
861 $error = $self->insert_reason( 'reason' => $options{'reason'},
862 'action' => $date ? 'adjourn' : 'suspend',
863 'date' => $date ? $date : $suspend_time,
864 'reason_otaker' => $options{'reason_otaker'},
867 dbh->rollback if $oldAutoCommit;
868 return "Error inserting cust_pkg_reason: $error";
876 foreach my $cust_svc (
877 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
879 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
881 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
882 $dbh->rollback if $oldAutoCommit;
883 return "Illegal svcdb value in part_svc!";
886 require "FS/$svcdb.pm";
888 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
890 $error = $svc->suspend;
892 $dbh->rollback if $oldAutoCommit;
895 my( $label, $value ) = $cust_svc->label;
896 push @labels, "$label: $value";
900 my $conf = new FS::Conf;
901 if ( $conf->config('suspend_email_admin') ) {
903 my $error = send_email(
904 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
905 #invoice_from ??? well as good as any
906 'to' => $conf->config('suspend_email_admin'),
907 'subject' => 'FREESIDE NOTIFICATION: Customer package suspended',
909 "This is an automatic message from your Freeside installation\n",
910 "informing you that the following customer package has been suspended:\n",
912 'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
913 'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
914 ( map { "Service : $_\n" } @labels ),
919 warn "WARNING: can't send suspension admin email (suspending anyway): ".
927 my %hash = $self->hash;
929 $hash{'adjourn'} = $date;
931 $hash{'susp'} = $suspend_time;
933 my $new = new FS::cust_pkg ( \%hash );
934 $error = $new->replace( $self, options => { $self->options } );
936 $dbh->rollback if $oldAutoCommit;
940 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
945 =item unsuspend [ OPTION => VALUE ... ]
947 Unsuspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
948 package, then unsuspends the package itself (clears the susp field and the
949 adjourn field if it is in the past).
951 Available options are:
955 =item adjust_next_bill
957 Can be set true to adjust the next bill date forward by
958 the amount of time the account was inactive. This was set true by default
959 since 1.4.2 and 1.5.0pre6; however, starting with 1.7.0 this needs to be
960 explicitly requested. Price plans for which this makes sense (anniversary-date
961 based than prorate or subscription) could have an option to enable this
966 If there is an error, returns the error, otherwise returns false.
971 my( $self, %opt ) = @_;
974 local $SIG{HUP} = 'IGNORE';
975 local $SIG{INT} = 'IGNORE';
976 local $SIG{QUIT} = 'IGNORE';
977 local $SIG{TERM} = 'IGNORE';
978 local $SIG{TSTP} = 'IGNORE';
979 local $SIG{PIPE} = 'IGNORE';
981 my $oldAutoCommit = $FS::UID::AutoCommit;
982 local $FS::UID::AutoCommit = 0;
985 my $old = $self->select_for_update;
987 my $pkgnum = $old->pkgnum;
988 if ( $old->get('cancel') || $self->get('cancel') ) {
989 dbh->rollback if $oldAutoCommit;
990 return "Can't unsuspend cancelled package $pkgnum";
993 unless ( $old->get('susp') && $self->get('susp') ) {
994 dbh->rollback if $oldAutoCommit;
995 return ""; # no error # complain instead?
998 foreach my $cust_svc (
999 qsearch('cust_svc',{'pkgnum'=> $self->pkgnum } )
1001 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
1003 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
1004 $dbh->rollback if $oldAutoCommit;
1005 return "Illegal svcdb value in part_svc!";
1008 require "FS/$svcdb.pm";
1010 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
1012 $error = $svc->unsuspend;
1014 $dbh->rollback if $oldAutoCommit;
1021 my %hash = $self->hash;
1022 my $inactive = time - $hash{'susp'};
1024 my $conf = new FS::Conf;
1026 if ( $inactive > 0 &&
1027 ( $hash{'bill'} || $hash{'setup'} ) &&
1028 ( $opt{'adjust_next_bill'} ||
1029 $conf->exists('unsuspend-always_adjust_next_bill_date') ||
1030 $self->part_pkg->option('unsuspend_adjust_bill', 1) )
1033 $hash{'bill'} = ( $hash{'bill'} || $hash{'setup'} ) + $inactive;
1038 $hash{'adjourn'} = '' if $hash{'adjourn'} < 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;
1053 Cancels any pending suspension (sets the adjourn field to null).
1055 If there is an error, returns the error, otherwise returns false.
1060 my( $self, %options ) = @_;
1063 local $SIG{HUP} = 'IGNORE';
1064 local $SIG{INT} = 'IGNORE';
1065 local $SIG{QUIT} = 'IGNORE';
1066 local $SIG{TERM} = 'IGNORE';
1067 local $SIG{TSTP} = 'IGNORE';
1068 local $SIG{PIPE} = 'IGNORE';
1070 my $oldAutoCommit = $FS::UID::AutoCommit;
1071 local $FS::UID::AutoCommit = 0;
1074 my $old = $self->select_for_update;
1076 my $pkgnum = $old->pkgnum;
1077 if ( $old->get('cancel') || $self->get('cancel') ) {
1078 dbh->rollback if $oldAutoCommit;
1079 return "Can't unadjourn cancelled package $pkgnum";
1080 # or at least it's pointless
1083 if ( $old->get('susp') || $self->get('susp') ) {
1084 dbh->rollback if $oldAutoCommit;
1085 return "Can't unadjourn suspended package $pkgnum";
1086 # perhaps this is arbitrary
1089 unless ( $old->get('adjourn') && $self->get('adjourn') ) {
1090 dbh->rollback if $oldAutoCommit;
1091 return ""; # no error
1094 my %hash = $self->hash;
1095 $hash{'adjourn'} = '';
1096 my $new = new FS::cust_pkg ( \%hash );
1097 $error = $new->replace( $self, options => { $self->options } );
1099 $dbh->rollback if $oldAutoCommit;
1103 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1110 =item change HASHREF | OPTION => VALUE ...
1112 Changes this package: cancels it and creates a new one, with a different
1113 pkgpart or locationnum or both. All services are transferred to the new
1114 package (no change will be made if this is not possible).
1116 Options may be passed as a list of key/value pairs or as a hash reference.
1123 New locationnum, to change the location for this package.
1127 New FS::cust_location object, to create a new location and assign it
1132 New pkgpart (see L<FS::part_pkg>).
1136 New refnum (see L<FS::part_referral>).
1140 Set to true to transfer billing dates (start_date, setup, last_bill, bill,
1141 susp, adjourn, cancel, expire, and contract_end) to the new package.
1145 At least one of locationnum, cust_location, pkgpart, refnum must be specified
1146 (otherwise, what's the point?)
1148 Returns either the new FS::cust_pkg object or a scalar error.
1152 my $err_or_new_cust_pkg = $old_cust_pkg->change
1156 #some false laziness w/order
1159 my $opt = ref($_[0]) ? shift : { @_ };
1161 # my ($custnum, $pkgparts, $remove_pkgnum, $return_cust_pkg, $refnum) = @_;
1164 my $conf = new FS::Conf;
1166 # Transactionize this whole mess
1167 local $SIG{HUP} = 'IGNORE';
1168 local $SIG{INT} = 'IGNORE';
1169 local $SIG{QUIT} = 'IGNORE';
1170 local $SIG{TERM} = 'IGNORE';
1171 local $SIG{TSTP} = 'IGNORE';
1172 local $SIG{PIPE} = 'IGNORE';
1174 my $oldAutoCommit = $FS::UID::AutoCommit;
1175 local $FS::UID::AutoCommit = 0;
1184 #$hash{$_} = $self->$_() foreach qw( last_bill bill );
1186 #$hash{$_} = $self->$_() foreach qw( setup );
1188 $hash{'setup'} = $time if $self->setup;
1190 $hash{'change_date'} = $time;
1191 $hash{"change_$_"} = $self->$_()
1192 foreach qw( pkgnum pkgpart locationnum );
1194 if ( $opt->{'cust_location'} &&
1195 ( ! $opt->{'locationnum'} || $opt->{'locationnum'} == -1 ) ) {
1196 $error = $opt->{'cust_location'}->insert;
1198 $dbh->rollback if $oldAutoCommit;
1199 return "inserting cust_location (transaction rolled back): $error";
1201 $opt->{'locationnum'} = $opt->{'cust_location'}->locationnum;
1204 if ( $opt->{'keep_dates'} ) {
1205 foreach my $date ( qw(setup bill last_bill susp adjourn cancel expire
1206 start_date contract_end ) ) {
1207 $hash{$date} = $self->getfield($date);
1211 # Create the new package.
1212 my $cust_pkg = new FS::cust_pkg {
1213 custnum => $self->custnum,
1214 pkgpart => ( $opt->{'pkgpart'} || $self->pkgpart ),
1215 refnum => ( $opt->{'refnum'} || $self->refnum ),
1216 locationnum => ( $opt->{'locationnum'} || $self->locationnum ),
1220 $error = $cust_pkg->insert( 'change' => 1 );
1222 $dbh->rollback if $oldAutoCommit;
1226 # Transfer services and cancel old package.
1228 $error = $self->transfer($cust_pkg);
1229 if ($error and $error == 0) {
1230 # $old_pkg->transfer failed.
1231 $dbh->rollback if $oldAutoCommit;
1235 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
1236 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
1237 $error = $self->transfer($cust_pkg, 'change_svcpart'=>1 );
1238 if ($error and $error == 0) {
1239 # $old_pkg->transfer failed.
1240 $dbh->rollback if $oldAutoCommit;
1246 # Transfers were successful, but we still had services left on the old
1247 # package. We can't change the package under this circumstances, so abort.
1248 $dbh->rollback if $oldAutoCommit;
1249 return "Unable to transfer all services from package ". $self->pkgnum;
1252 #reset usage if changing pkgpart
1253 # AND usage rollover is off (otherwise adds twice, now and at package bill)
1254 if ($self->pkgpart != $cust_pkg->pkgpart) {
1255 my $part_pkg = $cust_pkg->part_pkg;
1256 $error = $part_pkg->reset_usage($cust_pkg, $part_pkg->is_prepaid
1260 if $part_pkg->can('reset_usage') && ! $part_pkg->option('usage_rollover',1);
1263 $dbh->rollback if $oldAutoCommit;
1264 return "Error setting usage values: $error";
1268 #Good to go, cancel old package.
1269 $error = $self->cancel( quiet=>1 );
1271 $dbh->rollback if $oldAutoCommit;
1275 if ( $conf->exists('cust_pkg-change_pkgpart-bill_now') ) {
1277 my $error = $cust_pkg->cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1279 $dbh->rollback if $oldAutoCommit;
1284 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1291 use Storable 'thaw';
1293 sub process_bulk_cust_pkg {
1295 my $param = thaw(decode_base64(shift));
1296 warn Dumper($param) if $DEBUG;
1298 my $old_part_pkg = qsearchs('part_pkg',
1299 { pkgpart => $param->{'old_pkgpart'} });
1300 my $new_part_pkg = qsearchs('part_pkg',
1301 { pkgpart => $param->{'new_pkgpart'} });
1302 die "Must select a new package type\n" unless $new_part_pkg;
1303 my $keep_dates = $param->{'keep_dates'} || 0;
1305 local $SIG{HUP} = 'IGNORE';
1306 local $SIG{INT} = 'IGNORE';
1307 local $SIG{QUIT} = 'IGNORE';
1308 local $SIG{TERM} = 'IGNORE';
1309 local $SIG{TSTP} = 'IGNORE';
1310 local $SIG{PIPE} = 'IGNORE';
1312 my $oldAutoCommit = $FS::UID::AutoCommit;
1313 local $FS::UID::AutoCommit = 0;
1316 my @cust_pkgs = qsearch('cust_pkg', { 'pkgpart' => $param->{'old_pkgpart'} } );
1319 foreach my $old_cust_pkg ( @cust_pkgs ) {
1321 $job->update_statustext(int(100*$i/(scalar @cust_pkgs)));
1322 if ( $old_cust_pkg->getfield('cancel') ) {
1323 warn '[process_bulk_cust_pkg ] skipping canceled pkgnum '.
1324 $old_cust_pkg->pkgnum."\n"
1328 warn '[process_bulk_cust_pkg] changing pkgnum '.$old_cust_pkg->pkgnum."\n"
1330 my $error = $old_cust_pkg->change(
1331 'pkgpart' => $param->{'new_pkgpart'},
1332 'keep_dates' => $keep_dates
1334 if ( !ref($error) ) { # change returns the cust_pkg on success
1336 die "Error changing pkgnum ".$old_cust_pkg->pkgnum.": '$error'\n";
1339 $dbh->commit if $oldAutoCommit;
1345 Returns the last bill date, or if there is no last bill date, the setup date.
1346 Useful for billing metered services.
1352 return $self->setfield('last_bill', $_[0]) if @_;
1353 return $self->getfield('last_bill') if $self->getfield('last_bill');
1354 my $cust_bill_pkg = qsearchs('cust_bill_pkg', { 'pkgnum' => $self->pkgnum,
1355 'edate' => $self->bill, } );
1356 $cust_bill_pkg ? $cust_bill_pkg->sdate : $self->setup || 0;
1359 =item last_cust_pkg_reason ACTION
1361 Returns the most recent ACTION FS::cust_pkg_reason associated with the package.
1362 Returns false if there is no reason or the package is not currenly ACTION'd
1363 ACTION is one of adjourn, susp, cancel, or expire.
1367 sub last_cust_pkg_reason {
1368 my ( $self, $action ) = ( shift, shift );
1369 my $date = $self->get($action);
1371 'table' => 'cust_pkg_reason',
1372 'hashref' => { 'pkgnum' => $self->pkgnum,
1373 'action' => substr(uc($action), 0, 1),
1376 'order_by' => 'ORDER BY num DESC LIMIT 1',
1380 =item last_reason ACTION
1382 Returns the most recent ACTION FS::reason associated with the package.
1383 Returns false if there is no reason or the package is not currenly ACTION'd
1384 ACTION is one of adjourn, susp, cancel, or expire.
1389 my $cust_pkg_reason = shift->last_cust_pkg_reason(@_);
1390 $cust_pkg_reason->reason
1391 if $cust_pkg_reason;
1396 Returns the definition for this billing item, as an FS::part_pkg object (see
1403 return $self->{'_pkgpart'} if $self->{'_pkgpart'};
1404 cluck "cust_pkg->part_pkg called" if $DEBUG > 1;
1405 qsearchs( 'part_pkg', { 'pkgpart' => $self->pkgpart } );
1410 Returns the cancelled package this package was changed from, if any.
1416 return '' unless $self->change_pkgnum;
1417 qsearchs('cust_pkg', { 'pkgnum' => $self->change_pkgnum } );
1422 Calls the I<calc_setup> of the FS::part_pkg object associated with this billing
1429 $self->part_pkg->calc_setup($self, @_);
1434 Calls the I<calc_recur> of the FS::part_pkg object associated with this billing
1441 $self->part_pkg->calc_recur($self, @_);
1446 Calls the I<base_recur> of the FS::part_pkg object associated with this billing
1453 $self->part_pkg->base_recur($self, @_);
1458 Calls the I<calc_remain> of the FS::part_pkg object associated with this
1465 $self->part_pkg->calc_remain($self, @_);
1470 Calls the I<calc_cancel> of the FS::part_pkg object associated with this
1477 $self->part_pkg->calc_cancel($self, @_);
1482 Returns any invoice line items for this package (see L<FS::cust_bill_pkg>).
1488 qsearch( 'cust_bill_pkg', { 'pkgnum' => $self->pkgnum } );
1491 =item cust_pkg_detail [ DETAILTYPE ]
1493 Returns any customer package details for this package (see
1494 L<FS::cust_pkg_detail>).
1496 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
1500 sub cust_pkg_detail {
1502 my %hash = ( 'pkgnum' => $self->pkgnum );
1503 $hash{detailtype} = shift if @_;
1505 'table' => 'cust_pkg_detail',
1506 'hashref' => \%hash,
1507 'order_by' => 'ORDER BY weight, pkgdetailnum',
1511 =item set_cust_pkg_detail DETAILTYPE [ DETAIL, DETAIL, ... ]
1513 Sets customer package details for this package (see L<FS::cust_pkg_detail>).
1515 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
1517 If there is an error, returns the error, otherwise returns false.
1521 sub set_cust_pkg_detail {
1522 my( $self, $detailtype, @details ) = @_;
1524 local $SIG{HUP} = 'IGNORE';
1525 local $SIG{INT} = 'IGNORE';
1526 local $SIG{QUIT} = 'IGNORE';
1527 local $SIG{TERM} = 'IGNORE';
1528 local $SIG{TSTP} = 'IGNORE';
1529 local $SIG{PIPE} = 'IGNORE';
1531 my $oldAutoCommit = $FS::UID::AutoCommit;
1532 local $FS::UID::AutoCommit = 0;
1535 foreach my $current ( $self->cust_pkg_detail($detailtype) ) {
1536 my $error = $current->delete;
1538 $dbh->rollback if $oldAutoCommit;
1539 return "error removing old detail: $error";
1543 foreach my $detail ( @details ) {
1544 my $cust_pkg_detail = new FS::cust_pkg_detail {
1545 'pkgnum' => $self->pkgnum,
1546 'detailtype' => $detailtype,
1547 'detail' => $detail,
1549 my $error = $cust_pkg_detail->insert;
1551 $dbh->rollback if $oldAutoCommit;
1552 return "error adding new detail: $error";
1557 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1564 Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.
1568 #false laziness w/cust_bill.pm
1572 'table' => 'cust_event',
1573 'addl_from' => 'JOIN part_event USING ( eventpart )',
1574 'hashref' => { 'tablenum' => $self->pkgnum },
1575 'extra_sql' => " AND eventtable = 'cust_pkg' ",
1579 =item num_cust_event
1581 Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.
1585 #false laziness w/cust_bill.pm
1586 sub num_cust_event {
1589 "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
1590 " WHERE tablenum = ? AND eventtable = 'cust_pkg'";
1591 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
1592 $sth->execute($self->pkgnum) or die $sth->errstr. " executing $sql";
1593 $sth->fetchrow_arrayref->[0];
1596 =item cust_svc [ SVCPART ]
1598 Returns the services for this package, as FS::cust_svc objects (see
1599 L<FS::cust_svc>). If a svcpart is specified, return only the matching
1607 return () unless $self->num_cust_svc(@_);
1610 return qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum,
1611 'svcpart' => shift, } );
1614 cluck "cust_pkg->cust_svc called" if $DEBUG > 2;
1616 #if ( $self->{'_svcnum'} ) {
1617 # values %{ $self->{'_svcnum'}->cache };
1619 $self->_sort_cust_svc(
1620 [ qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } ) ]
1626 =item overlimit [ SVCPART ]
1628 Returns the services for this package which have exceeded their
1629 usage limit as FS::cust_svc objects (see L<FS::cust_svc>). If a svcpart
1630 is specified, return only the matching services.
1636 return () unless $self->num_cust_svc(@_);
1637 grep { $_->overlimit } $self->cust_svc(@_);
1640 =item h_cust_svc END_TIMESTAMP [ START_TIMESTAMP ]
1642 Returns historical services for this package created before END TIMESTAMP and
1643 (optionally) not cancelled before START_TIMESTAMP, as FS::h_cust_svc objects
1644 (see L<FS::h_cust_svc>).
1651 $self->_sort_cust_svc(
1652 [ qsearch( 'h_cust_svc',
1653 { 'pkgnum' => $self->pkgnum, },
1654 FS::h_cust_svc->sql_h_search(@_),
1660 sub _sort_cust_svc {
1661 my( $self, $arrayref ) = @_;
1664 sub ($$) { my ($a, $b) = @_; $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] };
1669 my $pkg_svc = qsearchs( 'pkg_svc', { 'pkgpart' => $self->pkgpart,
1670 'svcpart' => $_->svcpart } );
1672 $pkg_svc ? $pkg_svc->primary_svc : '',
1673 $pkg_svc ? $pkg_svc->quantity : 0,
1680 =item num_cust_svc [ SVCPART ]
1682 Returns the number of provisioned services for this package. If a svcpart is
1683 specified, counts only the matching services.
1690 return $self->{'_num_cust_svc'}
1692 && exists($self->{'_num_cust_svc'})
1693 && $self->{'_num_cust_svc'} =~ /\d/;
1695 cluck "cust_pkg->num_cust_svc called, _num_cust_svc:".$self->{'_num_cust_svc'}
1698 my $sql = 'SELECT COUNT(*) FROM cust_svc WHERE pkgnum = ?';
1699 $sql .= ' AND svcpart = ?' if @_;
1701 my $sth = dbh->prepare($sql) or die dbh->errstr;
1702 $sth->execute($self->pkgnum, @_) or die $sth->errstr;
1703 $sth->fetchrow_arrayref->[0];
1706 =item available_part_svc
1708 Returns a list of FS::part_svc objects representing services included in this
1709 package but not yet provisioned. Each FS::part_svc object also has an extra
1710 field, I<num_avail>, which specifies the number of available services.
1714 sub available_part_svc {
1716 grep { $_->num_avail > 0 }
1718 my $part_svc = $_->part_svc;
1719 $part_svc->{'Hash'}{'num_avail'} = #evil encapsulation-breaking
1720 $_->quantity - $self->num_cust_svc($_->svcpart);
1723 $self->part_pkg->pkg_svc;
1728 Returns a list of FS::part_svc objects representing provisioned and available
1729 services included in this package. Each FS::part_svc object also has the
1730 following extra fields:
1734 =item num_cust_svc (count)
1736 =item num_avail (quantity - count)
1738 =item cust_pkg_svc (services) - array reference containing the provisioned services, as cust_svc objects
1741 label -> ($cust_svc->label)[1]
1750 #XXX some sort of sort order besides numeric by svcpart...
1751 my @part_svc = sort { $a->svcpart <=> $b->svcpart } map {
1753 my $part_svc = $pkg_svc->part_svc;
1754 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
1755 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #more evil
1756 $part_svc->{'Hash'}{'num_avail'} =
1757 max( 0, $pkg_svc->quantity - $num_cust_svc );
1758 $part_svc->{'Hash'}{'cust_pkg_svc'} =
1759 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : [];
1761 } $self->part_pkg->pkg_svc;
1764 push @part_svc, map {
1766 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
1767 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #speak no evail
1768 $part_svc->{'Hash'}{'num_avail'} = 0; #0-$num_cust_svc ?
1769 $part_svc->{'Hash'}{'cust_pkg_svc'} =
1770 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : [];
1772 } $self->extra_part_svc;
1778 =item extra_part_svc
1780 Returns a list of FS::part_svc objects corresponding to services in this
1781 package which are still provisioned but not (any longer) available in the
1786 sub extra_part_svc {
1789 my $pkgnum = $self->pkgnum;
1790 my $pkgpart = $self->pkgpart;
1793 # 'table' => 'part_svc',
1796 # "WHERE 0 = ( SELECT COUNT(*) FROM pkg_svc
1797 # WHERE pkg_svc.svcpart = part_svc.svcpart
1798 # AND pkg_svc.pkgpart = ?
1801 # AND 0 < ( SELECT COUNT(*) FROM cust_svc
1802 # LEFT JOIN cust_pkg USING ( pkgnum )
1803 # WHERE cust_svc.svcpart = part_svc.svcpart
1806 # 'extra_param' => [ [$self->pkgpart=>'int'], [$self->pkgnum=>'int'] ],
1809 #seems to benchmark slightly faster...
1811 #'select' => 'DISTINCT ON (svcpart) part_svc.*',
1812 #MySQL doesn't grok DISINCT ON
1813 'select' => 'DISTINCT part_svc.*',
1814 'table' => 'part_svc',
1816 'LEFT JOIN pkg_svc ON ( pkg_svc.svcpart = part_svc.svcpart
1817 AND pkg_svc.pkgpart = ?
1820 LEFT JOIN cust_svc ON ( cust_svc.svcpart = part_svc.svcpart )
1821 LEFT JOIN cust_pkg USING ( pkgnum )
1824 'extra_sql' => "WHERE pkgsvcnum IS NULL AND cust_pkg.pkgnum = ? ",
1825 'extra_param' => [ [$self->pkgpart=>'int'], [$self->pkgnum=>'int'] ],
1831 Returns a short status string for this package, currently:
1835 =item not yet billed
1837 =item one-time charge
1852 my $freq = length($self->freq) ? $self->freq : $self->part_pkg->freq;
1854 return 'cancelled' if $self->get('cancel');
1855 return 'suspended' if $self->susp;
1856 return 'not yet billed' unless $self->setup;
1857 return 'one-time charge' if $freq =~ /^(0|$)/;
1861 =item ucfirst_status
1863 Returns the status with the first character capitalized.
1867 sub ucfirst_status {
1868 ucfirst(shift->status);
1873 Class method that returns the list of possible status strings for packages
1874 (see L<the status method|/status>). For example:
1876 @statuses = FS::cust_pkg->statuses();
1880 tie my %statuscolor, 'Tie::IxHash',
1881 'not yet billed' => '009999', #teal? cyan?
1882 'one-time charge' => '000000',
1883 'active' => '00CC00',
1884 'suspended' => 'FF9900',
1885 'cancelled' => 'FF0000',
1889 my $self = shift; #could be class...
1890 #grep { $_ !~ /^(not yet billed)$/ } #this is a dumb status anyway
1891 # # mayble split btw one-time vs. recur
1897 Returns a hex triplet color string for this package's status.
1903 $statuscolor{$self->status};
1908 Returns a label for this package. (Currently "pkgnum: pkg - comment" or
1909 "pkg-comment" depending on user preference).
1915 my $label = $self->part_pkg->pkg_comment( 'nopkgpart' => 1 );
1916 $label = $self->pkgnum. ": $label"
1917 if $FS::CurrentUser::CurrentUser->option('show_pkgnum');
1921 =item pkg_label_long
1923 Returns a long label for this package, adding the primary service's label to
1928 sub pkg_label_long {
1930 my $label = $self->pkg_label;
1931 my $cust_svc = $self->primary_cust_svc;
1932 $label .= ' ('. ($cust_svc->label)[1]. ')' if $cust_svc;
1936 =item primary_cust_svc
1938 Returns a primary service (as FS::cust_svc object) if one can be identified.
1942 #for labeling purposes - might not 100% match up with part_pkg->svcpart's idea
1944 sub primary_cust_svc {
1947 my @cust_svc = $self->cust_svc;
1949 return '' unless @cust_svc; #no serivces - irrelevant then
1951 return $cust_svc[0] if scalar(@cust_svc) == 1; #always return a single service
1953 # primary service as specified in the package definition
1954 # or exactly one service definition with quantity one
1955 my $svcpart = $self->part_pkg->svcpart;
1956 @cust_svc = grep { $_->svcpart == $svcpart } @cust_svc;
1957 return $cust_svc[0] if scalar(@cust_svc) == 1;
1959 #couldn't identify one thing..
1965 Returns a list of lists, calling the label method for all services
1966 (see L<FS::cust_svc>) of this billing item.
1972 map { [ $_->label ] } $self->cust_svc;
1975 =item h_labels END_TIMESTAMP [ START_TIMESTAMP ]
1977 Like the labels method, but returns historical information on services that
1978 were active as of END_TIMESTAMP and (optionally) not cancelled before
1981 Returns a list of lists, calling the label method for all (historical) services
1982 (see L<FS::h_cust_svc>) of this billing item.
1988 map { [ $_->label(@_) ] } $self->h_cust_svc(@_);
1993 Like labels, except returns a simple flat list, and shortens long
1994 (currently >5 or the cust_bill-max_same_services configuration value) lists of
1995 identical services to one line that lists the service label and the number of
1996 individual services rather than individual items.
2001 shift->_labels_short( 'labels', @_ );
2004 =item h_labels_short END_TIMESTAMP [ START_TIMESTAMP ]
2006 Like h_labels, except returns a simple flat list, and shortens long
2007 (currently >5 or the cust_bill-max_same_services configuration value) lists of
2008 identical services to one line that lists the service label and the number of
2009 individual services rather than individual items.
2013 sub h_labels_short {
2014 shift->_labels_short( 'h_labels', @_ );
2018 my( $self, $method ) = ( shift, shift );
2020 my $conf = new FS::Conf;
2021 my $max_same_services = $conf->config('cust_bill-max_same_services') || 5;
2024 #tie %labels, 'Tie::IxHash';
2025 push @{ $labels{$_->[0]} }, $_->[1]
2026 foreach $self->$method(@_);
2028 foreach my $label ( keys %labels ) {
2030 my @values = grep { ! $seen{$_}++ } @{ $labels{$label} };
2031 my $num = scalar(@values);
2032 if ( $num > $max_same_services ) {
2033 push @labels, "$label ($num)";
2035 if ( $conf->exists('cust_bill-consolidate_services') ) {
2036 # push @labels, "$label: ". join(', ', @values);
2038 my $detail = "$label: ";
2039 $detail .= shift(@values). ', '
2040 while @values && length($detail.$values[0]) < 78;
2042 push @labels, $detail;
2045 push @labels, map { "$label: $_" } @values;
2056 Returns the parent customer object (see L<FS::cust_main>).
2062 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
2065 #these subs are in location_Mixin.pm now... unfortunately the POD doesn't mixin
2069 Returns the location object, if any (see L<FS::cust_location>).
2071 =item cust_location_or_main
2073 If this package is associated with a location, returns the locaiton (see
2074 L<FS::cust_location>), otherwise returns the customer (see L<FS::cust_main>).
2076 =item location_label [ OPTION => VALUE ... ]
2078 Returns the label of the location object (see L<FS::cust_location>).
2082 #end of subs in location_Mixin.pm now... unfortunately the POD doesn't mixin
2084 =item seconds_since TIMESTAMP
2086 Returns the number of seconds all accounts (see L<FS::svc_acct>) in this
2087 package have been online since TIMESTAMP, according to the session monitor.
2089 TIMESTAMP is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
2090 L<Time::Local> and L<Date::Parse> for conversion functions.
2095 my($self, $since) = @_;
2098 foreach my $cust_svc (
2099 grep { $_->part_svc->svcdb eq 'svc_acct' } $self->cust_svc
2101 $seconds += $cust_svc->seconds_since($since);
2108 =item seconds_since_sqlradacct TIMESTAMP_START TIMESTAMP_END
2110 Returns the numbers of seconds all accounts (see L<FS::svc_acct>) in this
2111 package have been online between TIMESTAMP_START (inclusive) and TIMESTAMP_END
2114 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
2115 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
2121 sub seconds_since_sqlradacct {
2122 my($self, $start, $end) = @_;
2126 foreach my $cust_svc (
2128 my $part_svc = $_->part_svc;
2129 $part_svc->svcdb eq 'svc_acct'
2130 && scalar($part_svc->part_export('sqlradius'));
2133 $seconds += $cust_svc->seconds_since_sqlradacct($start, $end);
2140 =item attribute_since_sqlradacct TIMESTAMP_START TIMESTAMP_END ATTRIBUTE
2142 Returns the sum of the given attribute for all accounts (see L<FS::svc_acct>)
2143 in this package for sessions ending between TIMESTAMP_START (inclusive) and
2147 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
2148 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
2153 sub attribute_since_sqlradacct {
2154 my($self, $start, $end, $attrib) = @_;
2158 foreach my $cust_svc (
2160 my $part_svc = $_->part_svc;
2161 $part_svc->svcdb eq 'svc_acct'
2162 && scalar($part_svc->part_export('sqlradius'));
2165 $sum += $cust_svc->attribute_since_sqlradacct($start, $end, $attrib);
2177 my( $self, $value ) = @_;
2178 if ( defined($value) ) {
2179 $self->setfield('quantity', $value);
2181 $self->getfield('quantity') || 1;
2184 =item transfer DEST_PKGNUM | DEST_CUST_PKG, [ OPTION => VALUE ... ]
2186 Transfers as many services as possible from this package to another package.
2188 The destination package can be specified by pkgnum by passing an FS::cust_pkg
2189 object. The destination package must already exist.
2191 Services are moved only if the destination allows services with the correct
2192 I<svcpart> (not svcdb), unless the B<change_svcpart> option is set true. Use
2193 this option with caution! No provision is made for export differences
2194 between the old and new service definitions. Probably only should be used
2195 when your exports for all service definitions of a given svcdb are identical.
2196 (attempt a transfer without it first, to move all possible svcpart-matching
2199 Any services that can't be moved remain in the original package.
2201 Returns an error, if there is one; otherwise, returns the number of services
2202 that couldn't be moved.
2207 my ($self, $dest_pkgnum, %opt) = @_;
2213 if (ref ($dest_pkgnum) eq 'FS::cust_pkg') {
2214 $dest = $dest_pkgnum;
2215 $dest_pkgnum = $dest->pkgnum;
2217 $dest = qsearchs('cust_pkg', { pkgnum => $dest_pkgnum });
2220 return ('Package does not exist: '.$dest_pkgnum) unless $dest;
2222 foreach my $pkg_svc ( $dest->part_pkg->pkg_svc ) {
2223 $target{$pkg_svc->svcpart} = $pkg_svc->quantity;
2226 foreach my $cust_svc ($dest->cust_svc) {
2227 $target{$cust_svc->svcpart}--;
2230 my %svcpart2svcparts = ();
2231 if ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
2232 warn "change_svcpart option received, creating alternates list\n" if $DEBUG;
2233 foreach my $svcpart ( map { $_->svcpart } $self->cust_svc ) {
2234 next if exists $svcpart2svcparts{$svcpart};
2235 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2236 $svcpart2svcparts{$svcpart} = [
2238 sort { $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] }
2240 my $pkg_svc = qsearchs( 'pkg_svc', { 'pkgpart' => $dest->pkgpart,
2241 'svcpart' => $_ } );
2243 $pkg_svc ? $pkg_svc->primary_svc : '',
2244 $pkg_svc ? $pkg_svc->quantity : 0,
2248 grep { $_ != $svcpart }
2250 qsearch('part_svc', { 'svcdb' => $part_svc->svcdb } )
2252 warn "alternates for svcpart $svcpart: ".
2253 join(', ', @{$svcpart2svcparts{$svcpart}}). "\n"
2258 foreach my $cust_svc ($self->cust_svc) {
2259 if($target{$cust_svc->svcpart} > 0) {
2260 $target{$cust_svc->svcpart}--;
2261 my $new = new FS::cust_svc { $cust_svc->hash };
2262 $new->pkgnum($dest_pkgnum);
2263 my $error = $new->replace($cust_svc);
2264 return $error if $error;
2265 } elsif ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
2267 warn "looking for alternates for svcpart ". $cust_svc->svcpart. "\n";
2268 warn "alternates to consider: ".
2269 join(', ', @{$svcpart2svcparts{$cust_svc->svcpart}}). "\n";
2271 my @alternate = grep {
2272 warn "considering alternate svcpart $_: ".
2273 "$target{$_} available in new package\n"
2276 } @{$svcpart2svcparts{$cust_svc->svcpart}};
2278 warn "alternate(s) found\n" if $DEBUG;
2279 my $change_svcpart = $alternate[0];
2280 $target{$change_svcpart}--;
2281 my $new = new FS::cust_svc { $cust_svc->hash };
2282 $new->svcpart($change_svcpart);
2283 $new->pkgnum($dest_pkgnum);
2284 my $error = $new->replace($cust_svc);
2285 return $error if $error;
2298 This method is deprecated. See the I<depend_jobnum> option to the insert and
2299 order_pkgs methods in FS::cust_main for a better way to defer provisioning.
2306 local $SIG{HUP} = 'IGNORE';
2307 local $SIG{INT} = 'IGNORE';
2308 local $SIG{QUIT} = 'IGNORE';
2309 local $SIG{TERM} = 'IGNORE';
2310 local $SIG{TSTP} = 'IGNORE';
2311 local $SIG{PIPE} = 'IGNORE';
2313 my $oldAutoCommit = $FS::UID::AutoCommit;
2314 local $FS::UID::AutoCommit = 0;
2317 foreach my $cust_svc ( $self->cust_svc ) {
2318 #false laziness w/svc_Common::insert
2319 my $svc_x = $cust_svc->svc_x;
2320 foreach my $part_export ( $cust_svc->part_svc->part_export ) {
2321 my $error = $part_export->export_insert($svc_x);
2323 $dbh->rollback if $oldAutoCommit;
2329 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2336 Associates this package with a (suspension or cancellation) reason (see
2337 L<FS::cust_pkg_reason>, possibly inserting a new reason on the fly (see
2340 Available options are:
2346 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.
2350 the access_user (see L<FS::access_user>) providing the reason
2358 the action (cancel, susp, adjourn, expire) associated with the reason
2362 If there is an error, returns the error, otherwise returns false.
2367 my ($self, %options) = @_;
2369 my $otaker = $options{reason_otaker} ||
2370 $FS::CurrentUser::CurrentUser->username;
2373 if ( $options{'reason'} =~ /^(\d+)$/ ) {
2377 } elsif ( ref($options{'reason'}) ) {
2379 return 'Enter a new reason (or select an existing one)'
2380 unless $options{'reason'}->{'reason'} !~ /^\s*$/;
2382 my $reason = new FS::reason({
2383 'reason_type' => $options{'reason'}->{'typenum'},
2384 'reason' => $options{'reason'}->{'reason'},
2386 my $error = $reason->insert;
2387 return $error if $error;
2389 $reasonnum = $reason->reasonnum;
2392 return "Unparsable reason: ". $options{'reason'};
2395 my $cust_pkg_reason =
2396 new FS::cust_pkg_reason({ 'pkgnum' => $self->pkgnum,
2397 'reasonnum' => $reasonnum,
2398 'otaker' => $otaker,
2399 'action' => substr(uc($options{'action'}),0,1),
2400 'date' => $options{'date'}
2405 $cust_pkg_reason->insert;
2408 =item insert_discount
2410 Associates this package with a discount (see L<FS::cust_pkg_discount>, possibly
2411 inserting a new discount on the fly (see L<FS::discount>).
2413 Available options are:
2421 If there is an error, returns the error, otherwise returns false.
2425 sub insert_discount {
2426 #my ($self, %options) = @_;
2429 my $cust_pkg_discount = new FS::cust_pkg_discount {
2430 'pkgnum' => $self->pkgnum,
2431 'discountnum' => $self->discountnum,
2433 'end_date' => '', #XXX
2434 'otaker' => $self->otaker,
2435 #for the create a new discount case
2436 '_type' => $self->discountnum__type,
2437 'amount' => $self->discountnum_amount,
2438 'percent' => $self->discountnum_percent,
2439 'months' => $self->discountnum_months,
2440 #'disabled' => $self->discountnum_disabled,
2443 $cust_pkg_discount->insert;
2446 =item set_usage USAGE_VALUE_HASHREF
2448 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
2449 to which they should be set (see L<FS::svc_acct>). Currently seconds,
2450 upbytes, downbytes, and totalbytes are appropriate keys.
2452 All svc_accts which are part of this package have their values reset.
2457 my ($self, $valueref, %opt) = @_;
2459 foreach my $cust_svc ($self->cust_svc){
2460 my $svc_x = $cust_svc->svc_x;
2461 $svc_x->set_usage($valueref, %opt)
2462 if $svc_x->can("set_usage");
2466 =item recharge USAGE_VALUE_HASHREF
2468 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
2469 to which they should be set (see L<FS::svc_acct>). Currently seconds,
2470 upbytes, downbytes, and totalbytes are appropriate keys.
2472 All svc_accts which are part of this package have their values incremented.
2477 my ($self, $valueref) = @_;
2479 foreach my $cust_svc ($self->cust_svc){
2480 my $svc_x = $cust_svc->svc_x;
2481 $svc_x->recharge($valueref)
2482 if $svc_x->can("recharge");
2486 =item cust_pkg_discount
2490 sub cust_pkg_discount {
2492 qsearch('cust_pkg_discount', { 'pkgnum' => $self->pkgnum } );
2495 =item cust_pkg_discount_active
2499 sub cust_pkg_discount_active {
2501 grep { $_->status eq 'active' } $self->cust_pkg_discount;
2506 =head1 CLASS METHODS
2512 Returns an SQL expression identifying recurring packages.
2516 sub recurring_sql { "
2517 '0' != ( select freq from part_pkg
2518 where cust_pkg.pkgpart = part_pkg.pkgpart )
2523 Returns an SQL expression identifying one-time packages.
2528 '0' = ( select freq from part_pkg
2529 where cust_pkg.pkgpart = part_pkg.pkgpart )
2534 Returns an SQL expression identifying ordered packages (recurring packages not
2540 $_[0]->recurring_sql. " AND ". $_[0]->not_yet_billed_sql;
2545 Returns an SQL expression identifying active packages.
2550 $_[0]->recurring_sql. "
2551 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
2552 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
2553 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
2556 =item not_yet_billed_sql
2558 Returns an SQL expression identifying packages which have not yet been billed.
2562 sub not_yet_billed_sql { "
2563 ( cust_pkg.setup IS NULL OR cust_pkg.setup = 0 )
2564 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
2565 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
2570 Returns an SQL expression identifying inactive packages (one-time packages
2571 that are otherwise unsuspended/uncancelled).
2575 sub inactive_sql { "
2576 ". $_[0]->onetime_sql(). "
2577 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
2578 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
2579 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
2585 Returns an SQL expression identifying suspended packages.
2589 sub suspended_sql { susp_sql(@_); }
2591 #$_[0]->recurring_sql(). ' AND '.
2593 ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
2594 AND cust_pkg.susp IS NOT NULL AND cust_pkg.susp != 0
2601 Returns an SQL exprression identifying cancelled packages.
2605 sub cancelled_sql { cancel_sql(@_); }
2607 #$_[0]->recurring_sql(). ' AND '.
2608 "cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0";
2613 Returns an SQL expression to give the package status as a string.
2619 WHEN cust_pkg.cancel IS NOT NULL THEN 'cancelled'
2620 WHEN cust_pkg.susp IS NOT NULL THEN 'suspended'
2621 WHEN cust_pkg.setup IS NULL THEN 'not yet billed'
2622 WHEN ".onetime_sql()." THEN 'one-time charge'
2627 =item search HASHREF
2631 Returns a qsearch hash expression to search for parameters specified in HASHREF.
2632 Valid parameters are
2640 active, inactive, suspended, cancel (or cancelled)
2644 active, inactive, suspended, one-time charge, inactive, cancel (or cancelled)
2648 boolean selects custom packages
2654 pkgpart or arrayref or hashref of pkgparts
2658 arrayref of beginning and ending epoch date
2662 arrayref of beginning and ending epoch date
2666 arrayref of beginning and ending epoch date
2670 arrayref of beginning and ending epoch date
2674 arrayref of beginning and ending epoch date
2678 arrayref of beginning and ending epoch date
2682 arrayref of beginning and ending epoch date
2686 pkgnum or APKG_pkgnum
2690 a value suited to passing to FS::UI::Web::cust_header
2694 specifies the user for agent virtualization
2698 boolean selects packages containing fcc form 477 telco lines
2705 my ($class, $params) = @_;
2712 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
2714 "cust_main.agentnum = $1";
2721 if ( $params->{'custnum'} =~ /^(\d+)$/ and $1 ) {
2723 "cust_pkg.custnum = $1";
2730 if ( $params->{'pkgbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
2732 "cust_pkg.pkgbatch = '$1'";
2739 if ( $params->{'magic'} eq 'active'
2740 || $params->{'status'} eq 'active' ) {
2742 push @where, FS::cust_pkg->active_sql();
2744 } elsif ( $params->{'magic'} =~ /^not[ _]yet[ _]billed$/
2745 || $params->{'status'} =~ /^not[ _]yet[ _]billed$/ ) {
2747 push @where, FS::cust_pkg->not_yet_billed_sql();
2749 } elsif ( $params->{'magic'} =~ /^(one-time charge|inactive)/
2750 || $params->{'status'} =~ /^(one-time charge|inactive)/ ) {
2752 push @where, FS::cust_pkg->inactive_sql();
2754 } elsif ( $params->{'magic'} eq 'suspended'
2755 || $params->{'status'} eq 'suspended' ) {
2757 push @where, FS::cust_pkg->suspended_sql();
2759 } elsif ( $params->{'magic'} =~ /^cancell?ed$/
2760 || $params->{'status'} =~ /^cancell?ed$/ ) {
2762 push @where, FS::cust_pkg->cancelled_sql();
2767 # parse package class
2770 #false lazinessish w/graph/cust_bill_pkg.cgi
2773 if ( exists($params->{'classnum'})
2774 && $params->{'classnum'} =~ /^(\d*)$/
2778 if ( $classnum ) { #a specific class
2779 push @where, "part_pkg.classnum = $classnum";
2781 #@pkg_class = ( qsearchs('pkg_class', { 'classnum' => $classnum } ) );
2782 #die "classnum $classnum not found!" unless $pkg_class[0];
2783 #$title .= $pkg_class[0]->classname.' ';
2785 } elsif ( $classnum eq '' ) { #the empty class
2787 push @where, "part_pkg.classnum IS NULL";
2788 #$title .= 'Empty class ';
2789 #@pkg_class = ( '(empty class)' );
2790 } elsif ( $classnum eq '0' ) {
2791 #@pkg_class = qsearch('pkg_class', {} ); # { 'disabled' => '' } );
2792 #push @pkg_class, '(empty class)';
2794 die "illegal classnum";
2800 # parse package report options
2803 my @report_option = ();
2804 if ( exists($params->{'report_option'})
2805 && $params->{'report_option'} =~ /^([,\d]*)$/
2808 @report_option = split(',', $1);
2811 if (@report_option) {
2812 # this will result in the empty set for the dangling comma case as it should
2814 map{ "0 < ( SELECT count(*) FROM part_pkg_option
2815 WHERE part_pkg_option.pkgpart = part_pkg.pkgpart
2816 AND optionname = 'report_option_$_'
2817 AND optionvalue = '1' )"
2827 push @where, "part_pkg.custom = 'Y'" if $params->{custom};
2833 push @where, "part_pkg.fcc_ds0s > 0" if $params->{fcc_line};
2839 if ( exists($params->{'censustract'}) ) {
2840 $params->{'censustract'} =~ /^([.\d]*)$/;
2841 my $censustract = "cust_main.censustract = '$1'";
2842 $censustract .= ' OR cust_main.censustract is NULL' unless $1;
2843 push @where, "( $censustract )";
2850 if ( ref($params->{'pkgpart'}) ) {
2853 if ( ref($params->{'pkgpart'}) eq 'HASH' ) {
2854 @pkgpart = grep $params->{'pkgpart'}{$_}, keys %{ $params->{'pkgpart'} };
2855 } elsif ( ref($params->{'pkgpart'}) eq 'ARRAY' ) {
2856 @pkgpart = @{ $params->{'pkgpart'} };
2858 die 'unhandled pkgpart ref '. $params->{'pkgpart'};
2861 @pkgpart = grep /^(\d+)$/, @pkgpart;
2863 push @where, 'pkgpart IN ('. join(',', @pkgpart). ')' if scalar(@pkgpart);
2865 } elsif ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
2866 push @where, "pkgpart = $1";
2875 #false laziness w/report_cust_pkg.html
2878 'one-time charge' => { 'last_bill'=>1, 'bill'=>1, 'adjourn'=>1, 'susp'=>1, 'expire'=>1, 'cancel'=>1, },
2879 'active' => { 'susp'=>1, 'cancel'=>1 },
2880 'suspended' => { 'cancel' => 1 },
2885 if( exists($params->{'active'} ) ) {
2886 # This overrides all the other date-related fields
2887 my($beginning, $ending) = @{$params->{'active'}};
2889 "cust_pkg.setup IS NOT NULL",
2890 "cust_pkg.setup <= $ending",
2891 "(cust_pkg.cancel IS NULL OR cust_pkg.cancel >= $beginning )",
2892 "NOT (".FS::cust_pkg->onetime_sql . ")";
2895 foreach my $field (qw( setup last_bill bill adjourn susp expire contract_end cancel )) {
2897 next unless exists($params->{$field});
2899 my($beginning, $ending) = @{$params->{$field}};
2901 next if $beginning == 0 && $ending == 4294967295;
2904 "cust_pkg.$field IS NOT NULL",
2905 "cust_pkg.$field >= $beginning",
2906 "cust_pkg.$field <= $ending";
2908 $orderby ||= "ORDER BY cust_pkg.$field";
2913 $orderby ||= 'ORDER BY bill';
2916 # parse magic, legacy, etc.
2919 if ( $params->{'magic'} &&
2920 $params->{'magic'} =~ /^(active|inactive|suspended|cancell?ed)$/
2923 $orderby = 'ORDER BY pkgnum';
2925 if ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
2926 push @where, "pkgpart = $1";
2929 } elsif ( $params->{'query'} eq 'pkgnum' ) {
2931 $orderby = 'ORDER BY pkgnum';
2933 } elsif ( $params->{'query'} eq 'APKG_pkgnum' ) {
2935 $orderby = 'ORDER BY pkgnum';
2938 SELECT count(*) FROM pkg_svc
2939 WHERE pkg_svc.pkgpart = cust_pkg.pkgpart
2940 AND pkg_svc.quantity > ( SELECT count(*) FROM cust_svc
2941 WHERE cust_svc.pkgnum = cust_pkg.pkgnum
2942 AND cust_svc.svcpart = pkg_svc.svcpart
2949 # setup queries, links, subs, etc. for the search
2952 # here is the agent virtualization
2953 if ($params->{CurrentUser}) {
2955 qsearchs('access_user', { username => $params->{CurrentUser} });
2958 push @where, $access_user->agentnums_sql('table'=>'cust_main');
2963 push @where, $FS::CurrentUser::CurrentUser->agentnums_sql('table'=>'cust_main');
2966 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
2968 my $addl_from = 'LEFT JOIN cust_main USING ( custnum ) '.
2969 'LEFT JOIN part_pkg USING ( pkgpart ) '.
2970 'LEFT JOIN pkg_class ON ( part_pkg.classnum = pkg_class.classnum ) ';
2972 my $count_query = "SELECT COUNT(*) FROM cust_pkg $addl_from $extra_sql";
2975 'table' => 'cust_pkg',
2977 'select' => join(', ',
2979 ( map "part_pkg.$_", qw( pkg freq ) ),
2980 'pkg_class.classname',
2981 'cust_main.custnum AS cust_main_custnum',
2982 FS::UI::Web::cust_sql_fields(
2983 $params->{'cust_fields'}
2986 'extra_sql' => "$extra_sql $orderby",
2987 'addl_from' => $addl_from,
2988 'count_query' => $count_query,
2995 Returns a list of two package counts. The first is a count of packages
2996 based on the supplied criteria and the second is the count of residential
2997 packages with those same criteria. Criteria are specified as in the search
3003 my ($class, $params) = @_;
3005 my $sql_query = $class->search( $params );
3007 my $count_sql = delete($sql_query->{'count_query'});
3008 $count_sql =~ s/ FROM/,count(CASE WHEN cust_main.company IS NULL OR cust_main.company = '' THEN 1 END) FROM/
3009 or die "couldn't parse count_sql";
3011 my $count_sth = dbh->prepare($count_sql)
3012 or die "Error preparing $count_sql: ". dbh->errstr;
3014 or die "Error executing $count_sql: ". $count_sth->errstr;
3015 my $count_arrayref = $count_sth->fetchrow_arrayref;
3017 return ( @$count_arrayref );
3024 Returns a list: the first item is an SQL fragment identifying matching
3025 packages/customers via location (taking into account shipping and package
3026 address taxation, if enabled), and subsequent items are the parameters to
3027 substitute for the placeholders in that fragment.
3032 my($class, %opt) = @_;
3033 my $ornull = $opt{'ornull'};
3035 my $conf = new FS::Conf;
3037 # '?' placeholders in _location_sql_where
3038 my $x = $ornull ? 3 : 2;
3039 my @bill_param = ( ('city')x3, ('county')x$x, ('state')x$x, 'country' );
3043 if ( $conf->exists('tax-ship_address') ) {
3046 ( ( ship_last IS NULL OR ship_last = '' )
3047 AND ". _location_sql_where('cust_main', '', $ornull ). "
3049 OR ( ship_last IS NOT NULL AND ship_last != ''
3050 AND ". _location_sql_where('cust_main', 'ship_', $ornull ). "
3053 # AND payby != 'COMP'
3055 @main_param = ( @bill_param, @bill_param );
3059 $main_where = _location_sql_where('cust_main'); # AND payby != 'COMP'
3060 @main_param = @bill_param;
3066 if ( $conf->exists('tax-pkg_address') ) {
3068 my $loc_where = _location_sql_where( 'cust_location', '', $ornull );
3071 ( cust_pkg.locationnum IS NULL AND $main_where )
3072 OR ( cust_pkg.locationnum IS NOT NULL AND $loc_where )
3075 @param = ( @main_param, @bill_param );
3079 $where = $main_where;
3080 @param = @main_param;
3088 #subroutine, helper for location_sql
3089 sub _location_sql_where {
3091 my $prefix = @_ ? shift : '';
3092 my $ornull = @_ ? shift : '';
3094 # $ornull = $ornull ? " OR ( ? IS NULL AND $table.${prefix}county IS NULL ) " : '';
3096 $ornull = $ornull ? ' OR ? IS NULL ' : '';
3098 my $or_empty_city = " OR ( ? = '' AND $table.${prefix}city IS NULL ) ";
3099 my $or_empty_county = " OR ( ? = '' AND $table.${prefix}county IS NULL ) ";
3100 my $or_empty_state = " OR ( ? = '' AND $table.${prefix}state IS NULL ) ";
3102 # ( $table.${prefix}city = ? $or_empty_city $ornull )
3104 ( $table.${prefix}city = ? OR ? = '' OR CAST(? AS text) IS NULL )
3105 AND ( $table.${prefix}county = ? $or_empty_county $ornull )
3106 AND ( $table.${prefix}state = ? $or_empty_state $ornull )
3107 AND $table.${prefix}country = ?
3115 =item order CUSTNUM, PKGPARTS_ARYREF, [ REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF [ REFNUM ] ] ]
3117 CUSTNUM is a customer (see L<FS::cust_main>)
3119 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
3120 L<FS::part_pkg>) to order for this customer. Duplicates are of course
3123 REMOVE_PKGNUMS is an optional list of pkgnums specifying the billing items to
3124 remove for this customer. The services (see L<FS::cust_svc>) are moved to the
3125 new billing items. An error is returned if this is not possible (see
3126 L<FS::pkg_svc>). An empty arrayref is equivalent to not specifying this
3129 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
3130 newly-created cust_pkg objects.
3132 REFNUM, if specified, will specify the FS::pkg_referral record to be created
3133 and inserted. Multiple FS::pkg_referral records can be created by
3134 setting I<refnum> to an array reference of refnums or a hash reference with
3135 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
3136 record will be created corresponding to cust_main.refnum.
3141 my ($custnum, $pkgparts, $remove_pkgnum, $return_cust_pkg, $refnum) = @_;
3143 my $conf = new FS::Conf;
3145 # Transactionize this whole mess
3146 local $SIG{HUP} = 'IGNORE';
3147 local $SIG{INT} = 'IGNORE';
3148 local $SIG{QUIT} = 'IGNORE';
3149 local $SIG{TERM} = 'IGNORE';
3150 local $SIG{TSTP} = 'IGNORE';
3151 local $SIG{PIPE} = 'IGNORE';
3153 my $oldAutoCommit = $FS::UID::AutoCommit;
3154 local $FS::UID::AutoCommit = 0;
3158 # my $cust_main = qsearchs('cust_main', { custnum => $custnum });
3159 # return "Customer not found: $custnum" unless $cust_main;
3161 warn "$me order: pkgnums to remove: ". join(',', @$remove_pkgnum). "\n"
3164 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
3167 my $change = scalar(@old_cust_pkg) != 0;
3170 if ( scalar(@old_cust_pkg) == 1 && scalar(@$pkgparts) == 1 ) {
3172 warn "$me order: changing pkgnum ". $old_cust_pkg[0]->pkgnum.
3173 " to pkgpart ". $pkgparts->[0]. "\n"
3176 my $err_or_cust_pkg =
3177 $old_cust_pkg[0]->change( 'pkgpart' => $pkgparts->[0],
3178 'refnum' => $refnum,
3181 unless (ref($err_or_cust_pkg)) {
3182 $dbh->rollback if $oldAutoCommit;
3183 return $err_or_cust_pkg;
3186 push @$return_cust_pkg, $err_or_cust_pkg;
3187 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3192 # Create the new packages.
3193 foreach my $pkgpart (@$pkgparts) {
3195 warn "$me order: inserting pkgpart $pkgpart\n" if $DEBUG;
3197 my $cust_pkg = new FS::cust_pkg { custnum => $custnum,
3198 pkgpart => $pkgpart,
3202 $error = $cust_pkg->insert( 'change' => $change );
3204 $dbh->rollback if $oldAutoCommit;
3207 push @$return_cust_pkg, $cust_pkg;
3209 # $return_cust_pkg now contains refs to all of the newly
3212 # Transfer services and cancel old packages.
3213 foreach my $old_pkg (@old_cust_pkg) {
3215 warn "$me order: transferring services from pkgnum ". $old_pkg->pkgnum. "\n"
3218 foreach my $new_pkg (@$return_cust_pkg) {
3219 $error = $old_pkg->transfer($new_pkg);
3220 if ($error and $error == 0) {
3221 # $old_pkg->transfer failed.
3222 $dbh->rollback if $oldAutoCommit;
3227 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
3228 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
3229 foreach my $new_pkg (@$return_cust_pkg) {
3230 $error = $old_pkg->transfer($new_pkg, 'change_svcpart'=>1 );
3231 if ($error and $error == 0) {
3232 # $old_pkg->transfer failed.
3233 $dbh->rollback if $oldAutoCommit;
3240 # Transfers were successful, but we went through all of the
3241 # new packages and still had services left on the old package.
3242 # We can't cancel the package under the circumstances, so abort.
3243 $dbh->rollback if $oldAutoCommit;
3244 return "Unable to transfer all services from package ".$old_pkg->pkgnum;
3246 $error = $old_pkg->cancel( quiet=>1 );
3252 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3256 =item bulk_change PKGPARTS_ARYREF, REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF ]
3258 A bulk change method to change packages for multiple customers.
3260 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
3261 L<FS::part_pkg>) to order for each customer. Duplicates are of course
3264 REMOVE_PKGNUMS is an list of pkgnums specifying the billing items to
3265 replace. The services (see L<FS::cust_svc>) are moved to the
3266 new billing items. An error is returned if this is not possible (see
3269 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
3270 newly-created cust_pkg objects.
3275 my ($pkgparts, $remove_pkgnum, $return_cust_pkg) = @_;
3277 # Transactionize this whole mess
3278 local $SIG{HUP} = 'IGNORE';
3279 local $SIG{INT} = 'IGNORE';
3280 local $SIG{QUIT} = 'IGNORE';
3281 local $SIG{TERM} = 'IGNORE';
3282 local $SIG{TSTP} = 'IGNORE';
3283 local $SIG{PIPE} = 'IGNORE';
3285 my $oldAutoCommit = $FS::UID::AutoCommit;
3286 local $FS::UID::AutoCommit = 0;
3290 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
3293 while(scalar(@old_cust_pkg)) {
3295 my $custnum = $old_cust_pkg[0]->custnum;
3296 my (@remove) = map { $_->pkgnum }
3297 grep { $_->custnum == $custnum } @old_cust_pkg;
3298 @old_cust_pkg = grep { $_->custnum != $custnum } @old_cust_pkg;
3300 my $error = order $custnum, $pkgparts, \@remove, \@return;
3302 push @errors, $error
3304 push @$return_cust_pkg, @return;
3307 if (scalar(@errors)) {
3308 $dbh->rollback if $oldAutoCommit;
3309 return join(' / ', @errors);
3312 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3316 # Used by FS::Upgrade to migrate to a new database.
3317 sub _upgrade_data { # class method
3318 my ($class, %opts) = @_;
3319 $class->_upgrade_otaker(%opts);
3320 my $sql =('UPDATE cust_pkg SET contract_end = NULL WHERE contract_end = -1');
3321 my $sth = dbh->prepare($sql);
3322 $sth->execute or die $sth->errstr;
3329 sub order is not OO. Perhaps it should be moved to FS::cust_main and made so?
3331 In sub order, the @pkgparts array (passed by reference) is clobbered.
3333 Also in sub order, no money is adjusted. Once FS::part_pkg defines a standard
3334 method to pass dates to the recur_prog expression, it should do so.
3336 FS::svc_acct, FS::svc_domain, FS::svc_www, FS::svc_ip and FS::svc_forward are
3337 loaded via 'use' at compile time, rather than via 'require' in sub { setup,
3338 suspend, unsuspend, cancel } because they use %FS::UID::callback to load
3339 configuration values. Probably need a subroutine which decides what to do
3340 based on whether or not we've fetched the user yet, rather than a hash. See
3341 FS::UID and the TODO.
3343 Now that things are transactional should the check in the insert method be
3348 L<FS::Record>, L<FS::cust_main>, L<FS::part_pkg>, L<FS::cust_svc>,
3349 L<FS::pkg_svc>, schema.html from the base documentation