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 'table' => 'part_svc',
1709 'LEFT JOIN pkg_svc ON ( pkg_svc.svcpart = part_svc.svcpart
1710 AND pkg_svc.pkgpart = ?
1713 LEFT JOIN cust_svc ON ( cust_svc.svcpart = part_svc.svcpart )
1714 LEFT JOIN cust_pkg USING ( pkgnum )
1717 'extra_sql' => "WHERE pkgsvcnum IS NULL AND cust_pkg.pkgnum = ? ",
1718 'extra_param' => [ [$self->pkgpart=>'int'], [$self->pkgnum=>'int'] ],
1724 Returns a short status string for this package, currently:
1728 =item not yet billed
1730 =item one-time charge
1745 my $freq = length($self->freq) ? $self->freq : $self->part_pkg->freq;
1747 return 'cancelled' if $self->get('cancel');
1748 return 'suspended' if $self->susp;
1749 return 'not yet billed' unless $self->setup;
1750 return 'one-time charge' if $freq =~ /^(0|$)/;
1756 Class method that returns the list of possible status strings for packages
1757 (see L<the status method|/status>). For example:
1759 @statuses = FS::cust_pkg->statuses();
1763 tie my %statuscolor, 'Tie::IxHash',
1764 'not yet billed' => '000000',
1765 'one-time charge' => '000000',
1766 'active' => '00CC00',
1767 'suspended' => 'FF9900',
1768 'cancelled' => 'FF0000',
1772 my $self = shift; #could be class...
1773 #grep { $_ !~ /^(not yet billed)$/ } #this is a dumb status anyway
1774 # # mayble split btw one-time vs. recur
1780 Returns a hex triplet color string for this package's status.
1786 $statuscolor{$self->status};
1791 Returns a label for this package. (Currently "pkgnum: pkg - comment" or
1792 "pkg-comment" depending on user preference).
1798 my $label = $self->part_pkg->pkg_comment( 'nopkgpart' => 1 );
1799 $label = $self->pkgnum. ": $label"
1800 if $FS::CurrentUser::CurrentUser->option('show_pkgnum');
1804 =item pkg_label_long
1806 Returns a long label for this package, adding the primary service's label to
1811 sub pkg_label_long {
1813 my $label = $self->pkg_label;
1814 my $cust_svc = $self->primary_cust_svc;
1815 $label .= ' ('. ($cust_svc->label)[1]. ')' if $cust_svc;
1819 =item primary_cust_svc
1821 Returns a primary service (as FS::cust_svc object) if one can be identified.
1825 #for labeling purposes - might not 100% match up with part_pkg->svcpart's idea
1827 sub primary_cust_svc {
1830 my @cust_svc = $self->cust_svc;
1832 return '' unless @cust_svc; #no serivces - irrelevant then
1834 return $cust_svc[0] if scalar(@cust_svc) == 1; #always return a single service
1836 # primary service as specified in the package definition
1837 # or exactly one service definition with quantity one
1838 my $svcpart = $self->part_pkg->svcpart;
1839 @cust_svc = grep { $_->svcpart == $svcpart } @cust_svc;
1840 return $cust_svc[0] if scalar(@cust_svc) == 1;
1842 #couldn't identify one thing..
1848 Returns a list of lists, calling the label method for all services
1849 (see L<FS::cust_svc>) of this billing item.
1855 map { [ $_->label ] } $self->cust_svc;
1858 =item h_labels END_TIMESTAMP [ START_TIMESTAMP ]
1860 Like the labels method, but returns historical information on services that
1861 were active as of END_TIMESTAMP and (optionally) not cancelled before
1864 Returns a list of lists, calling the label method for all (historical) services
1865 (see L<FS::h_cust_svc>) of this billing item.
1871 map { [ $_->label(@_) ] } $self->h_cust_svc(@_);
1876 Like labels, except returns a simple flat list, and shortens long
1877 (currently >5 or the cust_bill-max_same_services configuration value) lists of
1878 identical services to one line that lists the service label and the number of
1879 individual services rather than individual items.
1884 shift->_labels_short( 'labels', @_ );
1887 =item h_labels_short END_TIMESTAMP [ START_TIMESTAMP ]
1889 Like h_labels, except returns a simple flat list, and shortens long
1890 (currently >5 or the cust_bill-max_same_services configuration value) lists of
1891 identical services to one line that lists the service label and the number of
1892 individual services rather than individual items.
1896 sub h_labels_short {
1897 shift->_labels_short( 'h_labels', @_ );
1901 my( $self, $method ) = ( shift, shift );
1903 my $conf = new FS::Conf;
1904 my $max_same_services = $conf->config('cust_bill-max_same_services') || 5;
1907 #tie %labels, 'Tie::IxHash';
1908 push @{ $labels{$_->[0]} }, $_->[1]
1909 foreach $self->h_labels(@_);
1911 foreach my $label ( keys %labels ) {
1913 my @values = grep { ! $seen{$_}++ } @{ $labels{$label} };
1914 my $num = scalar(@values);
1915 if ( $num > $max_same_services ) {
1916 push @labels, "$label ($num)";
1918 if ( $conf->exists('cust_bill-consolidate_services') ) {
1919 # push @labels, "$label: ". join(', ', @values);
1921 my $detail = "$label: ";
1922 $detail .= shift(@values). ', '
1923 while @values && length($detail.$values[0]) < 78;
1925 push @labels, $detail;
1928 push @labels, map { "$label: $_" } @values;
1939 Returns the parent customer object (see L<FS::cust_main>).
1945 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
1948 #these subs are in location_Mixin.pm now... unfortunately the POD doesn't mixin
1952 Returns the location object, if any (see L<FS::cust_location>).
1954 =item cust_location_or_main
1956 If this package is associated with a location, returns the locaiton (see
1957 L<FS::cust_location>), otherwise returns the customer (see L<FS::cust_main>).
1959 =item location_label [ OPTION => VALUE ... ]
1961 Returns the label of the location object (see L<FS::cust_location>).
1965 #end of subs in location_Mixin.pm now... unfortunately the POD doesn't mixin
1967 =item seconds_since TIMESTAMP
1969 Returns the number of seconds all accounts (see L<FS::svc_acct>) in this
1970 package have been online since TIMESTAMP, according to the session monitor.
1972 TIMESTAMP is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
1973 L<Time::Local> and L<Date::Parse> for conversion functions.
1978 my($self, $since) = @_;
1981 foreach my $cust_svc (
1982 grep { $_->part_svc->svcdb eq 'svc_acct' } $self->cust_svc
1984 $seconds += $cust_svc->seconds_since($since);
1991 =item seconds_since_sqlradacct TIMESTAMP_START TIMESTAMP_END
1993 Returns the numbers of seconds all accounts (see L<FS::svc_acct>) in this
1994 package have been online between TIMESTAMP_START (inclusive) and TIMESTAMP_END
1997 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
1998 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
2004 sub seconds_since_sqlradacct {
2005 my($self, $start, $end) = @_;
2009 foreach my $cust_svc (
2011 my $part_svc = $_->part_svc;
2012 $part_svc->svcdb eq 'svc_acct'
2013 && scalar($part_svc->part_export('sqlradius'));
2016 $seconds += $cust_svc->seconds_since_sqlradacct($start, $end);
2023 =item attribute_since_sqlradacct TIMESTAMP_START TIMESTAMP_END ATTRIBUTE
2025 Returns the sum of the given attribute for all accounts (see L<FS::svc_acct>)
2026 in this package for sessions ending between TIMESTAMP_START (inclusive) and
2030 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
2031 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
2036 sub attribute_since_sqlradacct {
2037 my($self, $start, $end, $attrib) = @_;
2041 foreach my $cust_svc (
2043 my $part_svc = $_->part_svc;
2044 $part_svc->svcdb eq 'svc_acct'
2045 && scalar($part_svc->part_export('sqlradius'));
2048 $sum += $cust_svc->attribute_since_sqlradacct($start, $end, $attrib);
2060 my( $self, $value ) = @_;
2061 if ( defined($value) ) {
2062 $self->setfield('quantity', $value);
2064 $self->getfield('quantity') || 1;
2067 =item transfer DEST_PKGNUM | DEST_CUST_PKG, [ OPTION => VALUE ... ]
2069 Transfers as many services as possible from this package to another package.
2071 The destination package can be specified by pkgnum by passing an FS::cust_pkg
2072 object. The destination package must already exist.
2074 Services are moved only if the destination allows services with the correct
2075 I<svcpart> (not svcdb), unless the B<change_svcpart> option is set true. Use
2076 this option with caution! No provision is made for export differences
2077 between the old and new service definitions. Probably only should be used
2078 when your exports for all service definitions of a given svcdb are identical.
2079 (attempt a transfer without it first, to move all possible svcpart-matching
2082 Any services that can't be moved remain in the original package.
2084 Returns an error, if there is one; otherwise, returns the number of services
2085 that couldn't be moved.
2090 my ($self, $dest_pkgnum, %opt) = @_;
2096 if (ref ($dest_pkgnum) eq 'FS::cust_pkg') {
2097 $dest = $dest_pkgnum;
2098 $dest_pkgnum = $dest->pkgnum;
2100 $dest = qsearchs('cust_pkg', { pkgnum => $dest_pkgnum });
2103 return ('Package does not exist: '.$dest_pkgnum) unless $dest;
2105 foreach my $pkg_svc ( $dest->part_pkg->pkg_svc ) {
2106 $target{$pkg_svc->svcpart} = $pkg_svc->quantity;
2109 foreach my $cust_svc ($dest->cust_svc) {
2110 $target{$cust_svc->svcpart}--;
2113 my %svcpart2svcparts = ();
2114 if ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
2115 warn "change_svcpart option received, creating alternates list\n" if $DEBUG;
2116 foreach my $svcpart ( map { $_->svcpart } $self->cust_svc ) {
2117 next if exists $svcpart2svcparts{$svcpart};
2118 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2119 $svcpart2svcparts{$svcpart} = [
2121 sort { $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] }
2123 my $pkg_svc = qsearchs( 'pkg_svc', { 'pkgpart' => $dest->pkgpart,
2124 'svcpart' => $_ } );
2126 $pkg_svc ? $pkg_svc->primary_svc : '',
2127 $pkg_svc ? $pkg_svc->quantity : 0,
2131 grep { $_ != $svcpart }
2133 qsearch('part_svc', { 'svcdb' => $part_svc->svcdb } )
2135 warn "alternates for svcpart $svcpart: ".
2136 join(', ', @{$svcpart2svcparts{$svcpart}}). "\n"
2141 foreach my $cust_svc ($self->cust_svc) {
2142 if($target{$cust_svc->svcpart} > 0) {
2143 $target{$cust_svc->svcpart}--;
2144 my $new = new FS::cust_svc { $cust_svc->hash };
2145 $new->pkgnum($dest_pkgnum);
2146 my $error = $new->replace($cust_svc);
2147 return $error if $error;
2148 } elsif ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
2150 warn "looking for alternates for svcpart ". $cust_svc->svcpart. "\n";
2151 warn "alternates to consider: ".
2152 join(', ', @{$svcpart2svcparts{$cust_svc->svcpart}}). "\n";
2154 my @alternate = grep {
2155 warn "considering alternate svcpart $_: ".
2156 "$target{$_} available in new package\n"
2159 } @{$svcpart2svcparts{$cust_svc->svcpart}};
2161 warn "alternate(s) found\n" if $DEBUG;
2162 my $change_svcpart = $alternate[0];
2163 $target{$change_svcpart}--;
2164 my $new = new FS::cust_svc { $cust_svc->hash };
2165 $new->svcpart($change_svcpart);
2166 $new->pkgnum($dest_pkgnum);
2167 my $error = $new->replace($cust_svc);
2168 return $error if $error;
2181 This method is deprecated. See the I<depend_jobnum> option to the insert and
2182 order_pkgs methods in FS::cust_main for a better way to defer provisioning.
2189 local $SIG{HUP} = 'IGNORE';
2190 local $SIG{INT} = 'IGNORE';
2191 local $SIG{QUIT} = 'IGNORE';
2192 local $SIG{TERM} = 'IGNORE';
2193 local $SIG{TSTP} = 'IGNORE';
2194 local $SIG{PIPE} = 'IGNORE';
2196 my $oldAutoCommit = $FS::UID::AutoCommit;
2197 local $FS::UID::AutoCommit = 0;
2200 foreach my $cust_svc ( $self->cust_svc ) {
2201 #false laziness w/svc_Common::insert
2202 my $svc_x = $cust_svc->svc_x;
2203 foreach my $part_export ( $cust_svc->part_svc->part_export ) {
2204 my $error = $part_export->export_insert($svc_x);
2206 $dbh->rollback if $oldAutoCommit;
2212 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2219 =head1 CLASS METHODS
2225 Returns an SQL expression identifying recurring packages.
2229 sub recurring_sql { "
2230 '0' != ( select freq from part_pkg
2231 where cust_pkg.pkgpart = part_pkg.pkgpart )
2236 Returns an SQL expression identifying one-time packages.
2241 '0' = ( select freq from part_pkg
2242 where cust_pkg.pkgpart = part_pkg.pkgpart )
2247 Returns an SQL expression identifying active packages.
2252 ". $_[0]->recurring_sql(). "
2253 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
2254 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
2255 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
2258 =item not_yet_billed_sql
2260 Returns an SQL expression identifying packages which have not yet been billed.
2264 sub not_yet_billed_sql { "
2265 ( cust_pkg.setup IS NULL OR cust_pkg.setup = 0 )
2266 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
2267 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
2272 Returns an SQL expression identifying inactive packages (one-time packages
2273 that are otherwise unsuspended/uncancelled).
2277 sub inactive_sql { "
2278 ". $_[0]->onetime_sql(). "
2279 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
2280 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
2281 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
2287 Returns an SQL expression identifying suspended packages.
2291 sub suspended_sql { susp_sql(@_); }
2293 #$_[0]->recurring_sql(). ' AND '.
2295 ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
2296 AND cust_pkg.susp IS NOT NULL AND cust_pkg.susp != 0
2303 Returns an SQL exprression identifying cancelled packages.
2307 sub cancelled_sql { cancel_sql(@_); }
2309 #$_[0]->recurring_sql(). ' AND '.
2310 "cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0";
2313 =item search HASHREF
2317 Returns a qsearch hash expression to search for parameters specified in HASHREF.
2318 Valid parameters are
2326 active, inactive, suspended, cancel (or cancelled)
2330 active, inactive, suspended, one-time charge, inactive, cancel (or cancelled)
2334 boolean selects custom packages
2340 pkgpart or arrayref or hashref of pkgparts
2344 arrayref of beginning and ending epoch date
2348 arrayref of beginning and ending epoch date
2352 arrayref of beginning and ending epoch date
2356 arrayref of beginning and ending epoch date
2360 arrayref of beginning and ending epoch date
2364 arrayref of beginning and ending epoch date
2368 arrayref of beginning and ending epoch date
2372 pkgnum or APKG_pkgnum
2376 a value suited to passing to FS::UI::Web::cust_header
2380 specifies the user for agent virtualization
2387 my ($class, $params) = @_;
2394 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
2396 "cust_main.agentnum = $1";
2403 if ( $params->{'custnum'} =~ /^(\d+)$/ and $1 ) {
2405 "cust_pkg.custnum = $1";
2412 if ( $params->{'magic'} eq 'active'
2413 || $params->{'status'} eq 'active' ) {
2415 push @where, FS::cust_pkg->active_sql();
2417 } elsif ( $params->{'magic'} =~ /^not[ _]yet[ _]billed$/
2418 || $params->{'status'} =~ /^not[ _]yet[ _]billed$/ ) {
2420 push @where, FS::cust_pkg->not_yet_billed_sql();
2422 } elsif ( $params->{'magic'} =~ /^(one-time charge|inactive)/
2423 || $params->{'status'} =~ /^(one-time charge|inactive)/ ) {
2425 push @where, FS::cust_pkg->inactive_sql();
2427 } elsif ( $params->{'magic'} eq 'suspended'
2428 || $params->{'status'} eq 'suspended' ) {
2430 push @where, FS::cust_pkg->suspended_sql();
2432 } elsif ( $params->{'magic'} =~ /^cancell?ed$/
2433 || $params->{'status'} =~ /^cancell?ed$/ ) {
2435 push @where, FS::cust_pkg->cancelled_sql();
2440 # parse package class
2443 #false lazinessish w/graph/cust_bill_pkg.cgi
2446 if ( exists($params->{'classnum'})
2447 && $params->{'classnum'} =~ /^(\d*)$/
2451 if ( $classnum ) { #a specific class
2452 push @where, "part_pkg.classnum = $classnum";
2454 #@pkg_class = ( qsearchs('pkg_class', { 'classnum' => $classnum } ) );
2455 #die "classnum $classnum not found!" unless $pkg_class[0];
2456 #$title .= $pkg_class[0]->classname.' ';
2458 } elsif ( $classnum eq '' ) { #the empty class
2460 push @where, "part_pkg.classnum IS NULL";
2461 #$title .= 'Empty class ';
2462 #@pkg_class = ( '(empty class)' );
2463 } elsif ( $classnum eq '0' ) {
2464 #@pkg_class = qsearch('pkg_class', {} ); # { 'disabled' => '' } );
2465 #push @pkg_class, '(empty class)';
2467 die "illegal classnum";
2473 # parse package report options
2476 my @report_option = ();
2477 if ( exists($params->{'report_option'})
2478 && $params->{'report_option'} =~ /^([,\d]*)$/
2481 @report_option = split(',', $1);
2484 if (@report_option) {
2485 # this will result in the empty set for the dangling comma case as it should
2487 map{ "0 < ( SELECT count(*) FROM part_pkg_option
2488 WHERE part_pkg_option.pkgpart = part_pkg.pkgpart
2489 AND optionname = 'report_option_$_'
2490 AND optionvalue = '1' )"
2500 push @where, "part_pkg.custom = 'Y'" if $params->{custom};
2506 if ( exists($params->{'censustract'}) ) {
2507 $params->{'censustract'} =~ /^([.\d]*)$/;
2508 my $censustract = "cust_main.censustract = '$1'";
2509 $censustract .= ' OR cust_main.censustract is NULL' unless $1;
2510 push @where, "( $censustract )";
2517 if ( ref($params->{'pkgpart'}) ) {
2520 if ( ref($params->{'pkgpart'}) eq 'HASH' ) {
2521 @pkgpart = grep $params->{'pkgpart'}{$_}, keys %{ $params->{'pkgpart'} };
2522 } elsif ( ref($params->{'pkgpart'}) eq 'ARRAY' ) {
2523 @pkgpart = @{ $params->{'pkgpart'} };
2525 die 'unhandled pkgpart ref '. $params->{'pkgpart'};
2528 @pkgpart = grep /^(\d+)$/, @pkgpart;
2530 push @where, 'pkgpart IN ('. join(',', @pkgpart). ')' if scalar(@pkgpart);
2532 } elsif ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
2533 push @where, "pkgpart = $1";
2542 #false laziness w/report_cust_pkg.html
2545 'one-time charge' => { 'last_bill'=>1, 'bill'=>1, 'adjourn'=>1, 'susp'=>1, 'expire'=>1, 'cancel'=>1, },
2546 'active' => { 'susp'=>1, 'cancel'=>1 },
2547 'suspended' => { 'cancel' => 1 },
2552 foreach my $field (qw( setup last_bill bill adjourn susp expire cancel )) {
2554 next unless exists($params->{$field});
2556 my($beginning, $ending) = @{$params->{$field}};
2558 next if $beginning == 0 && $ending == 4294967295;
2561 "cust_pkg.$field IS NOT NULL",
2562 "cust_pkg.$field >= $beginning",
2563 "cust_pkg.$field <= $ending";
2565 $orderby ||= "ORDER BY cust_pkg.$field";
2569 $orderby ||= 'ORDER BY bill';
2572 # parse magic, legacy, etc.
2575 if ( $params->{'magic'} &&
2576 $params->{'magic'} =~ /^(active|inactive|suspended|cancell?ed)$/
2579 $orderby = 'ORDER BY pkgnum';
2581 if ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
2582 push @where, "pkgpart = $1";
2585 } elsif ( $params->{'query'} eq 'pkgnum' ) {
2587 $orderby = 'ORDER BY pkgnum';
2589 } elsif ( $params->{'query'} eq 'APKG_pkgnum' ) {
2591 $orderby = 'ORDER BY pkgnum';
2594 SELECT count(*) FROM pkg_svc
2595 WHERE pkg_svc.pkgpart = cust_pkg.pkgpart
2596 AND pkg_svc.quantity > ( SELECT count(*) FROM cust_svc
2597 WHERE cust_svc.pkgnum = cust_pkg.pkgnum
2598 AND cust_svc.svcpart = pkg_svc.svcpart
2605 # setup queries, links, subs, etc. for the search
2608 # here is the agent virtualization
2609 if ($params->{CurrentUser}) {
2611 qsearchs('access_user', { username => $params->{CurrentUser} });
2614 push @where, $access_user->agentnums_sql('table'=>'cust_main');
2619 push @where, $FS::CurrentUser::CurrentUser->agentnums_sql('table'=>'cust_main');
2622 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
2624 my $addl_from = 'LEFT JOIN part_pkg USING ( pkgpart ) '.
2625 'LEFT JOIN pkg_class USING ( classnum ) '.
2626 'LEFT JOIN cust_main USING ( custnum ) ';
2628 my $count_query = "SELECT COUNT(*) FROM cust_pkg $addl_from $extra_sql";
2631 'table' => 'cust_pkg',
2633 'select' => join(', ',
2635 ( map "part_pkg.$_", qw( pkg freq ) ),
2636 'pkg_class.classname',
2637 'cust_main.custnum as cust_main_custnum',
2638 FS::UI::Web::cust_sql_fields(
2639 $params->{'cust_fields'}
2642 'extra_sql' => "$extra_sql $orderby",
2643 'addl_from' => $addl_from,
2644 'count_query' => $count_query,
2651 Returns a list: the first item is an SQL fragment identifying matching
2652 packages/customers via location (taking into account shipping and package
2653 address taxation, if enabled), and subsequent items are the parameters to
2654 substitute for the placeholders in that fragment.
2659 my($class, %opt) = @_;
2660 my $ornull = $opt{'ornull'};
2662 my $conf = new FS::Conf;
2664 # '?' placeholders in _location_sql_where
2667 @bill_param = qw( county county state state state country );
2669 @bill_param = qw( county state state country );
2671 unshift @bill_param, 'county'; # unless $nec;
2675 if ( $conf->exists('tax-ship_address') ) {
2678 ( ( ship_last IS NULL OR ship_last = '' )
2679 AND ". _location_sql_where('cust_main', '', $ornull ). "
2681 OR ( ship_last IS NOT NULL AND ship_last != ''
2682 AND ". _location_sql_where('cust_main', 'ship_', $ornull ). "
2685 # AND payby != 'COMP'
2687 @main_param = ( @bill_param, @bill_param );
2691 $main_where = _location_sql_where('cust_main'); # AND payby != 'COMP'
2692 @main_param = @bill_param;
2698 if ( $conf->exists('tax-pkg_address') ) {
2700 my $loc_where = _location_sql_where( 'cust_location', '', $ornull );
2703 ( cust_pkg.locationnum IS NULL AND $main_where )
2704 OR ( cust_pkg.locationnum IS NOT NULL AND $loc_where )
2707 @param = ( @main_param, @bill_param );
2711 $where = $main_where;
2712 @param = @main_param;
2720 #subroutine, helper for location_sql
2721 sub _location_sql_where {
2723 my $prefix = @_ ? shift : '';
2724 my $ornull = @_ ? shift : '';
2726 # $ornull = $ornull ? " OR ( ? IS NULL AND $table.${prefix}county IS NULL ) " : '';
2728 $ornull = $ornull ? ' OR ? IS NULL ' : '';
2730 my $or_empty_county = " OR ( ? = '' AND $table.${prefix}county IS NULL ) ";
2731 my $or_empty_state = " OR ( ? = '' AND $table.${prefix}state IS NULL ) ";
2734 ( $table.${prefix}county = ? $or_empty_county $ornull )
2735 AND ( $table.${prefix}state = ? $or_empty_state $ornull )
2736 AND $table.${prefix}country = ?
2744 =item order CUSTNUM, PKGPARTS_ARYREF, [ REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF [ REFNUM ] ] ]
2746 CUSTNUM is a customer (see L<FS::cust_main>)
2748 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
2749 L<FS::part_pkg>) to order for this customer. Duplicates are of course
2752 REMOVE_PKGNUMS is an optional list of pkgnums specifying the billing items to
2753 remove for this customer. The services (see L<FS::cust_svc>) are moved to the
2754 new billing items. An error is returned if this is not possible (see
2755 L<FS::pkg_svc>). An empty arrayref is equivalent to not specifying this
2758 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
2759 newly-created cust_pkg objects.
2761 REFNUM, if specified, will specify the FS::pkg_referral record to be created
2762 and inserted. Multiple FS::pkg_referral records can be created by
2763 setting I<refnum> to an array reference of refnums or a hash reference with
2764 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
2765 record will be created corresponding to cust_main.refnum.
2770 my ($custnum, $pkgparts, $remove_pkgnum, $return_cust_pkg, $refnum) = @_;
2772 my $conf = new FS::Conf;
2774 # Transactionize this whole mess
2775 local $SIG{HUP} = 'IGNORE';
2776 local $SIG{INT} = 'IGNORE';
2777 local $SIG{QUIT} = 'IGNORE';
2778 local $SIG{TERM} = 'IGNORE';
2779 local $SIG{TSTP} = 'IGNORE';
2780 local $SIG{PIPE} = 'IGNORE';
2782 my $oldAutoCommit = $FS::UID::AutoCommit;
2783 local $FS::UID::AutoCommit = 0;
2787 # my $cust_main = qsearchs('cust_main', { custnum => $custnum });
2788 # return "Customer not found: $custnum" unless $cust_main;
2790 warn "$me order: pkgnums to remove: ". join(',', @$remove_pkgnum). "\n"
2793 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
2796 my $change = scalar(@old_cust_pkg) != 0;
2799 if ( scalar(@old_cust_pkg) == 1 && scalar(@$pkgparts) == 1 ) {
2801 warn "$me order: changing pkgnum ". $old_cust_pkg[0]->pkgnum.
2802 " to pkgpart ". $pkgparts->[0]. "\n"
2805 my $err_or_cust_pkg =
2806 $old_cust_pkg[0]->change( 'pkgpart' => $pkgparts->[0],
2807 'refnum' => $refnum,
2810 unless (ref($err_or_cust_pkg)) {
2811 $dbh->rollback if $oldAutoCommit;
2812 return $err_or_cust_pkg;
2815 push @$return_cust_pkg, $err_or_cust_pkg;
2816 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2821 # Create the new packages.
2822 foreach my $pkgpart (@$pkgparts) {
2824 warn "$me order: inserting pkgpart $pkgpart\n" if $DEBUG;
2826 my $cust_pkg = new FS::cust_pkg { custnum => $custnum,
2827 pkgpart => $pkgpart,
2831 $error = $cust_pkg->insert( 'change' => $change );
2833 $dbh->rollback if $oldAutoCommit;
2836 push @$return_cust_pkg, $cust_pkg;
2838 # $return_cust_pkg now contains refs to all of the newly
2841 # Transfer services and cancel old packages.
2842 foreach my $old_pkg (@old_cust_pkg) {
2844 warn "$me order: transferring services from pkgnum ". $old_pkg->pkgnum. "\n"
2847 foreach my $new_pkg (@$return_cust_pkg) {
2848 $error = $old_pkg->transfer($new_pkg);
2849 if ($error and $error == 0) {
2850 # $old_pkg->transfer failed.
2851 $dbh->rollback if $oldAutoCommit;
2856 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
2857 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
2858 foreach my $new_pkg (@$return_cust_pkg) {
2859 $error = $old_pkg->transfer($new_pkg, 'change_svcpart'=>1 );
2860 if ($error and $error == 0) {
2861 # $old_pkg->transfer failed.
2862 $dbh->rollback if $oldAutoCommit;
2869 # Transfers were successful, but we went through all of the
2870 # new packages and still had services left on the old package.
2871 # We can't cancel the package under the circumstances, so abort.
2872 $dbh->rollback if $oldAutoCommit;
2873 return "Unable to transfer all services from package ".$old_pkg->pkgnum;
2875 $error = $old_pkg->cancel( quiet=>1 );
2881 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2885 =item bulk_change PKGPARTS_ARYREF, REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF ]
2887 A bulk change method to change packages for multiple customers.
2889 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
2890 L<FS::part_pkg>) to order for each customer. Duplicates are of course
2893 REMOVE_PKGNUMS is an list of pkgnums specifying the billing items to
2894 replace. The services (see L<FS::cust_svc>) are moved to the
2895 new billing items. An error is returned if this is not possible (see
2898 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
2899 newly-created cust_pkg objects.
2904 my ($pkgparts, $remove_pkgnum, $return_cust_pkg) = @_;
2906 # Transactionize this whole mess
2907 local $SIG{HUP} = 'IGNORE';
2908 local $SIG{INT} = 'IGNORE';
2909 local $SIG{QUIT} = 'IGNORE';
2910 local $SIG{TERM} = 'IGNORE';
2911 local $SIG{TSTP} = 'IGNORE';
2912 local $SIG{PIPE} = 'IGNORE';
2914 my $oldAutoCommit = $FS::UID::AutoCommit;
2915 local $FS::UID::AutoCommit = 0;
2919 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
2922 while(scalar(@old_cust_pkg)) {
2924 my $custnum = $old_cust_pkg[0]->custnum;
2925 my (@remove) = map { $_->pkgnum }
2926 grep { $_->custnum == $custnum } @old_cust_pkg;
2927 @old_cust_pkg = grep { $_->custnum != $custnum } @old_cust_pkg;
2929 my $error = order $custnum, $pkgparts, \@remove, \@return;
2931 push @errors, $error
2933 push @$return_cust_pkg, @return;
2936 if (scalar(@errors)) {
2937 $dbh->rollback if $oldAutoCommit;
2938 return join(' / ', @errors);
2941 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2947 Associates this package with a (suspension or cancellation) reason (see
2948 L<FS::cust_pkg_reason>, possibly inserting a new reason on the fly (see
2951 Available options are:
2957 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.
2961 the access_user (see L<FS::access_user>) providing the reason
2969 the action (cancel, susp, adjourn, expire) associated with the reason
2973 If there is an error, returns the error, otherwise returns false.
2978 my ($self, %options) = @_;
2980 my $otaker = $options{reason_otaker} ||
2981 $FS::CurrentUser::CurrentUser->username;
2984 if ( $options{'reason'} =~ /^(\d+)$/ ) {
2988 } elsif ( ref($options{'reason'}) ) {
2990 return 'Enter a new reason (or select an existing one)'
2991 unless $options{'reason'}->{'reason'} !~ /^\s*$/;
2993 my $reason = new FS::reason({
2994 'reason_type' => $options{'reason'}->{'typenum'},
2995 'reason' => $options{'reason'}->{'reason'},
2997 my $error = $reason->insert;
2998 return $error if $error;
3000 $reasonnum = $reason->reasonnum;
3003 return "Unparsable reason: ". $options{'reason'};
3006 my $cust_pkg_reason =
3007 new FS::cust_pkg_reason({ 'pkgnum' => $self->pkgnum,
3008 'reasonnum' => $reasonnum,
3009 'otaker' => $otaker,
3010 'action' => substr(uc($options{'action'}),0,1),
3011 'date' => $options{'date'}
3016 $cust_pkg_reason->insert;
3019 =item set_usage USAGE_VALUE_HASHREF
3021 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
3022 to which they should be set (see L<FS::svc_acct>). Currently seconds,
3023 upbytes, downbytes, and totalbytes are appropriate keys.
3025 All svc_accts which are part of this package have their values reset.
3030 my ($self, $valueref, %opt) = @_;
3032 foreach my $cust_svc ($self->cust_svc){
3033 my $svc_x = $cust_svc->svc_x;
3034 $svc_x->set_usage($valueref, %opt)
3035 if $svc_x->can("set_usage");
3039 =item recharge USAGE_VALUE_HASHREF
3041 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
3042 to which they should be set (see L<FS::svc_acct>). Currently seconds,
3043 upbytes, downbytes, and totalbytes are appropriate keys.
3045 All svc_accts which are part of this package have their values incremented.
3050 my ($self, $valueref) = @_;
3052 foreach my $cust_svc ($self->cust_svc){
3053 my $svc_x = $cust_svc->svc_x;
3054 $svc_x->recharge($valueref)
3055 if $svc_x->can("recharge");
3063 sub order is not OO. Perhaps it should be moved to FS::cust_main and made so?
3065 In sub order, the @pkgparts array (passed by reference) is clobbered.
3067 Also in sub order, no money is adjusted. Once FS::part_pkg defines a standard
3068 method to pass dates to the recur_prog expression, it should do so.
3070 FS::svc_acct, FS::svc_domain, FS::svc_www, FS::svc_ip and FS::svc_forward are
3071 loaded via 'use' at compile time, rather than via 'require' in sub { setup,
3072 suspend, unsuspend, cancel } because they use %FS::UID::callback to load
3073 configuration values. Probably need a subroutine which decides what to do
3074 based on whether or not we've fetched the user yet, rather than a hash. See
3075 FS::UID and the TODO.
3077 Now that things are transactional should the check in the insert method be
3082 L<FS::Record>, L<FS::cust_main>, L<FS::part_pkg>, L<FS::cust_svc>,
3083 L<FS::pkg_svc>, schema.html from the base documentation