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
2389 my ($class, $params) = @_;
2396 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
2398 "cust_main.agentnum = $1";
2405 if ( $params->{'custnum'} =~ /^(\d+)$/ and $1 ) {
2407 "cust_pkg.custnum = $1";
2414 if ( $params->{'magic'} eq 'active'
2415 || $params->{'status'} eq 'active' ) {
2417 push @where, FS::cust_pkg->active_sql();
2419 } elsif ( $params->{'magic'} =~ /^not[ _]yet[ _]billed$/
2420 || $params->{'status'} =~ /^not[ _]yet[ _]billed$/ ) {
2422 push @where, FS::cust_pkg->not_yet_billed_sql();
2424 } elsif ( $params->{'magic'} =~ /^(one-time charge|inactive)/
2425 || $params->{'status'} =~ /^(one-time charge|inactive)/ ) {
2427 push @where, FS::cust_pkg->inactive_sql();
2429 } elsif ( $params->{'magic'} eq 'suspended'
2430 || $params->{'status'} eq 'suspended' ) {
2432 push @where, FS::cust_pkg->suspended_sql();
2434 } elsif ( $params->{'magic'} =~ /^cancell?ed$/
2435 || $params->{'status'} =~ /^cancell?ed$/ ) {
2437 push @where, FS::cust_pkg->cancelled_sql();
2442 # parse package class
2445 #false lazinessish w/graph/cust_bill_pkg.cgi
2448 if ( exists($params->{'classnum'})
2449 && $params->{'classnum'} =~ /^(\d*)$/
2453 if ( $classnum ) { #a specific class
2454 push @where, "part_pkg.classnum = $classnum";
2456 #@pkg_class = ( qsearchs('pkg_class', { 'classnum' => $classnum } ) );
2457 #die "classnum $classnum not found!" unless $pkg_class[0];
2458 #$title .= $pkg_class[0]->classname.' ';
2460 } elsif ( $classnum eq '' ) { #the empty class
2462 push @where, "part_pkg.classnum IS NULL";
2463 #$title .= 'Empty class ';
2464 #@pkg_class = ( '(empty class)' );
2465 } elsif ( $classnum eq '0' ) {
2466 #@pkg_class = qsearch('pkg_class', {} ); # { 'disabled' => '' } );
2467 #push @pkg_class, '(empty class)';
2469 die "illegal classnum";
2475 # parse package report options
2478 my @report_option = ();
2479 if ( exists($params->{'report_option'})
2480 && $params->{'report_option'} =~ /^([,\d]*)$/
2483 @report_option = split(',', $1);
2486 if (@report_option) {
2487 # this will result in the empty set for the dangling comma case as it should
2489 map{ "0 < ( SELECT count(*) FROM part_pkg_option
2490 WHERE part_pkg_option.pkgpart = part_pkg.pkgpart
2491 AND optionname = 'report_option_$_'
2492 AND optionvalue = '1' )"
2502 push @where, "part_pkg.custom = 'Y'" if $params->{custom};
2508 if ( exists($params->{'censustract'}) ) {
2509 $params->{'censustract'} =~ /^([.\d]*)$/;
2510 my $censustract = "cust_main.censustract = '$1'";
2511 $censustract .= ' OR cust_main.censustract is NULL' unless $1;
2512 push @where, "( $censustract )";
2519 if ( ref($params->{'pkgpart'}) ) {
2522 if ( ref($params->{'pkgpart'}) eq 'HASH' ) {
2523 @pkgpart = grep $params->{'pkgpart'}{$_}, keys %{ $params->{'pkgpart'} };
2524 } elsif ( ref($params->{'pkgpart'}) eq 'ARRAY' ) {
2525 @pkgpart = @{ $params->{'pkgpart'} };
2527 die 'unhandled pkgpart ref '. $params->{'pkgpart'};
2530 @pkgpart = grep /^(\d+)$/, @pkgpart;
2532 push @where, 'pkgpart IN ('. join(',', @pkgpart). ')' if scalar(@pkgpart);
2534 } elsif ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
2535 push @where, "pkgpart = $1";
2544 #false laziness w/report_cust_pkg.html
2547 'one-time charge' => { 'last_bill'=>1, 'bill'=>1, 'adjourn'=>1, 'susp'=>1, 'expire'=>1, 'cancel'=>1, },
2548 'active' => { 'susp'=>1, 'cancel'=>1 },
2549 'suspended' => { 'cancel' => 1 },
2554 foreach my $field (qw( setup last_bill bill adjourn susp expire cancel )) {
2556 next unless exists($params->{$field});
2558 my($beginning, $ending) = @{$params->{$field}};
2560 next if $beginning == 0 && $ending == 4294967295;
2563 "cust_pkg.$field IS NOT NULL",
2564 "cust_pkg.$field >= $beginning",
2565 "cust_pkg.$field <= $ending";
2567 $orderby ||= "ORDER BY cust_pkg.$field";
2571 $orderby ||= 'ORDER BY bill';
2574 # parse magic, legacy, etc.
2577 if ( $params->{'magic'} &&
2578 $params->{'magic'} =~ /^(active|inactive|suspended|cancell?ed)$/
2581 $orderby = 'ORDER BY pkgnum';
2583 if ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
2584 push @where, "pkgpart = $1";
2587 } elsif ( $params->{'query'} eq 'pkgnum' ) {
2589 $orderby = 'ORDER BY pkgnum';
2591 } elsif ( $params->{'query'} eq 'APKG_pkgnum' ) {
2593 $orderby = 'ORDER BY pkgnum';
2596 SELECT count(*) FROM pkg_svc
2597 WHERE pkg_svc.pkgpart = cust_pkg.pkgpart
2598 AND pkg_svc.quantity > ( SELECT count(*) FROM cust_svc
2599 WHERE cust_svc.pkgnum = cust_pkg.pkgnum
2600 AND cust_svc.svcpart = pkg_svc.svcpart
2607 # setup queries, links, subs, etc. for the search
2610 # here is the agent virtualization
2611 if ($params->{CurrentUser}) {
2613 qsearchs('access_user', { username => $params->{CurrentUser} });
2616 push @where, $access_user->agentnums_sql('table'=>'cust_main');
2621 push @where, $FS::CurrentUser::CurrentUser->agentnums_sql('table'=>'cust_main');
2624 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
2626 my $addl_from = 'LEFT JOIN part_pkg USING ( pkgpart ) '.
2627 'LEFT JOIN pkg_class USING ( classnum ) '.
2628 'LEFT JOIN cust_main USING ( custnum ) ';
2630 my $count_query = "SELECT COUNT(*) FROM cust_pkg $addl_from $extra_sql";
2633 'table' => 'cust_pkg',
2635 'select' => join(', ',
2637 ( map "part_pkg.$_", qw( pkg freq ) ),
2638 'pkg_class.classname',
2639 'cust_main.custnum as cust_main_custnum',
2640 FS::UI::Web::cust_sql_fields(
2641 $params->{'cust_fields'}
2644 'extra_sql' => "$extra_sql $orderby",
2645 'addl_from' => $addl_from,
2646 'count_query' => $count_query,
2653 Returns a list: the first item is an SQL fragment identifying matching
2654 packages/customers via location (taking into account shipping and package
2655 address taxation, if enabled), and subsequent items are the parameters to
2656 substitute for the placeholders in that fragment.
2661 my($class, %opt) = @_;
2662 my $ornull = $opt{'ornull'};
2664 my $conf = new FS::Conf;
2666 # '?' placeholders in _location_sql_where
2669 @bill_param = qw( county county state state state country );
2671 @bill_param = qw( county state state country );
2673 unshift @bill_param, 'county'; # unless $nec;
2677 if ( $conf->exists('tax-ship_address') ) {
2680 ( ( ship_last IS NULL OR ship_last = '' )
2681 AND ". _location_sql_where('cust_main', '', $ornull ). "
2683 OR ( ship_last IS NOT NULL AND ship_last != ''
2684 AND ". _location_sql_where('cust_main', 'ship_', $ornull ). "
2687 # AND payby != 'COMP'
2689 @main_param = ( @bill_param, @bill_param );
2693 $main_where = _location_sql_where('cust_main'); # AND payby != 'COMP'
2694 @main_param = @bill_param;
2700 if ( $conf->exists('tax-pkg_address') ) {
2702 my $loc_where = _location_sql_where( 'cust_location', '', $ornull );
2705 ( cust_pkg.locationnum IS NULL AND $main_where )
2706 OR ( cust_pkg.locationnum IS NOT NULL AND $loc_where )
2709 @param = ( @main_param, @bill_param );
2713 $where = $main_where;
2714 @param = @main_param;
2722 #subroutine, helper for location_sql
2723 sub _location_sql_where {
2725 my $prefix = @_ ? shift : '';
2726 my $ornull = @_ ? shift : '';
2728 # $ornull = $ornull ? " OR ( ? IS NULL AND $table.${prefix}county IS NULL ) " : '';
2730 $ornull = $ornull ? ' OR ? IS NULL ' : '';
2732 my $or_empty_county = " OR ( ? = '' AND $table.${prefix}county IS NULL ) ";
2733 my $or_empty_state = " OR ( ? = '' AND $table.${prefix}state IS NULL ) ";
2736 ( $table.${prefix}county = ? $or_empty_county $ornull )
2737 AND ( $table.${prefix}state = ? $or_empty_state $ornull )
2738 AND $table.${prefix}country = ?
2746 =item order CUSTNUM, PKGPARTS_ARYREF, [ REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF [ REFNUM ] ] ]
2748 CUSTNUM is a customer (see L<FS::cust_main>)
2750 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
2751 L<FS::part_pkg>) to order for this customer. Duplicates are of course
2754 REMOVE_PKGNUMS is an optional list of pkgnums specifying the billing items to
2755 remove for this customer. The services (see L<FS::cust_svc>) are moved to the
2756 new billing items. An error is returned if this is not possible (see
2757 L<FS::pkg_svc>). An empty arrayref is equivalent to not specifying this
2760 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
2761 newly-created cust_pkg objects.
2763 REFNUM, if specified, will specify the FS::pkg_referral record to be created
2764 and inserted. Multiple FS::pkg_referral records can be created by
2765 setting I<refnum> to an array reference of refnums or a hash reference with
2766 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
2767 record will be created corresponding to cust_main.refnum.
2772 my ($custnum, $pkgparts, $remove_pkgnum, $return_cust_pkg, $refnum) = @_;
2774 my $conf = new FS::Conf;
2776 # Transactionize this whole mess
2777 local $SIG{HUP} = 'IGNORE';
2778 local $SIG{INT} = 'IGNORE';
2779 local $SIG{QUIT} = 'IGNORE';
2780 local $SIG{TERM} = 'IGNORE';
2781 local $SIG{TSTP} = 'IGNORE';
2782 local $SIG{PIPE} = 'IGNORE';
2784 my $oldAutoCommit = $FS::UID::AutoCommit;
2785 local $FS::UID::AutoCommit = 0;
2789 # my $cust_main = qsearchs('cust_main', { custnum => $custnum });
2790 # return "Customer not found: $custnum" unless $cust_main;
2792 warn "$me order: pkgnums to remove: ". join(',', @$remove_pkgnum). "\n"
2795 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
2798 my $change = scalar(@old_cust_pkg) != 0;
2801 if ( scalar(@old_cust_pkg) == 1 && scalar(@$pkgparts) == 1 ) {
2803 warn "$me order: changing pkgnum ". $old_cust_pkg[0]->pkgnum.
2804 " to pkgpart ". $pkgparts->[0]. "\n"
2807 my $err_or_cust_pkg =
2808 $old_cust_pkg[0]->change( 'pkgpart' => $pkgparts->[0],
2809 'refnum' => $refnum,
2812 unless (ref($err_or_cust_pkg)) {
2813 $dbh->rollback if $oldAutoCommit;
2814 return $err_or_cust_pkg;
2817 push @$return_cust_pkg, $err_or_cust_pkg;
2818 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2823 # Create the new packages.
2824 foreach my $pkgpart (@$pkgparts) {
2826 warn "$me order: inserting pkgpart $pkgpart\n" if $DEBUG;
2828 my $cust_pkg = new FS::cust_pkg { custnum => $custnum,
2829 pkgpart => $pkgpart,
2833 $error = $cust_pkg->insert( 'change' => $change );
2835 $dbh->rollback if $oldAutoCommit;
2838 push @$return_cust_pkg, $cust_pkg;
2840 # $return_cust_pkg now contains refs to all of the newly
2843 # Transfer services and cancel old packages.
2844 foreach my $old_pkg (@old_cust_pkg) {
2846 warn "$me order: transferring services from pkgnum ". $old_pkg->pkgnum. "\n"
2849 foreach my $new_pkg (@$return_cust_pkg) {
2850 $error = $old_pkg->transfer($new_pkg);
2851 if ($error and $error == 0) {
2852 # $old_pkg->transfer failed.
2853 $dbh->rollback if $oldAutoCommit;
2858 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
2859 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
2860 foreach my $new_pkg (@$return_cust_pkg) {
2861 $error = $old_pkg->transfer($new_pkg, 'change_svcpart'=>1 );
2862 if ($error and $error == 0) {
2863 # $old_pkg->transfer failed.
2864 $dbh->rollback if $oldAutoCommit;
2871 # Transfers were successful, but we went through all of the
2872 # new packages and still had services left on the old package.
2873 # We can't cancel the package under the circumstances, so abort.
2874 $dbh->rollback if $oldAutoCommit;
2875 return "Unable to transfer all services from package ".$old_pkg->pkgnum;
2877 $error = $old_pkg->cancel( quiet=>1 );
2883 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2887 =item bulk_change PKGPARTS_ARYREF, REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF ]
2889 A bulk change method to change packages for multiple customers.
2891 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
2892 L<FS::part_pkg>) to order for each customer. Duplicates are of course
2895 REMOVE_PKGNUMS is an list of pkgnums specifying the billing items to
2896 replace. The services (see L<FS::cust_svc>) are moved to the
2897 new billing items. An error is returned if this is not possible (see
2900 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
2901 newly-created cust_pkg objects.
2906 my ($pkgparts, $remove_pkgnum, $return_cust_pkg) = @_;
2908 # Transactionize this whole mess
2909 local $SIG{HUP} = 'IGNORE';
2910 local $SIG{INT} = 'IGNORE';
2911 local $SIG{QUIT} = 'IGNORE';
2912 local $SIG{TERM} = 'IGNORE';
2913 local $SIG{TSTP} = 'IGNORE';
2914 local $SIG{PIPE} = 'IGNORE';
2916 my $oldAutoCommit = $FS::UID::AutoCommit;
2917 local $FS::UID::AutoCommit = 0;
2921 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
2924 while(scalar(@old_cust_pkg)) {
2926 my $custnum = $old_cust_pkg[0]->custnum;
2927 my (@remove) = map { $_->pkgnum }
2928 grep { $_->custnum == $custnum } @old_cust_pkg;
2929 @old_cust_pkg = grep { $_->custnum != $custnum } @old_cust_pkg;
2931 my $error = order $custnum, $pkgparts, \@remove, \@return;
2933 push @errors, $error
2935 push @$return_cust_pkg, @return;
2938 if (scalar(@errors)) {
2939 $dbh->rollback if $oldAutoCommit;
2940 return join(' / ', @errors);
2943 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2949 Associates this package with a (suspension or cancellation) reason (see
2950 L<FS::cust_pkg_reason>, possibly inserting a new reason on the fly (see
2953 Available options are:
2959 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.
2963 the access_user (see L<FS::access_user>) providing the reason
2971 the action (cancel, susp, adjourn, expire) associated with the reason
2975 If there is an error, returns the error, otherwise returns false.
2980 my ($self, %options) = @_;
2982 my $otaker = $options{reason_otaker} ||
2983 $FS::CurrentUser::CurrentUser->username;
2986 if ( $options{'reason'} =~ /^(\d+)$/ ) {
2990 } elsif ( ref($options{'reason'}) ) {
2992 return 'Enter a new reason (or select an existing one)'
2993 unless $options{'reason'}->{'reason'} !~ /^\s*$/;
2995 my $reason = new FS::reason({
2996 'reason_type' => $options{'reason'}->{'typenum'},
2997 'reason' => $options{'reason'}->{'reason'},
2999 my $error = $reason->insert;
3000 return $error if $error;
3002 $reasonnum = $reason->reasonnum;
3005 return "Unparsable reason: ". $options{'reason'};
3008 my $cust_pkg_reason =
3009 new FS::cust_pkg_reason({ 'pkgnum' => $self->pkgnum,
3010 'reasonnum' => $reasonnum,
3011 'otaker' => $otaker,
3012 'action' => substr(uc($options{'action'}),0,1),
3013 'date' => $options{'date'}
3018 $cust_pkg_reason->insert;
3021 =item set_usage USAGE_VALUE_HASHREF
3023 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
3024 to which they should be set (see L<FS::svc_acct>). Currently seconds,
3025 upbytes, downbytes, and totalbytes are appropriate keys.
3027 All svc_accts which are part of this package have their values reset.
3032 my ($self, $valueref, %opt) = @_;
3034 foreach my $cust_svc ($self->cust_svc){
3035 my $svc_x = $cust_svc->svc_x;
3036 $svc_x->set_usage($valueref, %opt)
3037 if $svc_x->can("set_usage");
3041 =item recharge USAGE_VALUE_HASHREF
3043 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
3044 to which they should be set (see L<FS::svc_acct>). Currently seconds,
3045 upbytes, downbytes, and totalbytes are appropriate keys.
3047 All svc_accts which are part of this package have their values incremented.
3052 my ($self, $valueref) = @_;
3054 foreach my $cust_svc ($self->cust_svc){
3055 my $svc_x = $cust_svc->svc_x;
3056 $svc_x->recharge($valueref)
3057 if $svc_x->can("recharge");
3065 sub order is not OO. Perhaps it should be moved to FS::cust_main and made so?
3067 In sub order, the @pkgparts array (passed by reference) is clobbered.
3069 Also in sub order, no money is adjusted. Once FS::part_pkg defines a standard
3070 method to pass dates to the recur_prog expression, it should do so.
3072 FS::svc_acct, FS::svc_domain, FS::svc_www, FS::svc_ip and FS::svc_forward are
3073 loaded via 'use' at compile time, rather than via 'require' in sub { setup,
3074 suspend, unsuspend, cancel } because they use %FS::UID::callback to load
3075 configuration values. Probably need a subroutine which decides what to do
3076 based on whether or not we've fetched the user yet, rather than a hash. See
3077 FS::UID and the TODO.
3079 Now that things are transactional should the check in the insert method be
3084 L<FS::Record>, L<FS::cust_main>, L<FS::part_pkg>, L<FS::cust_svc>,
3085 L<FS::pkg_svc>, schema.html from the base documentation