4 use vars qw(@ISA $disable_agentcheck $DEBUG);
5 use List::Util qw(max);
7 use FS::UID qw( getotaker dbh );
8 use FS::Misc qw( send_email );
9 use FS::Record qw( qsearch qsearchs );
10 use FS::cust_main_Mixin;
16 use FS::cust_bill_pkg;
20 use FS::cust_pkg_reason;
23 # need to 'use' these instead of 'require' in sub { cancel, suspend, unsuspend,
25 # because they load configuration by setting FS::UID::callback (see TODO)
31 # for sending cancel emails in sub cancel
34 @ISA = qw( FS::cust_main_Mixin FS::option_Common FS::Record );
38 $disable_agentcheck = 0;
42 my ( $hashref, $cache ) = @_;
43 #if ( $hashref->{'pkgpart'} ) {
44 if ( $hashref->{'pkg'} ) {
45 # #@{ $self->{'_pkgnum'} } = ();
46 # my $subcache = $cache->subcache('pkgpart', 'part_pkg');
47 # $self->{'_pkgpart'} = $subcache;
48 # #push @{ $self->{'_pkgnum'} },
49 # FS::part_pkg->new_or_cached($hashref, $subcache);
50 $self->{'_pkgpart'} = FS::part_pkg->new($hashref);
52 if ( exists $hashref->{'svcnum'} ) {
53 #@{ $self->{'_pkgnum'} } = ();
54 my $subcache = $cache->subcache('svcnum', 'cust_svc', $hashref->{pkgnum});
55 $self->{'_svcnum'} = $subcache;
56 #push @{ $self->{'_pkgnum'} },
57 FS::cust_svc->new_or_cached($hashref, $subcache) if $hashref->{svcnum};
63 FS::cust_pkg - Object methods for cust_pkg objects
69 $record = new FS::cust_pkg \%hash;
70 $record = new FS::cust_pkg { 'column' => 'value' };
72 $error = $record->insert;
74 $error = $new_record->replace($old_record);
76 $error = $record->delete;
78 $error = $record->check;
80 $error = $record->cancel;
82 $error = $record->suspend;
84 $error = $record->unsuspend;
86 $part_pkg = $record->part_pkg;
88 @labels = $record->labels;
90 $seconds = $record->seconds_since($timestamp);
92 $error = FS::cust_pkg::order( $custnum, \@pkgparts );
93 $error = FS::cust_pkg::order( $custnum, \@pkgparts, \@remove_pkgnums ] );
97 An FS::cust_pkg object represents a customer billing item. FS::cust_pkg
98 inherits from FS::Record. The following fields are currently supported:
102 =item pkgnum - primary key (assigned automatically for new billing items)
104 =item custnum - Customer (see L<FS::cust_main>)
106 =item pkgpart - Billing item definition (see L<FS::part_pkg>)
110 =item bill - date (next bill date)
112 =item last_bill - last bill date
120 =item otaker - order taker (assigned automatically if null, see L<FS::UID>)
122 =item manual_flag - If this field is set to 1, disables the automatic
123 unsuspension of this package when using the B<unsuspendauto> config file.
127 Note: setup, bill, susp, expire and cancel are specified as UNIX timestamps;
128 see L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for
129 conversion functions.
137 Create a new billing item. To add the item to the database, see L<"insert">.
141 sub table { 'cust_pkg'; }
142 sub cust_linked { $_[0]->cust_main_custnum; }
143 sub cust_unlinked_msg {
145 "WARNING: can't find cust_main.custnum ". $self->custnum.
146 ' (cust_pkg.pkgnum '. $self->pkgnum. ')';
149 =item insert [ OPTION => VALUE ... ]
151 Adds this billing item to the database ("Orders" the item). If there is an
152 error, returns the error, otherwise returns false.
154 If the additional field I<promo_code> is defined instead of I<pkgpart>, it
155 will be used to look up the package definition and agent restrictions will be
158 The following options are available: I<change>
160 I<change>, if set true, supresses any referral credit to a referring customer.
165 my( $self, %options ) = @_;
167 local $SIG{HUP} = 'IGNORE';
168 local $SIG{INT} = 'IGNORE';
169 local $SIG{QUIT} = 'IGNORE';
170 local $SIG{TERM} = 'IGNORE';
171 local $SIG{TSTP} = 'IGNORE';
172 local $SIG{PIPE} = 'IGNORE';
174 my $oldAutoCommit = $FS::UID::AutoCommit;
175 local $FS::UID::AutoCommit = 0;
178 my $error = $self->SUPER::insert($options{options} ? %{$options{options}} : ());
180 $dbh->rollback if $oldAutoCommit;
184 #if ( $self->reg_code ) {
185 # my $reg_code = qsearchs('reg_code', { 'code' => $self->reg_code } );
186 # $error = $reg_code->delete;
188 # $dbh->rollback if $oldAutoCommit;
193 my $conf = new FS::Conf;
194 my $cust_main = $self->cust_main;
195 my $part_pkg = $self->part_pkg;
196 if ( $conf->exists('referral_credit')
197 && $cust_main->referral_custnum
198 && ! $options{'change'}
199 && $part_pkg->freq !~ /^0\D?$/
202 my $referring_cust_main = $cust_main->referring_cust_main;
203 if ( $referring_cust_main->status ne 'cancelled' ) {
205 if ( $part_pkg->freq !~ /^\d+$/ ) {
206 warn 'WARNING: Not crediting customer '. $cust_main->referral_custnum.
207 ' for package '. $self->pkgnum.
208 ' ( customer '. $self->custnum. ')'.
209 ' - One-time referral credits not (yet) available for '.
210 ' packages with '. $part_pkg->freq_pretty. ' frequency';
213 my $amount = sprintf( "%.2f", $part_pkg->base_recur / $part_pkg->freq );
215 $referring_cust_main->credit( $amount,
216 'Referral credit for '. $cust_main->name
219 $dbh->rollback if $oldAutoCommit;
220 return "Error crediting customer ". $cust_main->referral_custnum.
221 " for referral: $error";
229 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
236 This method now works but you probably shouldn't use it.
238 You don't want to delete billing items, because there would then be no record
239 the customer ever purchased the item. Instead, see the cancel method.
244 # return "Can't delete cust_pkg records!";
247 =item replace OLD_RECORD
249 Replaces the OLD_RECORD with this one in the database. If there is an error,
250 returns the error, otherwise returns false.
252 Currently, custnum, setup, bill, susp, expire, and cancel may be changed.
254 Changing pkgpart may have disasterous effects. See the order subroutine.
256 setup and bill are normally updated by calling the bill method of a customer
257 object (see L<FS::cust_main>).
259 suspend is normally updated by the suspend and unsuspend methods.
261 cancel is normally updated by the cancel method (and also the order subroutine
269 my( $new, $old, %options ) = @_;
271 # We absolutely have to have an old vs. new record to make this work.
272 if (!defined($old)) {
273 $old = qsearchs( 'cust_pkg', { 'pkgnum' => $new->pkgnum } );
275 #return "Can't (yet?) change pkgpart!" if $old->pkgpart != $new->pkgpart;
276 return "Can't change otaker!" if $old->otaker ne $new->otaker;
279 #return "Can't change setup once it exists!"
280 # if $old->getfield('setup') &&
281 # $old->getfield('setup') != $new->getfield('setup');
283 #some logic for bill, susp, cancel?
285 local($disable_agentcheck) = 1 if $old->pkgpart == $new->pkgpart;
287 local $SIG{HUP} = 'IGNORE';
288 local $SIG{INT} = 'IGNORE';
289 local $SIG{QUIT} = 'IGNORE';
290 local $SIG{TERM} = 'IGNORE';
291 local $SIG{TSTP} = 'IGNORE';
292 local $SIG{PIPE} = 'IGNORE';
294 my $oldAutoCommit = $FS::UID::AutoCommit;
295 local $FS::UID::AutoCommit = 0;
298 if ($options{'reason'} && $new->expire && $old->expire ne $new->expire) {
299 my $error = $new->insert_reason( 'reason' => $options{'reason'},
300 'date' => $new->expire,
303 dbh->rollback if $oldAutoCommit;
304 return "Error inserting cust_pkg_reason: $error";
308 #save off and freeze RADIUS attributes for any associated svc_acct records
310 if ( $old->part_pkg->is_prepaid || $new->part_pkg->is_prepaid ) {
312 #also check for specific exports?
313 # to avoid spurious modify export events
314 @svc_acct = map { $_->svc_x }
315 grep { $_->part_svc->svcdb eq 'svc_acct' }
318 $_->snapshot foreach @svc_acct;
322 my $error = $new->SUPER::replace($old,
323 $options{options} ? ${options{options}} : ()
326 $dbh->rollback if $oldAutoCommit;
330 #for prepaid packages,
331 #trigger export of new RADIUS Expiration attribute when cust_pkg.bill changes
332 foreach my $old_svc_acct ( @svc_acct ) {
333 my $new_svc_acct = new FS::svc_acct { $old_svc_acct->hash };
334 my $s_error = $new_svc_acct->replace($old_svc_acct);
336 $dbh->rollback if $oldAutoCommit;
341 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
348 Checks all fields to make sure this is a valid billing item. If there is an
349 error, returns the error, otherwise returns false. Called by the insert and
358 $self->ut_numbern('pkgnum')
359 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum')
360 || $self->ut_numbern('pkgpart')
361 || $self->ut_numbern('setup')
362 || $self->ut_numbern('bill')
363 || $self->ut_numbern('susp')
364 || $self->ut_numbern('cancel')
366 return $error if $error;
368 if ( $self->reg_code ) {
370 unless ( grep { $self->pkgpart == $_->pkgpart }
371 map { $_->reg_code_pkg }
372 qsearchs( 'reg_code', { 'code' => $self->reg_code,
373 'agentnum' => $self->cust_main->agentnum })
375 return "Unknown registration code";
378 } elsif ( $self->promo_code ) {
381 qsearchs('part_pkg', {
382 'pkgpart' => $self->pkgpart,
383 'promo_code' => { op=>'ILIKE', value=>$self->promo_code },
385 return 'Unknown promotional code' unless $promo_part_pkg;
389 unless ( $disable_agentcheck ) {
391 qsearchs( 'agent', { 'agentnum' => $self->cust_main->agentnum } );
392 my $pkgpart_href = $agent->pkgpart_hashref;
393 return "agent ". $agent->agentnum.
394 " can't purchase pkgpart ". $self->pkgpart
395 unless $pkgpart_href->{ $self->pkgpart };
398 $error = $self->ut_foreign_key('pkgpart', 'part_pkg', 'pkgpart' );
399 return $error if $error;
403 $self->otaker(getotaker) unless $self->otaker;
404 $self->otaker =~ /^([\w\.\-]{0,16})$/ or return "Illegal otaker";
407 if ( $self->dbdef_table->column('manual_flag') ) {
408 $self->manual_flag('') if $self->manual_flag eq ' ';
409 $self->manual_flag =~ /^([01]?)$/
410 or return "Illegal manual_flag ". $self->manual_flag;
411 $self->manual_flag($1);
417 =item cancel [ OPTION => VALUE ... ]
419 Cancels and removes all services (see L<FS::cust_svc> and L<FS::part_svc>)
420 in this package, then cancels the package itself (sets the cancel field to
423 Available options are: I<quiet>
425 I<quiet> can be set true to supress email cancellation notices.
427 If there is an error, returns the error, otherwise returns false.
432 my( $self, %options ) = @_;
435 local $SIG{HUP} = 'IGNORE';
436 local $SIG{INT} = 'IGNORE';
437 local $SIG{QUIT} = 'IGNORE';
438 local $SIG{TERM} = 'IGNORE';
439 local $SIG{TSTP} = 'IGNORE';
440 local $SIG{PIPE} = 'IGNORE';
442 my $oldAutoCommit = $FS::UID::AutoCommit;
443 local $FS::UID::AutoCommit = 0;
446 if ($options{'reason'}) {
447 $error = $self->insert_reason( 'reason' => $options{'reason'} );
449 dbh->rollback if $oldAutoCommit;
450 return "Error inserting cust_pkg_reason: $error";
455 foreach my $cust_svc (
458 sort { $a->[1] <=> $b->[1] }
459 map { [ $_, $_->svc_x->table_info->{'cancel_weight'} ]; }
460 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
463 my $error = $cust_svc->cancel;
466 $dbh->rollback if $oldAutoCommit;
467 return "Error cancelling cust_svc: $error";
471 # Add a credit for remaining service
472 my $remaining_value = $self->calc_remain();
473 if ( $remaining_value > 0 ) {
474 my $error = $self->cust_main->credit(
476 'Credit for unused time on '. $self->part_pkg->pkg,
479 $dbh->rollback if $oldAutoCommit;
480 return "Error crediting customer \$$remaining_value for unused time on".
481 $self->part_pkg->pkg. ": $error";
485 unless ( $self->getfield('cancel') ) {
486 my %hash = $self->hash;
487 $hash{'cancel'} = time;
488 my $new = new FS::cust_pkg ( \%hash );
489 $error = $new->replace( $self, options => { $self->options } );
491 $dbh->rollback if $oldAutoCommit;
496 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
498 my $conf = new FS::Conf;
499 my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ } $self->cust_main->invoicing_list;
500 if ( !$options{'quiet'} && $conf->exists('emailcancel') && @invoicing_list ) {
501 my $conf = new FS::Conf;
502 my $error = send_email(
503 'from' => $conf->config('invoice_from'),
504 'to' => \@invoicing_list,
505 'subject' => $conf->config('cancelsubject'),
506 'body' => [ map "$_\n", $conf->config('cancelmessage') ],
508 #should this do something on errors?
517 Suspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
518 package, then suspends the package itself (sets the susp field to now).
520 If there is an error, returns the error, otherwise returns false.
525 my( $self, %options ) = @_;
528 local $SIG{HUP} = 'IGNORE';
529 local $SIG{INT} = 'IGNORE';
530 local $SIG{QUIT} = 'IGNORE';
531 local $SIG{TERM} = 'IGNORE';
532 local $SIG{TSTP} = 'IGNORE';
533 local $SIG{PIPE} = 'IGNORE';
535 my $oldAutoCommit = $FS::UID::AutoCommit;
536 local $FS::UID::AutoCommit = 0;
539 if ($options{'reason'}) {
540 $error = $self->insert_reason( 'reason' => $options{'reason'} );
542 dbh->rollback if $oldAutoCommit;
543 return "Error inserting cust_pkg_reason: $error";
547 foreach my $cust_svc (
548 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
550 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
552 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
553 $dbh->rollback if $oldAutoCommit;
554 return "Illegal svcdb value in part_svc!";
557 require "FS/$svcdb.pm";
559 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
561 $error = $svc->suspend;
563 $dbh->rollback if $oldAutoCommit;
570 unless ( $self->getfield('susp') ) {
571 my %hash = $self->hash;
572 $hash{'susp'} = time;
573 my $new = new FS::cust_pkg ( \%hash );
574 $error = $new->replace( $self, options => { $self->options } );
576 $dbh->rollback if $oldAutoCommit;
581 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
586 =item unsuspend [ OPTION => VALUE ... ]
588 Unsuspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
589 package, then unsuspends the package itself (clears the susp field).
591 Available options are: I<adjust_next_bill>.
593 I<adjust_next_bill> can be set true to adjust the next bill date forward by
594 the amount of time the account was inactive. This was set true by default
595 since 1.4.2 and 1.5.0pre6; however, starting with 1.7.0 this needs to be
596 explicitly requested. Price plans for which this makes sense (anniversary-date
597 based than prorate or subscription) could have an option to enable this
600 If there is an error, returns the error, otherwise returns false.
605 my( $self, %opt ) = @_;
608 local $SIG{HUP} = 'IGNORE';
609 local $SIG{INT} = 'IGNORE';
610 local $SIG{QUIT} = 'IGNORE';
611 local $SIG{TERM} = 'IGNORE';
612 local $SIG{TSTP} = 'IGNORE';
613 local $SIG{PIPE} = 'IGNORE';
615 my $oldAutoCommit = $FS::UID::AutoCommit;
616 local $FS::UID::AutoCommit = 0;
619 foreach my $cust_svc (
620 qsearch('cust_svc',{'pkgnum'=> $self->pkgnum } )
622 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
624 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
625 $dbh->rollback if $oldAutoCommit;
626 return "Illegal svcdb value in part_svc!";
629 require "FS/$svcdb.pm";
631 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
633 $error = $svc->unsuspend;
635 $dbh->rollback if $oldAutoCommit;
642 unless ( ! $self->getfield('susp') ) {
643 my %hash = $self->hash;
644 my $inactive = time - $hash{'susp'};
646 my $conf = new FS::Conf;
648 $hash{'bill'} = ( $hash{'bill'} || $hash{'setup'} ) + $inactive
649 if ( $opt{'adjust_next_bill'}
650 || $conf->config('unsuspend-always_adjust_next_bill_date') )
651 && $inactive > 0 && ( $hash{'bill'} || $hash{'setup'} );
654 my $new = new FS::cust_pkg ( \%hash );
655 $error = $new->replace( $self, options => { $self->options } );
657 $dbh->rollback if $oldAutoCommit;
662 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
669 Returns the last bill date, or if there is no last bill date, the setup date.
670 Useful for billing metered services.
676 if ( $self->dbdef_table->column('last_bill') ) {
677 return $self->setfield('last_bill', $_[0]) if @_;
678 return $self->getfield('last_bill') if $self->getfield('last_bill');
680 my $cust_bill_pkg = qsearchs('cust_bill_pkg', { 'pkgnum' => $self->pkgnum,
681 'edate' => $self->bill, } );
682 $cust_bill_pkg ? $cust_bill_pkg->sdate : $self->setup || 0;
687 Returns the most recent FS::reason associated with the package.
693 my $cust_pkg_reason = qsearchs( {
694 'table' => 'cust_pkg_reason',
695 'hashref' => { 'pkgnum' => $self->pkgnum, },
696 'extra_sql'=> 'ORDER BY date DESC LIMIT 1',
698 qsearchs ( 'reason', { 'reasonnum' => $cust_pkg_reason->reasonnum } )
704 Returns the definition for this billing item, as an FS::part_pkg object (see
711 #exists( $self->{'_pkgpart'} )
713 ? $self->{'_pkgpart'}
714 : qsearchs( 'part_pkg', { 'pkgpart' => $self->pkgpart } );
719 Calls the I<calc_setup> of the FS::part_pkg object associated with this billing
726 $self->part_pkg->calc_setup($self, @_);
731 Calls the I<calc_recur> of the FS::part_pkg object associated with this billing
738 $self->part_pkg->calc_recur($self, @_);
743 Calls the I<calc_remain> of the FS::part_pkg object associated with this
750 $self->part_pkg->calc_remain($self, @_);
755 Calls the I<calc_cancel> of the FS::part_pkg object associated with this
762 $self->part_pkg->calc_cancel($self, @_);
767 Returns any invoice line items for this package (see L<FS::cust_bill_pkg>).
773 qsearch( 'cust_bill_pkg', { 'pkgnum' => $self->pkgnum } );
776 =item cust_svc [ SVCPART ]
778 Returns the services for this package, as FS::cust_svc objects (see
779 L<FS::cust_svc>). If a svcpart is specified, return only the matching
788 return qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum,
789 'svcpart' => shift, } );
792 #if ( $self->{'_svcnum'} ) {
793 # values %{ $self->{'_svcnum'}->cache };
795 $self->_sort_cust_svc(
796 [ qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } ) ]
802 =item h_cust_svc END_TIMESTAMP [ START_TIMESTAMP ]
804 Returns historical services for this package created before END TIMESTAMP and
805 (optionally) not cancelled before START_TIMESTAMP, as FS::h_cust_svc objects
806 (see L<FS::h_cust_svc>).
813 $self->_sort_cust_svc(
814 [ qsearch( 'h_cust_svc',
815 { 'pkgnum' => $self->pkgnum, },
816 FS::h_cust_svc->sql_h_search(@_),
823 my( $self, $arrayref ) = @_;
826 sort { $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] }
828 my $pkg_svc = qsearchs( 'pkg_svc', { 'pkgpart' => $self->pkgpart,
829 'svcpart' => $_->svcpart } );
831 $pkg_svc ? $pkg_svc->primary_svc : '',
832 $pkg_svc ? $pkg_svc->quantity : 0,
839 =item num_cust_svc [ SVCPART ]
841 Returns the number of provisioned services for this package. If a svcpart is
842 specified, counts only the matching services.
848 my $sql = 'SELECT COUNT(*) FROM cust_svc WHERE pkgnum = ?';
849 $sql .= ' AND svcpart = ?' if @_;
850 my $sth = dbh->prepare($sql) or die dbh->errstr;
851 $sth->execute($self->pkgnum, @_) or die $sth->errstr;
852 $sth->fetchrow_arrayref->[0];
855 =item available_part_svc
857 Returns a list of FS::part_svc objects representing services included in this
858 package but not yet provisioned. Each FS::part_svc object also has an extra
859 field, I<num_avail>, which specifies the number of available services.
863 sub available_part_svc {
865 grep { $_->num_avail > 0 }
867 my $part_svc = $_->part_svc;
868 $part_svc->{'Hash'}{'num_avail'} = #evil encapsulation-breaking
869 $_->quantity - $self->num_cust_svc($_->svcpart);
872 $self->part_pkg->pkg_svc;
877 Returns a list of FS::part_svc objects representing provisioned and available
878 services included in this package. Each FS::part_svc object also has the
879 following extra fields:
883 =item num_cust_svc (count)
885 =item num_avail (quantity - count)
887 =item cust_pkg_svc (services) - array reference containing the provisioned services, as cust_svc objects
890 label -> ($cust_svc->label)[1]
899 #XXX some sort of sort order besides numeric by svcpart...
900 my @part_svc = sort { $a->svcpart <=> $b->svcpart } map {
902 my $part_svc = $pkg_svc->part_svc;
903 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
904 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #more evil
905 $part_svc->{'Hash'}{'num_avail'} =
906 max( 0, $pkg_svc->quantity - $num_cust_svc );
907 $part_svc->{'Hash'}{'cust_pkg_svc'} = [ $self->cust_svc($part_svc->svcpart) ];
909 } $self->part_pkg->pkg_svc;
912 push @part_svc, map {
914 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
915 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #speak no evail
916 $part_svc->{'Hash'}{'num_avail'} = 0; #0-$num_cust_svc ?
917 $part_svc->{'Hash'}{'cust_pkg_svc'} = [ $self->cust_svc($part_svc->svcpart) ];
919 } $self->extra_part_svc;
927 Returns a list of FS::part_svc objects corresponding to services in this
928 package which are still provisioned but not (any longer) available in the
936 my $pkgnum = $self->pkgnum;
937 my $pkgpart = $self->pkgpart;
940 'table' => 'part_svc',
942 'extra_sql' => "WHERE 0 = ( SELECT COUNT(*) FROM pkg_svc
943 WHERE pkg_svc.svcpart = part_svc.svcpart
944 AND pkg_svc.pkgpart = $pkgpart
947 AND 0 < ( SELECT count(*)
949 LEFT JOIN cust_pkg using ( pkgnum )
950 WHERE cust_svc.svcpart = part_svc.svcpart
958 Returns a short status string for this package, currently:
964 =item one-time charge
979 my $freq = length($self->freq) ? $self->freq : $self->part_pkg->freq;
981 return 'cancelled' if $self->get('cancel');
982 return 'suspended' if $self->susp;
983 return 'not yet billed' unless $self->setup;
984 return 'one-time charge' if $freq =~ /^(0|$)/;
990 Class method that returns the list of possible status strings for pacakges
991 (see L<the status method|/status>). For example:
993 @statuses = FS::cust_pkg->statuses();
997 tie my %statuscolor, 'Tie::IxHash',
998 'not yet billed' => '000000',
999 'one-time charge' => '000000',
1000 'active' => '00CC00',
1001 'suspended' => 'FF9900',
1002 'cancelled' => 'FF0000',
1006 my $self = shift; #could be class...
1007 grep { $_ !~ /^(not yet billed)$/ } #this is a dumb status anyway
1008 # mayble split btw one-time vs. recur
1014 Returns a hex triplet color string for this package's status.
1020 $statuscolor{$self->status};
1025 Returns a list of lists, calling the label method for all services
1026 (see L<FS::cust_svc>) of this billing item.
1032 map { [ $_->label ] } $self->cust_svc;
1035 =item h_labels END_TIMESTAMP [ START_TIMESTAMP ]
1037 Like the labels method, but returns historical information on services that
1038 were active as of END_TIMESTAMP and (optionally) not cancelled before
1041 Returns a list of lists, calling the label method for all (historical) services
1042 (see L<FS::h_cust_svc>) of this billing item.
1048 map { [ $_->label(@_) ] } $self->h_cust_svc(@_);
1051 =item h_labels_short END_TIMESTAMP [ START_TIMESTAMP ]
1053 Like h_labels, except returns a simple flat list, and shortens long
1054 (currently >5) lists of identical services to one line that lists the service
1055 label and the number of individual services rather than individual items.
1059 sub h_labels_short {
1063 #tie %labels, 'Tie::IxHash';
1064 push @{ $labels{$_->[0]} }, $_->[1]
1065 foreach $self->h_labels(@_);
1067 foreach my $label ( keys %labels ) {
1068 my @values = @{ $labels{$label} };
1069 my $num = scalar(@values);
1071 push @labels, "$label ($num)";
1073 push @labels, map { "$label: $_" } @values;
1083 Returns the parent customer object (see L<FS::cust_main>).
1089 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
1092 =item seconds_since TIMESTAMP
1094 Returns the number of seconds all accounts (see L<FS::svc_acct>) in this
1095 package have been online since TIMESTAMP, according to the session monitor.
1097 TIMESTAMP is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
1098 L<Time::Local> and L<Date::Parse> for conversion functions.
1103 my($self, $since) = @_;
1106 foreach my $cust_svc (
1107 grep { $_->part_svc->svcdb eq 'svc_acct' } $self->cust_svc
1109 $seconds += $cust_svc->seconds_since($since);
1116 =item seconds_since_sqlradacct TIMESTAMP_START TIMESTAMP_END
1118 Returns the numbers of seconds all accounts (see L<FS::svc_acct>) in this
1119 package have been online between TIMESTAMP_START (inclusive) and TIMESTAMP_END
1122 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
1123 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
1129 sub seconds_since_sqlradacct {
1130 my($self, $start, $end) = @_;
1134 foreach my $cust_svc (
1136 my $part_svc = $_->part_svc;
1137 $part_svc->svcdb eq 'svc_acct'
1138 && scalar($part_svc->part_export('sqlradius'));
1141 $seconds += $cust_svc->seconds_since_sqlradacct($start, $end);
1148 =item attribute_since_sqlradacct TIMESTAMP_START TIMESTAMP_END ATTRIBUTE
1150 Returns the sum of the given attribute for all accounts (see L<FS::svc_acct>)
1151 in this package for sessions ending between TIMESTAMP_START (inclusive) and
1155 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
1156 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
1161 sub attribute_since_sqlradacct {
1162 my($self, $start, $end, $attrib) = @_;
1166 foreach my $cust_svc (
1168 my $part_svc = $_->part_svc;
1169 $part_svc->svcdb eq 'svc_acct'
1170 && scalar($part_svc->part_export('sqlradius'));
1173 $sum += $cust_svc->attribute_since_sqlradacct($start, $end, $attrib);
1180 =item transfer DEST_PKGNUM | DEST_CUST_PKG, [ OPTION => VALUE ... ]
1182 Transfers as many services as possible from this package to another package.
1184 The destination package can be specified by pkgnum by passing an FS::cust_pkg
1185 object. The destination package must already exist.
1187 Services are moved only if the destination allows services with the correct
1188 I<svcpart> (not svcdb), unless the B<change_svcpart> option is set true. Use
1189 this option with caution! No provision is made for export differences
1190 between the old and new service definitions. Probably only should be used
1191 when your exports for all service definitions of a given svcdb are identical.
1192 (attempt a transfer without it first, to move all possible svcpart-matching
1195 Any services that can't be moved remain in the original package.
1197 Returns an error, if there is one; otherwise, returns the number of services
1198 that couldn't be moved.
1203 my ($self, $dest_pkgnum, %opt) = @_;
1209 if (ref ($dest_pkgnum) eq 'FS::cust_pkg') {
1210 $dest = $dest_pkgnum;
1211 $dest_pkgnum = $dest->pkgnum;
1213 $dest = qsearchs('cust_pkg', { pkgnum => $dest_pkgnum });
1216 return ('Package does not exist: '.$dest_pkgnum) unless $dest;
1218 foreach my $pkg_svc ( $dest->part_pkg->pkg_svc ) {
1219 $target{$pkg_svc->svcpart} = $pkg_svc->quantity;
1222 foreach my $cust_svc ($dest->cust_svc) {
1223 $target{$cust_svc->svcpart}--;
1226 my %svcpart2svcparts = ();
1227 if ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
1228 warn "change_svcpart option received, creating alternates list\n" if $DEBUG;
1229 foreach my $svcpart ( map { $_->svcpart } $self->cust_svc ) {
1230 next if exists $svcpart2svcparts{$svcpart};
1231 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
1232 $svcpart2svcparts{$svcpart} = [
1234 sort { $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] }
1236 my $pkg_svc = qsearchs( 'pkg_svc', { 'pkgpart' => $dest->pkgpart,
1237 'svcpart' => $_ } );
1239 $pkg_svc ? $pkg_svc->primary_svc : '',
1240 $pkg_svc ? $pkg_svc->quantity : 0,
1244 grep { $_ != $svcpart }
1246 qsearch('part_svc', { 'svcdb' => $part_svc->svcdb } )
1248 warn "alternates for svcpart $svcpart: ".
1249 join(', ', @{$svcpart2svcparts{$svcpart}}). "\n"
1254 foreach my $cust_svc ($self->cust_svc) {
1255 if($target{$cust_svc->svcpart} > 0) {
1256 $target{$cust_svc->svcpart}--;
1257 my $new = new FS::cust_svc {
1258 svcnum => $cust_svc->svcnum,
1259 svcpart => $cust_svc->svcpart,
1260 pkgnum => $dest_pkgnum,
1262 my $error = $new->replace($cust_svc);
1263 return $error if $error;
1264 } elsif ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
1266 warn "looking for alternates for svcpart ". $cust_svc->svcpart. "\n";
1267 warn "alternates to consider: ".
1268 join(', ', @{$svcpart2svcparts{$cust_svc->svcpart}}). "\n";
1270 my @alternate = grep {
1271 warn "considering alternate svcpart $_: ".
1272 "$target{$_} available in new package\n"
1275 } @{$svcpart2svcparts{$cust_svc->svcpart}};
1277 warn "alternate(s) found\n" if $DEBUG;
1278 my $change_svcpart = $alternate[0];
1279 $target{$change_svcpart}--;
1280 my $new = new FS::cust_svc {
1281 svcnum => $cust_svc->svcnum,
1282 svcpart => $change_svcpart,
1283 pkgnum => $dest_pkgnum,
1285 my $error = $new->replace($cust_svc);
1286 return $error if $error;
1299 This method is deprecated. See the I<depend_jobnum> option to the insert and
1300 order_pkgs methods in FS::cust_main for a better way to defer provisioning.
1307 local $SIG{HUP} = 'IGNORE';
1308 local $SIG{INT} = 'IGNORE';
1309 local $SIG{QUIT} = 'IGNORE';
1310 local $SIG{TERM} = 'IGNORE';
1311 local $SIG{TSTP} = 'IGNORE';
1312 local $SIG{PIPE} = 'IGNORE';
1314 my $oldAutoCommit = $FS::UID::AutoCommit;
1315 local $FS::UID::AutoCommit = 0;
1318 foreach my $cust_svc ( $self->cust_svc ) {
1319 #false laziness w/svc_Common::insert
1320 my $svc_x = $cust_svc->svc_x;
1321 foreach my $part_export ( $cust_svc->part_svc->part_export ) {
1322 my $error = $part_export->export_insert($svc_x);
1324 $dbh->rollback if $oldAutoCommit;
1330 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1337 =head1 CLASS METHODS
1343 Returns an SQL expression identifying recurring packages.
1347 sub recurring_sql { "
1348 '0' != ( select freq from part_pkg
1349 where cust_pkg.pkgpart = part_pkg.pkgpart )
1354 Returns an SQL expression identifying one-time packages.
1359 '0' = ( select freq from part_pkg
1360 where cust_pkg.pkgpart = part_pkg.pkgpart )
1365 Returns an SQL expression identifying active packages.
1370 ". $_[0]->recurring_sql(). "
1371 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
1372 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
1377 Returns an SQL expression identifying inactive packages (one-time packages
1378 that are otherwise unsuspended/uncancelled).
1382 sub inactive_sql { "
1383 ". $_[0]->onetime_sql(). "
1384 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
1385 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
1391 Returns an SQL expression identifying suspended packages.
1395 sub suspended_sql { susp_sql(@_); }
1397 #$_[0]->recurring_sql(). ' AND '.
1399 ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
1400 AND cust_pkg.susp IS NOT NULL AND cust_pkg.susp != 0
1407 Returns an SQL exprression identifying cancelled packages.
1411 sub cancelled_sql { cancel_sql(@_); }
1413 #$_[0]->recurring_sql(). ' AND '.
1414 "cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0";
1421 =item order CUSTNUM, PKGPARTS_ARYREF, [ REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF ] ]
1423 CUSTNUM is a customer (see L<FS::cust_main>)
1425 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
1426 L<FS::part_pkg>) to order for this customer. Duplicates are of course
1429 REMOVE_PKGNUMS is an optional list of pkgnums specifying the billing items to
1430 remove for this customer. The services (see L<FS::cust_svc>) are moved to the
1431 new billing items. An error is returned if this is not possible (see
1432 L<FS::pkg_svc>). An empty arrayref is equivalent to not specifying this
1435 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
1436 newly-created cust_pkg objects.
1441 my ($custnum, $pkgparts, $remove_pkgnum, $return_cust_pkg) = @_;
1443 my $conf = new FS::Conf;
1445 # Transactionize this whole mess
1446 local $SIG{HUP} = 'IGNORE';
1447 local $SIG{INT} = 'IGNORE';
1448 local $SIG{QUIT} = 'IGNORE';
1449 local $SIG{TERM} = 'IGNORE';
1450 local $SIG{TSTP} = 'IGNORE';
1451 local $SIG{PIPE} = 'IGNORE';
1453 my $oldAutoCommit = $FS::UID::AutoCommit;
1454 local $FS::UID::AutoCommit = 0;
1458 my $cust_main = qsearchs('cust_main', { custnum => $custnum });
1459 return "Customer not found: $custnum" unless $cust_main;
1461 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
1464 my $change = scalar(@old_cust_pkg) != 0;
1467 if ( scalar(@old_cust_pkg) == 1 ) {
1468 #$hash{$_} = $old_cust_pkg[0]->$_() foreach qw( last_bill bill );
1469 $hash{'setup'} = time;
1472 # Create the new packages.
1473 foreach my $pkgpart (@$pkgparts) {
1474 my $cust_pkg = new FS::cust_pkg { custnum => $custnum,
1475 pkgpart => $pkgpart,
1478 $error = $cust_pkg->insert( 'change' => $change );
1480 $dbh->rollback if $oldAutoCommit;
1483 push @$return_cust_pkg, $cust_pkg;
1485 # $return_cust_pkg now contains refs to all of the newly
1488 # Transfer services and cancel old packages.
1489 foreach my $old_pkg (@old_cust_pkg) {
1491 foreach my $new_pkg (@$return_cust_pkg) {
1492 $error = $old_pkg->transfer($new_pkg);
1493 if ($error and $error == 0) {
1494 # $old_pkg->transfer failed.
1495 $dbh->rollback if $oldAutoCommit;
1500 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
1501 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
1502 foreach my $new_pkg (@$return_cust_pkg) {
1503 $error = $old_pkg->transfer($new_pkg, 'change_svcpart'=>1 );
1504 if ($error and $error == 0) {
1505 # $old_pkg->transfer failed.
1506 $dbh->rollback if $oldAutoCommit;
1513 # Transfers were successful, but we went through all of the
1514 # new packages and still had services left on the old package.
1515 # We can't cancel the package under the circumstances, so abort.
1516 $dbh->rollback if $oldAutoCommit;
1517 return "Unable to transfer all services from package ".$old_pkg->pkgnum;
1519 $error = $old_pkg->cancel( quiet=>1 );
1525 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1530 my ($self, %options) = @_;
1532 my $otaker = $FS::CurrentUser::CurrentUser->name;
1533 $otaker = $FS::CurrentUser::CurrentUser->username
1534 if (($otaker) eq "User, Legacy");
1536 my $cust_pkg_reason =
1537 new FS::cust_pkg_reason({ 'pkgnum' => $self->pkgnum,
1538 'reasonnum' => $options{'reason'},
1539 'otaker' => $otaker,
1540 'date' => $options{'date'}
1544 return $cust_pkg_reason->insert;
1547 =item set_usage USAGE_VALUE_HASHREF
1549 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
1550 to which they should be set (see L<FS::svc_acct>). Currently seconds,
1551 upbytes, downbytes, and totalbytes are appropriate keys.
1553 All svc_accts which are part of this package have their values reset.
1558 my ($self, $valueref) = @_;
1560 foreach my $cust_svc ($self->cust_svc){
1561 my $svc_x = $cust_svc->svc_x;
1562 $svc_x->set_usage($valueref)
1563 if $svc_x->can("set_usage");
1571 sub order is not OO. Perhaps it should be moved to FS::cust_main and made so?
1573 In sub order, the @pkgparts array (passed by reference) is clobbered.
1575 Also in sub order, no money is adjusted. Once FS::part_pkg defines a standard
1576 method to pass dates to the recur_prog expression, it should do so.
1578 FS::svc_acct, FS::svc_domain, FS::svc_www, FS::svc_ip and FS::svc_forward are
1579 loaded via 'use' at compile time, rather than via 'require' in sub { setup,
1580 suspend, unsuspend, cancel } because they use %FS::UID::callback to load
1581 configuration values. Probably need a subroutine which decides what to do
1582 based on whether or not we've fetched the user yet, rather than a hash. See
1583 FS::UID and the TODO.
1585 Now that things are transactional should the check in the insert method be
1590 L<FS::Record>, L<FS::cust_main>, L<FS::part_pkg>, L<FS::cust_svc>,
1591 L<FS::pkg_svc>, schema.html from the base documentation