4 use base qw( FS::cust_main_Mixin FS::location_Mixin
5 FS::m2m_Common FS::option_Common FS::Record
7 use vars qw(@ISA $disable_agentcheck $DEBUG $me);
9 use Scalar::Util qw( blessed );
10 use List::Util qw(max);
12 use Time::Local qw( timelocal_nocheck );
14 use FS::UID qw( getotaker dbh );
15 use FS::Misc qw( send_email );
16 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;
32 # need to 'use' these instead of 'require' in sub { cancel, suspend, unsuspend,
34 # because they load configuration by setting FS::UID::callback (see TODO)
40 # for sending cancel emails in sub cancel
44 $me = '[FS::cust_pkg]';
46 $disable_agentcheck = 0;
50 my ( $hashref, $cache ) = @_;
51 #if ( $hashref->{'pkgpart'} ) {
52 if ( $hashref->{'pkg'} ) {
53 # #@{ $self->{'_pkgnum'} } = ();
54 # my $subcache = $cache->subcache('pkgpart', 'part_pkg');
55 # $self->{'_pkgpart'} = $subcache;
56 # #push @{ $self->{'_pkgnum'} },
57 # FS::part_pkg->new_or_cached($hashref, $subcache);
58 $self->{'_pkgpart'} = FS::part_pkg->new($hashref);
60 if ( exists $hashref->{'svcnum'} ) {
61 #@{ $self->{'_pkgnum'} } = ();
62 my $subcache = $cache->subcache('svcnum', 'cust_svc', $hashref->{pkgnum});
63 $self->{'_svcnum'} = $subcache;
64 #push @{ $self->{'_pkgnum'} },
65 FS::cust_svc->new_or_cached($hashref, $subcache) if $hashref->{svcnum};
71 FS::cust_pkg - Object methods for cust_pkg objects
77 $record = new FS::cust_pkg \%hash;
78 $record = new FS::cust_pkg { 'column' => 'value' };
80 $error = $record->insert;
82 $error = $new_record->replace($old_record);
84 $error = $record->delete;
86 $error = $record->check;
88 $error = $record->cancel;
90 $error = $record->suspend;
92 $error = $record->unsuspend;
94 $part_pkg = $record->part_pkg;
96 @labels = $record->labels;
98 $seconds = $record->seconds_since($timestamp);
100 $error = FS::cust_pkg::order( $custnum, \@pkgparts );
101 $error = FS::cust_pkg::order( $custnum, \@pkgparts, \@remove_pkgnums ] );
105 An FS::cust_pkg object represents a customer billing item. FS::cust_pkg
106 inherits from FS::Record. The following fields are currently supported:
112 Primary key (assigned automatically for new billing items)
116 Customer (see L<FS::cust_main>)
120 Billing item definition (see L<FS::part_pkg>)
124 Optional link to package location (see L<FS::location>)
136 date (next bill date)
160 order taker (assigned automatically if null, see L<FS::UID>)
164 If this field is set to 1, disables the automatic
165 unsuspension of this package when using the B<unsuspendauto> config option.
169 If not set, defaults to 1
173 Date of change from previous package
183 =item change_locationnum
189 Note: setup, last_bill, bill, adjourn, susp, expire, cancel and change_date
190 are specified as UNIX timestamps; see L<perlfunc/"time">. Also see
191 L<Time::Local> and L<Date::Parse> for conversion functions.
199 Create a new billing item. To add the item to the database, see L<"insert">.
203 sub table { 'cust_pkg'; }
204 sub cust_linked { $_[0]->cust_main_custnum; }
205 sub cust_unlinked_msg {
207 "WARNING: can't find cust_main.custnum ". $self->custnum.
208 ' (cust_pkg.pkgnum '. $self->pkgnum. ')';
211 =item insert [ OPTION => VALUE ... ]
213 Adds this billing item to the database ("Orders" the item). If there is an
214 error, returns the error, otherwise returns false.
216 If the additional field I<promo_code> is defined instead of I<pkgpart>, it
217 will be used to look up the package definition and agent restrictions will be
220 If the additional field I<refnum> is defined, an FS::pkg_referral record will
221 be created and inserted. Multiple FS::pkg_referral records can be created by
222 setting I<refnum> to an array reference of refnums or a hash reference with
223 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
224 record will be created corresponding to cust_main.refnum.
226 The following options are available:
232 If set true, supresses any referral credit to a referring customer.
236 cust_pkg_option records will be created
240 a ticket will be added to this customer with this subject
244 an optional queue name for ticket additions
251 my( $self, %options ) = @_;
253 if ( $self->part_pkg->option('start_1st', 1) && !$self->start_date ) {
254 my ($sec,$min,$hour,$mday,$mon,$year) = (localtime(time) )[0,1,2,3,4,5];
255 $mon += 1 unless $mday == 1;
256 until ( $mon < 12 ) { $mon -= 12; $year++; }
257 $self->start_date( timelocal_nocheck(0,0,0,1,$mon,$year) );
260 my $expire_months = $self->part_pkg->option('expire_months', 1);
261 if ( $expire_months && !$self->expire ) {
262 my $start = $self->start_date || $self->setup || time;
264 #false laziness w/part_pkg::add_freq
265 my ($sec,$min,$hour,$mday,$mon,$year) = (localtime($start) )[0,1,2,3,4,5];
266 $mon += $expire_months;
267 until ( $mon < 12 ) { $mon -= 12; $year++; }
269 #$self->expire( timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year) );
270 $self->expire( timelocal_nocheck(0,0,0,$mday,$mon,$year) );
273 local $SIG{HUP} = 'IGNORE';
274 local $SIG{INT} = 'IGNORE';
275 local $SIG{QUIT} = 'IGNORE';
276 local $SIG{TERM} = 'IGNORE';
277 local $SIG{TSTP} = 'IGNORE';
278 local $SIG{PIPE} = 'IGNORE';
280 my $oldAutoCommit = $FS::UID::AutoCommit;
281 local $FS::UID::AutoCommit = 0;
284 my $error = $self->SUPER::insert($options{options} ? %{$options{options}} : ());
286 $dbh->rollback if $oldAutoCommit;
290 $self->refnum($self->cust_main->refnum) unless $self->refnum;
291 $self->refnum( [ $self->refnum ] ) unless ref($self->refnum);
292 $self->process_m2m( 'link_table' => 'pkg_referral',
293 'target_table' => 'part_referral',
294 'params' => $self->refnum,
297 #if ( $self->reg_code ) {
298 # my $reg_code = qsearchs('reg_code', { 'code' => $self->reg_code } );
299 # $error = $reg_code->delete;
301 # $dbh->rollback if $oldAutoCommit;
306 my $conf = new FS::Conf;
308 if ( $conf->config('ticket_system') && $options{ticket_subject} ) {
310 use lib ( "/opt/rt3/local/lib", "/opt/rt3/lib" );
317 my $q = new RT::Queue($RT::SystemUser);
318 $q->Load($options{ticket_queue}) if $options{ticket_queue};
319 my $t = new RT::Ticket($RT::SystemUser);
320 my $mime = new MIME::Entity;
321 $mime->build( Type => 'text/plain', Data => $options{ticket_subject} );
322 $t->Create( $options{ticket_queue} ? (Queue => $q) : (),
323 Subject => $options{ticket_subject},
326 $t->AddLink( Type => 'MemberOf',
327 Target => 'freeside://freeside/cust_main/'. $self->custnum,
331 if ($conf->config('welcome_letter') && $self->cust_main->num_pkgs == 1) {
332 my $queue = new FS::queue {
333 'job' => 'FS::cust_main::queueable_print',
335 $error = $queue->insert(
336 'custnum' => $self->custnum,
337 'template' => 'welcome_letter',
341 warn "can't send welcome letter: $error";
346 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
353 This method now works but you probably shouldn't use it.
355 You don't want to delete billing items, because there would then be no record
356 the customer ever purchased the item. Instead, see the cancel method.
361 # return "Can't delete cust_pkg records!";
364 =item replace [ OLD_RECORD ] [ HASHREF | OPTION => VALUE ... ]
366 Replaces the OLD_RECORD with this one in the database. If there is an error,
367 returns the error, otherwise returns false.
369 Currently, custnum, setup, bill, adjourn, susp, expire, and cancel may be changed.
371 Changing pkgpart may have disasterous effects. See the order subroutine.
373 setup and bill are normally updated by calling the bill method of a customer
374 object (see L<FS::cust_main>).
376 suspend is normally updated by the suspend and unsuspend methods.
378 cancel is normally updated by the cancel method (and also the order subroutine
381 Available options are:
387 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.
391 the access_user (see L<FS::access_user>) providing the reason
395 hashref of keys and values - cust_pkg_option records will be created, updated or removed as appopriate
404 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
409 ( ref($_[0]) eq 'HASH' )
413 #return "Can't (yet?) change pkgpart!" if $old->pkgpart != $new->pkgpart;
414 return "Can't change otaker!" if $old->otaker ne $new->otaker;
417 #return "Can't change setup once it exists!"
418 # if $old->getfield('setup') &&
419 # $old->getfield('setup') != $new->getfield('setup');
421 #some logic for bill, susp, cancel?
423 local($disable_agentcheck) = 1 if $old->pkgpart == $new->pkgpart;
425 local $SIG{HUP} = 'IGNORE';
426 local $SIG{INT} = 'IGNORE';
427 local $SIG{QUIT} = 'IGNORE';
428 local $SIG{TERM} = 'IGNORE';
429 local $SIG{TSTP} = 'IGNORE';
430 local $SIG{PIPE} = 'IGNORE';
432 my $oldAutoCommit = $FS::UID::AutoCommit;
433 local $FS::UID::AutoCommit = 0;
436 foreach my $method ( qw(adjourn expire) ) { # How many reasons?
437 if ($options->{'reason'} && $new->$method && $old->$method ne $new->$method) {
438 my $error = $new->insert_reason(
439 'reason' => $options->{'reason'},
440 'date' => $new->$method,
442 'reason_otaker' => $options->{'reason_otaker'},
445 dbh->rollback if $oldAutoCommit;
446 return "Error inserting cust_pkg_reason: $error";
451 #save off and freeze RADIUS attributes for any associated svc_acct records
453 if ( $old->part_pkg->is_prepaid || $new->part_pkg->is_prepaid ) {
455 #also check for specific exports?
456 # to avoid spurious modify export events
457 @svc_acct = map { $_->svc_x }
458 grep { $_->part_svc->svcdb eq 'svc_acct' }
461 $_->snapshot foreach @svc_acct;
465 my $error = $new->SUPER::replace($old,
466 $options->{options} ? $options->{options} : ()
469 $dbh->rollback if $oldAutoCommit;
473 #for prepaid packages,
474 #trigger export of new RADIUS Expiration attribute when cust_pkg.bill changes
475 foreach my $old_svc_acct ( @svc_acct ) {
476 my $new_svc_acct = new FS::svc_acct { $old_svc_acct->hash };
477 my $s_error = $new_svc_acct->replace($old_svc_acct);
479 $dbh->rollback if $oldAutoCommit;
484 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
491 Checks all fields to make sure this is a valid billing item. If there is an
492 error, returns the error, otherwise returns false. Called by the insert and
500 $self->locationnum('') if !$self->locationnum || $self->locationnum == -1;
503 $self->ut_numbern('pkgnum')
504 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum')
505 || $self->ut_numbern('pkgpart')
506 || $self->ut_foreign_keyn('locationnum', 'cust_location', 'locationnum')
507 || $self->ut_numbern('start_date')
508 || $self->ut_numbern('setup')
509 || $self->ut_numbern('bill')
510 || $self->ut_numbern('susp')
511 || $self->ut_numbern('cancel')
512 || $self->ut_numbern('adjourn')
513 || $self->ut_numbern('expire')
515 return $error if $error;
517 if ( $self->reg_code ) {
519 unless ( grep { $self->pkgpart == $_->pkgpart }
520 map { $_->reg_code_pkg }
521 qsearchs( 'reg_code', { 'code' => $self->reg_code,
522 'agentnum' => $self->cust_main->agentnum })
524 return "Unknown registration code";
527 } elsif ( $self->promo_code ) {
530 qsearchs('part_pkg', {
531 'pkgpart' => $self->pkgpart,
532 'promo_code' => { op=>'ILIKE', value=>$self->promo_code },
534 return 'Unknown promotional code' unless $promo_part_pkg;
538 unless ( $disable_agentcheck ) {
540 qsearchs( 'agent', { 'agentnum' => $self->cust_main->agentnum } );
541 return "agent ". $agent->agentnum. ':'. $agent->agent.
542 " can't purchase pkgpart ". $self->pkgpart
543 unless $agent->pkgpart_hashref->{ $self->pkgpart }
544 || $agent->agentnum == $self->part_pkg->agentnum;
547 $error = $self->ut_foreign_key('pkgpart', 'part_pkg', 'pkgpart' );
548 return $error if $error;
552 $self->otaker(getotaker) unless $self->otaker;
553 $self->otaker =~ /^(\w{1,32})$/ or return "Illegal otaker";
556 if ( $self->dbdef_table->column('manual_flag') ) {
557 $self->manual_flag('') if $self->manual_flag eq ' ';
558 $self->manual_flag =~ /^([01]?)$/
559 or return "Illegal manual_flag ". $self->manual_flag;
560 $self->manual_flag($1);
566 =item cancel [ OPTION => VALUE ... ]
568 Cancels and removes all services (see L<FS::cust_svc> and L<FS::part_svc>)
569 in this package, then cancels the package itself (sets the cancel field to
572 Available options are:
576 =item quiet - can be set true to supress email cancellation notices.
578 =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.
580 =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.
582 =item date - can be set to a unix style timestamp to specify when to cancel (expire)
584 =item nobill - can be set true to skip billing if it might otherwise be done.
588 If there is an error, returns the error, otherwise returns false.
593 my( $self, %options ) = @_;
596 my $conf = new FS::Conf;
598 warn "cust_pkg::cancel called with options".
599 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
602 local $SIG{HUP} = 'IGNORE';
603 local $SIG{INT} = 'IGNORE';
604 local $SIG{QUIT} = 'IGNORE';
605 local $SIG{TERM} = 'IGNORE';
606 local $SIG{TSTP} = 'IGNORE';
607 local $SIG{PIPE} = 'IGNORE';
609 my $oldAutoCommit = $FS::UID::AutoCommit;
610 local $FS::UID::AutoCommit = 0;
613 my $old = $self->select_for_update;
615 if ( $old->get('cancel') || $self->get('cancel') ) {
616 dbh->rollback if $oldAutoCommit;
617 return ""; # no error
620 my $date = $options{date} if $options{date}; # expire/cancel later
621 $date = '' if ($date && $date <= time); # complain instead?
623 #race condition: usage could be ongoing until unprovisioned
624 #resolved by performing a change package instead (which unprovisions) and
626 if ( !$options{nobill} && !$date && $conf->exists('bill_usage_on_cancel') ) {
627 my $copy = $self->new({$self->hash});
629 $copy->cust_main->bill( pkg_list => [ $copy ], cancel => 1 );
630 warn "Error billing during cancel, custnum ".
631 #$self->cust_main->custnum. ": $error"
637 my $cancel_time = $options{'time'} || time;
639 if ( $options{'reason'} ) {
640 $error = $self->insert_reason( 'reason' => $options{'reason'},
641 'action' => $date ? 'expire' : 'cancel',
642 'date' => $date ? $date : $cancel_time,
643 'reason_otaker' => $options{'reason_otaker'},
646 dbh->rollback if $oldAutoCommit;
647 return "Error inserting cust_pkg_reason: $error";
653 foreach my $cust_svc (
656 sort { $a->[1] <=> $b->[1] }
657 map { [ $_, $_->svc_x->table_info->{'cancel_weight'} ]; }
658 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
661 my $error = $cust_svc->cancel;
664 $dbh->rollback if $oldAutoCommit;
665 return "Error cancelling cust_svc: $error";
669 # Add a credit for remaining service
670 my $remaining_value = $self->calc_remain(time=>$cancel_time);
671 if ( $remaining_value > 0 && !$options{'no_credit'} ) {
672 my $error = $self->cust_main->credit(
674 'Credit for unused time on '. $self->part_pkg->pkg,
675 'reason_type' => $conf->config('cancel_credit_type'),
678 $dbh->rollback if $oldAutoCommit;
679 return "Error crediting customer \$$remaining_value for unused time on".
680 $self->part_pkg->pkg. ": $error";
685 my %hash = $self->hash;
686 $date ? ($hash{'expire'} = $date) : ($hash{'cancel'} = $cancel_time);
687 my $new = new FS::cust_pkg ( \%hash );
688 $error = $new->replace( $self, options => { $self->options } );
690 $dbh->rollback if $oldAutoCommit;
694 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
695 return '' if $date; #no errors
697 my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ } $self->cust_main->invoicing_list;
698 if ( !$options{'quiet'} && $conf->exists('emailcancel') && @invoicing_list ) {
699 my $error = send_email(
700 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
701 'to' => \@invoicing_list,
702 'subject' => ( $conf->config('cancelsubject') || 'Cancellation Notice' ),
703 'body' => [ map "$_\n", $conf->config('cancelmessage') ],
705 #should this do something on errors?
712 =item cancel_if_expired [ NOW_TIMESTAMP ]
714 Cancels this package if its expire date has been reached.
718 sub cancel_if_expired {
720 my $time = shift || time;
721 return '' unless $self->expire && $self->expire <= $time;
722 my $error = $self->cancel;
724 return "Error cancelling expired pkg ". $self->pkgnum. " for custnum ".
725 $self->custnum. ": $error";
732 Cancels any pending expiration (sets the expire field to null).
734 If there is an error, returns the error, otherwise returns false.
739 my( $self, %options ) = @_;
742 local $SIG{HUP} = 'IGNORE';
743 local $SIG{INT} = 'IGNORE';
744 local $SIG{QUIT} = 'IGNORE';
745 local $SIG{TERM} = 'IGNORE';
746 local $SIG{TSTP} = 'IGNORE';
747 local $SIG{PIPE} = 'IGNORE';
749 my $oldAutoCommit = $FS::UID::AutoCommit;
750 local $FS::UID::AutoCommit = 0;
753 my $old = $self->select_for_update;
755 my $pkgnum = $old->pkgnum;
756 if ( $old->get('cancel') || $self->get('cancel') ) {
757 dbh->rollback if $oldAutoCommit;
758 return "Can't unexpire cancelled package $pkgnum";
759 # or at least it's pointless
762 unless ( $old->get('expire') && $self->get('expire') ) {
763 dbh->rollback if $oldAutoCommit;
764 return ""; # no error
767 my %hash = $self->hash;
768 $hash{'expire'} = '';
769 my $new = new FS::cust_pkg ( \%hash );
770 $error = $new->replace( $self, options => { $self->options } );
772 $dbh->rollback if $oldAutoCommit;
776 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
782 =item suspend [ OPTION => VALUE ... ]
784 Suspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
785 package, then suspends the package itself (sets the susp field to now).
787 Available options are:
791 =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.
793 =item date - can be set to a unix style timestamp to specify when to suspend (adjourn)
797 If there is an error, returns the error, otherwise returns false.
802 my( $self, %options ) = @_;
805 local $SIG{HUP} = 'IGNORE';
806 local $SIG{INT} = 'IGNORE';
807 local $SIG{QUIT} = 'IGNORE';
808 local $SIG{TERM} = 'IGNORE';
809 local $SIG{TSTP} = 'IGNORE';
810 local $SIG{PIPE} = 'IGNORE';
812 my $oldAutoCommit = $FS::UID::AutoCommit;
813 local $FS::UID::AutoCommit = 0;
816 my $old = $self->select_for_update;
818 my $pkgnum = $old->pkgnum;
819 if ( $old->get('cancel') || $self->get('cancel') ) {
820 dbh->rollback if $oldAutoCommit;
821 return "Can't suspend cancelled package $pkgnum";
824 if ( $old->get('susp') || $self->get('susp') ) {
825 dbh->rollback if $oldAutoCommit;
826 return ""; # no error # complain on adjourn?
829 my $date = $options{date} if $options{date}; # adjourn/suspend later
830 $date = '' if ($date && $date <= time); # complain instead?
832 if ( $date && $old->get('expire') && $old->get('expire') < $date ) {
833 dbh->rollback if $oldAutoCommit;
834 return "Package $pkgnum expires before it would be suspended.";
837 my $suspend_time = $options{'time'} || time;
839 if ( $options{'reason'} ) {
840 $error = $self->insert_reason( 'reason' => $options{'reason'},
841 'action' => $date ? 'adjourn' : 'suspend',
842 'date' => $date ? $date : $suspend_time,
843 'reason_otaker' => $options{'reason_otaker'},
846 dbh->rollback if $oldAutoCommit;
847 return "Error inserting cust_pkg_reason: $error";
855 foreach my $cust_svc (
856 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
858 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
860 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
861 $dbh->rollback if $oldAutoCommit;
862 return "Illegal svcdb value in part_svc!";
865 require "FS/$svcdb.pm";
867 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
869 $error = $svc->suspend;
871 $dbh->rollback if $oldAutoCommit;
874 my( $label, $value ) = $cust_svc->label;
875 push @labels, "$label: $value";
879 my $conf = new FS::Conf;
880 if ( $conf->config('suspend_email_admin') ) {
882 my $error = send_email(
883 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
884 #invoice_from ??? well as good as any
885 'to' => $conf->config('suspend_email_admin'),
886 'subject' => 'FREESIDE NOTIFICATION: Customer package suspended',
888 "This is an automatic message from your Freeside installation\n",
889 "informing you that the following customer package has been suspended:\n",
891 'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
892 'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
893 ( map { "Service : $_\n" } @labels ),
898 warn "WARNING: can't send suspension admin email (suspending anyway): ".
906 my %hash = $self->hash;
908 $hash{'adjourn'} = $date;
910 $hash{'susp'} = $suspend_time;
912 my $new = new FS::cust_pkg ( \%hash );
913 $error = $new->replace( $self, options => { $self->options } );
915 $dbh->rollback if $oldAutoCommit;
919 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
924 =item unsuspend [ OPTION => VALUE ... ]
926 Unsuspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
927 package, then unsuspends the package itself (clears the susp field and the
928 adjourn field if it is in the past).
930 Available options are:
934 =item adjust_next_bill
936 Can be set true to adjust the next bill date forward by
937 the amount of time the account was inactive. This was set true by default
938 since 1.4.2 and 1.5.0pre6; however, starting with 1.7.0 this needs to be
939 explicitly requested. Price plans for which this makes sense (anniversary-date
940 based than prorate or subscription) could have an option to enable this
945 If there is an error, returns the error, otherwise returns false.
950 my( $self, %opt ) = @_;
953 local $SIG{HUP} = 'IGNORE';
954 local $SIG{INT} = 'IGNORE';
955 local $SIG{QUIT} = 'IGNORE';
956 local $SIG{TERM} = 'IGNORE';
957 local $SIG{TSTP} = 'IGNORE';
958 local $SIG{PIPE} = 'IGNORE';
960 my $oldAutoCommit = $FS::UID::AutoCommit;
961 local $FS::UID::AutoCommit = 0;
964 my $old = $self->select_for_update;
966 my $pkgnum = $old->pkgnum;
967 if ( $old->get('cancel') || $self->get('cancel') ) {
968 dbh->rollback if $oldAutoCommit;
969 return "Can't unsuspend cancelled package $pkgnum";
972 unless ( $old->get('susp') && $self->get('susp') ) {
973 dbh->rollback if $oldAutoCommit;
974 return ""; # no error # complain instead?
977 foreach my $cust_svc (
978 qsearch('cust_svc',{'pkgnum'=> $self->pkgnum } )
980 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
982 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
983 $dbh->rollback if $oldAutoCommit;
984 return "Illegal svcdb value in part_svc!";
987 require "FS/$svcdb.pm";
989 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
991 $error = $svc->unsuspend;
993 $dbh->rollback if $oldAutoCommit;
1000 my %hash = $self->hash;
1001 my $inactive = time - $hash{'susp'};
1003 my $conf = new FS::Conf;
1005 $hash{'bill'} = ( $hash{'bill'} || $hash{'setup'} ) + $inactive
1006 if ( $opt{'adjust_next_bill'}
1007 || $conf->exists('unsuspend-always_adjust_next_bill_date') )
1008 && $inactive > 0 && ( $hash{'bill'} || $hash{'setup'} );
1011 $hash{'adjourn'} = '' if $hash{'adjourn'} < time;
1012 my $new = new FS::cust_pkg ( \%hash );
1013 $error = $new->replace( $self, options => { $self->options } );
1015 $dbh->rollback if $oldAutoCommit;
1019 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1026 Cancels any pending suspension (sets the adjourn field to null).
1028 If there is an error, returns the error, otherwise returns false.
1033 my( $self, %options ) = @_;
1036 local $SIG{HUP} = 'IGNORE';
1037 local $SIG{INT} = 'IGNORE';
1038 local $SIG{QUIT} = 'IGNORE';
1039 local $SIG{TERM} = 'IGNORE';
1040 local $SIG{TSTP} = 'IGNORE';
1041 local $SIG{PIPE} = 'IGNORE';
1043 my $oldAutoCommit = $FS::UID::AutoCommit;
1044 local $FS::UID::AutoCommit = 0;
1047 my $old = $self->select_for_update;
1049 my $pkgnum = $old->pkgnum;
1050 if ( $old->get('cancel') || $self->get('cancel') ) {
1051 dbh->rollback if $oldAutoCommit;
1052 return "Can't unadjourn cancelled package $pkgnum";
1053 # or at least it's pointless
1056 if ( $old->get('susp') || $self->get('susp') ) {
1057 dbh->rollback if $oldAutoCommit;
1058 return "Can't unadjourn suspended package $pkgnum";
1059 # perhaps this is arbitrary
1062 unless ( $old->get('adjourn') && $self->get('adjourn') ) {
1063 dbh->rollback if $oldAutoCommit;
1064 return ""; # no error
1067 my %hash = $self->hash;
1068 $hash{'adjourn'} = '';
1069 my $new = new FS::cust_pkg ( \%hash );
1070 $error = $new->replace( $self, options => { $self->options } );
1072 $dbh->rollback if $oldAutoCommit;
1076 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1083 =item change HASHREF | OPTION => VALUE ...
1085 Changes this package: cancels it and creates a new one, with a different
1086 pkgpart or locationnum or both. All services are transferred to the new
1087 package (no change will be made if this is not possible).
1089 Options may be passed as a list of key/value pairs or as a hash reference.
1096 New locationnum, to change the location for this package.
1100 New FS::cust_location object, to create a new location and assign it
1105 New pkgpart (see L<FS::part_pkg>).
1109 New refnum (see L<FS::part_referral>).
1113 At least one option must be specified (otherwise, what's the point?)
1115 Returns either the new FS::cust_pkg object or a scalar error.
1119 my $err_or_new_cust_pkg = $old_cust_pkg->change
1123 #some false laziness w/order
1126 my $opt = ref($_[0]) ? shift : { @_ };
1128 # my ($custnum, $pkgparts, $remove_pkgnum, $return_cust_pkg, $refnum) = @_;
1131 my $conf = new FS::Conf;
1133 # Transactionize this whole mess
1134 local $SIG{HUP} = 'IGNORE';
1135 local $SIG{INT} = 'IGNORE';
1136 local $SIG{QUIT} = 'IGNORE';
1137 local $SIG{TERM} = 'IGNORE';
1138 local $SIG{TSTP} = 'IGNORE';
1139 local $SIG{PIPE} = 'IGNORE';
1141 my $oldAutoCommit = $FS::UID::AutoCommit;
1142 local $FS::UID::AutoCommit = 0;
1151 #$hash{$_} = $self->$_() foreach qw( last_bill bill );
1153 #$hash{$_} = $self->$_() foreach qw( setup );
1155 $hash{'setup'} = $time if $self->setup;
1157 $hash{'change_date'} = $time;
1158 $hash{"change_$_"} = $self->$_()
1159 foreach qw( pkgnum pkgpart locationnum );
1161 if ( $opt->{'cust_location'} &&
1162 ( ! $opt->{'locationnum'} || $opt->{'locationnum'} == -1 ) ) {
1163 $error = $opt->{'cust_location'}->insert;
1165 $dbh->rollback if $oldAutoCommit;
1166 return "inserting cust_location (transaction rolled back): $error";
1168 $opt->{'locationnum'} = $opt->{'cust_location'}->locationnum;
1171 # Create the new package.
1172 my $cust_pkg = new FS::cust_pkg {
1173 custnum => $self->custnum,
1174 pkgpart => ( $opt->{'pkgpart'} || $self->pkgpart ),
1175 refnum => ( $opt->{'refnum'} || $self->refnum ),
1176 locationnum => ( $opt->{'locationnum'} || $self->locationnum ),
1180 $error = $cust_pkg->insert( 'change' => 1 );
1182 $dbh->rollback if $oldAutoCommit;
1186 # Transfer services and cancel old package.
1188 $error = $self->transfer($cust_pkg);
1189 if ($error and $error == 0) {
1190 # $old_pkg->transfer failed.
1191 $dbh->rollback if $oldAutoCommit;
1195 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
1196 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
1197 $error = $self->transfer($cust_pkg, 'change_svcpart'=>1 );
1198 if ($error and $error == 0) {
1199 # $old_pkg->transfer failed.
1200 $dbh->rollback if $oldAutoCommit;
1206 # Transfers were successful, but we still had services left on the old
1207 # package. We can't change the package under this circumstances, so abort.
1208 $dbh->rollback if $oldAutoCommit;
1209 return "Unable to transfer all services from package ". $self->pkgnum;
1212 #reset usage if changing pkgpart
1213 # AND usage rollover is off (otherwise adds twice, now and at package bill)
1214 if ($self->pkgpart != $cust_pkg->pkgpart) {
1215 my $part_pkg = $cust_pkg->part_pkg;
1216 $error = $part_pkg->reset_usage($cust_pkg, $part_pkg->is_prepaid
1220 if $part_pkg->can('reset_usage') && ! $part_pkg->option('usage_rollover');
1223 $dbh->rollback if $oldAutoCommit;
1224 return "Error setting usage values: $error";
1228 #Good to go, cancel old package.
1229 $error = $self->cancel( quiet=>1 );
1231 $dbh->rollback if $oldAutoCommit;
1235 if ( $conf->exists('cust_pkg-change_pkgpart-bill_now') ) {
1237 my $error = $cust_pkg->cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1239 $dbh->rollback if $oldAutoCommit;
1244 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1252 Returns the last bill date, or if there is no last bill date, the setup date.
1253 Useful for billing metered services.
1259 return $self->setfield('last_bill', $_[0]) if @_;
1260 return $self->getfield('last_bill') if $self->getfield('last_bill');
1261 my $cust_bill_pkg = qsearchs('cust_bill_pkg', { 'pkgnum' => $self->pkgnum,
1262 'edate' => $self->bill, } );
1263 $cust_bill_pkg ? $cust_bill_pkg->sdate : $self->setup || 0;
1266 =item last_cust_pkg_reason ACTION
1268 Returns the most recent ACTION FS::cust_pkg_reason associated with the package.
1269 Returns false if there is no reason or the package is not currenly ACTION'd
1270 ACTION is one of adjourn, susp, cancel, or expire.
1274 sub last_cust_pkg_reason {
1275 my ( $self, $action ) = ( shift, shift );
1276 my $date = $self->get($action);
1278 'table' => 'cust_pkg_reason',
1279 'hashref' => { 'pkgnum' => $self->pkgnum,
1280 'action' => substr(uc($action), 0, 1),
1283 'order_by' => 'ORDER BY num DESC LIMIT 1',
1287 =item last_reason ACTION
1289 Returns the most recent ACTION FS::reason associated with the package.
1290 Returns false if there is no reason or the package is not currenly ACTION'd
1291 ACTION is one of adjourn, susp, cancel, or expire.
1296 my $cust_pkg_reason = shift->last_cust_pkg_reason(@_);
1297 $cust_pkg_reason->reason
1298 if $cust_pkg_reason;
1303 Returns the definition for this billing item, as an FS::part_pkg object (see
1310 return $self->{'_pkgpart'} if $self->{'_pkgpart'};
1311 cluck "cust_pkg->part_pkg called" if $DEBUG > 1;
1312 qsearchs( 'part_pkg', { 'pkgpart' => $self->pkgpart } );
1317 Returns the cancelled package this package was changed from, if any.
1323 return '' unless $self->change_pkgnum;
1324 qsearchs('cust_pkg', { 'pkgnum' => $self->change_pkgnum } );
1329 Calls the I<calc_setup> of the FS::part_pkg object associated with this billing
1336 $self->part_pkg->calc_setup($self, @_);
1341 Calls the I<calc_recur> of the FS::part_pkg object associated with this billing
1348 $self->part_pkg->calc_recur($self, @_);
1353 Calls the I<calc_remain> of the FS::part_pkg object associated with this
1360 $self->part_pkg->calc_remain($self, @_);
1365 Calls the I<calc_cancel> of the FS::part_pkg object associated with this
1372 $self->part_pkg->calc_cancel($self, @_);
1377 Returns any invoice line items for this package (see L<FS::cust_bill_pkg>).
1383 qsearch( 'cust_bill_pkg', { 'pkgnum' => $self->pkgnum } );
1386 =item cust_pkg_detail [ DETAILTYPE ]
1388 Returns any customer package details for this package (see
1389 L<FS::cust_pkg_detail>).
1391 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
1395 sub cust_pkg_detail {
1397 my %hash = ( 'pkgnum' => $self->pkgnum );
1398 $hash{detailtype} = shift if @_;
1400 'table' => 'cust_pkg_detail',
1401 'hashref' => \%hash,
1402 'order_by' => 'ORDER BY weight, pkgdetailnum',
1406 =item set_cust_pkg_detail DETAILTYPE [ DETAIL, DETAIL, ... ]
1408 Sets customer package details for this package (see L<FS::cust_pkg_detail>).
1410 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
1412 If there is an error, returns the error, otherwise returns false.
1416 sub set_cust_pkg_detail {
1417 my( $self, $detailtype, @details ) = @_;
1419 local $SIG{HUP} = 'IGNORE';
1420 local $SIG{INT} = 'IGNORE';
1421 local $SIG{QUIT} = 'IGNORE';
1422 local $SIG{TERM} = 'IGNORE';
1423 local $SIG{TSTP} = 'IGNORE';
1424 local $SIG{PIPE} = 'IGNORE';
1426 my $oldAutoCommit = $FS::UID::AutoCommit;
1427 local $FS::UID::AutoCommit = 0;
1430 foreach my $current ( $self->cust_pkg_detail($detailtype) ) {
1431 my $error = $current->delete;
1433 $dbh->rollback if $oldAutoCommit;
1434 return "error removing old detail: $error";
1438 foreach my $detail ( @details ) {
1439 my $cust_pkg_detail = new FS::cust_pkg_detail {
1440 'pkgnum' => $self->pkgnum,
1441 'detailtype' => $detailtype,
1442 'detail' => $detail,
1444 my $error = $cust_pkg_detail->insert;
1446 $dbh->rollback if $oldAutoCommit;
1447 return "error adding new detail: $error";
1452 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1459 Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.
1463 #false laziness w/cust_bill.pm
1467 'table' => 'cust_event',
1468 'addl_from' => 'JOIN part_event USING ( eventpart )',
1469 'hashref' => { 'tablenum' => $self->pkgnum },
1470 'extra_sql' => " AND eventtable = 'cust_pkg' ",
1474 =item num_cust_event
1476 Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.
1480 #false laziness w/cust_bill.pm
1481 sub num_cust_event {
1484 "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
1485 " WHERE tablenum = ? AND eventtable = 'cust_pkg'";
1486 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
1487 $sth->execute($self->pkgnum) or die $sth->errstr. " executing $sql";
1488 $sth->fetchrow_arrayref->[0];
1491 =item cust_svc [ SVCPART ]
1493 Returns the services for this package, as FS::cust_svc objects (see
1494 L<FS::cust_svc>). If a svcpart is specified, return only the matching
1502 return () unless $self->num_cust_svc(@_);
1505 return qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum,
1506 'svcpart' => shift, } );
1509 cluck "cust_pkg->cust_svc called" if $DEBUG > 2;
1511 #if ( $self->{'_svcnum'} ) {
1512 # values %{ $self->{'_svcnum'}->cache };
1514 $self->_sort_cust_svc(
1515 [ qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } ) ]
1521 =item overlimit [ SVCPART ]
1523 Returns the services for this package which have exceeded their
1524 usage limit as FS::cust_svc objects (see L<FS::cust_svc>). If a svcpart
1525 is specified, return only the matching services.
1531 return () unless $self->num_cust_svc(@_);
1532 grep { $_->overlimit } $self->cust_svc(@_);
1535 =item h_cust_svc END_TIMESTAMP [ START_TIMESTAMP ]
1537 Returns historical services for this package created before END TIMESTAMP and
1538 (optionally) not cancelled before START_TIMESTAMP, as FS::h_cust_svc objects
1539 (see L<FS::h_cust_svc>).
1546 $self->_sort_cust_svc(
1547 [ qsearch( 'h_cust_svc',
1548 { 'pkgnum' => $self->pkgnum, },
1549 FS::h_cust_svc->sql_h_search(@_),
1555 sub _sort_cust_svc {
1556 my( $self, $arrayref ) = @_;
1559 sub ($$) { my ($a, $b) = @_; $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] };
1564 my $pkg_svc = qsearchs( 'pkg_svc', { 'pkgpart' => $self->pkgpart,
1565 'svcpart' => $_->svcpart } );
1567 $pkg_svc ? $pkg_svc->primary_svc : '',
1568 $pkg_svc ? $pkg_svc->quantity : 0,
1575 =item num_cust_svc [ SVCPART ]
1577 Returns the number of provisioned services for this package. If a svcpart is
1578 specified, counts only the matching services.
1585 return $self->{'_num_cust_svc'}
1587 && exists($self->{'_num_cust_svc'})
1588 && $self->{'_num_cust_svc'} =~ /\d/;
1590 cluck "cust_pkg->num_cust_svc called, _num_cust_svc:".$self->{'_num_cust_svc'}
1593 my $sql = 'SELECT COUNT(*) FROM cust_svc WHERE pkgnum = ?';
1594 $sql .= ' AND svcpart = ?' if @_;
1596 my $sth = dbh->prepare($sql) or die dbh->errstr;
1597 $sth->execute($self->pkgnum, @_) or die $sth->errstr;
1598 $sth->fetchrow_arrayref->[0];
1601 =item available_part_svc
1603 Returns a list of FS::part_svc objects representing services included in this
1604 package but not yet provisioned. Each FS::part_svc object also has an extra
1605 field, I<num_avail>, which specifies the number of available services.
1609 sub available_part_svc {
1611 grep { $_->num_avail > 0 }
1613 my $part_svc = $_->part_svc;
1614 $part_svc->{'Hash'}{'num_avail'} = #evil encapsulation-breaking
1615 $_->quantity - $self->num_cust_svc($_->svcpart);
1618 $self->part_pkg->pkg_svc;
1623 Returns a list of FS::part_svc objects representing provisioned and available
1624 services included in this package. Each FS::part_svc object also has the
1625 following extra fields:
1629 =item num_cust_svc (count)
1631 =item num_avail (quantity - count)
1633 =item cust_pkg_svc (services) - array reference containing the provisioned services, as cust_svc objects
1636 label -> ($cust_svc->label)[1]
1645 #XXX some sort of sort order besides numeric by svcpart...
1646 my @part_svc = sort { $a->svcpart <=> $b->svcpart } map {
1648 my $part_svc = $pkg_svc->part_svc;
1649 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
1650 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #more evil
1651 $part_svc->{'Hash'}{'num_avail'} =
1652 max( 0, $pkg_svc->quantity - $num_cust_svc );
1653 $part_svc->{'Hash'}{'cust_pkg_svc'} =
1654 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : [];
1656 } $self->part_pkg->pkg_svc;
1659 push @part_svc, map {
1661 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
1662 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #speak no evail
1663 $part_svc->{'Hash'}{'num_avail'} = 0; #0-$num_cust_svc ?
1664 $part_svc->{'Hash'}{'cust_pkg_svc'} =
1665 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : [];
1667 } $self->extra_part_svc;
1673 =item extra_part_svc
1675 Returns a list of FS::part_svc objects corresponding to services in this
1676 package which are still provisioned but not (any longer) available in the
1681 sub extra_part_svc {
1684 my $pkgnum = $self->pkgnum;
1685 my $pkgpart = $self->pkgpart;
1688 # 'table' => 'part_svc',
1691 # "WHERE 0 = ( SELECT COUNT(*) FROM pkg_svc
1692 # WHERE pkg_svc.svcpart = part_svc.svcpart
1693 # AND pkg_svc.pkgpart = ?
1696 # AND 0 < ( SELECT COUNT(*) FROM cust_svc
1697 # LEFT JOIN cust_pkg USING ( pkgnum )
1698 # WHERE cust_svc.svcpart = part_svc.svcpart
1701 # 'extra_param' => [ [$self->pkgpart=>'int'], [$self->pkgnum=>'int'] ],
1704 #seems to benchmark slightly faster...
1706 #'select' => 'DISTINCT ON (svcpart) part_svc.*',
1707 #MySQL doesn't grok DISINCT ON
1708 'select' => 'DISTINCT part_svc.*',
1709 'table' => 'part_svc',
1711 'LEFT JOIN pkg_svc ON ( pkg_svc.svcpart = part_svc.svcpart
1712 AND pkg_svc.pkgpart = ?
1715 LEFT JOIN cust_svc ON ( cust_svc.svcpart = part_svc.svcpart )
1716 LEFT JOIN cust_pkg USING ( pkgnum )
1719 'extra_sql' => "WHERE pkgsvcnum IS NULL AND cust_pkg.pkgnum = ? ",
1720 'extra_param' => [ [$self->pkgpart=>'int'], [$self->pkgnum=>'int'] ],
1726 Returns a short status string for this package, currently:
1730 =item not yet billed
1732 =item one-time charge
1747 my $freq = length($self->freq) ? $self->freq : $self->part_pkg->freq;
1749 return 'cancelled' if $self->get('cancel');
1750 return 'suspended' if $self->susp;
1751 return 'not yet billed' unless $self->setup;
1752 return 'one-time charge' if $freq =~ /^(0|$)/;
1758 Class method that returns the list of possible status strings for packages
1759 (see L<the status method|/status>). For example:
1761 @statuses = FS::cust_pkg->statuses();
1765 tie my %statuscolor, 'Tie::IxHash',
1766 'not yet billed' => '000000',
1767 'one-time charge' => '000000',
1768 'active' => '00CC00',
1769 'suspended' => 'FF9900',
1770 'cancelled' => 'FF0000',
1774 my $self = shift; #could be class...
1775 #grep { $_ !~ /^(not yet billed)$/ } #this is a dumb status anyway
1776 # # mayble split btw one-time vs. recur
1782 Returns a hex triplet color string for this package's status.
1788 $statuscolor{$self->status};
1793 Returns a label for this package. (Currently "pkgnum: pkg - comment" or
1794 "pkg-comment" depending on user preference).
1800 my $label = $self->part_pkg->pkg_comment( 'nopkgpart' => 1 );
1801 $label = $self->pkgnum. ": $label"
1802 if $FS::CurrentUser::CurrentUser->option('show_pkgnum');
1806 =item pkg_label_long
1808 Returns a long label for this package, adding the primary service's label to
1813 sub pkg_label_long {
1815 my $label = $self->pkg_label;
1816 my $cust_svc = $self->primary_cust_svc;
1817 $label .= ' ('. ($cust_svc->label)[1]. ')' if $cust_svc;
1821 =item primary_cust_svc
1823 Returns a primary service (as FS::cust_svc object) if one can be identified.
1827 #for labeling purposes - might not 100% match up with part_pkg->svcpart's idea
1829 sub primary_cust_svc {
1832 my @cust_svc = $self->cust_svc;
1834 return '' unless @cust_svc; #no serivces - irrelevant then
1836 return $cust_svc[0] if scalar(@cust_svc) == 1; #always return a single service
1838 # primary service as specified in the package definition
1839 # or exactly one service definition with quantity one
1840 my $svcpart = $self->part_pkg->svcpart;
1841 @cust_svc = grep { $_->svcpart == $svcpart } @cust_svc;
1842 return $cust_svc[0] if scalar(@cust_svc) == 1;
1844 #couldn't identify one thing..
1850 Returns a list of lists, calling the label method for all services
1851 (see L<FS::cust_svc>) of this billing item.
1857 map { [ $_->label ] } $self->cust_svc;
1860 =item h_labels END_TIMESTAMP [ START_TIMESTAMP ]
1862 Like the labels method, but returns historical information on services that
1863 were active as of END_TIMESTAMP and (optionally) not cancelled before
1866 Returns a list of lists, calling the label method for all (historical) services
1867 (see L<FS::h_cust_svc>) of this billing item.
1873 map { [ $_->label(@_) ] } $self->h_cust_svc(@_);
1878 Like labels, except returns a simple flat list, and shortens long
1879 (currently >5 or the cust_bill-max_same_services configuration value) lists of
1880 identical services to one line that lists the service label and the number of
1881 individual services rather than individual items.
1886 shift->_labels_short( 'labels', @_ );
1889 =item h_labels_short END_TIMESTAMP [ START_TIMESTAMP ]
1891 Like h_labels, except returns a simple flat list, and shortens long
1892 (currently >5 or the cust_bill-max_same_services configuration value) lists of
1893 identical services to one line that lists the service label and the number of
1894 individual services rather than individual items.
1898 sub h_labels_short {
1899 shift->_labels_short( 'h_labels', @_ );
1903 my( $self, $method ) = ( shift, shift );
1905 my $conf = new FS::Conf;
1906 my $max_same_services = $conf->config('cust_bill-max_same_services') || 5;
1909 #tie %labels, 'Tie::IxHash';
1910 push @{ $labels{$_->[0]} }, $_->[1]
1911 foreach $self->h_labels(@_);
1913 foreach my $label ( keys %labels ) {
1915 my @values = grep { ! $seen{$_}++ } @{ $labels{$label} };
1916 my $num = scalar(@values);
1917 if ( $num > $max_same_services ) {
1918 push @labels, "$label ($num)";
1920 if ( $conf->exists('cust_bill-consolidate_services') ) {
1921 # push @labels, "$label: ". join(', ', @values);
1923 my $detail = "$label: ";
1924 $detail .= shift(@values). ', '
1925 while @values && length($detail.$values[0]) < 78;
1927 push @labels, $detail;
1930 push @labels, map { "$label: $_" } @values;
1941 Returns the parent customer object (see L<FS::cust_main>).
1947 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
1950 #these subs are in location_Mixin.pm now... unfortunately the POD doesn't mixin
1954 Returns the location object, if any (see L<FS::cust_location>).
1956 =item cust_location_or_main
1958 If this package is associated with a location, returns the locaiton (see
1959 L<FS::cust_location>), otherwise returns the customer (see L<FS::cust_main>).
1961 =item location_label [ OPTION => VALUE ... ]
1963 Returns the label of the location object (see L<FS::cust_location>).
1967 #end of subs in location_Mixin.pm now... unfortunately the POD doesn't mixin
1969 =item seconds_since TIMESTAMP
1971 Returns the number of seconds all accounts (see L<FS::svc_acct>) in this
1972 package have been online since TIMESTAMP, according to the session monitor.
1974 TIMESTAMP is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
1975 L<Time::Local> and L<Date::Parse> for conversion functions.
1980 my($self, $since) = @_;
1983 foreach my $cust_svc (
1984 grep { $_->part_svc->svcdb eq 'svc_acct' } $self->cust_svc
1986 $seconds += $cust_svc->seconds_since($since);
1993 =item seconds_since_sqlradacct TIMESTAMP_START TIMESTAMP_END
1995 Returns the numbers of seconds all accounts (see L<FS::svc_acct>) in this
1996 package have been online between TIMESTAMP_START (inclusive) and TIMESTAMP_END
1999 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
2000 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
2006 sub seconds_since_sqlradacct {
2007 my($self, $start, $end) = @_;
2011 foreach my $cust_svc (
2013 my $part_svc = $_->part_svc;
2014 $part_svc->svcdb eq 'svc_acct'
2015 && scalar($part_svc->part_export('sqlradius'));
2018 $seconds += $cust_svc->seconds_since_sqlradacct($start, $end);
2025 =item attribute_since_sqlradacct TIMESTAMP_START TIMESTAMP_END ATTRIBUTE
2027 Returns the sum of the given attribute for all accounts (see L<FS::svc_acct>)
2028 in this package for sessions ending between TIMESTAMP_START (inclusive) and
2032 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
2033 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
2038 sub attribute_since_sqlradacct {
2039 my($self, $start, $end, $attrib) = @_;
2043 foreach my $cust_svc (
2045 my $part_svc = $_->part_svc;
2046 $part_svc->svcdb eq 'svc_acct'
2047 && scalar($part_svc->part_export('sqlradius'));
2050 $sum += $cust_svc->attribute_since_sqlradacct($start, $end, $attrib);
2062 my( $self, $value ) = @_;
2063 if ( defined($value) ) {
2064 $self->setfield('quantity', $value);
2066 $self->getfield('quantity') || 1;
2069 =item transfer DEST_PKGNUM | DEST_CUST_PKG, [ OPTION => VALUE ... ]
2071 Transfers as many services as possible from this package to another package.
2073 The destination package can be specified by pkgnum by passing an FS::cust_pkg
2074 object. The destination package must already exist.
2076 Services are moved only if the destination allows services with the correct
2077 I<svcpart> (not svcdb), unless the B<change_svcpart> option is set true. Use
2078 this option with caution! No provision is made for export differences
2079 between the old and new service definitions. Probably only should be used
2080 when your exports for all service definitions of a given svcdb are identical.
2081 (attempt a transfer without it first, to move all possible svcpart-matching
2084 Any services that can't be moved remain in the original package.
2086 Returns an error, if there is one; otherwise, returns the number of services
2087 that couldn't be moved.
2092 my ($self, $dest_pkgnum, %opt) = @_;
2098 if (ref ($dest_pkgnum) eq 'FS::cust_pkg') {
2099 $dest = $dest_pkgnum;
2100 $dest_pkgnum = $dest->pkgnum;
2102 $dest = qsearchs('cust_pkg', { pkgnum => $dest_pkgnum });
2105 return ('Package does not exist: '.$dest_pkgnum) unless $dest;
2107 foreach my $pkg_svc ( $dest->part_pkg->pkg_svc ) {
2108 $target{$pkg_svc->svcpart} = $pkg_svc->quantity;
2111 foreach my $cust_svc ($dest->cust_svc) {
2112 $target{$cust_svc->svcpart}--;
2115 my %svcpart2svcparts = ();
2116 if ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
2117 warn "change_svcpart option received, creating alternates list\n" if $DEBUG;
2118 foreach my $svcpart ( map { $_->svcpart } $self->cust_svc ) {
2119 next if exists $svcpart2svcparts{$svcpart};
2120 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2121 $svcpart2svcparts{$svcpart} = [
2123 sort { $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] }
2125 my $pkg_svc = qsearchs( 'pkg_svc', { 'pkgpart' => $dest->pkgpart,
2126 'svcpart' => $_ } );
2128 $pkg_svc ? $pkg_svc->primary_svc : '',
2129 $pkg_svc ? $pkg_svc->quantity : 0,
2133 grep { $_ != $svcpart }
2135 qsearch('part_svc', { 'svcdb' => $part_svc->svcdb } )
2137 warn "alternates for svcpart $svcpart: ".
2138 join(', ', @{$svcpart2svcparts{$svcpart}}). "\n"
2143 foreach my $cust_svc ($self->cust_svc) {
2144 if($target{$cust_svc->svcpart} > 0) {
2145 $target{$cust_svc->svcpart}--;
2146 my $new = new FS::cust_svc { $cust_svc->hash };
2147 $new->pkgnum($dest_pkgnum);
2148 my $error = $new->replace($cust_svc);
2149 return $error if $error;
2150 } elsif ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
2152 warn "looking for alternates for svcpart ". $cust_svc->svcpart. "\n";
2153 warn "alternates to consider: ".
2154 join(', ', @{$svcpart2svcparts{$cust_svc->svcpart}}). "\n";
2156 my @alternate = grep {
2157 warn "considering alternate svcpart $_: ".
2158 "$target{$_} available in new package\n"
2161 } @{$svcpart2svcparts{$cust_svc->svcpart}};
2163 warn "alternate(s) found\n" if $DEBUG;
2164 my $change_svcpart = $alternate[0];
2165 $target{$change_svcpart}--;
2166 my $new = new FS::cust_svc { $cust_svc->hash };
2167 $new->svcpart($change_svcpart);
2168 $new->pkgnum($dest_pkgnum);
2169 my $error = $new->replace($cust_svc);
2170 return $error if $error;
2183 This method is deprecated. See the I<depend_jobnum> option to the insert and
2184 order_pkgs methods in FS::cust_main for a better way to defer provisioning.
2191 local $SIG{HUP} = 'IGNORE';
2192 local $SIG{INT} = 'IGNORE';
2193 local $SIG{QUIT} = 'IGNORE';
2194 local $SIG{TERM} = 'IGNORE';
2195 local $SIG{TSTP} = 'IGNORE';
2196 local $SIG{PIPE} = 'IGNORE';
2198 my $oldAutoCommit = $FS::UID::AutoCommit;
2199 local $FS::UID::AutoCommit = 0;
2202 foreach my $cust_svc ( $self->cust_svc ) {
2203 #false laziness w/svc_Common::insert
2204 my $svc_x = $cust_svc->svc_x;
2205 foreach my $part_export ( $cust_svc->part_svc->part_export ) {
2206 my $error = $part_export->export_insert($svc_x);
2208 $dbh->rollback if $oldAutoCommit;
2214 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2221 =head1 CLASS METHODS
2227 Returns an SQL expression identifying recurring packages.
2231 sub recurring_sql { "
2232 '0' != ( select freq from part_pkg
2233 where cust_pkg.pkgpart = part_pkg.pkgpart )
2238 Returns an SQL expression identifying one-time packages.
2243 '0' = ( select freq from part_pkg
2244 where cust_pkg.pkgpart = part_pkg.pkgpart )
2249 Returns an SQL expression identifying active packages.
2254 ". $_[0]->recurring_sql(). "
2255 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
2256 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
2257 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
2260 =item not_yet_billed_sql
2262 Returns an SQL expression identifying packages which have not yet been billed.
2266 sub not_yet_billed_sql { "
2267 ( cust_pkg.setup IS NULL OR cust_pkg.setup = 0 )
2268 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
2269 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
2274 Returns an SQL expression identifying inactive packages (one-time packages
2275 that are otherwise unsuspended/uncancelled).
2279 sub inactive_sql { "
2280 ". $_[0]->onetime_sql(). "
2281 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
2282 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
2283 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
2289 Returns an SQL expression identifying suspended packages.
2293 sub suspended_sql { susp_sql(@_); }
2295 #$_[0]->recurring_sql(). ' AND '.
2297 ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
2298 AND cust_pkg.susp IS NOT NULL AND cust_pkg.susp != 0
2305 Returns an SQL exprression identifying cancelled packages.
2309 sub cancelled_sql { cancel_sql(@_); }
2311 #$_[0]->recurring_sql(). ' AND '.
2312 "cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0";
2315 =item search HASHREF
2319 Returns a qsearch hash expression to search for parameters specified in HASHREF.
2320 Valid parameters are
2328 active, inactive, suspended, cancel (or cancelled)
2332 active, inactive, suspended, one-time charge, inactive, cancel (or cancelled)
2336 boolean selects custom packages
2342 pkgpart or arrayref or hashref of pkgparts
2346 arrayref of beginning and ending epoch date
2350 arrayref of beginning and ending epoch date
2354 arrayref of beginning and ending epoch date
2358 arrayref of beginning and ending epoch date
2362 arrayref of beginning and ending epoch date
2366 arrayref of beginning and ending epoch date
2370 arrayref of beginning and ending epoch date
2374 pkgnum or APKG_pkgnum
2378 a value suited to passing to FS::UI::Web::cust_header
2382 specifies the user for agent virtualization
2386 boolean selects packages containing fcc form 477 telco lines
2393 my ($class, $params) = @_;
2400 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
2402 "cust_main.agentnum = $1";
2409 if ( $params->{'custnum'} =~ /^(\d+)$/ and $1 ) {
2411 "cust_pkg.custnum = $1";
2418 if ( $params->{'magic'} eq 'active'
2419 || $params->{'status'} eq 'active' ) {
2421 push @where, FS::cust_pkg->active_sql();
2423 } elsif ( $params->{'magic'} =~ /^not[ _]yet[ _]billed$/
2424 || $params->{'status'} =~ /^not[ _]yet[ _]billed$/ ) {
2426 push @where, FS::cust_pkg->not_yet_billed_sql();
2428 } elsif ( $params->{'magic'} =~ /^(one-time charge|inactive)/
2429 || $params->{'status'} =~ /^(one-time charge|inactive)/ ) {
2431 push @where, FS::cust_pkg->inactive_sql();
2433 } elsif ( $params->{'magic'} eq 'suspended'
2434 || $params->{'status'} eq 'suspended' ) {
2436 push @where, FS::cust_pkg->suspended_sql();
2438 } elsif ( $params->{'magic'} =~ /^cancell?ed$/
2439 || $params->{'status'} =~ /^cancell?ed$/ ) {
2441 push @where, FS::cust_pkg->cancelled_sql();
2446 # parse package class
2449 #false lazinessish w/graph/cust_bill_pkg.cgi
2452 if ( exists($params->{'classnum'})
2453 && $params->{'classnum'} =~ /^(\d*)$/
2457 if ( $classnum ) { #a specific class
2458 push @where, "part_pkg.classnum = $classnum";
2460 #@pkg_class = ( qsearchs('pkg_class', { 'classnum' => $classnum } ) );
2461 #die "classnum $classnum not found!" unless $pkg_class[0];
2462 #$title .= $pkg_class[0]->classname.' ';
2464 } elsif ( $classnum eq '' ) { #the empty class
2466 push @where, "part_pkg.classnum IS NULL";
2467 #$title .= 'Empty class ';
2468 #@pkg_class = ( '(empty class)' );
2469 } elsif ( $classnum eq '0' ) {
2470 #@pkg_class = qsearch('pkg_class', {} ); # { 'disabled' => '' } );
2471 #push @pkg_class, '(empty class)';
2473 die "illegal classnum";
2479 # parse package report options
2482 my @report_option = ();
2483 if ( exists($params->{'report_option'})
2484 && $params->{'report_option'} =~ /^([,\d]*)$/
2487 @report_option = split(',', $1);
2490 if (@report_option) {
2491 # this will result in the empty set for the dangling comma case as it should
2493 map{ "0 < ( SELECT count(*) FROM part_pkg_option
2494 WHERE part_pkg_option.pkgpart = part_pkg.pkgpart
2495 AND optionname = 'report_option_$_'
2496 AND optionvalue = '1' )"
2506 push @where, "part_pkg.custom = 'Y'" if $params->{custom};
2512 push @where, "part_pkg.fcc_ds0s > 0" if $params->{fcc_line};
2518 if ( exists($params->{'censustract'}) ) {
2519 $params->{'censustract'} =~ /^([.\d]*)$/;
2520 my $censustract = "cust_main.censustract = '$1'";
2521 $censustract .= ' OR cust_main.censustract is NULL' unless $1;
2522 push @where, "( $censustract )";
2529 if ( ref($params->{'pkgpart'}) ) {
2532 if ( ref($params->{'pkgpart'}) eq 'HASH' ) {
2533 @pkgpart = grep $params->{'pkgpart'}{$_}, keys %{ $params->{'pkgpart'} };
2534 } elsif ( ref($params->{'pkgpart'}) eq 'ARRAY' ) {
2535 @pkgpart = @{ $params->{'pkgpart'} };
2537 die 'unhandled pkgpart ref '. $params->{'pkgpart'};
2540 @pkgpart = grep /^(\d+)$/, @pkgpart;
2542 push @where, 'pkgpart IN ('. join(',', @pkgpart). ')' if scalar(@pkgpart);
2544 } elsif ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
2545 push @where, "pkgpart = $1";
2554 #false laziness w/report_cust_pkg.html
2557 'one-time charge' => { 'last_bill'=>1, 'bill'=>1, 'adjourn'=>1, 'susp'=>1, 'expire'=>1, 'cancel'=>1, },
2558 'active' => { 'susp'=>1, 'cancel'=>1 },
2559 'suspended' => { 'cancel' => 1 },
2564 foreach my $field (qw( setup last_bill bill adjourn susp expire cancel )) {
2566 next unless exists($params->{$field});
2568 my($beginning, $ending) = @{$params->{$field}};
2570 next if $beginning == 0 && $ending == 4294967295;
2573 "cust_pkg.$field IS NOT NULL",
2574 "cust_pkg.$field >= $beginning",
2575 "cust_pkg.$field <= $ending";
2577 $orderby ||= "ORDER BY cust_pkg.$field";
2581 $orderby ||= 'ORDER BY bill';
2584 # parse magic, legacy, etc.
2587 if ( $params->{'magic'} &&
2588 $params->{'magic'} =~ /^(active|inactive|suspended|cancell?ed)$/
2591 $orderby = 'ORDER BY pkgnum';
2593 if ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
2594 push @where, "pkgpart = $1";
2597 } elsif ( $params->{'query'} eq 'pkgnum' ) {
2599 $orderby = 'ORDER BY pkgnum';
2601 } elsif ( $params->{'query'} eq 'APKG_pkgnum' ) {
2603 $orderby = 'ORDER BY pkgnum';
2606 SELECT count(*) FROM pkg_svc
2607 WHERE pkg_svc.pkgpart = cust_pkg.pkgpart
2608 AND pkg_svc.quantity > ( SELECT count(*) FROM cust_svc
2609 WHERE cust_svc.pkgnum = cust_pkg.pkgnum
2610 AND cust_svc.svcpart = pkg_svc.svcpart
2617 # setup queries, links, subs, etc. for the search
2620 # here is the agent virtualization
2621 if ($params->{CurrentUser}) {
2623 qsearchs('access_user', { username => $params->{CurrentUser} });
2626 push @where, $access_user->agentnums_sql('table'=>'cust_main');
2631 push @where, $FS::CurrentUser::CurrentUser->agentnums_sql('table'=>'cust_main');
2634 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
2636 my $addl_from = 'LEFT JOIN part_pkg USING ( pkgpart ) '.
2637 'LEFT JOIN pkg_class USING ( classnum ) '.
2638 'LEFT JOIN cust_main USING ( custnum ) ';
2640 my $count_query = "SELECT COUNT(*) FROM cust_pkg $addl_from $extra_sql";
2643 'table' => 'cust_pkg',
2645 'select' => join(', ',
2647 ( map "part_pkg.$_", qw( pkg freq ) ),
2648 'pkg_class.classname',
2649 'cust_main.custnum as cust_main_custnum',
2650 FS::UI::Web::cust_sql_fields(
2651 $params->{'cust_fields'}
2654 'extra_sql' => "$extra_sql $orderby",
2655 'addl_from' => $addl_from,
2656 'count_query' => $count_query,
2663 Returns a list of two package counts. The first is a count of packages
2664 based on the supplied criteria and the second is the count of residential
2665 packages with those same criteria. Criteria are specified as in the search
2671 my ($class, $params) = @_;
2673 my $sql_query = $class->search( $params );
2675 my $count_sql = delete($sql_query->{'count_query'});
2676 $count_sql =~ s/ FROM/,count(CASE WHEN cust_main.company IS NULL OR cust_main.company = '' THEN 1 END) FROM/
2677 or die "couldn't parse count_sql";
2679 my $count_sth = dbh->prepare($count_sql)
2680 or die "Error preparing $count_sql: ". dbh->errstr;
2682 or die "Error executing $count_sql: ". $count_sth->errstr;
2683 my $count_arrayref = $count_sth->fetchrow_arrayref;
2685 return ( @$count_arrayref );
2692 Returns a list: the first item is an SQL fragment identifying matching
2693 packages/customers via location (taking into account shipping and package
2694 address taxation, if enabled), and subsequent items are the parameters to
2695 substitute for the placeholders in that fragment.
2700 my($class, %opt) = @_;
2701 my $ornull = $opt{'ornull'};
2703 my $conf = new FS::Conf;
2705 # '?' placeholders in _location_sql_where
2708 @bill_param = qw( county county state state state country );
2710 @bill_param = qw( county state state country );
2712 unshift @bill_param, 'county'; # unless $nec;
2716 if ( $conf->exists('tax-ship_address') ) {
2719 ( ( ship_last IS NULL OR ship_last = '' )
2720 AND ". _location_sql_where('cust_main', '', $ornull ). "
2722 OR ( ship_last IS NOT NULL AND ship_last != ''
2723 AND ". _location_sql_where('cust_main', 'ship_', $ornull ). "
2726 # AND payby != 'COMP'
2728 @main_param = ( @bill_param, @bill_param );
2732 $main_where = _location_sql_where('cust_main'); # AND payby != 'COMP'
2733 @main_param = @bill_param;
2739 if ( $conf->exists('tax-pkg_address') ) {
2741 my $loc_where = _location_sql_where( 'cust_location', '', $ornull );
2744 ( cust_pkg.locationnum IS NULL AND $main_where )
2745 OR ( cust_pkg.locationnum IS NOT NULL AND $loc_where )
2748 @param = ( @main_param, @bill_param );
2752 $where = $main_where;
2753 @param = @main_param;
2761 #subroutine, helper for location_sql
2762 sub _location_sql_where {
2764 my $prefix = @_ ? shift : '';
2765 my $ornull = @_ ? shift : '';
2767 # $ornull = $ornull ? " OR ( ? IS NULL AND $table.${prefix}county IS NULL ) " : '';
2769 $ornull = $ornull ? ' OR ? IS NULL ' : '';
2771 my $or_empty_county = " OR ( ? = '' AND $table.${prefix}county IS NULL ) ";
2772 my $or_empty_state = " OR ( ? = '' AND $table.${prefix}state IS NULL ) ";
2775 ( $table.${prefix}county = ? $or_empty_county $ornull )
2776 AND ( $table.${prefix}state = ? $or_empty_state $ornull )
2777 AND $table.${prefix}country = ?
2785 =item order CUSTNUM, PKGPARTS_ARYREF, [ REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF [ REFNUM ] ] ]
2787 CUSTNUM is a customer (see L<FS::cust_main>)
2789 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
2790 L<FS::part_pkg>) to order for this customer. Duplicates are of course
2793 REMOVE_PKGNUMS is an optional list of pkgnums specifying the billing items to
2794 remove for this customer. The services (see L<FS::cust_svc>) are moved to the
2795 new billing items. An error is returned if this is not possible (see
2796 L<FS::pkg_svc>). An empty arrayref is equivalent to not specifying this
2799 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
2800 newly-created cust_pkg objects.
2802 REFNUM, if specified, will specify the FS::pkg_referral record to be created
2803 and inserted. Multiple FS::pkg_referral records can be created by
2804 setting I<refnum> to an array reference of refnums or a hash reference with
2805 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
2806 record will be created corresponding to cust_main.refnum.
2811 my ($custnum, $pkgparts, $remove_pkgnum, $return_cust_pkg, $refnum) = @_;
2813 my $conf = new FS::Conf;
2815 # Transactionize this whole mess
2816 local $SIG{HUP} = 'IGNORE';
2817 local $SIG{INT} = 'IGNORE';
2818 local $SIG{QUIT} = 'IGNORE';
2819 local $SIG{TERM} = 'IGNORE';
2820 local $SIG{TSTP} = 'IGNORE';
2821 local $SIG{PIPE} = 'IGNORE';
2823 my $oldAutoCommit = $FS::UID::AutoCommit;
2824 local $FS::UID::AutoCommit = 0;
2828 # my $cust_main = qsearchs('cust_main', { custnum => $custnum });
2829 # return "Customer not found: $custnum" unless $cust_main;
2831 warn "$me order: pkgnums to remove: ". join(',', @$remove_pkgnum). "\n"
2834 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
2837 my $change = scalar(@old_cust_pkg) != 0;
2840 if ( scalar(@old_cust_pkg) == 1 && scalar(@$pkgparts) == 1 ) {
2842 warn "$me order: changing pkgnum ". $old_cust_pkg[0]->pkgnum.
2843 " to pkgpart ". $pkgparts->[0]. "\n"
2846 my $err_or_cust_pkg =
2847 $old_cust_pkg[0]->change( 'pkgpart' => $pkgparts->[0],
2848 'refnum' => $refnum,
2851 unless (ref($err_or_cust_pkg)) {
2852 $dbh->rollback if $oldAutoCommit;
2853 return $err_or_cust_pkg;
2856 push @$return_cust_pkg, $err_or_cust_pkg;
2857 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2862 # Create the new packages.
2863 foreach my $pkgpart (@$pkgparts) {
2865 warn "$me order: inserting pkgpart $pkgpart\n" if $DEBUG;
2867 my $cust_pkg = new FS::cust_pkg { custnum => $custnum,
2868 pkgpart => $pkgpart,
2872 $error = $cust_pkg->insert( 'change' => $change );
2874 $dbh->rollback if $oldAutoCommit;
2877 push @$return_cust_pkg, $cust_pkg;
2879 # $return_cust_pkg now contains refs to all of the newly
2882 # Transfer services and cancel old packages.
2883 foreach my $old_pkg (@old_cust_pkg) {
2885 warn "$me order: transferring services from pkgnum ". $old_pkg->pkgnum. "\n"
2888 foreach my $new_pkg (@$return_cust_pkg) {
2889 $error = $old_pkg->transfer($new_pkg);
2890 if ($error and $error == 0) {
2891 # $old_pkg->transfer failed.
2892 $dbh->rollback if $oldAutoCommit;
2897 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
2898 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
2899 foreach my $new_pkg (@$return_cust_pkg) {
2900 $error = $old_pkg->transfer($new_pkg, 'change_svcpart'=>1 );
2901 if ($error and $error == 0) {
2902 # $old_pkg->transfer failed.
2903 $dbh->rollback if $oldAutoCommit;
2910 # Transfers were successful, but we went through all of the
2911 # new packages and still had services left on the old package.
2912 # We can't cancel the package under the circumstances, so abort.
2913 $dbh->rollback if $oldAutoCommit;
2914 return "Unable to transfer all services from package ".$old_pkg->pkgnum;
2916 $error = $old_pkg->cancel( quiet=>1 );
2922 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2926 =item bulk_change PKGPARTS_ARYREF, REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF ]
2928 A bulk change method to change packages for multiple customers.
2930 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
2931 L<FS::part_pkg>) to order for each customer. Duplicates are of course
2934 REMOVE_PKGNUMS is an list of pkgnums specifying the billing items to
2935 replace. The services (see L<FS::cust_svc>) are moved to the
2936 new billing items. An error is returned if this is not possible (see
2939 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
2940 newly-created cust_pkg objects.
2945 my ($pkgparts, $remove_pkgnum, $return_cust_pkg) = @_;
2947 # Transactionize this whole mess
2948 local $SIG{HUP} = 'IGNORE';
2949 local $SIG{INT} = 'IGNORE';
2950 local $SIG{QUIT} = 'IGNORE';
2951 local $SIG{TERM} = 'IGNORE';
2952 local $SIG{TSTP} = 'IGNORE';
2953 local $SIG{PIPE} = 'IGNORE';
2955 my $oldAutoCommit = $FS::UID::AutoCommit;
2956 local $FS::UID::AutoCommit = 0;
2960 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
2963 while(scalar(@old_cust_pkg)) {
2965 my $custnum = $old_cust_pkg[0]->custnum;
2966 my (@remove) = map { $_->pkgnum }
2967 grep { $_->custnum == $custnum } @old_cust_pkg;
2968 @old_cust_pkg = grep { $_->custnum != $custnum } @old_cust_pkg;
2970 my $error = order $custnum, $pkgparts, \@remove, \@return;
2972 push @errors, $error
2974 push @$return_cust_pkg, @return;
2977 if (scalar(@errors)) {
2978 $dbh->rollback if $oldAutoCommit;
2979 return join(' / ', @errors);
2982 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2988 Associates this package with a (suspension or cancellation) reason (see
2989 L<FS::cust_pkg_reason>, possibly inserting a new reason on the fly (see
2992 Available options are:
2998 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.
3002 the access_user (see L<FS::access_user>) providing the reason
3010 the action (cancel, susp, adjourn, expire) associated with the reason
3014 If there is an error, returns the error, otherwise returns false.
3019 my ($self, %options) = @_;
3021 my $otaker = $options{reason_otaker} ||
3022 $FS::CurrentUser::CurrentUser->username;
3025 if ( $options{'reason'} =~ /^(\d+)$/ ) {
3029 } elsif ( ref($options{'reason'}) ) {
3031 return 'Enter a new reason (or select an existing one)'
3032 unless $options{'reason'}->{'reason'} !~ /^\s*$/;
3034 my $reason = new FS::reason({
3035 'reason_type' => $options{'reason'}->{'typenum'},
3036 'reason' => $options{'reason'}->{'reason'},
3038 my $error = $reason->insert;
3039 return $error if $error;
3041 $reasonnum = $reason->reasonnum;
3044 return "Unparsable reason: ". $options{'reason'};
3047 my $cust_pkg_reason =
3048 new FS::cust_pkg_reason({ 'pkgnum' => $self->pkgnum,
3049 'reasonnum' => $reasonnum,
3050 'otaker' => $otaker,
3051 'action' => substr(uc($options{'action'}),0,1),
3052 'date' => $options{'date'}
3057 $cust_pkg_reason->insert;
3060 =item set_usage USAGE_VALUE_HASHREF
3062 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
3063 to which they should be set (see L<FS::svc_acct>). Currently seconds,
3064 upbytes, downbytes, and totalbytes are appropriate keys.
3066 All svc_accts which are part of this package have their values reset.
3071 my ($self, $valueref, %opt) = @_;
3073 foreach my $cust_svc ($self->cust_svc){
3074 my $svc_x = $cust_svc->svc_x;
3075 $svc_x->set_usage($valueref, %opt)
3076 if $svc_x->can("set_usage");
3080 =item recharge USAGE_VALUE_HASHREF
3082 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
3083 to which they should be set (see L<FS::svc_acct>). Currently seconds,
3084 upbytes, downbytes, and totalbytes are appropriate keys.
3086 All svc_accts which are part of this package have their values incremented.
3091 my ($self, $valueref) = @_;
3093 foreach my $cust_svc ($self->cust_svc){
3094 my $svc_x = $cust_svc->svc_x;
3095 $svc_x->recharge($valueref)
3096 if $svc_x->can("recharge");
3104 sub order is not OO. Perhaps it should be moved to FS::cust_main and made so?
3106 In sub order, the @pkgparts array (passed by reference) is clobbered.
3108 Also in sub order, no money is adjusted. Once FS::part_pkg defines a standard
3109 method to pass dates to the recur_prog expression, it should do so.
3111 FS::svc_acct, FS::svc_domain, FS::svc_www, FS::svc_ip and FS::svc_forward are
3112 loaded via 'use' at compile time, rather than via 'require' in sub { setup,
3113 suspend, unsuspend, cancel } because they use %FS::UID::callback to load
3114 configuration values. Probably need a subroutine which decides what to do
3115 based on whether or not we've fetched the user yet, rather than a hash. See
3116 FS::UID and the TODO.
3118 Now that things are transactional should the check in the insert method be
3123 L<FS::Record>, L<FS::cust_main>, L<FS::part_pkg>, L<FS::cust_svc>,
3124 L<FS::pkg_svc>, schema.html from the base documentation