4 use vars qw(@ISA $disable_agentcheck @SVCDB_CANCEL_SEQ $DEBUG);
6 use FS::UID qw( getotaker dbh );
7 use FS::Misc qw( send_email );
8 use FS::Record qw( qsearch qsearchs );
9 use FS::cust_main_Mixin;
15 use FS::cust_bill_pkg;
18 use FS::cust_pkg_reason;
20 # need to 'use' these instead of 'require' in sub { cancel, suspend, unsuspend,
22 # because they load configuration by setting FS::UID::callback (see TODO)
28 # for sending cancel emails in sub cancel
31 @ISA = qw( FS::cust_main_Mixin FS::Record );
35 $disable_agentcheck = 0;
37 # The order in which to unprovision services.
38 @SVCDB_CANCEL_SEQ = qw( svc_external
47 my ( $hashref, $cache ) = @_;
48 #if ( $hashref->{'pkgpart'} ) {
49 if ( $hashref->{'pkg'} ) {
50 # #@{ $self->{'_pkgnum'} } = ();
51 # my $subcache = $cache->subcache('pkgpart', 'part_pkg');
52 # $self->{'_pkgpart'} = $subcache;
53 # #push @{ $self->{'_pkgnum'} },
54 # FS::part_pkg->new_or_cached($hashref, $subcache);
55 $self->{'_pkgpart'} = FS::part_pkg->new($hashref);
57 if ( exists $hashref->{'svcnum'} ) {
58 #@{ $self->{'_pkgnum'} } = ();
59 my $subcache = $cache->subcache('svcnum', 'cust_svc', $hashref->{pkgnum});
60 $self->{'_svcnum'} = $subcache;
61 #push @{ $self->{'_pkgnum'} },
62 FS::cust_svc->new_or_cached($hashref, $subcache) if $hashref->{svcnum};
68 FS::cust_pkg - Object methods for cust_pkg objects
74 $record = new FS::cust_pkg \%hash;
75 $record = new FS::cust_pkg { 'column' => 'value' };
77 $error = $record->insert;
79 $error = $new_record->replace($old_record);
81 $error = $record->delete;
83 $error = $record->check;
85 $error = $record->cancel;
87 $error = $record->suspend;
89 $error = $record->unsuspend;
91 $part_pkg = $record->part_pkg;
93 @labels = $record->labels;
95 $seconds = $record->seconds_since($timestamp);
97 $error = FS::cust_pkg::order( $custnum, \@pkgparts );
98 $error = FS::cust_pkg::order( $custnum, \@pkgparts, \@remove_pkgnums ] );
102 An FS::cust_pkg object represents a customer billing item. FS::cust_pkg
103 inherits from FS::Record. The following fields are currently supported:
107 =item pkgnum - primary key (assigned automatically for new billing items)
109 =item custnum - Customer (see L<FS::cust_main>)
111 =item pkgpart - Billing item definition (see L<FS::part_pkg>)
115 =item bill - date (next bill date)
117 =item last_bill - last bill date
125 =item otaker - order taker (assigned automatically if null, see L<FS::UID>)
127 =item manual_flag - If this field is set to 1, disables the automatic
128 unsuspension of this package when using the B<unsuspendauto> config file.
132 Note: setup, bill, susp, expire and cancel are specified as UNIX timestamps;
133 see L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for
134 conversion functions.
142 Create a new billing item. To add the item to the database, see L<"insert">.
146 sub table { 'cust_pkg'; }
147 sub cust_linked { $_[0]->cust_main_custnum; }
148 sub cust_unlinked_msg {
150 "WARNING: can't find cust_main.custnum ". $self->custnum.
151 ' (cust_pkg.pkgnum '. $self->pkgnum. ')';
154 =item insert [ OPTION => VALUE ... ]
156 Adds this billing item to the database ("Orders" the item). If there is an
157 error, returns the error, otherwise returns false.
159 If the additional field I<promo_code> is defined instead of I<pkgpart>, it
160 will be used to look up the package definition and agent restrictions will be
163 The following options are available: I<change>
165 I<change>, if set true, supresses any referral credit to a referring customer.
170 my( $self, %options ) = @_;
172 local $SIG{HUP} = 'IGNORE';
173 local $SIG{INT} = 'IGNORE';
174 local $SIG{QUIT} = 'IGNORE';
175 local $SIG{TERM} = 'IGNORE';
176 local $SIG{TSTP} = 'IGNORE';
177 local $SIG{PIPE} = 'IGNORE';
179 my $oldAutoCommit = $FS::UID::AutoCommit;
180 local $FS::UID::AutoCommit = 0;
183 my $error = $self->SUPER::insert;
185 $dbh->rollback if $oldAutoCommit;
189 #if ( $self->reg_code ) {
190 # my $reg_code = qsearchs('reg_code', { 'code' => $self->reg_code } );
191 # $error = $reg_code->delete;
193 # $dbh->rollback if $oldAutoCommit;
198 my $conf = new FS::Conf;
199 my $cust_main = $self->cust_main;
200 my $part_pkg = $self->part_pkg;
201 if ( $conf->exists('referral_credit')
202 && $cust_main->referral_custnum
203 && ! $options{'change'}
204 && $part_pkg->freq !~ /^0\D?$/
207 my $referring_cust_main = $cust_main->referring_cust_main;
208 if ( $referring_cust_main->status ne 'cancelled' ) {
210 if ( $part_pkg->freq !~ /^\d+$/ ) {
211 warn 'WARNING: Not crediting customer '. $cust_main->referral_custnum.
212 ' for package '. $self->pkgnum.
213 ' ( customer '. $self->custnum. ')'.
214 ' - One-time referral credits not (yet) available for '.
215 ' packages with '. $part_pkg->freq_pretty. ' frequency';
218 my $amount = sprintf( "%.2f", $part_pkg->base_recur / $part_pkg->freq );
220 $referring_cust_main->credit( $amount,
221 'Referral credit for '. $cust_main->name
224 $dbh->rollback if $oldAutoCommit;
225 return "Error crediting customer ". $cust_main->referral_custnum.
226 " for referral: $error";
234 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
241 This method now works but you probably shouldn't use it.
243 You don't want to delete billing items, because there would then be no record
244 the customer ever purchased the item. Instead, see the cancel method.
249 # return "Can't delete cust_pkg records!";
252 =item replace OLD_RECORD
254 Replaces the OLD_RECORD with this one in the database. If there is an error,
255 returns the error, otherwise returns false.
257 Currently, custnum, setup, bill, susp, expire, and cancel may be changed.
259 Changing pkgpart may have disasterous effects. See the order subroutine.
261 setup and bill are normally updated by calling the bill method of a customer
262 object (see L<FS::cust_main>).
264 suspend is normally updated by the suspend and unsuspend methods.
266 cancel is normally updated by the cancel method (and also the order subroutine
274 my( $new, $old, %options ) = @_;
276 #return "Can't (yet?) change pkgpart!" if $old->pkgpart != $new->pkgpart;
277 return "Can't change otaker!" if $old->otaker ne $new->otaker;
280 #return "Can't change setup once it exists!"
281 # if $old->getfield('setup') &&
282 # $old->getfield('setup') != $new->getfield('setup');
284 #some logic for bill, susp, cancel?
286 local($disable_agentcheck) = 1 if $old->pkgpart == $new->pkgpart;
288 local $SIG{HUP} = 'IGNORE';
289 local $SIG{INT} = 'IGNORE';
290 local $SIG{QUIT} = 'IGNORE';
291 local $SIG{TERM} = 'IGNORE';
292 local $SIG{TSTP} = 'IGNORE';
293 local $SIG{PIPE} = 'IGNORE';
295 my $oldAutoCommit = $FS::UID::AutoCommit;
296 local $FS::UID::AutoCommit = 0;
299 if ($options{'reason'} && $new->expire && $old->expire ne $new->expire) {
300 my $error = $new->insert_reason( 'reason' => $options{'reason'},
301 'date' => $new->expire,
304 dbh->rollback if $oldAutoCommit;
305 return "Error inserting cust_pkg_reason: $error";
309 #save off and freeze RADIUS attributes for any associated svc_acct records
311 if ( $old->part_pkg->is_prepaid || $new->part_pkg->is_prepaid ) {
313 #also check for specific exports?
314 # to avoid spurious modify export events
315 @svc_acct = map { $_->svc_x }
316 grep { $_->part_svc->svcdb eq 'svc_acct' }
319 $_->snapshot foreach @svc_acct;
323 my $error = $new->SUPER::replace($old);
325 $dbh->rollback if $oldAutoCommit;
329 #for prepaid packages,
330 #trigger export of new RADIUS Expiration attribute when cust_pkg.bill changes
331 foreach my $old_svc_acct ( @svc_acct ) {
332 my $new_svc_acct = new FS::svc_acct { $old_svc_acct->hash };
333 my $s_error = $new_svc_acct->replace($old_svc_acct);
335 $dbh->rollback if $oldAutoCommit;
340 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
347 Checks all fields to make sure this is a valid billing item. If there is an
348 error, returns the error, otherwise returns false. Called by the insert and
357 $self->ut_numbern('pkgnum')
358 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum')
359 || $self->ut_numbern('pkgpart')
360 || $self->ut_numbern('setup')
361 || $self->ut_numbern('bill')
362 || $self->ut_numbern('susp')
363 || $self->ut_numbern('cancel')
365 return $error if $error;
367 if ( $self->reg_code ) {
369 unless ( grep { $self->pkgpart == $_->pkgpart }
370 map { $_->reg_code_pkg }
371 qsearchs( 'reg_code', { 'code' => $self->reg_code,
372 'agentnum' => $self->cust_main->agentnum })
374 return "Unknown registration code";
377 } elsif ( $self->promo_code ) {
380 qsearchs('part_pkg', {
381 'pkgpart' => $self->pkgpart,
382 'promo_code' => { op=>'ILIKE', value=>$self->promo_code },
384 return 'Unknown promotional code' unless $promo_part_pkg;
388 unless ( $disable_agentcheck ) {
390 qsearchs( 'agent', { 'agentnum' => $self->cust_main->agentnum } );
391 my $pkgpart_href = $agent->pkgpart_hashref;
392 return "agent ". $agent->agentnum.
393 " can't purchase pkgpart ". $self->pkgpart
394 unless $pkgpart_href->{ $self->pkgpart };
397 $error = $self->ut_foreign_key('pkgpart', 'part_pkg', 'pkgpart' );
398 return $error if $error;
402 $self->otaker(getotaker) unless $self->otaker;
403 $self->otaker =~ /^([\w\.\-]{0,16})$/ or return "Illegal otaker";
406 if ( $self->dbdef_table->column('manual_flag') ) {
407 $self->manual_flag('') if $self->manual_flag eq ' ';
408 $self->manual_flag =~ /^([01]?)$/
409 or return "Illegal manual_flag ". $self->manual_flag;
410 $self->manual_flag($1);
416 =item cancel [ OPTION => VALUE ... ]
418 Cancels and removes all services (see L<FS::cust_svc> and L<FS::part_svc>)
419 in this package, then cancels the package itself (sets the cancel field to
422 Available options are: I<quiet>
424 I<quiet> can be set true to supress email cancellation notices.
426 If there is an error, returns the error, otherwise returns false.
431 my( $self, %options ) = @_;
434 local $SIG{HUP} = 'IGNORE';
435 local $SIG{INT} = 'IGNORE';
436 local $SIG{QUIT} = 'IGNORE';
437 local $SIG{TERM} = 'IGNORE';
438 local $SIG{TSTP} = 'IGNORE';
439 local $SIG{PIPE} = 'IGNORE';
441 my $oldAutoCommit = $FS::UID::AutoCommit;
442 local $FS::UID::AutoCommit = 0;
445 if ($options{'reason'}) {
446 $error = $self->insert_reason( 'reason' => $options{'reason'} );
448 dbh->rollback if $oldAutoCommit;
449 return "Error inserting cust_pkg_reason: $error";
454 foreach my $cust_svc (
455 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
457 push @{ $svc{$cust_svc->part_svc->svcdb} }, $cust_svc;
460 foreach my $svcdb (@SVCDB_CANCEL_SEQ) {
461 foreach my $cust_svc (@{ $svc{$svcdb} }) {
462 my $error = $cust_svc->cancel;
465 $dbh->rollback if $oldAutoCommit;
466 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);
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);
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 $hash{'bill'} = ( $hash{'bill'} || $hash{'setup'} ) + $inactive
647 if $opt{'adjust_next_bill'}
648 && $inactive > 0 && ( $hash{'bill'} || $hash{'setup'} );
651 my $new = new FS::cust_pkg ( \%hash );
652 $error = $new->replace($self);
654 $dbh->rollback if $oldAutoCommit;
659 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
666 Returns the last bill date, or if there is no last bill date, the setup date.
667 Useful for billing metered services.
673 if ( $self->dbdef_table->column('last_bill') ) {
674 return $self->setfield('last_bill', $_[0]) if @_;
675 return $self->getfield('last_bill') if $self->getfield('last_bill');
677 my $cust_bill_pkg = qsearchs('cust_bill_pkg', { 'pkgnum' => $self->pkgnum,
678 'edate' => $self->bill, } );
679 $cust_bill_pkg ? $cust_bill_pkg->sdate : $self->setup || 0;
684 Returns the most recent FS::reason associated with the package.
690 my $cust_pkg_reason = qsearchs( {
691 'table' => 'cust_pkg_reason',
692 'hashref' => { 'pkgnum' => $self->pkgnum, },
693 'extra_sql'=> 'ORDER BY date DESC',
695 qsearchs ( 'reason', { 'reasonnum' => $cust_pkg_reason->reasonnum } )
701 Returns the definition for this billing item, as an FS::part_pkg object (see
708 #exists( $self->{'_pkgpart'} )
710 ? $self->{'_pkgpart'}
711 : qsearchs( 'part_pkg', { 'pkgpart' => $self->pkgpart } );
716 Calls the I<calc_setup> of the FS::part_pkg object associated with this billing
723 $self->part_pkg->calc_setup($self, @_);
728 Calls the I<calc_recur> of the FS::part_pkg object associated with this billing
735 $self->part_pkg->calc_recur($self, @_);
740 Calls the I<calc_remain> of the FS::part_pkg object associated with this
747 $self->part_pkg->calc_remain($self, @_);
752 Calls the I<calc_cancel> of the FS::part_pkg object associated with this
759 $self->part_pkg->calc_cancel($self, @_);
762 =item cust_svc [ SVCPART ]
764 Returns the services for this package, as FS::cust_svc objects (see
765 L<FS::cust_svc>). If a svcpart is specified, return only the matching
774 return qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum,
775 'svcpart' => shift, } );
778 #if ( $self->{'_svcnum'} ) {
779 # values %{ $self->{'_svcnum'}->cache };
781 $self->_sort_cust_svc(
782 [ qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } ) ]
788 =item h_cust_svc END_TIMESTAMP [ START_TIMESTAMP ]
790 Returns historical services for this package created before END TIMESTAMP and
791 (optionally) not cancelled before START_TIMESTAMP, as FS::h_cust_svc objects
792 (see L<FS::h_cust_svc>).
799 $self->_sort_cust_svc(
800 [ qsearch( 'h_cust_svc',
801 { 'pkgnum' => $self->pkgnum, },
802 FS::h_cust_svc->sql_h_search(@_),
809 my( $self, $arrayref ) = @_;
812 sort { $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] }
814 my $pkg_svc = qsearchs( 'pkg_svc', { 'pkgpart' => $self->pkgpart,
815 'svcpart' => $_->svcpart } );
817 $pkg_svc ? $pkg_svc->primary_svc : '',
818 $pkg_svc ? $pkg_svc->quantity : 0,
825 =item num_cust_svc [ SVCPART ]
827 Returns the number of provisioned services for this package. If a svcpart is
828 specified, counts only the matching services.
834 my $sql = 'SELECT COUNT(*) FROM cust_svc WHERE pkgnum = ?';
835 $sql .= ' AND svcpart = ?' if @_;
836 my $sth = dbh->prepare($sql) or die dbh->errstr;
837 $sth->execute($self->pkgnum, @_) or die $sth->errstr;
838 $sth->fetchrow_arrayref->[0];
841 =item available_part_svc
843 Returns a list FS::part_svc objects representing services included in this
844 package but not yet provisioned. Each FS::part_svc object also has an extra
845 field, I<num_avail>, which specifies the number of available services.
849 sub available_part_svc {
851 grep { $_->num_avail > 0 }
853 my $part_svc = $_->part_svc;
854 $part_svc->{'Hash'}{'num_avail'} = #evil encapsulation-breaking
855 $_->quantity - $self->num_cust_svc($_->svcpart);
858 $self->part_pkg->pkg_svc;
863 Returns a short status string for this package, currently:
869 =item one-time charge
884 my $freq = length($self->freq) ? $self->freq : $self->part_pkg->freq;
886 return 'cancelled' if $self->get('cancel');
887 return 'suspended' if $self->susp;
888 return 'not yet billed' unless $self->setup;
889 return 'one-time charge' if $freq =~ /^(0|$)/;
895 Class method that returns the list of possible status strings for pacakges
896 (see L<the status method|/status>). For example:
898 @statuses = FS::cust_pkg->statuses();
902 tie my %statuscolor, 'Tie::IxHash',
903 'not yet billed' => '000000',
904 'one-time charge' => '000000',
905 'active' => '00CC00',
906 'suspended' => 'FF9900',
907 'cancelled' => 'FF0000',
911 my $self = shift; #could be class...
912 grep { $_ !~ /^(not yet billed)$/ } #this is a dumb status anyway
913 # mayble split btw one-time vs. recur
919 Returns a hex triplet color string for this package's status.
925 $statuscolor{$self->status};
930 Returns a list of lists, calling the label method for all services
931 (see L<FS::cust_svc>) of this billing item.
937 map { [ $_->label ] } $self->cust_svc;
940 =item h_labels END_TIMESTAMP [ START_TIMESTAMP ]
942 Like the labels method, but returns historical information on services that
943 were active as of END_TIMESTAMP and (optionally) not cancelled before
946 Returns a list of lists, calling the label method for all (historical) services
947 (see L<FS::h_cust_svc>) of this billing item.
953 map { [ $_->label(@_) ] } $self->h_cust_svc(@_);
956 =item h_labels_short END_TIMESTAMP [ START_TIMESTAMP ]
958 Like h_labels, except returns a simple flat list, and shortens long
959 (currently >5) lists of identical services to one line that lists the service
960 label and the number of individual services rather than individual items.
968 #tie %labels, 'Tie::IxHash';
969 push @{ $labels{$_->[0]} }, $_->[1]
970 foreach $self->h_labels(@_);
972 foreach my $label ( keys %labels ) {
973 my @values = @{ $labels{$label} };
974 my $num = scalar(@values);
976 push @labels, "$label ($num)";
978 push @labels, map { "$label: $_" } @values;
988 Returns the parent customer object (see L<FS::cust_main>).
994 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
997 =item seconds_since TIMESTAMP
999 Returns the number of seconds all accounts (see L<FS::svc_acct>) in this
1000 package have been online since TIMESTAMP, according to the session monitor.
1002 TIMESTAMP is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
1003 L<Time::Local> and L<Date::Parse> for conversion functions.
1008 my($self, $since) = @_;
1011 foreach my $cust_svc (
1012 grep { $_->part_svc->svcdb eq 'svc_acct' } $self->cust_svc
1014 $seconds += $cust_svc->seconds_since($since);
1021 =item seconds_since_sqlradacct TIMESTAMP_START TIMESTAMP_END
1023 Returns the numbers of seconds all accounts (see L<FS::svc_acct>) in this
1024 package have been online between TIMESTAMP_START (inclusive) and TIMESTAMP_END
1027 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
1028 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
1034 sub seconds_since_sqlradacct {
1035 my($self, $start, $end) = @_;
1039 foreach my $cust_svc (
1041 my $part_svc = $_->part_svc;
1042 $part_svc->svcdb eq 'svc_acct'
1043 && scalar($part_svc->part_export('sqlradius'));
1046 $seconds += $cust_svc->seconds_since_sqlradacct($start, $end);
1053 =item attribute_since_sqlradacct TIMESTAMP_START TIMESTAMP_END ATTRIBUTE
1055 Returns the sum of the given attribute for all accounts (see L<FS::svc_acct>)
1056 in this package for sessions ending between TIMESTAMP_START (inclusive) and
1060 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
1061 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
1066 sub attribute_since_sqlradacct {
1067 my($self, $start, $end, $attrib) = @_;
1071 foreach my $cust_svc (
1073 my $part_svc = $_->part_svc;
1074 $part_svc->svcdb eq 'svc_acct'
1075 && scalar($part_svc->part_export('sqlradius'));
1078 $sum += $cust_svc->attribute_since_sqlradacct($start, $end, $attrib);
1085 =item transfer DEST_PKGNUM | DEST_CUST_PKG, [ OPTION => VALUE ... ]
1087 Transfers as many services as possible from this package to another package.
1089 The destination package can be specified by pkgnum by passing an FS::cust_pkg
1090 object. The destination package must already exist.
1092 Services are moved only if the destination allows services with the correct
1093 I<svcpart> (not svcdb), unless the B<change_svcpart> option is set true. Use
1094 this option with caution! No provision is made for export differences
1095 between the old and new service definitions. Probably only should be used
1096 when your exports for all service definitions of a given svcdb are identical.
1097 (attempt a transfer without it first, to move all possible svcpart-matching
1100 Any services that can't be moved remain in the original package.
1102 Returns an error, if there is one; otherwise, returns the number of services
1103 that couldn't be moved.
1108 my ($self, $dest_pkgnum, %opt) = @_;
1114 if (ref ($dest_pkgnum) eq 'FS::cust_pkg') {
1115 $dest = $dest_pkgnum;
1116 $dest_pkgnum = $dest->pkgnum;
1118 $dest = qsearchs('cust_pkg', { pkgnum => $dest_pkgnum });
1121 return ('Package does not exist: '.$dest_pkgnum) unless $dest;
1123 foreach my $pkg_svc ( $dest->part_pkg->pkg_svc ) {
1124 $target{$pkg_svc->svcpart} = $pkg_svc->quantity;
1127 foreach my $cust_svc ($dest->cust_svc) {
1128 $target{$cust_svc->svcpart}--;
1131 my %svcpart2svcparts = ();
1132 if ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
1133 warn "change_svcpart option received, creating alternates list\n" if $DEBUG;
1134 foreach my $svcpart ( map { $_->svcpart } $self->cust_svc ) {
1135 next if exists $svcpart2svcparts{$svcpart};
1136 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
1137 $svcpart2svcparts{$svcpart} = [
1139 sort { $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] }
1141 my $pkg_svc = qsearchs( 'pkg_svc', { 'pkgpart' => $dest->pkgpart,
1142 'svcpart' => $_ } );
1144 $pkg_svc ? $pkg_svc->primary_svc : '',
1145 $pkg_svc ? $pkg_svc->quantity : 0,
1149 grep { $_ != $svcpart }
1151 qsearch('part_svc', { 'svcdb' => $part_svc->svcdb } )
1153 warn "alternates for svcpart $svcpart: ".
1154 join(', ', @{$svcpart2svcparts{$svcpart}}). "\n"
1159 foreach my $cust_svc ($self->cust_svc) {
1160 if($target{$cust_svc->svcpart} > 0) {
1161 $target{$cust_svc->svcpart}--;
1162 my $new = new FS::cust_svc {
1163 svcnum => $cust_svc->svcnum,
1164 svcpart => $cust_svc->svcpart,
1165 pkgnum => $dest_pkgnum,
1167 my $error = $new->replace($cust_svc);
1168 return $error if $error;
1169 } elsif ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
1171 warn "looking for alternates for svcpart ". $cust_svc->svcpart. "\n";
1172 warn "alternates to consider: ".
1173 join(', ', @{$svcpart2svcparts{$cust_svc->svcpart}}). "\n";
1175 my @alternate = grep {
1176 warn "considering alternate svcpart $_: ".
1177 "$target{$_} available in new package\n"
1180 } @{$svcpart2svcparts{$cust_svc->svcpart}};
1182 warn "alternate(s) found\n" if $DEBUG;
1183 my $change_svcpart = $alternate[0];
1184 $target{$change_svcpart}--;
1185 my $new = new FS::cust_svc {
1186 svcnum => $cust_svc->svcnum,
1187 svcpart => $change_svcpart,
1188 pkgnum => $dest_pkgnum,
1190 my $error = $new->replace($cust_svc);
1191 return $error if $error;
1204 This method is deprecated. See the I<depend_jobnum> option to the insert and
1205 order_pkgs methods in FS::cust_main for a better way to defer provisioning.
1212 local $SIG{HUP} = 'IGNORE';
1213 local $SIG{INT} = 'IGNORE';
1214 local $SIG{QUIT} = 'IGNORE';
1215 local $SIG{TERM} = 'IGNORE';
1216 local $SIG{TSTP} = 'IGNORE';
1217 local $SIG{PIPE} = 'IGNORE';
1219 my $oldAutoCommit = $FS::UID::AutoCommit;
1220 local $FS::UID::AutoCommit = 0;
1223 foreach my $cust_svc ( $self->cust_svc ) {
1224 #false laziness w/svc_Common::insert
1225 my $svc_x = $cust_svc->svc_x;
1226 foreach my $part_export ( $cust_svc->part_svc->part_export ) {
1227 my $error = $part_export->export_insert($svc_x);
1229 $dbh->rollback if $oldAutoCommit;
1235 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1242 =head1 CLASS METHODS
1248 Returns an SQL expression identifying recurring packages.
1252 sub recurring_sql { "
1253 '0' != ( select freq from part_pkg
1254 where cust_pkg.pkgpart = part_pkg.pkgpart )
1259 Returns an SQL expression identifying one-time packages.
1264 '0' = ( select freq from part_pkg
1265 where cust_pkg.pkgpart = part_pkg.pkgpart )
1270 Returns an SQL expression identifying active packages.
1275 ". $_[0]->recurring_sql(). "
1276 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
1277 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
1282 Returns an SQL expression identifying inactive packages (one-time packages
1283 that are otherwise unsuspended/uncancelled).
1287 sub inactive_sql { "
1288 ". $_[0]->onetime_sql(). "
1289 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
1290 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
1296 Returns an SQL expression identifying suspended packages.
1300 sub suspended_sql { susp_sql(@_); }
1302 #$_[0]->recurring_sql(). ' AND '.
1304 ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
1305 AND cust_pkg.susp IS NOT NULL AND cust_pkg.susp != 0
1312 Returns an SQL exprression identifying cancelled packages.
1316 sub cancelled_sql { cancel_sql(@_); }
1318 #$_[0]->recurring_sql(). ' AND '.
1319 "cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0";
1326 =item order CUSTNUM, PKGPARTS_ARYREF, [ REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF ] ]
1328 CUSTNUM is a customer (see L<FS::cust_main>)
1330 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
1331 L<FS::part_pkg>) to order for this customer. Duplicates are of course
1334 REMOVE_PKGNUMS is an optional list of pkgnums specifying the billing items to
1335 remove for this customer. The services (see L<FS::cust_svc>) are moved to the
1336 new billing items. An error is returned if this is not possible (see
1337 L<FS::pkg_svc>). An empty arrayref is equivalent to not specifying this
1340 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
1341 newly-created cust_pkg objects.
1346 my ($custnum, $pkgparts, $remove_pkgnum, $return_cust_pkg) = @_;
1348 my $conf = new FS::Conf;
1350 # Transactionize this whole mess
1351 local $SIG{HUP} = 'IGNORE';
1352 local $SIG{INT} = 'IGNORE';
1353 local $SIG{QUIT} = 'IGNORE';
1354 local $SIG{TERM} = 'IGNORE';
1355 local $SIG{TSTP} = 'IGNORE';
1356 local $SIG{PIPE} = 'IGNORE';
1358 my $oldAutoCommit = $FS::UID::AutoCommit;
1359 local $FS::UID::AutoCommit = 0;
1363 my $cust_main = qsearchs('cust_main', { custnum => $custnum });
1364 return "Customer not found: $custnum" unless $cust_main;
1366 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
1369 my $change = scalar(@old_cust_pkg) != 0;
1372 if ( scalar(@old_cust_pkg) == 1 ) {
1373 #$hash{$_} = $old_cust_pkg[0]->$_() foreach qw( last_bill bill );
1374 $hash{'setup'} = time;
1377 # Create the new packages.
1378 foreach my $pkgpart (@$pkgparts) {
1379 my $cust_pkg = new FS::cust_pkg { custnum => $custnum,
1380 pkgpart => $pkgpart,
1383 $error = $cust_pkg->insert( 'change' => $change );
1385 $dbh->rollback if $oldAutoCommit;
1388 push @$return_cust_pkg, $cust_pkg;
1390 # $return_cust_pkg now contains refs to all of the newly
1393 # Transfer services and cancel old packages.
1394 foreach my $old_pkg (@old_cust_pkg) {
1396 foreach my $new_pkg (@$return_cust_pkg) {
1397 $error = $old_pkg->transfer($new_pkg);
1398 if ($error and $error == 0) {
1399 # $old_pkg->transfer failed.
1400 $dbh->rollback if $oldAutoCommit;
1405 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
1406 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
1407 foreach my $new_pkg (@$return_cust_pkg) {
1408 $error = $old_pkg->transfer($new_pkg, 'change_svcpart'=>1 );
1409 if ($error and $error == 0) {
1410 # $old_pkg->transfer failed.
1411 $dbh->rollback if $oldAutoCommit;
1418 # Transfers were successful, but we went through all of the
1419 # new packages and still had services left on the old package.
1420 # We can't cancel the package under the circumstances, so abort.
1421 $dbh->rollback if $oldAutoCommit;
1422 return "Unable to transfer all services from package ".$old_pkg->pkgnum;
1424 $error = $old_pkg->cancel( quiet=>1 );
1430 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1435 my ($self, %options) = @_;
1437 my $otaker = $FS::CurrentUser::CurrentUser->name;
1438 $otaker = $FS::CurrentUser::CurrentUser->username
1439 if (($otaker) eq "User, Legacy");
1441 my $cust_pkg_reason =
1442 new FS::cust_pkg_reason({ 'pkgnum' => $self->pkgnum,
1443 'reasonnum' => $options{'reason'},
1444 'otaker' => $otaker,
1445 'date' => $options{'date'}
1449 return $cust_pkg_reason->insert;
1456 sub order is not OO. Perhaps it should be moved to FS::cust_main and made so?
1458 In sub order, the @pkgparts array (passed by reference) is clobbered.
1460 Also in sub order, no money is adjusted. Once FS::part_pkg defines a standard
1461 method to pass dates to the recur_prog expression, it should do so.
1463 FS::svc_acct, FS::svc_domain, FS::svc_www, FS::svc_ip and FS::svc_forward are
1464 loaded via 'use' at compile time, rather than via 'require' in sub { setup,
1465 suspend, unsuspend, cancel } because they use %FS::UID::callback to load
1466 configuration values. Probably need a subroutine which decides what to do
1467 based on whether or not we've fetched the user yet, rather than a hash. See
1468 FS::UID and the TODO.
1470 Now that things are transactional should the check in the insert method be
1475 L<FS::Record>, L<FS::cust_main>, L<FS::part_pkg>, L<FS::cust_svc>,
1476 L<FS::pkg_svc>, schema.html from the base documentation