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;
30 use FS::cust_pkg_discount;
34 # need to 'use' these instead of 'require' in sub { cancel, suspend, unsuspend,
36 # because they load configuration by setting FS::UID::callback (see TODO)
42 # for sending cancel emails in sub cancel
46 $me = '[FS::cust_pkg]';
48 $disable_agentcheck = 0;
52 my ( $hashref, $cache ) = @_;
53 #if ( $hashref->{'pkgpart'} ) {
54 if ( $hashref->{'pkg'} ) {
55 # #@{ $self->{'_pkgnum'} } = ();
56 # my $subcache = $cache->subcache('pkgpart', 'part_pkg');
57 # $self->{'_pkgpart'} = $subcache;
58 # #push @{ $self->{'_pkgnum'} },
59 # FS::part_pkg->new_or_cached($hashref, $subcache);
60 $self->{'_pkgpart'} = FS::part_pkg->new($hashref);
62 if ( exists $hashref->{'svcnum'} ) {
63 #@{ $self->{'_pkgnum'} } = ();
64 my $subcache = $cache->subcache('svcnum', 'cust_svc', $hashref->{pkgnum});
65 $self->{'_svcnum'} = $subcache;
66 #push @{ $self->{'_pkgnum'} },
67 FS::cust_svc->new_or_cached($hashref, $subcache) if $hashref->{svcnum};
73 FS::cust_pkg - Object methods for cust_pkg objects
79 $record = new FS::cust_pkg \%hash;
80 $record = new FS::cust_pkg { 'column' => 'value' };
82 $error = $record->insert;
84 $error = $new_record->replace($old_record);
86 $error = $record->delete;
88 $error = $record->check;
90 $error = $record->cancel;
92 $error = $record->suspend;
94 $error = $record->unsuspend;
96 $part_pkg = $record->part_pkg;
98 @labels = $record->labels;
100 $seconds = $record->seconds_since($timestamp);
102 $error = FS::cust_pkg::order( $custnum, \@pkgparts );
103 $error = FS::cust_pkg::order( $custnum, \@pkgparts, \@remove_pkgnums ] );
107 An FS::cust_pkg object represents a customer billing item. FS::cust_pkg
108 inherits from FS::Record. The following fields are currently supported:
114 Primary key (assigned automatically for new billing items)
118 Customer (see L<FS::cust_main>)
122 Billing item definition (see L<FS::part_pkg>)
126 Optional link to package location (see L<FS::location>)
138 date (next bill date)
162 order taker (assigned automatically if null, see L<FS::UID>)
166 If this field is set to 1, disables the automatic
167 unsuspension of this package when using the B<unsuspendauto> config option.
171 If not set, defaults to 1
175 Date of change from previous package
185 =item change_locationnum
191 Note: setup, last_bill, bill, adjourn, susp, expire, cancel and change_date
192 are specified as UNIX timestamps; see L<perlfunc/"time">. Also see
193 L<Time::Local> and L<Date::Parse> for conversion functions.
201 Create a new billing item. To add the item to the database, see L<"insert">.
205 sub table { 'cust_pkg'; }
206 sub cust_linked { $_[0]->cust_main_custnum; }
207 sub cust_unlinked_msg {
209 "WARNING: can't find cust_main.custnum ". $self->custnum.
210 ' (cust_pkg.pkgnum '. $self->pkgnum. ')';
213 =item insert [ OPTION => VALUE ... ]
215 Adds this billing item to the database ("Orders" the item). If there is an
216 error, returns the error, otherwise returns false.
218 If the additional field I<promo_code> is defined instead of I<pkgpart>, it
219 will be used to look up the package definition and agent restrictions will be
222 If the additional field I<refnum> is defined, an FS::pkg_referral record will
223 be created and inserted. Multiple FS::pkg_referral records can be created by
224 setting I<refnum> to an array reference of refnums or a hash reference with
225 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
226 record will be created corresponding to cust_main.refnum.
228 The following options are available:
234 If set true, supresses any referral credit to a referring customer.
238 cust_pkg_option records will be created
242 a ticket will be added to this customer with this subject
246 an optional queue name for ticket additions
253 my( $self, %options ) = @_;
255 if ( $self->part_pkg->option('start_1st', 1) && !$self->start_date ) {
256 my ($sec,$min,$hour,$mday,$mon,$year) = (localtime(time) )[0,1,2,3,4,5];
257 $mon += 1 unless $mday == 1;
258 until ( $mon < 12 ) { $mon -= 12; $year++; }
259 $self->start_date( timelocal_nocheck(0,0,0,1,$mon,$year) );
262 my $expire_months = $self->part_pkg->option('expire_months', 1);
263 if ( $expire_months && !$self->expire ) {
264 my $start = $self->start_date || $self->setup || time;
266 #false laziness w/part_pkg::add_freq
267 my ($sec,$min,$hour,$mday,$mon,$year) = (localtime($start) )[0,1,2,3,4,5];
268 $mon += $expire_months;
269 until ( $mon < 12 ) { $mon -= 12; $year++; }
271 #$self->expire( timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year) );
272 $self->expire( timelocal_nocheck(0,0,0,$mday,$mon,$year) );
275 local $SIG{HUP} = 'IGNORE';
276 local $SIG{INT} = 'IGNORE';
277 local $SIG{QUIT} = 'IGNORE';
278 local $SIG{TERM} = 'IGNORE';
279 local $SIG{TSTP} = 'IGNORE';
280 local $SIG{PIPE} = 'IGNORE';
282 my $oldAutoCommit = $FS::UID::AutoCommit;
283 local $FS::UID::AutoCommit = 0;
286 my $error = $self->SUPER::insert($options{options} ? %{$options{options}} : ());
288 $dbh->rollback if $oldAutoCommit;
292 $self->refnum($self->cust_main->refnum) unless $self->refnum;
293 $self->refnum( [ $self->refnum ] ) unless ref($self->refnum);
294 $self->process_m2m( 'link_table' => 'pkg_referral',
295 'target_table' => 'part_referral',
296 'params' => $self->refnum,
299 if ( $self->discountnum ) {
300 my $error = $self->insert_discount();
302 $dbh->rollback if $oldAutoCommit;
307 #if ( $self->reg_code ) {
308 # my $reg_code = qsearchs('reg_code', { 'code' => $self->reg_code } );
309 # $error = $reg_code->delete;
311 # $dbh->rollback if $oldAutoCommit;
316 my $conf = new FS::Conf;
318 if ( $conf->config('ticket_system') && $options{ticket_subject} ) {
321 # use lib ( "/opt/rt3/local/lib", "/opt/rt3/lib" );
328 use FS::TicketSystem;
329 FS::TicketSystem->init();
331 my $q = new RT::Queue($RT::SystemUser);
332 $q->Load($options{ticket_queue}) if $options{ticket_queue};
333 my $t = new RT::Ticket($RT::SystemUser);
334 my $mime = new MIME::Entity;
335 $mime->build( Type => 'text/plain', Data => $options{ticket_subject} );
336 $t->Create( $options{ticket_queue} ? (Queue => $q) : (),
337 Subject => $options{ticket_subject},
340 $t->AddLink( Type => 'MemberOf',
341 Target => 'freeside://freeside/cust_main/'. $self->custnum,
345 if ($conf->config('welcome_letter') && $self->cust_main->num_pkgs == 1) {
346 my $queue = new FS::queue {
347 'job' => 'FS::cust_main::queueable_print',
349 $error = $queue->insert(
350 'custnum' => $self->custnum,
351 'template' => 'welcome_letter',
355 warn "can't send welcome letter: $error";
360 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
367 This method now works but you probably shouldn't use it.
369 You don't want to delete billing items, because there would then be no record
370 the customer ever purchased the item. Instead, see the cancel method.
375 # return "Can't delete cust_pkg records!";
378 =item replace [ OLD_RECORD ] [ HASHREF | OPTION => VALUE ... ]
380 Replaces the OLD_RECORD with this one in the database. If there is an error,
381 returns the error, otherwise returns false.
383 Currently, custnum, setup, bill, adjourn, susp, expire, and cancel may be changed.
385 Changing pkgpart may have disasterous effects. See the order subroutine.
387 setup and bill are normally updated by calling the bill method of a customer
388 object (see L<FS::cust_main>).
390 suspend is normally updated by the suspend and unsuspend methods.
392 cancel is normally updated by the cancel method (and also the order subroutine
395 Available options are:
401 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.
405 the access_user (see L<FS::access_user>) providing the reason
409 hashref of keys and values - cust_pkg_option records will be created, updated or removed as appopriate
418 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
423 ( ref($_[0]) eq 'HASH' )
427 #return "Can't (yet?) change pkgpart!" if $old->pkgpart != $new->pkgpart;
428 return "Can't change otaker!" if $old->otaker ne $new->otaker;
431 #return "Can't change setup once it exists!"
432 # if $old->getfield('setup') &&
433 # $old->getfield('setup') != $new->getfield('setup');
435 #some logic for bill, susp, cancel?
437 local($disable_agentcheck) = 1 if $old->pkgpart == $new->pkgpart;
439 local $SIG{HUP} = 'IGNORE';
440 local $SIG{INT} = 'IGNORE';
441 local $SIG{QUIT} = 'IGNORE';
442 local $SIG{TERM} = 'IGNORE';
443 local $SIG{TSTP} = 'IGNORE';
444 local $SIG{PIPE} = 'IGNORE';
446 my $oldAutoCommit = $FS::UID::AutoCommit;
447 local $FS::UID::AutoCommit = 0;
450 foreach my $method ( qw(adjourn expire) ) { # How many reasons?
451 if ($options->{'reason'} && $new->$method && $old->$method ne $new->$method) {
452 my $error = $new->insert_reason(
453 'reason' => $options->{'reason'},
454 'date' => $new->$method,
456 'reason_otaker' => $options->{'reason_otaker'},
459 dbh->rollback if $oldAutoCommit;
460 return "Error inserting cust_pkg_reason: $error";
465 #save off and freeze RADIUS attributes for any associated svc_acct records
467 if ( $old->part_pkg->is_prepaid || $new->part_pkg->is_prepaid ) {
469 #also check for specific exports?
470 # to avoid spurious modify export events
471 @svc_acct = map { $_->svc_x }
472 grep { $_->part_svc->svcdb eq 'svc_acct' }
475 $_->snapshot foreach @svc_acct;
479 my $error = $new->SUPER::replace($old,
480 $options->{options} ? $options->{options} : ()
483 $dbh->rollback if $oldAutoCommit;
487 #for prepaid packages,
488 #trigger export of new RADIUS Expiration attribute when cust_pkg.bill changes
489 foreach my $old_svc_acct ( @svc_acct ) {
490 my $new_svc_acct = new FS::svc_acct { $old_svc_acct->hash };
491 my $s_error = $new_svc_acct->replace($old_svc_acct);
493 $dbh->rollback if $oldAutoCommit;
498 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
505 Checks all fields to make sure this is a valid billing item. If there is an
506 error, returns the error, otherwise returns false. Called by the insert and
514 $self->locationnum('') if !$self->locationnum || $self->locationnum == -1;
517 $self->ut_numbern('pkgnum')
518 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum')
519 || $self->ut_numbern('pkgpart')
520 || $self->ut_foreign_keyn('locationnum', 'cust_location', 'locationnum')
521 || $self->ut_numbern('start_date')
522 || $self->ut_numbern('setup')
523 || $self->ut_numbern('bill')
524 || $self->ut_numbern('susp')
525 || $self->ut_numbern('cancel')
526 || $self->ut_numbern('adjourn')
527 || $self->ut_numbern('expire')
529 return $error if $error;
531 if ( $self->reg_code ) {
533 unless ( grep { $self->pkgpart == $_->pkgpart }
534 map { $_->reg_code_pkg }
535 qsearchs( 'reg_code', { 'code' => $self->reg_code,
536 'agentnum' => $self->cust_main->agentnum })
538 return "Unknown registration code";
541 } elsif ( $self->promo_code ) {
544 qsearchs('part_pkg', {
545 'pkgpart' => $self->pkgpart,
546 'promo_code' => { op=>'ILIKE', value=>$self->promo_code },
548 return 'Unknown promotional code' unless $promo_part_pkg;
552 unless ( $disable_agentcheck ) {
554 qsearchs( 'agent', { 'agentnum' => $self->cust_main->agentnum } );
555 return "agent ". $agent->agentnum. ':'. $agent->agent.
556 " can't purchase pkgpart ". $self->pkgpart
557 unless $agent->pkgpart_hashref->{ $self->pkgpart }
558 || $agent->agentnum == $self->part_pkg->agentnum;
561 $error = $self->ut_foreign_key('pkgpart', 'part_pkg', 'pkgpart' );
562 return $error if $error;
566 $self->otaker(getotaker) unless $self->otaker;
567 $self->otaker =~ /^(\w{1,32})$/ or return "Illegal otaker";
570 if ( $self->dbdef_table->column('manual_flag') ) {
571 $self->manual_flag('') if $self->manual_flag eq ' ';
572 $self->manual_flag =~ /^([01]?)$/
573 or return "Illegal manual_flag ". $self->manual_flag;
574 $self->manual_flag($1);
580 =item cancel [ OPTION => VALUE ... ]
582 Cancels and removes all services (see L<FS::cust_svc> and L<FS::part_svc>)
583 in this package, then cancels the package itself (sets the cancel field to
586 Available options are:
590 =item quiet - can be set true to supress email cancellation notices.
592 =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.
594 =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.
596 =item date - can be set to a unix style timestamp to specify when to cancel (expire)
598 =item nobill - can be set true to skip billing if it might otherwise be done.
602 If there is an error, returns the error, otherwise returns false.
607 my( $self, %options ) = @_;
610 my $conf = new FS::Conf;
612 warn "cust_pkg::cancel called with options".
613 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
616 local $SIG{HUP} = 'IGNORE';
617 local $SIG{INT} = 'IGNORE';
618 local $SIG{QUIT} = 'IGNORE';
619 local $SIG{TERM} = 'IGNORE';
620 local $SIG{TSTP} = 'IGNORE';
621 local $SIG{PIPE} = 'IGNORE';
623 my $oldAutoCommit = $FS::UID::AutoCommit;
624 local $FS::UID::AutoCommit = 0;
627 my $old = $self->select_for_update;
629 if ( $old->get('cancel') || $self->get('cancel') ) {
630 dbh->rollback if $oldAutoCommit;
631 return ""; # no error
634 my $date = $options{date} if $options{date}; # expire/cancel later
635 $date = '' if ($date && $date <= time); # complain instead?
637 #race condition: usage could be ongoing until unprovisioned
638 #resolved by performing a change package instead (which unprovisions) and
640 if ( !$options{nobill} && !$date && $conf->exists('bill_usage_on_cancel') ) {
641 my $copy = $self->new({$self->hash});
643 $copy->cust_main->bill( pkg_list => [ $copy ], cancel => 1 );
644 warn "Error billing during cancel, custnum ".
645 #$self->cust_main->custnum. ": $error"
651 my $cancel_time = $options{'time'} || time;
653 if ( $options{'reason'} ) {
654 $error = $self->insert_reason( 'reason' => $options{'reason'},
655 'action' => $date ? 'expire' : 'cancel',
656 'date' => $date ? $date : $cancel_time,
657 'reason_otaker' => $options{'reason_otaker'},
660 dbh->rollback if $oldAutoCommit;
661 return "Error inserting cust_pkg_reason: $error";
667 foreach my $cust_svc (
670 sort { $a->[1] <=> $b->[1] }
671 map { [ $_, $_->svc_x->table_info->{'cancel_weight'} ]; }
672 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
675 my $error = $cust_svc->cancel;
678 $dbh->rollback if $oldAutoCommit;
679 return "Error cancelling cust_svc: $error";
683 # Add a credit for remaining service
684 my $remaining_value = $self->calc_remain(time=>$cancel_time);
685 if ( $remaining_value > 0 && !$options{'no_credit'} ) {
686 my $error = $self->cust_main->credit(
688 'Credit for unused time on '. $self->part_pkg->pkg,
689 'reason_type' => $conf->config('cancel_credit_type'),
692 $dbh->rollback if $oldAutoCommit;
693 return "Error crediting customer \$$remaining_value for unused time on".
694 $self->part_pkg->pkg. ": $error";
699 my %hash = $self->hash;
700 $date ? ($hash{'expire'} = $date) : ($hash{'cancel'} = $cancel_time);
701 my $new = new FS::cust_pkg ( \%hash );
702 $error = $new->replace( $self, options => { $self->options } );
704 $dbh->rollback if $oldAutoCommit;
708 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
709 return '' if $date; #no errors
711 my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ } $self->cust_main->invoicing_list;
712 if ( !$options{'quiet'} && $conf->exists('emailcancel') && @invoicing_list ) {
713 my $error = send_email(
714 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
715 'to' => \@invoicing_list,
716 'subject' => ( $conf->config('cancelsubject') || 'Cancellation Notice' ),
717 'body' => [ map "$_\n", $conf->config('cancelmessage') ],
719 #should this do something on errors?
726 =item cancel_if_expired [ NOW_TIMESTAMP ]
728 Cancels this package if its expire date has been reached.
732 sub cancel_if_expired {
734 my $time = shift || time;
735 return '' unless $self->expire && $self->expire <= $time;
736 my $error = $self->cancel;
738 return "Error cancelling expired pkg ". $self->pkgnum. " for custnum ".
739 $self->custnum. ": $error";
746 Cancels any pending expiration (sets the expire field to null).
748 If there is an error, returns the error, otherwise returns false.
753 my( $self, %options ) = @_;
756 local $SIG{HUP} = 'IGNORE';
757 local $SIG{INT} = 'IGNORE';
758 local $SIG{QUIT} = 'IGNORE';
759 local $SIG{TERM} = 'IGNORE';
760 local $SIG{TSTP} = 'IGNORE';
761 local $SIG{PIPE} = 'IGNORE';
763 my $oldAutoCommit = $FS::UID::AutoCommit;
764 local $FS::UID::AutoCommit = 0;
767 my $old = $self->select_for_update;
769 my $pkgnum = $old->pkgnum;
770 if ( $old->get('cancel') || $self->get('cancel') ) {
771 dbh->rollback if $oldAutoCommit;
772 return "Can't unexpire cancelled package $pkgnum";
773 # or at least it's pointless
776 unless ( $old->get('expire') && $self->get('expire') ) {
777 dbh->rollback if $oldAutoCommit;
778 return ""; # no error
781 my %hash = $self->hash;
782 $hash{'expire'} = '';
783 my $new = new FS::cust_pkg ( \%hash );
784 $error = $new->replace( $self, options => { $self->options } );
786 $dbh->rollback if $oldAutoCommit;
790 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
796 =item suspend [ OPTION => VALUE ... ]
798 Suspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
799 package, then suspends the package itself (sets the susp field to now).
801 Available options are:
805 =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.
807 =item date - can be set to a unix style timestamp to specify when to suspend (adjourn)
811 If there is an error, returns the error, otherwise returns false.
816 my( $self, %options ) = @_;
819 local $SIG{HUP} = 'IGNORE';
820 local $SIG{INT} = 'IGNORE';
821 local $SIG{QUIT} = 'IGNORE';
822 local $SIG{TERM} = 'IGNORE';
823 local $SIG{TSTP} = 'IGNORE';
824 local $SIG{PIPE} = 'IGNORE';
826 my $oldAutoCommit = $FS::UID::AutoCommit;
827 local $FS::UID::AutoCommit = 0;
830 my $old = $self->select_for_update;
832 my $pkgnum = $old->pkgnum;
833 if ( $old->get('cancel') || $self->get('cancel') ) {
834 dbh->rollback if $oldAutoCommit;
835 return "Can't suspend cancelled package $pkgnum";
838 if ( $old->get('susp') || $self->get('susp') ) {
839 dbh->rollback if $oldAutoCommit;
840 return ""; # no error # complain on adjourn?
843 my $date = $options{date} if $options{date}; # adjourn/suspend later
844 $date = '' if ($date && $date <= time); # complain instead?
846 if ( $date && $old->get('expire') && $old->get('expire') < $date ) {
847 dbh->rollback if $oldAutoCommit;
848 return "Package $pkgnum expires before it would be suspended.";
851 my $suspend_time = $options{'time'} || time;
853 if ( $options{'reason'} ) {
854 $error = $self->insert_reason( 'reason' => $options{'reason'},
855 'action' => $date ? 'adjourn' : 'suspend',
856 'date' => $date ? $date : $suspend_time,
857 'reason_otaker' => $options{'reason_otaker'},
860 dbh->rollback if $oldAutoCommit;
861 return "Error inserting cust_pkg_reason: $error";
869 foreach my $cust_svc (
870 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
872 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
874 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
875 $dbh->rollback if $oldAutoCommit;
876 return "Illegal svcdb value in part_svc!";
879 require "FS/$svcdb.pm";
881 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
883 $error = $svc->suspend;
885 $dbh->rollback if $oldAutoCommit;
888 my( $label, $value ) = $cust_svc->label;
889 push @labels, "$label: $value";
893 my $conf = new FS::Conf;
894 if ( $conf->config('suspend_email_admin') ) {
896 my $error = send_email(
897 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
898 #invoice_from ??? well as good as any
899 'to' => $conf->config('suspend_email_admin'),
900 'subject' => 'FREESIDE NOTIFICATION: Customer package suspended',
902 "This is an automatic message from your Freeside installation\n",
903 "informing you that the following customer package has been suspended:\n",
905 'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
906 'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
907 ( map { "Service : $_\n" } @labels ),
912 warn "WARNING: can't send suspension admin email (suspending anyway): ".
920 my %hash = $self->hash;
922 $hash{'adjourn'} = $date;
924 $hash{'susp'} = $suspend_time;
926 my $new = new FS::cust_pkg ( \%hash );
927 $error = $new->replace( $self, options => { $self->options } );
929 $dbh->rollback if $oldAutoCommit;
933 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
938 =item unsuspend [ OPTION => VALUE ... ]
940 Unsuspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
941 package, then unsuspends the package itself (clears the susp field and the
942 adjourn field if it is in the past).
944 Available options are:
948 =item adjust_next_bill
950 Can be set true to adjust the next bill date forward by
951 the amount of time the account was inactive. This was set true by default
952 since 1.4.2 and 1.5.0pre6; however, starting with 1.7.0 this needs to be
953 explicitly requested. Price plans for which this makes sense (anniversary-date
954 based than prorate or subscription) could have an option to enable this
959 If there is an error, returns the error, otherwise returns false.
964 my( $self, %opt ) = @_;
967 local $SIG{HUP} = 'IGNORE';
968 local $SIG{INT} = 'IGNORE';
969 local $SIG{QUIT} = 'IGNORE';
970 local $SIG{TERM} = 'IGNORE';
971 local $SIG{TSTP} = 'IGNORE';
972 local $SIG{PIPE} = 'IGNORE';
974 my $oldAutoCommit = $FS::UID::AutoCommit;
975 local $FS::UID::AutoCommit = 0;
978 my $old = $self->select_for_update;
980 my $pkgnum = $old->pkgnum;
981 if ( $old->get('cancel') || $self->get('cancel') ) {
982 dbh->rollback if $oldAutoCommit;
983 return "Can't unsuspend cancelled package $pkgnum";
986 unless ( $old->get('susp') && $self->get('susp') ) {
987 dbh->rollback if $oldAutoCommit;
988 return ""; # no error # complain instead?
991 foreach my $cust_svc (
992 qsearch('cust_svc',{'pkgnum'=> $self->pkgnum } )
994 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
996 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
997 $dbh->rollback if $oldAutoCommit;
998 return "Illegal svcdb value in part_svc!";
1001 require "FS/$svcdb.pm";
1003 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
1005 $error = $svc->unsuspend;
1007 $dbh->rollback if $oldAutoCommit;
1014 my %hash = $self->hash;
1015 my $inactive = time - $hash{'susp'};
1017 my $conf = new FS::Conf;
1019 $hash{'bill'} = ( $hash{'bill'} || $hash{'setup'} ) + $inactive
1020 if ( $opt{'adjust_next_bill'}
1021 || $conf->exists('unsuspend-always_adjust_next_bill_date') )
1022 && $inactive > 0 && ( $hash{'bill'} || $hash{'setup'} );
1025 $hash{'adjourn'} = '' if $hash{'adjourn'} < time;
1026 my $new = new FS::cust_pkg ( \%hash );
1027 $error = $new->replace( $self, options => { $self->options } );
1029 $dbh->rollback if $oldAutoCommit;
1033 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1040 Cancels any pending suspension (sets the adjourn field to null).
1042 If there is an error, returns the error, otherwise returns false.
1047 my( $self, %options ) = @_;
1050 local $SIG{HUP} = 'IGNORE';
1051 local $SIG{INT} = 'IGNORE';
1052 local $SIG{QUIT} = 'IGNORE';
1053 local $SIG{TERM} = 'IGNORE';
1054 local $SIG{TSTP} = 'IGNORE';
1055 local $SIG{PIPE} = 'IGNORE';
1057 my $oldAutoCommit = $FS::UID::AutoCommit;
1058 local $FS::UID::AutoCommit = 0;
1061 my $old = $self->select_for_update;
1063 my $pkgnum = $old->pkgnum;
1064 if ( $old->get('cancel') || $self->get('cancel') ) {
1065 dbh->rollback if $oldAutoCommit;
1066 return "Can't unadjourn cancelled package $pkgnum";
1067 # or at least it's pointless
1070 if ( $old->get('susp') || $self->get('susp') ) {
1071 dbh->rollback if $oldAutoCommit;
1072 return "Can't unadjourn suspended package $pkgnum";
1073 # perhaps this is arbitrary
1076 unless ( $old->get('adjourn') && $self->get('adjourn') ) {
1077 dbh->rollback if $oldAutoCommit;
1078 return ""; # no error
1081 my %hash = $self->hash;
1082 $hash{'adjourn'} = '';
1083 my $new = new FS::cust_pkg ( \%hash );
1084 $error = $new->replace( $self, options => { $self->options } );
1086 $dbh->rollback if $oldAutoCommit;
1090 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1097 =item change HASHREF | OPTION => VALUE ...
1099 Changes this package: cancels it and creates a new one, with a different
1100 pkgpart or locationnum or both. All services are transferred to the new
1101 package (no change will be made if this is not possible).
1103 Options may be passed as a list of key/value pairs or as a hash reference.
1110 New locationnum, to change the location for this package.
1114 New FS::cust_location object, to create a new location and assign it
1119 New pkgpart (see L<FS::part_pkg>).
1123 New refnum (see L<FS::part_referral>).
1127 At least one option must be specified (otherwise, what's the point?)
1129 Returns either the new FS::cust_pkg object or a scalar error.
1133 my $err_or_new_cust_pkg = $old_cust_pkg->change
1137 #some false laziness w/order
1140 my $opt = ref($_[0]) ? shift : { @_ };
1142 # my ($custnum, $pkgparts, $remove_pkgnum, $return_cust_pkg, $refnum) = @_;
1145 my $conf = new FS::Conf;
1147 # Transactionize this whole mess
1148 local $SIG{HUP} = 'IGNORE';
1149 local $SIG{INT} = 'IGNORE';
1150 local $SIG{QUIT} = 'IGNORE';
1151 local $SIG{TERM} = 'IGNORE';
1152 local $SIG{TSTP} = 'IGNORE';
1153 local $SIG{PIPE} = 'IGNORE';
1155 my $oldAutoCommit = $FS::UID::AutoCommit;
1156 local $FS::UID::AutoCommit = 0;
1165 #$hash{$_} = $self->$_() foreach qw( last_bill bill );
1167 #$hash{$_} = $self->$_() foreach qw( setup );
1169 $hash{'setup'} = $time if $self->setup;
1171 $hash{'change_date'} = $time;
1172 $hash{"change_$_"} = $self->$_()
1173 foreach qw( pkgnum pkgpart locationnum );
1175 if ( $opt->{'cust_location'} &&
1176 ( ! $opt->{'locationnum'} || $opt->{'locationnum'} == -1 ) ) {
1177 $error = $opt->{'cust_location'}->insert;
1179 $dbh->rollback if $oldAutoCommit;
1180 return "inserting cust_location (transaction rolled back): $error";
1182 $opt->{'locationnum'} = $opt->{'cust_location'}->locationnum;
1185 # Create the new package.
1186 my $cust_pkg = new FS::cust_pkg {
1187 custnum => $self->custnum,
1188 pkgpart => ( $opt->{'pkgpart'} || $self->pkgpart ),
1189 refnum => ( $opt->{'refnum'} || $self->refnum ),
1190 locationnum => ( $opt->{'locationnum'} || $self->locationnum ),
1194 $error = $cust_pkg->insert( 'change' => 1 );
1196 $dbh->rollback if $oldAutoCommit;
1200 # Transfer services and cancel old package.
1202 $error = $self->transfer($cust_pkg);
1203 if ($error and $error == 0) {
1204 # $old_pkg->transfer failed.
1205 $dbh->rollback if $oldAutoCommit;
1209 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
1210 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
1211 $error = $self->transfer($cust_pkg, 'change_svcpart'=>1 );
1212 if ($error and $error == 0) {
1213 # $old_pkg->transfer failed.
1214 $dbh->rollback if $oldAutoCommit;
1220 # Transfers were successful, but we still had services left on the old
1221 # package. We can't change the package under this circumstances, so abort.
1222 $dbh->rollback if $oldAutoCommit;
1223 return "Unable to transfer all services from package ". $self->pkgnum;
1226 #reset usage if changing pkgpart
1227 # AND usage rollover is off (otherwise adds twice, now and at package bill)
1228 if ($self->pkgpart != $cust_pkg->pkgpart) {
1229 my $part_pkg = $cust_pkg->part_pkg;
1230 $error = $part_pkg->reset_usage($cust_pkg, $part_pkg->is_prepaid
1234 if $part_pkg->can('reset_usage') && ! $part_pkg->option('usage_rollover');
1237 $dbh->rollback if $oldAutoCommit;
1238 return "Error setting usage values: $error";
1242 #Good to go, cancel old package.
1243 $error = $self->cancel( quiet=>1 );
1245 $dbh->rollback if $oldAutoCommit;
1249 if ( $conf->exists('cust_pkg-change_pkgpart-bill_now') ) {
1251 my $error = $cust_pkg->cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1253 $dbh->rollback if $oldAutoCommit;
1258 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1266 Returns the last bill date, or if there is no last bill date, the setup date.
1267 Useful for billing metered services.
1273 return $self->setfield('last_bill', $_[0]) if @_;
1274 return $self->getfield('last_bill') if $self->getfield('last_bill');
1275 my $cust_bill_pkg = qsearchs('cust_bill_pkg', { 'pkgnum' => $self->pkgnum,
1276 'edate' => $self->bill, } );
1277 $cust_bill_pkg ? $cust_bill_pkg->sdate : $self->setup || 0;
1280 =item last_cust_pkg_reason ACTION
1282 Returns the most recent ACTION FS::cust_pkg_reason associated with the package.
1283 Returns false if there is no reason or the package is not currenly ACTION'd
1284 ACTION is one of adjourn, susp, cancel, or expire.
1288 sub last_cust_pkg_reason {
1289 my ( $self, $action ) = ( shift, shift );
1290 my $date = $self->get($action);
1292 'table' => 'cust_pkg_reason',
1293 'hashref' => { 'pkgnum' => $self->pkgnum,
1294 'action' => substr(uc($action), 0, 1),
1297 'order_by' => 'ORDER BY num DESC LIMIT 1',
1301 =item last_reason ACTION
1303 Returns the most recent ACTION FS::reason associated with the package.
1304 Returns false if there is no reason or the package is not currenly ACTION'd
1305 ACTION is one of adjourn, susp, cancel, or expire.
1310 my $cust_pkg_reason = shift->last_cust_pkg_reason(@_);
1311 $cust_pkg_reason->reason
1312 if $cust_pkg_reason;
1317 Returns the definition for this billing item, as an FS::part_pkg object (see
1324 return $self->{'_pkgpart'} if $self->{'_pkgpart'};
1325 cluck "cust_pkg->part_pkg called" if $DEBUG > 1;
1326 qsearchs( 'part_pkg', { 'pkgpart' => $self->pkgpart } );
1331 Returns the cancelled package this package was changed from, if any.
1337 return '' unless $self->change_pkgnum;
1338 qsearchs('cust_pkg', { 'pkgnum' => $self->change_pkgnum } );
1343 Calls the I<calc_setup> of the FS::part_pkg object associated with this billing
1350 $self->part_pkg->calc_setup($self, @_);
1355 Calls the I<calc_recur> of the FS::part_pkg object associated with this billing
1362 $self->part_pkg->calc_recur($self, @_);
1367 Calls the I<calc_remain> of the FS::part_pkg object associated with this
1374 $self->part_pkg->calc_remain($self, @_);
1379 Calls the I<calc_cancel> of the FS::part_pkg object associated with this
1386 $self->part_pkg->calc_cancel($self, @_);
1391 Returns any invoice line items for this package (see L<FS::cust_bill_pkg>).
1397 qsearch( 'cust_bill_pkg', { 'pkgnum' => $self->pkgnum } );
1400 =item cust_pkg_detail [ DETAILTYPE ]
1402 Returns any customer package details for this package (see
1403 L<FS::cust_pkg_detail>).
1405 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
1409 sub cust_pkg_detail {
1411 my %hash = ( 'pkgnum' => $self->pkgnum );
1412 $hash{detailtype} = shift if @_;
1414 'table' => 'cust_pkg_detail',
1415 'hashref' => \%hash,
1416 'order_by' => 'ORDER BY weight, pkgdetailnum',
1420 =item set_cust_pkg_detail DETAILTYPE [ DETAIL, DETAIL, ... ]
1422 Sets customer package details for this package (see L<FS::cust_pkg_detail>).
1424 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
1426 If there is an error, returns the error, otherwise returns false.
1430 sub set_cust_pkg_detail {
1431 my( $self, $detailtype, @details ) = @_;
1433 local $SIG{HUP} = 'IGNORE';
1434 local $SIG{INT} = 'IGNORE';
1435 local $SIG{QUIT} = 'IGNORE';
1436 local $SIG{TERM} = 'IGNORE';
1437 local $SIG{TSTP} = 'IGNORE';
1438 local $SIG{PIPE} = 'IGNORE';
1440 my $oldAutoCommit = $FS::UID::AutoCommit;
1441 local $FS::UID::AutoCommit = 0;
1444 foreach my $current ( $self->cust_pkg_detail($detailtype) ) {
1445 my $error = $current->delete;
1447 $dbh->rollback if $oldAutoCommit;
1448 return "error removing old detail: $error";
1452 foreach my $detail ( @details ) {
1453 my $cust_pkg_detail = new FS::cust_pkg_detail {
1454 'pkgnum' => $self->pkgnum,
1455 'detailtype' => $detailtype,
1456 'detail' => $detail,
1458 my $error = $cust_pkg_detail->insert;
1460 $dbh->rollback if $oldAutoCommit;
1461 return "error adding new detail: $error";
1466 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1473 Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.
1477 #false laziness w/cust_bill.pm
1481 'table' => 'cust_event',
1482 'addl_from' => 'JOIN part_event USING ( eventpart )',
1483 'hashref' => { 'tablenum' => $self->pkgnum },
1484 'extra_sql' => " AND eventtable = 'cust_pkg' ",
1488 =item num_cust_event
1490 Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.
1494 #false laziness w/cust_bill.pm
1495 sub num_cust_event {
1498 "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
1499 " WHERE tablenum = ? AND eventtable = 'cust_pkg'";
1500 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
1501 $sth->execute($self->pkgnum) or die $sth->errstr. " executing $sql";
1502 $sth->fetchrow_arrayref->[0];
1505 =item cust_svc [ SVCPART ]
1507 Returns the services for this package, as FS::cust_svc objects (see
1508 L<FS::cust_svc>). If a svcpart is specified, return only the matching
1516 return () unless $self->num_cust_svc(@_);
1519 return qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum,
1520 'svcpart' => shift, } );
1523 cluck "cust_pkg->cust_svc called" if $DEBUG > 2;
1525 #if ( $self->{'_svcnum'} ) {
1526 # values %{ $self->{'_svcnum'}->cache };
1528 $self->_sort_cust_svc(
1529 [ qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } ) ]
1535 =item overlimit [ SVCPART ]
1537 Returns the services for this package which have exceeded their
1538 usage limit as FS::cust_svc objects (see L<FS::cust_svc>). If a svcpart
1539 is specified, return only the matching services.
1545 return () unless $self->num_cust_svc(@_);
1546 grep { $_->overlimit } $self->cust_svc(@_);
1549 =item h_cust_svc END_TIMESTAMP [ START_TIMESTAMP ]
1551 Returns historical services for this package created before END TIMESTAMP and
1552 (optionally) not cancelled before START_TIMESTAMP, as FS::h_cust_svc objects
1553 (see L<FS::h_cust_svc>).
1560 $self->_sort_cust_svc(
1561 [ qsearch( 'h_cust_svc',
1562 { 'pkgnum' => $self->pkgnum, },
1563 FS::h_cust_svc->sql_h_search(@_),
1569 sub _sort_cust_svc {
1570 my( $self, $arrayref ) = @_;
1573 sub ($$) { my ($a, $b) = @_; $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] };
1578 my $pkg_svc = qsearchs( 'pkg_svc', { 'pkgpart' => $self->pkgpart,
1579 'svcpart' => $_->svcpart } );
1581 $pkg_svc ? $pkg_svc->primary_svc : '',
1582 $pkg_svc ? $pkg_svc->quantity : 0,
1589 =item num_cust_svc [ SVCPART ]
1591 Returns the number of provisioned services for this package. If a svcpart is
1592 specified, counts only the matching services.
1599 return $self->{'_num_cust_svc'}
1601 && exists($self->{'_num_cust_svc'})
1602 && $self->{'_num_cust_svc'} =~ /\d/;
1604 cluck "cust_pkg->num_cust_svc called, _num_cust_svc:".$self->{'_num_cust_svc'}
1607 my $sql = 'SELECT COUNT(*) FROM cust_svc WHERE pkgnum = ?';
1608 $sql .= ' AND svcpart = ?' if @_;
1610 my $sth = dbh->prepare($sql) or die dbh->errstr;
1611 $sth->execute($self->pkgnum, @_) or die $sth->errstr;
1612 $sth->fetchrow_arrayref->[0];
1615 =item available_part_svc
1617 Returns a list of FS::part_svc objects representing services included in this
1618 package but not yet provisioned. Each FS::part_svc object also has an extra
1619 field, I<num_avail>, which specifies the number of available services.
1623 sub available_part_svc {
1625 grep { $_->num_avail > 0 }
1627 my $part_svc = $_->part_svc;
1628 $part_svc->{'Hash'}{'num_avail'} = #evil encapsulation-breaking
1629 $_->quantity - $self->num_cust_svc($_->svcpart);
1632 $self->part_pkg->pkg_svc;
1637 Returns a list of FS::part_svc objects representing provisioned and available
1638 services included in this package. Each FS::part_svc object also has the
1639 following extra fields:
1643 =item num_cust_svc (count)
1645 =item num_avail (quantity - count)
1647 =item cust_pkg_svc (services) - array reference containing the provisioned services, as cust_svc objects
1650 label -> ($cust_svc->label)[1]
1659 #XXX some sort of sort order besides numeric by svcpart...
1660 my @part_svc = sort { $a->svcpart <=> $b->svcpart } map {
1662 my $part_svc = $pkg_svc->part_svc;
1663 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
1664 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #more evil
1665 $part_svc->{'Hash'}{'num_avail'} =
1666 max( 0, $pkg_svc->quantity - $num_cust_svc );
1667 $part_svc->{'Hash'}{'cust_pkg_svc'} =
1668 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : [];
1670 } $self->part_pkg->pkg_svc;
1673 push @part_svc, map {
1675 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
1676 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #speak no evail
1677 $part_svc->{'Hash'}{'num_avail'} = 0; #0-$num_cust_svc ?
1678 $part_svc->{'Hash'}{'cust_pkg_svc'} =
1679 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : [];
1681 } $self->extra_part_svc;
1687 =item extra_part_svc
1689 Returns a list of FS::part_svc objects corresponding to services in this
1690 package which are still provisioned but not (any longer) available in the
1695 sub extra_part_svc {
1698 my $pkgnum = $self->pkgnum;
1699 my $pkgpart = $self->pkgpart;
1702 # 'table' => 'part_svc',
1705 # "WHERE 0 = ( SELECT COUNT(*) FROM pkg_svc
1706 # WHERE pkg_svc.svcpart = part_svc.svcpart
1707 # AND pkg_svc.pkgpart = ?
1710 # AND 0 < ( SELECT COUNT(*) FROM cust_svc
1711 # LEFT JOIN cust_pkg USING ( pkgnum )
1712 # WHERE cust_svc.svcpart = part_svc.svcpart
1715 # 'extra_param' => [ [$self->pkgpart=>'int'], [$self->pkgnum=>'int'] ],
1718 #seems to benchmark slightly faster...
1720 'select' => 'DISTINCT ON (svcpart) part_svc.*',
1721 'table' => 'part_svc',
1723 'LEFT JOIN pkg_svc ON ( pkg_svc.svcpart = part_svc.svcpart
1724 AND pkg_svc.pkgpart = ?
1727 LEFT JOIN cust_svc ON ( cust_svc.svcpart = part_svc.svcpart )
1728 LEFT JOIN cust_pkg USING ( pkgnum )
1731 'extra_sql' => "WHERE pkgsvcnum IS NULL AND cust_pkg.pkgnum = ? ",
1732 'extra_param' => [ [$self->pkgpart=>'int'], [$self->pkgnum=>'int'] ],
1738 Returns a short status string for this package, currently:
1742 =item not yet billed
1744 =item one-time charge
1759 my $freq = length($self->freq) ? $self->freq : $self->part_pkg->freq;
1761 return 'cancelled' if $self->get('cancel');
1762 return 'suspended' if $self->susp;
1763 return 'not yet billed' unless $self->setup;
1764 return 'one-time charge' if $freq =~ /^(0|$)/;
1770 Class method that returns the list of possible status strings for packages
1771 (see L<the status method|/status>). For example:
1773 @statuses = FS::cust_pkg->statuses();
1777 tie my %statuscolor, 'Tie::IxHash',
1778 'not yet billed' => '000000',
1779 'one-time charge' => '000000',
1780 'active' => '00CC00',
1781 'suspended' => 'FF9900',
1782 'cancelled' => 'FF0000',
1786 my $self = shift; #could be class...
1787 #grep { $_ !~ /^(not yet billed)$/ } #this is a dumb status anyway
1788 # # mayble split btw one-time vs. recur
1794 Returns a hex triplet color string for this package's status.
1800 $statuscolor{$self->status};
1805 Returns a label for this package. (Currently "pkgnum: pkg - comment" or
1806 "pkg-comment" depending on user preference).
1812 my $label = $self->part_pkg->pkg_comment( 'nopkgpart' => 1 );
1813 $label = $self->pkgnum. ": $label"
1814 if $FS::CurrentUser::CurrentUser->option('show_pkgnum');
1818 =item pkg_label_long
1820 Returns a long label for this package, adding the primary service's label to
1825 sub pkg_label_long {
1827 my $label = $self->pkg_label;
1828 my $cust_svc = $self->primary_cust_svc;
1829 $label .= ' ('. ($cust_svc->label)[1]. ')' if $cust_svc;
1833 =item primary_cust_svc
1835 Returns a primary service (as FS::cust_svc object) if one can be identified.
1839 #for labeling purposes - might not 100% match up with part_pkg->svcpart's idea
1841 sub primary_cust_svc {
1844 my @cust_svc = $self->cust_svc;
1846 return '' unless @cust_svc; #no serivces - irrelevant then
1848 return $cust_svc[0] if scalar(@cust_svc) == 1; #always return a single service
1850 # primary service as specified in the package definition
1851 # or exactly one service definition with quantity one
1852 my $svcpart = $self->part_pkg->svcpart;
1853 @cust_svc = grep { $_->svcpart == $svcpart } @cust_svc;
1854 return $cust_svc[0] if scalar(@cust_svc) == 1;
1856 #couldn't identify one thing..
1862 Returns a list of lists, calling the label method for all services
1863 (see L<FS::cust_svc>) of this billing item.
1869 map { [ $_->label ] } $self->cust_svc;
1872 =item h_labels END_TIMESTAMP [ START_TIMESTAMP ]
1874 Like the labels method, but returns historical information on services that
1875 were active as of END_TIMESTAMP and (optionally) not cancelled before
1878 Returns a list of lists, calling the label method for all (historical) services
1879 (see L<FS::h_cust_svc>) of this billing item.
1885 map { [ $_->label(@_) ] } $self->h_cust_svc(@_);
1890 Like labels, except returns a simple flat list, and shortens long
1891 (currently >5 or the cust_bill-max_same_services configuration value) lists of
1892 identical services to one line that lists the service label and the number of
1893 individual services rather than individual items.
1898 shift->_labels_short( 'labels', @_ );
1901 =item h_labels_short END_TIMESTAMP [ START_TIMESTAMP ]
1903 Like h_labels, except returns a simple flat list, and shortens long
1904 (currently >5 or the cust_bill-max_same_services configuration value) lists of
1905 identical services to one line that lists the service label and the number of
1906 individual services rather than individual items.
1910 sub h_labels_short {
1911 shift->_labels_short( 'h_labels', @_ );
1915 my( $self, $method ) = ( shift, shift );
1917 my $conf = new FS::Conf;
1918 my $max_same_services = $conf->config('cust_bill-max_same_services') || 5;
1921 #tie %labels, 'Tie::IxHash';
1922 push @{ $labels{$_->[0]} }, $_->[1]
1923 foreach $self->h_labels(@_);
1925 foreach my $label ( keys %labels ) {
1927 my @values = grep { ! $seen{$_}++ } @{ $labels{$label} };
1928 my $num = scalar(@values);
1929 if ( $num > $max_same_services ) {
1930 push @labels, "$label ($num)";
1932 if ( $conf->exists('cust_bill-consolidate_services') ) {
1933 # push @labels, "$label: ". join(', ', @values);
1935 my $detail = "$label: ";
1936 $detail .= shift(@values). ', '
1937 while @values && length($detail.$values[0]) < 78;
1939 push @labels, $detail;
1942 push @labels, map { "$label: $_" } @values;
1953 Returns the parent customer object (see L<FS::cust_main>).
1959 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
1962 #these subs are in location_Mixin.pm now... unfortunately the POD doesn't mixin
1966 Returns the location object, if any (see L<FS::cust_location>).
1968 =item cust_location_or_main
1970 If this package is associated with a location, returns the locaiton (see
1971 L<FS::cust_location>), otherwise returns the customer (see L<FS::cust_main>).
1973 =item location_label [ OPTION => VALUE ... ]
1975 Returns the label of the location object (see L<FS::cust_location>).
1979 #end of subs in location_Mixin.pm now... unfortunately the POD doesn't mixin
1981 =item seconds_since TIMESTAMP
1983 Returns the number of seconds all accounts (see L<FS::svc_acct>) in this
1984 package have been online since TIMESTAMP, according to the session monitor.
1986 TIMESTAMP is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
1987 L<Time::Local> and L<Date::Parse> for conversion functions.
1992 my($self, $since) = @_;
1995 foreach my $cust_svc (
1996 grep { $_->part_svc->svcdb eq 'svc_acct' } $self->cust_svc
1998 $seconds += $cust_svc->seconds_since($since);
2005 =item seconds_since_sqlradacct TIMESTAMP_START TIMESTAMP_END
2007 Returns the numbers of seconds all accounts (see L<FS::svc_acct>) in this
2008 package have been online between TIMESTAMP_START (inclusive) and TIMESTAMP_END
2011 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
2012 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
2018 sub seconds_since_sqlradacct {
2019 my($self, $start, $end) = @_;
2023 foreach my $cust_svc (
2025 my $part_svc = $_->part_svc;
2026 $part_svc->svcdb eq 'svc_acct'
2027 && scalar($part_svc->part_export('sqlradius'));
2030 $seconds += $cust_svc->seconds_since_sqlradacct($start, $end);
2037 =item attribute_since_sqlradacct TIMESTAMP_START TIMESTAMP_END ATTRIBUTE
2039 Returns the sum of the given attribute for all accounts (see L<FS::svc_acct>)
2040 in this package for sessions ending between TIMESTAMP_START (inclusive) and
2044 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
2045 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
2050 sub attribute_since_sqlradacct {
2051 my($self, $start, $end, $attrib) = @_;
2055 foreach my $cust_svc (
2057 my $part_svc = $_->part_svc;
2058 $part_svc->svcdb eq 'svc_acct'
2059 && scalar($part_svc->part_export('sqlradius'));
2062 $sum += $cust_svc->attribute_since_sqlradacct($start, $end, $attrib);
2074 my( $self, $value ) = @_;
2075 if ( defined($value) ) {
2076 $self->setfield('quantity', $value);
2078 $self->getfield('quantity') || 1;
2081 =item transfer DEST_PKGNUM | DEST_CUST_PKG, [ OPTION => VALUE ... ]
2083 Transfers as many services as possible from this package to another package.
2085 The destination package can be specified by pkgnum by passing an FS::cust_pkg
2086 object. The destination package must already exist.
2088 Services are moved only if the destination allows services with the correct
2089 I<svcpart> (not svcdb), unless the B<change_svcpart> option is set true. Use
2090 this option with caution! No provision is made for export differences
2091 between the old and new service definitions. Probably only should be used
2092 when your exports for all service definitions of a given svcdb are identical.
2093 (attempt a transfer without it first, to move all possible svcpart-matching
2096 Any services that can't be moved remain in the original package.
2098 Returns an error, if there is one; otherwise, returns the number of services
2099 that couldn't be moved.
2104 my ($self, $dest_pkgnum, %opt) = @_;
2110 if (ref ($dest_pkgnum) eq 'FS::cust_pkg') {
2111 $dest = $dest_pkgnum;
2112 $dest_pkgnum = $dest->pkgnum;
2114 $dest = qsearchs('cust_pkg', { pkgnum => $dest_pkgnum });
2117 return ('Package does not exist: '.$dest_pkgnum) unless $dest;
2119 foreach my $pkg_svc ( $dest->part_pkg->pkg_svc ) {
2120 $target{$pkg_svc->svcpart} = $pkg_svc->quantity;
2123 foreach my $cust_svc ($dest->cust_svc) {
2124 $target{$cust_svc->svcpart}--;
2127 my %svcpart2svcparts = ();
2128 if ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
2129 warn "change_svcpart option received, creating alternates list\n" if $DEBUG;
2130 foreach my $svcpart ( map { $_->svcpart } $self->cust_svc ) {
2131 next if exists $svcpart2svcparts{$svcpart};
2132 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2133 $svcpart2svcparts{$svcpart} = [
2135 sort { $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] }
2137 my $pkg_svc = qsearchs( 'pkg_svc', { 'pkgpart' => $dest->pkgpart,
2138 'svcpart' => $_ } );
2140 $pkg_svc ? $pkg_svc->primary_svc : '',
2141 $pkg_svc ? $pkg_svc->quantity : 0,
2145 grep { $_ != $svcpart }
2147 qsearch('part_svc', { 'svcdb' => $part_svc->svcdb } )
2149 warn "alternates for svcpart $svcpart: ".
2150 join(', ', @{$svcpart2svcparts{$svcpart}}). "\n"
2155 foreach my $cust_svc ($self->cust_svc) {
2156 if($target{$cust_svc->svcpart} > 0) {
2157 $target{$cust_svc->svcpart}--;
2158 my $new = new FS::cust_svc { $cust_svc->hash };
2159 $new->pkgnum($dest_pkgnum);
2160 my $error = $new->replace($cust_svc);
2161 return $error if $error;
2162 } elsif ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
2164 warn "looking for alternates for svcpart ". $cust_svc->svcpart. "\n";
2165 warn "alternates to consider: ".
2166 join(', ', @{$svcpart2svcparts{$cust_svc->svcpart}}). "\n";
2168 my @alternate = grep {
2169 warn "considering alternate svcpart $_: ".
2170 "$target{$_} available in new package\n"
2173 } @{$svcpart2svcparts{$cust_svc->svcpart}};
2175 warn "alternate(s) found\n" if $DEBUG;
2176 my $change_svcpart = $alternate[0];
2177 $target{$change_svcpart}--;
2178 my $new = new FS::cust_svc { $cust_svc->hash };
2179 $new->svcpart($change_svcpart);
2180 $new->pkgnum($dest_pkgnum);
2181 my $error = $new->replace($cust_svc);
2182 return $error if $error;
2195 This method is deprecated. See the I<depend_jobnum> option to the insert and
2196 order_pkgs methods in FS::cust_main for a better way to defer provisioning.
2203 local $SIG{HUP} = 'IGNORE';
2204 local $SIG{INT} = 'IGNORE';
2205 local $SIG{QUIT} = 'IGNORE';
2206 local $SIG{TERM} = 'IGNORE';
2207 local $SIG{TSTP} = 'IGNORE';
2208 local $SIG{PIPE} = 'IGNORE';
2210 my $oldAutoCommit = $FS::UID::AutoCommit;
2211 local $FS::UID::AutoCommit = 0;
2214 foreach my $cust_svc ( $self->cust_svc ) {
2215 #false laziness w/svc_Common::insert
2216 my $svc_x = $cust_svc->svc_x;
2217 foreach my $part_export ( $cust_svc->part_svc->part_export ) {
2218 my $error = $part_export->export_insert($svc_x);
2220 $dbh->rollback if $oldAutoCommit;
2226 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2233 Associates this package with a (suspension or cancellation) reason (see
2234 L<FS::cust_pkg_reason>, possibly inserting a new reason on the fly (see
2237 Available options are:
2243 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.
2247 the access_user (see L<FS::access_user>) providing the reason
2255 the action (cancel, susp, adjourn, expire) associated with the reason
2259 If there is an error, returns the error, otherwise returns false.
2264 my ($self, %options) = @_;
2266 my $otaker = $options{reason_otaker} ||
2267 $FS::CurrentUser::CurrentUser->username;
2270 if ( $options{'reason'} =~ /^(\d+)$/ ) {
2274 } elsif ( ref($options{'reason'}) ) {
2276 return 'Enter a new reason (or select an existing one)'
2277 unless $options{'reason'}->{'reason'} !~ /^\s*$/;
2279 my $reason = new FS::reason({
2280 'reason_type' => $options{'reason'}->{'typenum'},
2281 'reason' => $options{'reason'}->{'reason'},
2283 my $error = $reason->insert;
2284 return $error if $error;
2286 $reasonnum = $reason->reasonnum;
2289 return "Unparsable reason: ". $options{'reason'};
2292 my $cust_pkg_reason =
2293 new FS::cust_pkg_reason({ 'pkgnum' => $self->pkgnum,
2294 'reasonnum' => $reasonnum,
2295 'otaker' => $otaker,
2296 'action' => substr(uc($options{'action'}),0,1),
2297 'date' => $options{'date'}
2302 $cust_pkg_reason->insert;
2305 =item insert_discount
2307 Associates this package with a discount (see L<FS::cust_pkg_discount>, possibly
2308 inserting a new discount on the fly (see L<FS::discount>).
2310 Available options are:
2318 If there is an error, returns the error, otherwise returns false.
2322 sub insert_discount {
2323 #my ($self, %options) = @_;
2326 my $cust_pkg_discount = new FS::cust_pkg_discount {
2327 'pkgnum' => $self->pkgnum,
2328 'discountnum' => $self->discountnum,
2330 'end_date' => '', #XXX
2331 'otaker' => $self->otaker,
2332 #for the create a new discount case
2333 '_type' => $self->discountnum__type,
2334 'amount' => $self->discountnum_amount,
2335 'percent' => $self->discountnum_percent,
2336 'months' => $self->discountnum_months,
2337 #'disabled' => $self->discountnum_disabled,
2340 $cust_pkg_discount->insert;
2343 =item set_usage USAGE_VALUE_HASHREF
2345 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
2346 to which they should be set (see L<FS::svc_acct>). Currently seconds,
2347 upbytes, downbytes, and totalbytes are appropriate keys.
2349 All svc_accts which are part of this package have their values reset.
2354 my ($self, $valueref, %opt) = @_;
2356 foreach my $cust_svc ($self->cust_svc){
2357 my $svc_x = $cust_svc->svc_x;
2358 $svc_x->set_usage($valueref, %opt)
2359 if $svc_x->can("set_usage");
2363 =item recharge USAGE_VALUE_HASHREF
2365 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
2366 to which they should be set (see L<FS::svc_acct>). Currently seconds,
2367 upbytes, downbytes, and totalbytes are appropriate keys.
2369 All svc_accts which are part of this package have their values incremented.
2374 my ($self, $valueref) = @_;
2376 foreach my $cust_svc ($self->cust_svc){
2377 my $svc_x = $cust_svc->svc_x;
2378 $svc_x->recharge($valueref)
2379 if $svc_x->can("recharge");
2383 =item cust_pkg_discount
2387 sub cust_pkg_discount {
2389 qsearch('cust_pkg_discount', { 'pkgnum' => $self->pkgnum } );
2392 =item cust_pkg_discount_active
2396 sub cust_pkg_discount_active {
2398 grep { $_->status eq 'active' } $self->cust_pkg_discount;
2403 =head1 CLASS METHODS
2409 Returns an SQL expression identifying recurring packages.
2413 sub recurring_sql { "
2414 '0' != ( select freq from part_pkg
2415 where cust_pkg.pkgpart = part_pkg.pkgpart )
2420 Returns an SQL expression identifying one-time packages.
2425 '0' = ( select freq from part_pkg
2426 where cust_pkg.pkgpart = part_pkg.pkgpart )
2431 Returns an SQL expression identifying active packages.
2436 ". $_[0]->recurring_sql(). "
2437 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
2438 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
2439 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
2442 =item not_yet_billed_sql
2444 Returns an SQL expression identifying packages which have not yet been billed.
2448 sub not_yet_billed_sql { "
2449 ( cust_pkg.setup IS NULL OR cust_pkg.setup = 0 )
2450 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
2451 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
2456 Returns an SQL expression identifying inactive packages (one-time packages
2457 that are otherwise unsuspended/uncancelled).
2461 sub inactive_sql { "
2462 ". $_[0]->onetime_sql(). "
2463 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
2464 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
2465 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
2471 Returns an SQL expression identifying suspended packages.
2475 sub suspended_sql { susp_sql(@_); }
2477 #$_[0]->recurring_sql(). ' AND '.
2479 ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
2480 AND cust_pkg.susp IS NOT NULL AND cust_pkg.susp != 0
2487 Returns an SQL exprression identifying cancelled packages.
2491 sub cancelled_sql { cancel_sql(@_); }
2493 #$_[0]->recurring_sql(). ' AND '.
2494 "cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0";
2497 =item search HASHREF
2501 Returns a qsearch hash expression to search for parameters specified in HASHREF.
2502 Valid parameters are
2510 active, inactive, suspended, cancel (or cancelled)
2514 active, inactive, suspended, one-time charge, inactive, cancel (or cancelled)
2518 boolean selects custom packages
2524 pkgpart or arrayref or hashref of pkgparts
2528 arrayref of beginning and ending epoch date
2532 arrayref of beginning and ending epoch date
2536 arrayref of beginning and ending epoch date
2540 arrayref of beginning and ending epoch date
2544 arrayref of beginning and ending epoch date
2548 arrayref of beginning and ending epoch date
2552 arrayref of beginning and ending epoch date
2556 pkgnum or APKG_pkgnum
2560 a value suited to passing to FS::UI::Web::cust_header
2564 specifies the user for agent virtualization
2571 my ($class, $params) = @_;
2578 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
2580 "cust_main.agentnum = $1";
2587 if ( $params->{'custnum'} =~ /^(\d+)$/ and $1 ) {
2589 "cust_pkg.custnum = $1";
2596 if ( $params->{'magic'} eq 'active'
2597 || $params->{'status'} eq 'active' ) {
2599 push @where, FS::cust_pkg->active_sql();
2601 } elsif ( $params->{'magic'} =~ /^not[ _]yet[ _]billed$/
2602 || $params->{'status'} =~ /^not[ _]yet[ _]billed$/ ) {
2604 push @where, FS::cust_pkg->not_yet_billed_sql();
2606 } elsif ( $params->{'magic'} =~ /^(one-time charge|inactive)/
2607 || $params->{'status'} =~ /^(one-time charge|inactive)/ ) {
2609 push @where, FS::cust_pkg->inactive_sql();
2611 } elsif ( $params->{'magic'} eq 'suspended'
2612 || $params->{'status'} eq 'suspended' ) {
2614 push @where, FS::cust_pkg->suspended_sql();
2616 } elsif ( $params->{'magic'} =~ /^cancell?ed$/
2617 || $params->{'status'} =~ /^cancell?ed$/ ) {
2619 push @where, FS::cust_pkg->cancelled_sql();
2624 # parse package class
2627 #false lazinessish w/graph/cust_bill_pkg.cgi
2630 if ( exists($params->{'classnum'})
2631 && $params->{'classnum'} =~ /^(\d*)$/
2635 if ( $classnum ) { #a specific class
2636 push @where, "part_pkg.classnum = $classnum";
2638 #@pkg_class = ( qsearchs('pkg_class', { 'classnum' => $classnum } ) );
2639 #die "classnum $classnum not found!" unless $pkg_class[0];
2640 #$title .= $pkg_class[0]->classname.' ';
2642 } elsif ( $classnum eq '' ) { #the empty class
2644 push @where, "part_pkg.classnum IS NULL";
2645 #$title .= 'Empty class ';
2646 #@pkg_class = ( '(empty class)' );
2647 } elsif ( $classnum eq '0' ) {
2648 #@pkg_class = qsearch('pkg_class', {} ); # { 'disabled' => '' } );
2649 #push @pkg_class, '(empty class)';
2651 die "illegal classnum";
2657 # parse package report options
2660 my @report_option = ();
2661 if ( exists($params->{'report_option'})
2662 && $params->{'report_option'} =~ /^([,\d]*)$/
2665 @report_option = split(',', $1);
2668 if (@report_option) {
2669 # this will result in the empty set for the dangling comma case as it should
2671 map{ "0 < ( SELECT count(*) FROM part_pkg_option
2672 WHERE part_pkg_option.pkgpart = part_pkg.pkgpart
2673 AND optionname = 'report_option_$_'
2674 AND optionvalue = '1' )"
2684 push @where, "part_pkg.custom = 'Y'" if $params->{custom};
2690 if ( exists($params->{'censustract'}) ) {
2691 $params->{'censustract'} =~ /^([.\d]*)$/;
2692 my $censustract = "cust_main.censustract = '$1'";
2693 $censustract .= ' OR cust_main.censustract is NULL' unless $1;
2694 push @where, "( $censustract )";
2701 if ( ref($params->{'pkgpart'}) ) {
2704 if ( ref($params->{'pkgpart'}) eq 'HASH' ) {
2705 @pkgpart = grep $params->{'pkgpart'}{$_}, keys %{ $params->{'pkgpart'} };
2706 } elsif ( ref($params->{'pkgpart'}) eq 'ARRAY' ) {
2707 @pkgpart = @{ $params->{'pkgpart'} };
2709 die 'unhandled pkgpart ref '. $params->{'pkgpart'};
2712 @pkgpart = grep /^(\d+)$/, @pkgpart;
2714 push @where, 'pkgpart IN ('. join(',', @pkgpart). ')' if scalar(@pkgpart);
2716 } elsif ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
2717 push @where, "pkgpart = $1";
2726 #false laziness w/report_cust_pkg.html
2729 'one-time charge' => { 'last_bill'=>1, 'bill'=>1, 'adjourn'=>1, 'susp'=>1, 'expire'=>1, 'cancel'=>1, },
2730 'active' => { 'susp'=>1, 'cancel'=>1 },
2731 'suspended' => { 'cancel' => 1 },
2736 foreach my $field (qw( setup last_bill bill adjourn susp expire cancel )) {
2738 next unless exists($params->{$field});
2740 my($beginning, $ending) = @{$params->{$field}};
2742 next if $beginning == 0 && $ending == 4294967295;
2745 "cust_pkg.$field IS NOT NULL",
2746 "cust_pkg.$field >= $beginning",
2747 "cust_pkg.$field <= $ending";
2749 $orderby ||= "ORDER BY cust_pkg.$field";
2753 $orderby ||= 'ORDER BY bill';
2756 # parse magic, legacy, etc.
2759 if ( $params->{'magic'} &&
2760 $params->{'magic'} =~ /^(active|inactive|suspended|cancell?ed)$/
2763 $orderby = 'ORDER BY pkgnum';
2765 if ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
2766 push @where, "pkgpart = $1";
2769 } elsif ( $params->{'query'} eq 'pkgnum' ) {
2771 $orderby = 'ORDER BY pkgnum';
2773 } elsif ( $params->{'query'} eq 'APKG_pkgnum' ) {
2775 $orderby = 'ORDER BY pkgnum';
2778 SELECT count(*) FROM pkg_svc
2779 WHERE pkg_svc.pkgpart = cust_pkg.pkgpart
2780 AND pkg_svc.quantity > ( SELECT count(*) FROM cust_svc
2781 WHERE cust_svc.pkgnum = cust_pkg.pkgnum
2782 AND cust_svc.svcpart = pkg_svc.svcpart
2789 # setup queries, links, subs, etc. for the search
2792 # here is the agent virtualization
2793 if ($params->{CurrentUser}) {
2795 qsearchs('access_user', { username => $params->{CurrentUser} });
2798 push @where, $access_user->agentnums_sql('table'=>'cust_main');
2803 push @where, $FS::CurrentUser::CurrentUser->agentnums_sql('table'=>'cust_main');
2806 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
2808 my $addl_from = 'LEFT JOIN cust_main USING ( custnum ) '.
2809 'LEFT JOIN part_pkg USING ( pkgpart ) '.
2810 'LEFT JOIN pkg_class ON ( part_pkg.classnum = pkg_class.classnum ) ';
2812 my $count_query = "SELECT COUNT(*) FROM cust_pkg $addl_from $extra_sql";
2815 'table' => 'cust_pkg',
2817 'select' => join(', ',
2819 ( map "part_pkg.$_", qw( pkg freq ) ),
2820 'pkg_class.classname',
2821 'cust_main.custnum AS cust_main_custnum',
2822 FS::UI::Web::cust_sql_fields(
2823 $params->{'cust_fields'}
2826 'extra_sql' => "$extra_sql $orderby",
2827 'addl_from' => $addl_from,
2828 'count_query' => $count_query,
2835 Returns a list: the first item is an SQL fragment identifying matching
2836 packages/customers via location (taking into account shipping and package
2837 address taxation, if enabled), and subsequent items are the parameters to
2838 substitute for the placeholders in that fragment.
2843 my($class, %opt) = @_;
2844 my $ornull = $opt{'ornull'};
2846 my $conf = new FS::Conf;
2848 # '?' placeholders in _location_sql_where
2849 my $x = $ornull ? 3 : 2;
2850 my @bill_param = ( ('city')x3, ('county')x$x, ('state')x$x, 'country' );
2854 if ( $conf->exists('tax-ship_address') ) {
2857 ( ( ship_last IS NULL OR ship_last = '' )
2858 AND ". _location_sql_where('cust_main', '', $ornull ). "
2860 OR ( ship_last IS NOT NULL AND ship_last != ''
2861 AND ". _location_sql_where('cust_main', 'ship_', $ornull ). "
2864 # AND payby != 'COMP'
2866 @main_param = ( @bill_param, @bill_param );
2870 $main_where = _location_sql_where('cust_main'); # AND payby != 'COMP'
2871 @main_param = @bill_param;
2877 if ( $conf->exists('tax-pkg_address') ) {
2879 my $loc_where = _location_sql_where( 'cust_location', '', $ornull );
2882 ( cust_pkg.locationnum IS NULL AND $main_where )
2883 OR ( cust_pkg.locationnum IS NOT NULL AND $loc_where )
2886 @param = ( @main_param, @bill_param );
2890 $where = $main_where;
2891 @param = @main_param;
2899 #subroutine, helper for location_sql
2900 sub _location_sql_where {
2902 my $prefix = @_ ? shift : '';
2903 my $ornull = @_ ? shift : '';
2905 # $ornull = $ornull ? " OR ( ? IS NULL AND $table.${prefix}county IS NULL ) " : '';
2907 $ornull = $ornull ? ' OR ? IS NULL ' : '';
2909 my $or_empty_city = " OR ( ? = '' AND $table.${prefix}city IS NULL ) ";
2910 my $or_empty_county = " OR ( ? = '' AND $table.${prefix}county IS NULL ) ";
2911 my $or_empty_state = " OR ( ? = '' AND $table.${prefix}state IS NULL ) ";
2913 # ( $table.${prefix}city = ? $or_empty_city $ornull )
2915 ( $table.${prefix}city = ? OR ? = '' OR CAST(? AS text) IS NULL )
2916 AND ( $table.${prefix}county = ? $or_empty_county $ornull )
2917 AND ( $table.${prefix}state = ? $or_empty_state $ornull )
2918 AND $table.${prefix}country = ?
2926 =item order CUSTNUM, PKGPARTS_ARYREF, [ REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF [ REFNUM ] ] ]
2928 CUSTNUM is a customer (see L<FS::cust_main>)
2930 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
2931 L<FS::part_pkg>) to order for this customer. Duplicates are of course
2934 REMOVE_PKGNUMS is an optional list of pkgnums specifying the billing items to
2935 remove for this customer. The services (see L<FS::cust_svc>) are moved to the
2936 new billing items. An error is returned if this is not possible (see
2937 L<FS::pkg_svc>). An empty arrayref is equivalent to not specifying this
2940 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
2941 newly-created cust_pkg objects.
2943 REFNUM, if specified, will specify the FS::pkg_referral record to be created
2944 and inserted. Multiple FS::pkg_referral records can be created by
2945 setting I<refnum> to an array reference of refnums or a hash reference with
2946 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
2947 record will be created corresponding to cust_main.refnum.
2952 my ($custnum, $pkgparts, $remove_pkgnum, $return_cust_pkg, $refnum) = @_;
2954 my $conf = new FS::Conf;
2956 # Transactionize this whole mess
2957 local $SIG{HUP} = 'IGNORE';
2958 local $SIG{INT} = 'IGNORE';
2959 local $SIG{QUIT} = 'IGNORE';
2960 local $SIG{TERM} = 'IGNORE';
2961 local $SIG{TSTP} = 'IGNORE';
2962 local $SIG{PIPE} = 'IGNORE';
2964 my $oldAutoCommit = $FS::UID::AutoCommit;
2965 local $FS::UID::AutoCommit = 0;
2969 # my $cust_main = qsearchs('cust_main', { custnum => $custnum });
2970 # return "Customer not found: $custnum" unless $cust_main;
2972 warn "$me order: pkgnums to remove: ". join(',', @$remove_pkgnum). "\n"
2975 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
2978 my $change = scalar(@old_cust_pkg) != 0;
2981 if ( scalar(@old_cust_pkg) == 1 && scalar(@$pkgparts) == 1 ) {
2983 warn "$me order: changing pkgnum ". $old_cust_pkg[0]->pkgnum.
2984 " to pkgpart ". $pkgparts->[0]. "\n"
2987 my $err_or_cust_pkg =
2988 $old_cust_pkg[0]->change( 'pkgpart' => $pkgparts->[0],
2989 'refnum' => $refnum,
2992 unless (ref($err_or_cust_pkg)) {
2993 $dbh->rollback if $oldAutoCommit;
2994 return $err_or_cust_pkg;
2997 push @$return_cust_pkg, $err_or_cust_pkg;
2998 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3003 # Create the new packages.
3004 foreach my $pkgpart (@$pkgparts) {
3006 warn "$me order: inserting pkgpart $pkgpart\n" if $DEBUG;
3008 my $cust_pkg = new FS::cust_pkg { custnum => $custnum,
3009 pkgpart => $pkgpart,
3013 $error = $cust_pkg->insert( 'change' => $change );
3015 $dbh->rollback if $oldAutoCommit;
3018 push @$return_cust_pkg, $cust_pkg;
3020 # $return_cust_pkg now contains refs to all of the newly
3023 # Transfer services and cancel old packages.
3024 foreach my $old_pkg (@old_cust_pkg) {
3026 warn "$me order: transferring services from pkgnum ". $old_pkg->pkgnum. "\n"
3029 foreach my $new_pkg (@$return_cust_pkg) {
3030 $error = $old_pkg->transfer($new_pkg);
3031 if ($error and $error == 0) {
3032 # $old_pkg->transfer failed.
3033 $dbh->rollback if $oldAutoCommit;
3038 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
3039 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
3040 foreach my $new_pkg (@$return_cust_pkg) {
3041 $error = $old_pkg->transfer($new_pkg, 'change_svcpart'=>1 );
3042 if ($error and $error == 0) {
3043 # $old_pkg->transfer failed.
3044 $dbh->rollback if $oldAutoCommit;
3051 # Transfers were successful, but we went through all of the
3052 # new packages and still had services left on the old package.
3053 # We can't cancel the package under the circumstances, so abort.
3054 $dbh->rollback if $oldAutoCommit;
3055 return "Unable to transfer all services from package ".$old_pkg->pkgnum;
3057 $error = $old_pkg->cancel( quiet=>1 );
3063 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3067 =item bulk_change PKGPARTS_ARYREF, REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF ]
3069 A bulk change method to change packages for multiple customers.
3071 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
3072 L<FS::part_pkg>) to order for each customer. Duplicates are of course
3075 REMOVE_PKGNUMS is an list of pkgnums specifying the billing items to
3076 replace. The services (see L<FS::cust_svc>) are moved to the
3077 new billing items. An error is returned if this is not possible (see
3080 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
3081 newly-created cust_pkg objects.
3086 my ($pkgparts, $remove_pkgnum, $return_cust_pkg) = @_;
3088 # Transactionize this whole mess
3089 local $SIG{HUP} = 'IGNORE';
3090 local $SIG{INT} = 'IGNORE';
3091 local $SIG{QUIT} = 'IGNORE';
3092 local $SIG{TERM} = 'IGNORE';
3093 local $SIG{TSTP} = 'IGNORE';
3094 local $SIG{PIPE} = 'IGNORE';
3096 my $oldAutoCommit = $FS::UID::AutoCommit;
3097 local $FS::UID::AutoCommit = 0;
3101 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
3104 while(scalar(@old_cust_pkg)) {
3106 my $custnum = $old_cust_pkg[0]->custnum;
3107 my (@remove) = map { $_->pkgnum }
3108 grep { $_->custnum == $custnum } @old_cust_pkg;
3109 @old_cust_pkg = grep { $_->custnum != $custnum } @old_cust_pkg;
3111 my $error = order $custnum, $pkgparts, \@remove, \@return;
3113 push @errors, $error
3115 push @$return_cust_pkg, @return;
3118 if (scalar(@errors)) {
3119 $dbh->rollback if $oldAutoCommit;
3120 return join(' / ', @errors);
3123 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3131 sub order is not OO. Perhaps it should be moved to FS::cust_main and made so?
3133 In sub order, the @pkgparts array (passed by reference) is clobbered.
3135 Also in sub order, no money is adjusted. Once FS::part_pkg defines a standard
3136 method to pass dates to the recur_prog expression, it should do so.
3138 FS::svc_acct, FS::svc_domain, FS::svc_www, FS::svc_ip and FS::svc_forward are
3139 loaded via 'use' at compile time, rather than via 'require' in sub { setup,
3140 suspend, unsuspend, cancel } because they use %FS::UID::callback to load
3141 configuration values. Probably need a subroutine which decides what to do
3142 based on whether or not we've fetched the user yet, rather than a hash. See
3143 FS::UID and the TODO.
3145 Now that things are transactional should the check in the insert method be
3150 L<FS::Record>, L<FS::cust_main>, L<FS::part_pkg>, L<FS::cust_svc>,
3151 L<FS::pkg_svc>, schema.html from the base documentation