2 use base qw( FS::otaker_Mixin FS::cust_main_Mixin FS::Sales_Mixin
3 FS::contact_Mixin FS::location_Mixin
4 FS::m2m_Common FS::option_Common );
7 use vars qw($disable_agentcheck $DEBUG $me);
9 use Scalar::Util qw( blessed );
10 use List::Util qw(min max);
12 use Time::Local qw( timelocal timelocal_nocheck );
14 use FS::UID qw( getotaker dbh driver_name );
15 use FS::Misc qw( send_email );
16 use FS::Record qw( qsearch qsearchs fields );
22 use FS::cust_location;
24 use FS::cust_bill_pkg;
25 use FS::cust_pkg_detail;
26 use FS::cust_pkg_usage;
27 use FS::cdr_cust_pkg_usage;
32 use FS::cust_pkg_reason;
34 use FS::cust_pkg_discount;
41 # need to 'use' these instead of 'require' in sub { cancel, suspend, unsuspend,
43 # because they load configuration by setting FS::UID::callback (see TODO)
49 # for sending cancel emails in sub cancel
53 $me = '[FS::cust_pkg]';
55 $disable_agentcheck = 0;
59 my ( $hashref, $cache ) = @_;
60 #if ( $hashref->{'pkgpart'} ) {
61 if ( $hashref->{'pkg'} ) {
62 # #@{ $self->{'_pkgnum'} } = ();
63 # my $subcache = $cache->subcache('pkgpart', 'part_pkg');
64 # $self->{'_pkgpart'} = $subcache;
65 # #push @{ $self->{'_pkgnum'} },
66 # FS::part_pkg->new_or_cached($hashref, $subcache);
67 $self->{'_pkgpart'} = FS::part_pkg->new($hashref);
69 if ( exists $hashref->{'svcnum'} ) {
70 #@{ $self->{'_pkgnum'} } = ();
71 my $subcache = $cache->subcache('svcnum', 'cust_svc', $hashref->{pkgnum});
72 $self->{'_svcnum'} = $subcache;
73 #push @{ $self->{'_pkgnum'} },
74 FS::cust_svc->new_or_cached($hashref, $subcache) if $hashref->{svcnum};
80 FS::cust_pkg - Object methods for cust_pkg objects
86 $record = new FS::cust_pkg \%hash;
87 $record = new FS::cust_pkg { 'column' => 'value' };
89 $error = $record->insert;
91 $error = $new_record->replace($old_record);
93 $error = $record->delete;
95 $error = $record->check;
97 $error = $record->cancel;
99 $error = $record->suspend;
101 $error = $record->unsuspend;
103 $part_pkg = $record->part_pkg;
105 @labels = $record->labels;
107 $seconds = $record->seconds_since($timestamp);
109 $error = FS::cust_pkg::order( $custnum, \@pkgparts );
110 $error = FS::cust_pkg::order( $custnum, \@pkgparts, \@remove_pkgnums ] );
114 An FS::cust_pkg object represents a customer billing item. FS::cust_pkg
115 inherits from FS::Record. The following fields are currently supported:
121 Primary key (assigned automatically for new billing items)
125 Customer (see L<FS::cust_main>)
129 Billing item definition (see L<FS::part_pkg>)
133 Optional link to package location (see L<FS::location>)
137 date package was ordered (also remains same on changes)
149 date (next bill date)
177 order taker (see L<FS::access_user>)
181 If this field is set to 1, disables the automatic
182 unsuspension of this package when using the B<unsuspendauto> config option.
186 If not set, defaults to 1
190 Date of change from previous package
200 =item change_locationnum
208 The pkgnum of the package that this package is supplemental to, if any.
212 The package link (L<FS::part_pkg_link>) that defines this supplemental
213 package, if it is one.
215 =item change_to_pkgnum
217 The pkgnum of the package this one will be "changed to" in the future
218 (on its expiration date).
222 Note: setup, last_bill, bill, adjourn, susp, expire, cancel and change_date
223 are specified as UNIX timestamps; see L<perlfunc/"time">. Also see
224 L<Time::Local> and L<Date::Parse> for conversion functions.
232 Create a new billing item. To add the item to the database, see L<"insert">.
236 sub table { 'cust_pkg'; }
237 sub cust_linked { $_[0]->cust_main_custnum || $_[0]->custnum }
238 sub cust_unlinked_msg {
240 "WARNING: can't find cust_main.custnum ". $self->custnum.
241 ' (cust_pkg.pkgnum '. $self->pkgnum. ')';
244 =item insert [ OPTION => VALUE ... ]
246 Adds this billing item to the database ("Orders" the item). If there is an
247 error, returns the error, otherwise returns false.
249 If the additional field I<promo_code> is defined instead of I<pkgpart>, it
250 will be used to look up the package definition and agent restrictions will be
253 If the additional field I<refnum> is defined, an FS::pkg_referral record will
254 be created and inserted. Multiple FS::pkg_referral records can be created by
255 setting I<refnum> to an array reference of refnums or a hash reference with
256 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
257 record will be created corresponding to cust_main.refnum.
259 The following options are available:
265 If set true, supresses actions that should only be taken for new package
266 orders. (Currently this includes: intro periods when delay_setup is on.)
270 cust_pkg_option records will be created
274 a ticket will be added to this customer with this subject
278 an optional queue name for ticket additions
282 Don't check the legality of the package definition. This should be used
283 when performing a package change that doesn't change the pkgpart (i.e.
291 my( $self, %options ) = @_;
294 $error = $self->check_pkgpart unless $options{'allow_pkgpart'};
295 return $error if $error;
297 my $part_pkg = $self->part_pkg;
299 # if the package def says to start only on the first of the month:
300 if ( $part_pkg->option('start_1st', 1) && !$self->start_date ) {
301 my ($sec,$min,$hour,$mday,$mon,$year) = (localtime(time) )[0,1,2,3,4,5];
302 $mon += 1 unless $mday == 1;
303 until ( $mon < 12 ) { $mon -= 12; $year++; }
304 $self->start_date( timelocal_nocheck(0,0,0,1,$mon,$year) );
307 # set up any automatic expire/adjourn/contract_end timers
308 # based on the start date
309 foreach my $action ( qw(expire adjourn contract_end) ) {
310 my $months = $part_pkg->option("${action}_months",1);
311 if($months and !$self->$action) {
312 my $start = $self->start_date || $self->setup || time;
313 $self->$action( $part_pkg->add_freq($start, $months) );
317 # if this package has "free days" and delayed setup fee, tehn
318 # set start date that many days in the future.
319 # (this should have been set in the UI, but enforce it here)
320 if ( ! $options{'change'}
321 && ( my $free_days = $part_pkg->option('free_days',1) )
322 && $part_pkg->option('delay_setup',1)
323 #&& ! $self->start_date
326 $self->start_date( $part_pkg->default_start_date );
329 $self->order_date(time);
331 local $SIG{HUP} = 'IGNORE';
332 local $SIG{INT} = 'IGNORE';
333 local $SIG{QUIT} = 'IGNORE';
334 local $SIG{TERM} = 'IGNORE';
335 local $SIG{TSTP} = 'IGNORE';
336 local $SIG{PIPE} = 'IGNORE';
338 my $oldAutoCommit = $FS::UID::AutoCommit;
339 local $FS::UID::AutoCommit = 0;
342 $error = $self->SUPER::insert($options{options} ? %{$options{options}} : ());
344 $dbh->rollback if $oldAutoCommit;
348 $self->refnum($self->cust_main->refnum) unless $self->refnum;
349 $self->refnum( [ $self->refnum ] ) unless ref($self->refnum);
350 $self->process_m2m( 'link_table' => 'pkg_referral',
351 'target_table' => 'part_referral',
352 'params' => $self->refnum,
355 if ( $self->discountnum ) {
356 my $error = $self->insert_discount();
358 $dbh->rollback if $oldAutoCommit;
363 my $conf = new FS::Conf;
365 if ( $conf->config('ticket_system') && $options{ticket_subject} ) {
367 #this init stuff is still inefficient, but at least its limited to
368 # the small number (any?) folks using ticket emailing on pkg order
371 # use lib ( "/opt/rt3/local/lib", "/opt/rt3/lib" );
378 use FS::TicketSystem;
379 FS::TicketSystem->init();
381 my $q = new RT::Queue($RT::SystemUser);
382 $q->Load($options{ticket_queue}) if $options{ticket_queue};
383 my $t = new RT::Ticket($RT::SystemUser);
384 my $mime = new MIME::Entity;
385 $mime->build( Type => 'text/plain', Data => $options{ticket_subject} );
386 $t->Create( $options{ticket_queue} ? (Queue => $q) : (),
387 Subject => $options{ticket_subject},
390 $t->AddLink( Type => 'MemberOf',
391 Target => 'freeside://freeside/cust_main/'. $self->custnum,
395 if ($conf->config('welcome_letter') && $self->cust_main->num_pkgs == 1) {
396 my $queue = new FS::queue {
397 'job' => 'FS::cust_main::queueable_print',
399 $error = $queue->insert(
400 'custnum' => $self->custnum,
401 'template' => 'welcome_letter',
405 warn "can't send welcome letter: $error";
410 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
417 This method now works but you probably shouldn't use it.
419 You don't want to delete packages, because there would then be no record
420 the customer ever purchased the package. Instead, see the cancel method and
421 hide cancelled packages.
428 local $SIG{HUP} = 'IGNORE';
429 local $SIG{INT} = 'IGNORE';
430 local $SIG{QUIT} = 'IGNORE';
431 local $SIG{TERM} = 'IGNORE';
432 local $SIG{TSTP} = 'IGNORE';
433 local $SIG{PIPE} = 'IGNORE';
435 my $oldAutoCommit = $FS::UID::AutoCommit;
436 local $FS::UID::AutoCommit = 0;
439 foreach my $cust_pkg_discount ($self->cust_pkg_discount) {
440 my $error = $cust_pkg_discount->delete;
442 $dbh->rollback if $oldAutoCommit;
446 #cust_bill_pkg_discount?
448 foreach my $cust_pkg_detail ($self->cust_pkg_detail) {
449 my $error = $cust_pkg_detail->delete;
451 $dbh->rollback if $oldAutoCommit;
456 foreach my $cust_pkg_reason (
458 'table' => 'cust_pkg_reason',
459 'hashref' => { 'pkgnum' => $self->pkgnum },
463 my $error = $cust_pkg_reason->delete;
465 $dbh->rollback if $oldAutoCommit;
472 my $error = $self->SUPER::delete(@_);
474 $dbh->rollback if $oldAutoCommit;
478 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
484 =item replace [ OLD_RECORD ] [ HASHREF | OPTION => VALUE ... ]
486 Replaces the OLD_RECORD with this one in the database. If there is an error,
487 returns the error, otherwise returns false.
489 Currently, custnum, setup, bill, adjourn, susp, expire, and cancel may be changed.
491 Changing pkgpart may have disasterous effects. See the order subroutine.
493 setup and bill are normally updated by calling the bill method of a customer
494 object (see L<FS::cust_main>).
496 suspend is normally updated by the suspend and unsuspend methods.
498 cancel is normally updated by the cancel method (and also the order subroutine
501 Available options are:
507 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.
511 the access_user (see L<FS::access_user>) providing the reason
515 hashref of keys and values - cust_pkg_option records will be created, updated or removed as appopriate
524 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
529 ( ref($_[0]) eq 'HASH' )
533 #return "Can't (yet?) change pkgpart!" if $old->pkgpart != $new->pkgpart;
534 #return "Can't change otaker!" if $old->otaker ne $new->otaker;
537 #return "Can't change setup once it exists!"
538 # if $old->getfield('setup') &&
539 # $old->getfield('setup') != $new->getfield('setup');
541 #some logic for bill, susp, cancel?
543 local($disable_agentcheck) = 1 if $old->pkgpart == $new->pkgpart;
545 local $SIG{HUP} = 'IGNORE';
546 local $SIG{INT} = 'IGNORE';
547 local $SIG{QUIT} = 'IGNORE';
548 local $SIG{TERM} = 'IGNORE';
549 local $SIG{TSTP} = 'IGNORE';
550 local $SIG{PIPE} = 'IGNORE';
552 my $oldAutoCommit = $FS::UID::AutoCommit;
553 local $FS::UID::AutoCommit = 0;
556 foreach my $method ( qw(adjourn expire) ) { # How many reasons?
557 if ($options->{'reason'} && $new->$method && $old->$method ne $new->$method) {
558 my $error = $new->insert_reason(
559 'reason' => $options->{'reason'},
560 'date' => $new->$method,
562 'reason_otaker' => $options->{'reason_otaker'},
565 dbh->rollback if $oldAutoCommit;
566 return "Error inserting cust_pkg_reason: $error";
571 #save off and freeze RADIUS attributes for any associated svc_acct records
573 if ( $old->part_pkg->is_prepaid || $new->part_pkg->is_prepaid ) {
575 #also check for specific exports?
576 # to avoid spurious modify export events
577 @svc_acct = map { $_->svc_x }
578 grep { $_->part_svc->svcdb eq 'svc_acct' }
581 $_->snapshot foreach @svc_acct;
585 my $error = $new->export_pkg_change($old)
586 || $new->SUPER::replace( $old,
588 ? $options->{options}
592 $dbh->rollback if $oldAutoCommit;
596 #for prepaid packages,
597 #trigger export of new RADIUS Expiration attribute when cust_pkg.bill changes
598 foreach my $old_svc_acct ( @svc_acct ) {
599 my $new_svc_acct = new FS::svc_acct { $old_svc_acct->hash };
601 $new_svc_acct->replace( $old_svc_acct,
602 'depend_jobnum' => $options->{depend_jobnum},
605 $dbh->rollback if $oldAutoCommit;
610 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
617 Checks all fields to make sure this is a valid billing item. If there is an
618 error, returns the error, otherwise returns false. Called by the insert and
626 if ( !$self->locationnum or $self->locationnum == -1 ) {
627 $self->set('locationnum', $self->cust_main->ship_locationnum);
631 $self->ut_numbern('pkgnum')
632 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum')
633 || $self->ut_numbern('pkgpart')
634 || $self->ut_foreign_keyn('contactnum', 'contact', 'contactnum' )
635 || $self->ut_foreign_keyn('locationnum', 'cust_location', 'locationnum')
636 || $self->ut_foreign_keyn('salesnum', 'sales', 'salesnum')
637 || $self->ut_numbern('quantity')
638 || $self->ut_numbern('start_date')
639 || $self->ut_numbern('setup')
640 || $self->ut_numbern('bill')
641 || $self->ut_numbern('susp')
642 || $self->ut_numbern('cancel')
643 || $self->ut_numbern('adjourn')
644 || $self->ut_numbern('resume')
645 || $self->ut_numbern('expire')
646 || $self->ut_numbern('dundate')
647 || $self->ut_enum('no_auto', [ '', 'Y' ])
648 || $self->ut_enum('waive_setup', [ '', 'Y' ])
649 || $self->ut_numbern('agent_pkgid')
650 || $self->ut_enum('recur_show_zero', [ '', 'Y', 'N', ])
651 || $self->ut_enum('setup_show_zero', [ '', 'Y', 'N', ])
652 || $self->ut_foreign_keyn('main_pkgnum', 'cust_pkg', 'pkgnum')
653 || $self->ut_foreign_keyn('pkglinknum', 'part_pkg_link', 'pkglinknum')
654 || $self->ut_foreign_keyn('change_to_pkgnum', 'cust_pkg', 'pkgnum')
656 return $error if $error;
658 return "A package with both start date (future start) and setup date (already started) will never bill"
659 if $self->start_date && $self->setup;
661 return "A future unsuspend date can only be set for a package with a suspend date"
662 if $self->resume and !$self->susp and !$self->adjourn;
664 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
666 if ( $self->dbdef_table->column('manual_flag') ) {
667 $self->manual_flag('') if $self->manual_flag eq ' ';
668 $self->manual_flag =~ /^([01]?)$/
669 or return "Illegal manual_flag ". $self->manual_flag;
670 $self->manual_flag($1);
678 Check the pkgpart to make sure it's allowed with the reg_code and/or
679 promo_code of the package (if present) and with the customer's agent.
680 Called from C<insert>, unless we are doing a package change that doesn't
688 # my $error = $self->ut_numbern('pkgpart'); # already done
691 if ( $self->reg_code ) {
693 unless ( grep { $self->pkgpart == $_->pkgpart }
694 map { $_->reg_code_pkg }
695 qsearchs( 'reg_code', { 'code' => $self->reg_code,
696 'agentnum' => $self->cust_main->agentnum })
698 return "Unknown registration code";
701 } elsif ( $self->promo_code ) {
704 qsearchs('part_pkg', {
705 'pkgpart' => $self->pkgpart,
706 'promo_code' => { op=>'ILIKE', value=>$self->promo_code },
708 return 'Unknown promotional code' unless $promo_part_pkg;
712 unless ( $disable_agentcheck ) {
714 qsearchs( 'agent', { 'agentnum' => $self->cust_main->agentnum } );
715 return "agent ". $agent->agentnum. ':'. $agent->agent.
716 " can't purchase pkgpart ". $self->pkgpart
717 unless $agent->pkgpart_hashref->{ $self->pkgpart }
718 || $agent->agentnum == $self->part_pkg->agentnum;
721 $error = $self->ut_foreign_key('pkgpart', 'part_pkg', 'pkgpart' );
722 return $error if $error;
730 =item cancel [ OPTION => VALUE ... ]
732 Cancels and removes all services (see L<FS::cust_svc> and L<FS::part_svc>)
733 in this package, then cancels the package itself (sets the cancel field to
736 Available options are:
740 =item quiet - can be set true to supress email cancellation notices.
742 =item time - can be set to cancel the package based on a specific future or
743 historical date. Using time ensures that the remaining amount is calculated
744 correctly. Note however that this is an immediate cancel and just changes
745 the date. You are PROBABLY looking to expire the account instead of using
748 =item reason - can be set to a cancellation reason (see L<FS:reason>),
749 either a reasonnum of an existing reason, or passing a hashref will create
750 a new reason. The hashref should have the following keys: typenum - Reason
751 type (see L<FS::reason_type>, reason - Text of the new reason.
753 =item date - can be set to a unix style timestamp to specify when to
756 =item nobill - can be set true to skip billing if it might otherwise be done.
758 =item unused_credit - can be set to 1 to credit the remaining time, or 0 to
759 not credit it. This must be set (by change()) when changing the package
760 to a different pkgpart or location, and probably shouldn't be in any other
761 case. If it's not set, the 'unused_credit_cancel' part_pkg option will
766 If there is an error, returns the error, otherwise returns false.
771 my( $self, %options ) = @_;
774 # pass all suspend/cancel actions to the main package
775 if ( $self->main_pkgnum and !$options{'from_main'} ) {
776 return $self->main_pkg->cancel(%options);
779 my $conf = new FS::Conf;
781 warn "cust_pkg::cancel called with options".
782 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
785 local $SIG{HUP} = 'IGNORE';
786 local $SIG{INT} = 'IGNORE';
787 local $SIG{QUIT} = 'IGNORE';
788 local $SIG{TERM} = 'IGNORE';
789 local $SIG{TSTP} = 'IGNORE';
790 local $SIG{PIPE} = 'IGNORE';
792 my $oldAutoCommit = $FS::UID::AutoCommit;
793 local $FS::UID::AutoCommit = 0;
796 my $old = $self->select_for_update;
798 if ( $old->get('cancel') || $self->get('cancel') ) {
799 dbh->rollback if $oldAutoCommit;
800 return ""; # no error
803 # XXX possibly set cancel_time to the expire date?
804 my $cancel_time = $options{'time'} || time;
805 my $date = $options{'date'} if $options{'date'}; # expire/cancel later
806 $date = '' if ($date && $date <= $cancel_time); # complain instead?
808 #race condition: usage could be ongoing until unprovisioned
809 #resolved by performing a change package instead (which unprovisions) and
811 if ( !$options{nobill} && !$date ) {
812 # && $conf->exists('bill_usage_on_cancel') ) { #calc_cancel checks this
813 my $copy = $self->new({$self->hash});
815 $copy->cust_main->bill( 'pkg_list' => [ $copy ],
817 'time' => $cancel_time );
818 warn "Error billing during cancel, custnum ".
819 #$self->cust_main->custnum. ": $error"
824 if ( $options{'reason'} ) {
825 $error = $self->insert_reason( 'reason' => $options{'reason'},
826 'action' => $date ? 'expire' : 'cancel',
827 'date' => $date ? $date : $cancel_time,
828 'reason_otaker' => $options{'reason_otaker'},
831 dbh->rollback if $oldAutoCommit;
832 return "Error inserting cust_pkg_reason: $error";
836 my %svc_cancel_opt = ();
837 $svc_cancel_opt{'date'} = $date if $date;
838 foreach my $cust_svc (
841 sort { $a->[1] <=> $b->[1] }
842 map { [ $_, $_->svc_x ? $_->svc_x->table_info->{'cancel_weight'} : -1 ]; }
843 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
845 my $part_svc = $cust_svc->part_svc;
846 next if ( defined($part_svc) and $part_svc->preserve );
847 my $error = $cust_svc->cancel( %svc_cancel_opt );
850 $dbh->rollback if $oldAutoCommit;
851 return 'Error '. ($svc_cancel_opt{'date'} ? 'expiring' : 'canceling' ).
857 # credit remaining time if appropriate
859 if ( exists($options{'unused_credit'}) ) {
860 $do_credit = $options{'unused_credit'};
863 $do_credit = $self->part_pkg->option('unused_credit_cancel', 1);
866 my $error = $self->credit_remaining('cancel', $cancel_time);
868 $dbh->rollback if $oldAutoCommit;
875 my %hash = $self->hash;
877 $hash{'expire'} = $date;
879 $hash{'cancel'} = $cancel_time;
881 $hash{'change_custnum'} = $options{'change_custnum'};
883 my $new = new FS::cust_pkg ( \%hash );
884 $error = $new->replace( $self, options => { $self->options } );
885 if ( $self->change_to_pkgnum ) {
886 my $change_to = FS::cust_pkg->by_key($self->change_to_pkgnum);
887 $error ||= $change_to->cancel || $change_to->delete;
890 $dbh->rollback if $oldAutoCommit;
894 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
895 $error = $supp_pkg->cancel(%options, 'from_main' => 1);
897 $dbh->rollback if $oldAutoCommit;
898 return "canceling supplemental pkg#".$supp_pkg->pkgnum.": $error";
902 foreach my $usage ( $self->cust_pkg_usage ) {
903 $error = $usage->delete;
905 $dbh->rollback if $oldAutoCommit;
906 return "deleting usage pools: $error";
910 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
911 return '' if $date; #no errors
913 my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ } $self->cust_main->invoicing_list;
914 if ( !$options{'quiet'} &&
915 $conf->exists('emailcancel', $self->cust_main->agentnum) &&
917 my $msgnum = $conf->config('cancel_msgnum', $self->cust_main->agentnum);
920 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum });
921 $error = $msg_template->send( 'cust_main' => $self->cust_main,
926 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
927 'to' => \@invoicing_list,
928 'subject' => ( $conf->config('cancelsubject') || 'Cancellation Notice' ),
929 'body' => [ map "$_\n", $conf->config('cancelmessage') ],
932 #should this do something on errors?
939 =item cancel_if_expired [ NOW_TIMESTAMP ]
941 Cancels this package if its expire date has been reached.
945 sub cancel_if_expired {
947 my $time = shift || time;
948 return '' unless $self->expire && $self->expire <= $time;
949 my $error = $self->cancel;
951 return "Error cancelling expired pkg ". $self->pkgnum. " for custnum ".
952 $self->custnum. ": $error";
959 "Un-cancels" this package: Orders a new package with the same custnum, pkgpart,
960 locationnum, (other fields?). Attempts to re-provision cancelled services
961 using history information (errors at this stage are not fatal).
963 cust_pkg: pass a scalar reference, will be filled in with the new cust_pkg object
965 svc_fatal: service provisioning errors are fatal
967 svc_errors: pass an array reference, will be filled in with any provisioning errors
969 main_pkgnum: link the package as a supplemental package of this one. For
975 my( $self, %options ) = @_;
977 #in case you try do do $uncancel-date = $cust_pkg->uncacel
978 return '' unless $self->get('cancel');
980 if ( $self->main_pkgnum and !$options{'main_pkgnum'} ) {
981 return $self->main_pkg->uncancel(%options);
988 local $SIG{HUP} = 'IGNORE';
989 local $SIG{INT} = 'IGNORE';
990 local $SIG{QUIT} = 'IGNORE';
991 local $SIG{TERM} = 'IGNORE';
992 local $SIG{TSTP} = 'IGNORE';
993 local $SIG{PIPE} = 'IGNORE';
995 my $oldAutoCommit = $FS::UID::AutoCommit;
996 local $FS::UID::AutoCommit = 0;
1000 # insert the new package
1003 my $cust_pkg = new FS::cust_pkg {
1004 last_bill => ( $options{'last_bill'} || $self->get('last_bill') ),
1005 bill => ( $options{'bill'} || $self->get('bill') ),
1007 uncancel_pkgnum => $self->pkgnum,
1008 main_pkgnum => ($options{'main_pkgnum'} || ''),
1009 map { $_ => $self->get($_) } qw(
1010 custnum pkgpart locationnum
1012 susp adjourn resume expire start_date contract_end dundate
1013 change_date change_pkgpart change_locationnum
1014 manual_flag no_auto quantity agent_pkgid recur_show_zero setup_show_zero
1018 my $error = $cust_pkg->insert(
1019 'change' => 1, #supresses any referral credit to a referring customer
1020 'allow_pkgpart' => 1, # allow this even if the package def is disabled
1023 $dbh->rollback if $oldAutoCommit;
1031 #find historical services within this timeframe before the package cancel
1032 # (incompatible with "time" option to cust_pkg->cancel?)
1033 my $fuzz = 2 * 60; #2 minutes? too much? (might catch separate unprovision)
1034 # too little? (unprovisioing export delay?)
1035 my($end, $start) = ( $self->get('cancel'), $self->get('cancel') - $fuzz );
1036 my @h_cust_svc = $self->h_cust_svc( $end, $start );
1039 foreach my $h_cust_svc (@h_cust_svc) {
1040 my $h_svc_x = $h_cust_svc->h_svc_x( $end, $start );
1041 #next unless $h_svc_x; #should this happen?
1042 (my $table = $h_svc_x->table) =~ s/^h_//;
1043 require "FS/$table.pm";
1044 my $class = "FS::$table";
1045 my $svc_x = $class->new( {
1046 'pkgnum' => $cust_pkg->pkgnum,
1047 'svcpart' => $h_cust_svc->svcpart,
1048 map { $_ => $h_svc_x->get($_) } fields($table)
1052 if ( $h_svc_x->isa('FS::h_svc_Radius_Mixin') ) {
1053 $svc_x->usergroup( [ $h_svc_x->h_usergroup($end, $start) ] );
1056 my $svc_error = $svc_x->insert;
1058 if ( $options{svc_fatal} ) {
1059 $dbh->rollback if $oldAutoCommit;
1062 # if we've failed to insert the svc_x object, svc_Common->insert
1063 # will have removed the cust_svc already. if not, then both records
1064 # were inserted but we failed for some other reason (export, most
1065 # likely). in that case, report the error and delete the records.
1066 push @svc_errors, $svc_error;
1067 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svc_x->svcnum });
1069 # except if export_insert failed, export_delete probably won't be
1071 local $FS::svc_Common::noexport_hack = 1;
1072 my $cleanup_error = $svc_x->delete; # also deletes cust_svc
1073 if ( $cleanup_error ) { # and if THAT fails, then run away
1074 $dbh->rollback if $oldAutoCommit;
1075 return $cleanup_error;
1080 } #foreach $h_cust_svc
1082 #these are pretty rare, but should handle them
1083 # - dsl_device (mac addresses)
1084 # - phone_device (mac addresses)
1085 # - dsl_note (ikano notes)
1086 # - domain_record (i.e. restore DNS information w/domains)
1087 # - inventory_item(?) (inventory w/un-cancelling service?)
1088 # - nas (svc_broaband nas stuff)
1089 #this stuff is unused in the wild afaik
1090 # - mailinglistmember
1092 # - svc_domain.parent_svcnum?
1093 # - acct_snarf (ancient mail fetching config)
1094 # - cgp_rule (communigate)
1095 # - cust_svc_option (used by our Tron stuff)
1096 # - acct_rt_transaction (used by our time worked stuff)
1099 # also move over any services that didn't unprovision at cancellation
1102 foreach my $cust_svc ( qsearch('cust_svc', { pkgnum => $self->pkgnum } ) ) {
1103 $cust_svc->pkgnum( $cust_pkg->pkgnum );
1104 my $error = $cust_svc->replace;
1106 $dbh->rollback if $oldAutoCommit;
1112 # Uncancel any supplemental packages, and make them supplemental to the
1116 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1118 $error = $supp_pkg->uncancel(%options, 'main_pkgnum' => $cust_pkg->pkgnum);
1120 $dbh->rollback if $oldAutoCommit;
1121 return "canceling supplemental pkg#".$supp_pkg->pkgnum.": $error";
1129 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1131 ${ $options{cust_pkg} } = $cust_pkg if ref($options{cust_pkg});
1132 @{ $options{svc_errors} } = @svc_errors if ref($options{svc_errors});
1139 Cancels any pending expiration (sets the expire field to null).
1141 If there is an error, returns the error, otherwise returns false.
1146 my( $self, %options ) = @_;
1149 local $SIG{HUP} = 'IGNORE';
1150 local $SIG{INT} = 'IGNORE';
1151 local $SIG{QUIT} = 'IGNORE';
1152 local $SIG{TERM} = 'IGNORE';
1153 local $SIG{TSTP} = 'IGNORE';
1154 local $SIG{PIPE} = 'IGNORE';
1156 my $oldAutoCommit = $FS::UID::AutoCommit;
1157 local $FS::UID::AutoCommit = 0;
1160 my $old = $self->select_for_update;
1162 my $pkgnum = $old->pkgnum;
1163 if ( $old->get('cancel') || $self->get('cancel') ) {
1164 dbh->rollback if $oldAutoCommit;
1165 return "Can't unexpire cancelled package $pkgnum";
1166 # or at least it's pointless
1169 unless ( $old->get('expire') && $self->get('expire') ) {
1170 dbh->rollback if $oldAutoCommit;
1171 return ""; # no error
1174 my %hash = $self->hash;
1175 $hash{'expire'} = '';
1176 my $new = new FS::cust_pkg ( \%hash );
1177 $error = $new->replace( $self, options => { $self->options } );
1179 $dbh->rollback if $oldAutoCommit;
1183 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1189 =item suspend [ OPTION => VALUE ... ]
1191 Suspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
1192 package, then suspends the package itself (sets the susp field to now).
1194 Available options are:
1198 =item reason - can be set to a cancellation reason (see L<FS:reason>),
1199 either a reasonnum of an existing reason, or passing a hashref will create
1200 a new reason. The hashref should have the following keys:
1201 - typenum - Reason type (see L<FS::reason_type>
1202 - reason - Text of the new reason.
1204 =item date - can be set to a unix style timestamp to specify when to
1207 =item time - can be set to override the current time, for calculation
1208 of final invoices or unused-time credits
1210 =item resume_date - can be set to a time when the package should be
1211 unsuspended. This may be more convenient than calling C<unsuspend()>
1214 =item from_main - allows a supplemental package to be suspended, rather
1215 than redirecting the method call to its main package. For internal use.
1219 If there is an error, returns the error, otherwise returns false.
1224 my( $self, %options ) = @_;
1227 # pass all suspend/cancel actions to the main package
1228 if ( $self->main_pkgnum and !$options{'from_main'} ) {
1229 return $self->main_pkg->suspend(%options);
1232 local $SIG{HUP} = 'IGNORE';
1233 local $SIG{INT} = 'IGNORE';
1234 local $SIG{QUIT} = 'IGNORE';
1235 local $SIG{TERM} = 'IGNORE';
1236 local $SIG{TSTP} = 'IGNORE';
1237 local $SIG{PIPE} = 'IGNORE';
1239 my $oldAutoCommit = $FS::UID::AutoCommit;
1240 local $FS::UID::AutoCommit = 0;
1243 my $old = $self->select_for_update;
1245 my $pkgnum = $old->pkgnum;
1246 if ( $old->get('cancel') || $self->get('cancel') ) {
1247 dbh->rollback if $oldAutoCommit;
1248 return "Can't suspend cancelled package $pkgnum";
1251 if ( $old->get('susp') || $self->get('susp') ) {
1252 dbh->rollback if $oldAutoCommit;
1253 return ""; # no error # complain on adjourn?
1256 my $suspend_time = $options{'time'} || time;
1257 my $date = $options{date} if $options{date}; # adjourn/suspend later
1258 $date = '' if ($date && $date <= $suspend_time); # complain instead?
1260 if ( $date && $old->get('expire') && $old->get('expire') < $date ) {
1261 dbh->rollback if $oldAutoCommit;
1262 return "Package $pkgnum expires before it would be suspended.";
1265 # some false laziness with sub cancel
1266 if ( !$options{nobill} && !$date &&
1267 $self->part_pkg->option('bill_suspend_as_cancel',1) ) {
1268 # kind of a kludge--'bill_suspend_as_cancel' to avoid having to
1269 # make the entire cust_main->bill path recognize 'suspend' and
1270 # 'cancel' separately.
1271 warn "Billing $pkgnum on suspension (at $suspend_time)\n" if $DEBUG;
1272 my $copy = $self->new({$self->hash});
1274 $copy->cust_main->bill( 'pkg_list' => [ $copy ],
1276 'time' => $suspend_time );
1277 warn "Error billing during suspend, custnum ".
1278 #$self->cust_main->custnum. ": $error"
1283 if ( $options{'reason'} ) {
1284 $error = $self->insert_reason( 'reason' => $options{'reason'},
1285 'action' => $date ? 'adjourn' : 'suspend',
1286 'date' => $date ? $date : $suspend_time,
1287 'reason_otaker' => $options{'reason_otaker'},
1290 dbh->rollback if $oldAutoCommit;
1291 return "Error inserting cust_pkg_reason: $error";
1295 my %hash = $self->hash;
1297 $hash{'adjourn'} = $date;
1299 $hash{'susp'} = $suspend_time;
1302 my $resume_date = $options{'resume_date'} || 0;
1303 if ( $resume_date > ($date || $suspend_time) ) {
1304 $hash{'resume'} = $resume_date;
1307 $options{options} ||= {};
1309 my $new = new FS::cust_pkg ( \%hash );
1310 $error = $new->replace( $self, options => { $self->options,
1311 %{ $options{options} },
1315 $dbh->rollback if $oldAutoCommit;
1320 # credit remaining time if appropriate
1321 if ( $self->part_pkg->option('unused_credit_suspend', 1) ) {
1322 my $error = $self->credit_remaining('suspend', $suspend_time);
1324 $dbh->rollback if $oldAutoCommit;
1331 foreach my $cust_svc (
1332 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
1334 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
1336 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
1337 $dbh->rollback if $oldAutoCommit;
1338 return "Illegal svcdb value in part_svc!";
1341 require "FS/$svcdb.pm";
1343 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
1345 $error = $svc->suspend;
1347 $dbh->rollback if $oldAutoCommit;
1350 my( $label, $value ) = $cust_svc->label;
1351 push @labels, "$label: $value";
1355 my $conf = new FS::Conf;
1356 if ( $conf->config('suspend_email_admin') ) {
1358 my $error = send_email(
1359 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
1360 #invoice_from ??? well as good as any
1361 'to' => $conf->config('suspend_email_admin'),
1362 'subject' => 'FREESIDE NOTIFICATION: Customer package suspended',
1364 "This is an automatic message from your Freeside installation\n",
1365 "informing you that the following customer package has been suspended:\n",
1367 'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
1368 'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
1369 ( map { "Service : $_\n" } @labels ),
1374 warn "WARNING: can't send suspension admin email (suspending anyway): ".
1382 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1383 $error = $supp_pkg->suspend(%options, 'from_main' => 1);
1385 $dbh->rollback if $oldAutoCommit;
1386 return "suspending supplemental pkg#".$supp_pkg->pkgnum.": $error";
1390 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1395 =item credit_remaining MODE TIME
1397 Generate a credit for this package for the time remaining in the current
1398 billing period. MODE is either "suspend" or "cancel" (determines the
1399 credit type). TIME is the time of suspension/cancellation. Both arguments
1404 sub credit_remaining {
1405 # Add a credit for remaining service
1406 my ($self, $mode, $time) = @_;
1407 die 'credit_remaining requires suspend or cancel'
1408 unless $mode eq 'suspend' or $mode eq 'cancel';
1409 die 'no suspend/cancel time' unless $time > 0;
1411 my $conf = FS::Conf->new;
1412 my $reason_type = $conf->config($mode.'_credit_type');
1414 my $last_bill = $self->getfield('last_bill') || 0;
1415 my $next_bill = $self->getfield('bill') || 0;
1416 if ( $last_bill > 0 # the package has been billed
1417 and $next_bill > 0 # the package has a next bill date
1418 and $next_bill >= $time # which is in the future
1420 my $remaining_value = $self->calc_remain('time' => $time);
1421 if ( $remaining_value > 0 ) {
1422 warn "Crediting for $remaining_value on package ".$self->pkgnum."\n"
1424 my $error = $self->cust_main->credit(
1426 'Credit for unused time on '. $self->part_pkg->pkg,
1427 'reason_type' => $reason_type,
1429 return "Error crediting customer \$$remaining_value for unused time".
1430 " on ". $self->part_pkg->pkg. ": $error"
1432 } #if $remaining_value
1433 } #if $last_bill, etc.
1437 =item unsuspend [ OPTION => VALUE ... ]
1439 Unsuspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
1440 package, then unsuspends the package itself (clears the susp field and the
1441 adjourn field if it is in the past). If the suspend reason includes an
1442 unsuspension package, that package will be ordered.
1444 Available options are:
1450 Can be set to a date to unsuspend the package in the future (the 'resume'
1453 =item adjust_next_bill
1455 Can be set true to adjust the next bill date forward by
1456 the amount of time the account was inactive. This was set true by default
1457 in the past (from 1.4.2 and 1.5.0pre6 through 1.7.0), but now needs to be
1458 explicitly requested with this option or in the price plan.
1462 If there is an error, returns the error, otherwise returns false.
1467 my( $self, %opt ) = @_;
1470 # pass all suspend/cancel actions to the main package
1471 if ( $self->main_pkgnum and !$opt{'from_main'} ) {
1472 return $self->main_pkg->unsuspend(%opt);
1475 local $SIG{HUP} = 'IGNORE';
1476 local $SIG{INT} = 'IGNORE';
1477 local $SIG{QUIT} = 'IGNORE';
1478 local $SIG{TERM} = 'IGNORE';
1479 local $SIG{TSTP} = 'IGNORE';
1480 local $SIG{PIPE} = 'IGNORE';
1482 my $oldAutoCommit = $FS::UID::AutoCommit;
1483 local $FS::UID::AutoCommit = 0;
1486 my $old = $self->select_for_update;
1488 my $pkgnum = $old->pkgnum;
1489 if ( $old->get('cancel') || $self->get('cancel') ) {
1490 $dbh->rollback if $oldAutoCommit;
1491 return "Can't unsuspend cancelled package $pkgnum";
1494 unless ( $old->get('susp') && $self->get('susp') ) {
1495 $dbh->rollback if $oldAutoCommit;
1496 return ""; # no error # complain instead?
1499 my $date = $opt{'date'};
1500 if ( $date and $date > time ) { # return an error if $date <= time?
1502 if ( $old->get('expire') && $old->get('expire') < $date ) {
1503 $dbh->rollback if $oldAutoCommit;
1504 return "Package $pkgnum expires before it would be unsuspended.";
1507 my $new = new FS::cust_pkg { $self->hash };
1508 $new->set('resume', $date);
1509 $error = $new->replace($self, options => $self->options);
1512 $dbh->rollback if $oldAutoCommit;
1516 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1524 foreach my $cust_svc (
1525 qsearch('cust_svc',{'pkgnum'=> $self->pkgnum } )
1527 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
1529 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
1530 $dbh->rollback if $oldAutoCommit;
1531 return "Illegal svcdb value in part_svc!";
1534 require "FS/$svcdb.pm";
1536 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
1538 $error = $svc->unsuspend;
1540 $dbh->rollback if $oldAutoCommit;
1543 my( $label, $value ) = $cust_svc->label;
1544 push @labels, "$label: $value";
1549 my $cust_pkg_reason = $self->last_cust_pkg_reason('susp');
1550 my $reason = $cust_pkg_reason ? $cust_pkg_reason->reason : '';
1552 my %hash = $self->hash;
1553 my $inactive = time - $hash{'susp'};
1555 my $conf = new FS::Conf;
1557 if ( $inactive > 0 &&
1558 ( $hash{'bill'} || $hash{'setup'} ) &&
1559 ( $opt{'adjust_next_bill'} ||
1560 $conf->exists('unsuspend-always_adjust_next_bill_date') ||
1561 $self->part_pkg->option('unsuspend_adjust_bill', 1) )
1564 $hash{'bill'} = ( $hash{'bill'} || $hash{'setup'} ) + $inactive;
1569 $hash{'adjourn'} = '' if $hash{'adjourn'} and $hash{'adjourn'} < time;
1570 $hash{'resume'} = '' if !$hash{'adjourn'};
1571 my $new = new FS::cust_pkg ( \%hash );
1572 $error = $new->replace( $self, options => { $self->options } );
1574 $dbh->rollback if $oldAutoCommit;
1580 if ( $reason && $reason->unsuspend_pkgpart ) {
1581 my $part_pkg = FS::part_pkg->by_key($reason->unsuspend_pkgpart)
1582 or $error = "Unsuspend package definition ".$reason->unsuspend_pkgpart.
1584 my $start_date = $self->cust_main->next_bill_date
1585 if $reason->unsuspend_hold;
1588 $unsusp_pkg = FS::cust_pkg->new({
1589 'custnum' => $self->custnum,
1590 'pkgpart' => $reason->unsuspend_pkgpart,
1591 'start_date' => $start_date,
1592 'locationnum' => $self->locationnum,
1593 # discount? probably not...
1596 $error ||= $self->cust_main->order_pkg( 'cust_pkg' => $unsusp_pkg );
1600 $dbh->rollback if $oldAutoCommit;
1605 if ( $conf->config('unsuspend_email_admin') ) {
1607 my $error = send_email(
1608 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
1609 #invoice_from ??? well as good as any
1610 'to' => $conf->config('unsuspend_email_admin'),
1611 'subject' => 'FREESIDE NOTIFICATION: Customer package unsuspended', 'body' => [
1612 "This is an automatic message from your Freeside installation\n",
1613 "informing you that the following customer package has been unsuspended:\n",
1615 'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
1616 'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
1617 ( map { "Service : $_\n" } @labels ),
1619 "An unsuspension fee was charged: ".
1620 $unsusp_pkg->part_pkg->pkg_comment."\n"
1627 warn "WARNING: can't send unsuspension admin email (unsuspending anyway): ".
1633 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1634 $error = $supp_pkg->unsuspend(%opt, 'from_main' => 1);
1636 $dbh->rollback if $oldAutoCommit;
1637 return "unsuspending supplemental pkg#".$supp_pkg->pkgnum.": $error";
1641 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1648 Cancels any pending suspension (sets the adjourn field to null).
1650 If there is an error, returns the error, otherwise returns false.
1655 my( $self, %options ) = @_;
1658 local $SIG{HUP} = 'IGNORE';
1659 local $SIG{INT} = 'IGNORE';
1660 local $SIG{QUIT} = 'IGNORE';
1661 local $SIG{TERM} = 'IGNORE';
1662 local $SIG{TSTP} = 'IGNORE';
1663 local $SIG{PIPE} = 'IGNORE';
1665 my $oldAutoCommit = $FS::UID::AutoCommit;
1666 local $FS::UID::AutoCommit = 0;
1669 my $old = $self->select_for_update;
1671 my $pkgnum = $old->pkgnum;
1672 if ( $old->get('cancel') || $self->get('cancel') ) {
1673 dbh->rollback if $oldAutoCommit;
1674 return "Can't unadjourn cancelled package $pkgnum";
1675 # or at least it's pointless
1678 if ( $old->get('susp') || $self->get('susp') ) {
1679 dbh->rollback if $oldAutoCommit;
1680 return "Can't unadjourn suspended package $pkgnum";
1681 # perhaps this is arbitrary
1684 unless ( $old->get('adjourn') && $self->get('adjourn') ) {
1685 dbh->rollback if $oldAutoCommit;
1686 return ""; # no error
1689 my %hash = $self->hash;
1690 $hash{'adjourn'} = '';
1691 $hash{'resume'} = '';
1692 my $new = new FS::cust_pkg ( \%hash );
1693 $error = $new->replace( $self, options => { $self->options } );
1695 $dbh->rollback if $oldAutoCommit;
1699 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1706 =item change HASHREF | OPTION => VALUE ...
1708 Changes this package: cancels it and creates a new one, with a different
1709 pkgpart or locationnum or both. All services are transferred to the new
1710 package (no change will be made if this is not possible).
1712 Options may be passed as a list of key/value pairs or as a hash reference.
1719 New locationnum, to change the location for this package.
1723 New FS::cust_location object, to create a new location and assign it
1728 New FS::cust_main object, to create a new customer and assign the new package
1733 New pkgpart (see L<FS::part_pkg>).
1737 New refnum (see L<FS::part_referral>).
1741 New quantity; if unspecified, the new package will have the same quantity
1746 "New" (existing) FS::cust_pkg object. The package's services and other
1747 attributes will be transferred to this package.
1751 Set to true to transfer billing dates (start_date, setup, last_bill, bill,
1752 susp, adjourn, cancel, expire, and contract_end) to the new package.
1754 =item unprotect_svcs
1756 Normally, change() will rollback and return an error if some services
1757 can't be transferred (also see the I<cust_pkg-change_svcpart> config option).
1758 If unprotect_svcs is true, this method will transfer as many services as
1759 it can and then unconditionally cancel the old package.
1763 At least one of locationnum, cust_location, pkgpart, refnum, cust_main, or
1764 cust_pkg must be specified (otherwise, what's the point?)
1766 Returns either the new FS::cust_pkg object or a scalar error.
1770 my $err_or_new_cust_pkg = $old_cust_pkg->change
1774 #some false laziness w/order
1777 my $opt = ref($_[0]) ? shift : { @_ };
1779 my $conf = new FS::Conf;
1781 # Transactionize this whole mess
1782 local $SIG{HUP} = 'IGNORE';
1783 local $SIG{INT} = 'IGNORE';
1784 local $SIG{QUIT} = 'IGNORE';
1785 local $SIG{TERM} = 'IGNORE';
1786 local $SIG{TSTP} = 'IGNORE';
1787 local $SIG{PIPE} = 'IGNORE';
1789 my $oldAutoCommit = $FS::UID::AutoCommit;
1790 local $FS::UID::AutoCommit = 0;
1799 $hash{'setup'} = $time if $self->setup;
1801 $hash{'change_date'} = $time;
1802 $hash{"change_$_"} = $self->$_()
1803 foreach qw( pkgnum pkgpart locationnum );
1805 if ( $opt->{'cust_location'} ) {
1806 $error = $opt->{'cust_location'}->find_or_insert;
1808 $dbh->rollback if $oldAutoCommit;
1809 return "inserting cust_location (transaction rolled back): $error";
1811 $opt->{'locationnum'} = $opt->{'cust_location'}->locationnum;
1814 if ( $opt->{'cust_pkg'} ) {
1815 # treat changing to a package with a different pkgpart as a
1816 # pkgpart change (because it is)
1817 $opt->{'pkgpart'} = $opt->{'cust_pkg'}->pkgpart;
1820 # whether to override pkgpart checking on the new package
1821 my $same_pkgpart = 1;
1822 if ( $opt->{'pkgpart'} and ( $opt->{'pkgpart'} != $self->pkgpart ) ) {
1826 my $unused_credit = 0;
1827 my $keep_dates = $opt->{'keep_dates'};
1828 # Special case. If the pkgpart is changing, and the customer is
1829 # going to be credited for remaining time, don't keep setup, bill,
1830 # or last_bill dates, and DO pass the flag to cancel() to credit
1832 if ( $opt->{'pkgpart'}
1833 and $opt->{'pkgpart'} != $self->pkgpart
1834 and $self->part_pkg->option('unused_credit_change', 1) ) {
1837 $hash{$_} = '' foreach qw(setup bill last_bill);
1840 if ( $keep_dates ) {
1841 foreach my $date ( qw(setup bill last_bill susp adjourn cancel expire
1842 resume start_date contract_end ) ) {
1843 $hash{$date} = $self->getfield($date);
1847 # allow $opt->{'locationnum'} = '' to specifically set it to null
1848 # (i.e. customer default location)
1849 $opt->{'locationnum'} = $self->locationnum if !exists($opt->{'locationnum'});
1851 # usually this doesn't matter. the two cases where it does are:
1852 # 1. unused_credit_change + pkgpart change + setup fee on the new package
1854 # 2. (more importantly) changing a package before it's billed
1855 $hash{'waive_setup'} = $self->waive_setup;
1857 my $custnum = $self->custnum;
1858 if ( $opt->{cust_main} ) {
1859 my $cust_main = $opt->{cust_main};
1860 unless ( $cust_main->custnum ) {
1861 my $error = $cust_main->insert;
1863 $dbh->rollback if $oldAutoCommit;
1864 return "inserting cust_main (transaction rolled back): $error";
1867 $custnum = $cust_main->custnum;
1870 $hash{'contactnum'} = $opt->{'contactnum'} if $opt->{'contactnum'};
1873 if ( $opt->{'cust_pkg'} ) {
1874 # The target package already exists; update it to show that it was
1875 # changed from this package.
1876 $cust_pkg = $opt->{'cust_pkg'};
1878 foreach ( qw( pkgnum pkgpart locationnum ) ) {
1879 $cust_pkg->set("change_$_", $self->get($_));
1881 $cust_pkg->set('change_date', $time);
1882 $error = $cust_pkg->replace;
1885 # Create the new package.
1886 $cust_pkg = new FS::cust_pkg {
1887 custnum => $custnum,
1888 locationnum => $opt->{'locationnum'},
1889 ( map { $_ => ( $opt->{$_} || $self->$_() ) }
1890 qw( pkgpart quantity refnum salesnum )
1894 $error = $cust_pkg->insert( 'change' => 1,
1895 'allow_pkgpart' => $same_pkgpart );
1898 $dbh->rollback if $oldAutoCommit;
1902 # Transfer services and cancel old package.
1904 $error = $self->transfer($cust_pkg);
1905 if ($error and $error == 0) {
1906 # $old_pkg->transfer failed.
1907 $dbh->rollback if $oldAutoCommit;
1911 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
1912 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
1913 $error = $self->transfer($cust_pkg, 'change_svcpart'=>1 );
1914 if ($error and $error == 0) {
1915 # $old_pkg->transfer failed.
1916 $dbh->rollback if $oldAutoCommit;
1921 # We set unprotect_svcs when executing a "future package change". It's
1922 # not a user-interactive operation, so returning an error means the
1923 # package change will just fail. Rather than have that happen, we'll
1924 # let leftover services be deleted.
1925 if ($error > 0 and !$opt->{'unprotect_svcs'}) {
1926 # Transfers were successful, but we still had services left on the old
1927 # package. We can't change the package under this circumstances, so abort.
1928 $dbh->rollback if $oldAutoCommit;
1929 return "Unable to transfer all services from package ". $self->pkgnum;
1932 #reset usage if changing pkgpart
1933 # AND usage rollover is off (otherwise adds twice, now and at package bill)
1934 if ($self->pkgpart != $cust_pkg->pkgpart) {
1935 my $part_pkg = $cust_pkg->part_pkg;
1936 $error = $part_pkg->reset_usage($cust_pkg, $part_pkg->is_prepaid
1940 if $part_pkg->can('reset_usage') && ! $part_pkg->option('usage_rollover',1);
1943 $dbh->rollback if $oldAutoCommit;
1944 return "Error setting usage values: $error";
1947 # if NOT changing pkgpart, transfer any usage pools over
1948 foreach my $usage ($self->cust_pkg_usage) {
1949 $usage->set('pkgnum', $cust_pkg->pkgnum);
1950 $error = $usage->replace;
1952 $dbh->rollback if $oldAutoCommit;
1953 return "Error transferring usage pools: $error";
1958 # transfer discounts, if we're not changing pkgpart
1959 if ( $same_pkgpart ) {
1960 foreach my $old_discount ($self->cust_pkg_discount_active) {
1961 # don't remove the old discount, we may still need to bill that package.
1962 my $new_discount = new FS::cust_pkg_discount {
1963 'pkgnum' => $cust_pkg->pkgnum,
1964 'discountnum' => $old_discount->discountnum,
1965 'months_used' => $old_discount->months_used,
1967 $error = $new_discount->insert;
1969 $dbh->rollback if $oldAutoCommit;
1970 return "Error transferring discounts: $error";
1975 # transfer (copy) invoice details
1976 foreach my $detail ($self->cust_pkg_detail) {
1977 my $new_detail = FS::cust_pkg_detail->new({ $detail->hash });
1978 $new_detail->set('pkgdetailnum', '');
1979 $new_detail->set('pkgnum', $cust_pkg->pkgnum);
1980 $error = $new_detail->insert;
1982 $dbh->rollback if $oldAutoCommit;
1983 return "Error transferring package notes: $error";
1989 if ( !$opt->{'cust_pkg'} ) {
1990 # Order any supplemental packages.
1991 my $part_pkg = $cust_pkg->part_pkg;
1992 my @old_supp_pkgs = $self->supplemental_pkgs;
1993 foreach my $link ($part_pkg->supp_part_pkg_link) {
1995 foreach (@old_supp_pkgs) {
1996 if ($_->pkgpart == $link->dst_pkgpart) {
1998 $_->pkgpart(0); # so that it can't match more than once
2002 # false laziness with FS::cust_main::Packages::order_pkg
2003 my $new = FS::cust_pkg->new({
2004 pkgpart => $link->dst_pkgpart,
2005 pkglinknum => $link->pkglinknum,
2006 custnum => $custnum,
2007 main_pkgnum => $cust_pkg->pkgnum,
2008 locationnum => $cust_pkg->locationnum,
2009 start_date => $cust_pkg->start_date,
2010 order_date => $cust_pkg->order_date,
2011 expire => $cust_pkg->expire,
2012 adjourn => $cust_pkg->adjourn,
2013 contract_end => $cust_pkg->contract_end,
2014 refnum => $cust_pkg->refnum,
2015 discountnum => $cust_pkg->discountnum,
2016 waive_setup => $cust_pkg->waive_setup,
2018 if ( $old and $opt->{'keep_dates'} ) {
2019 foreach (qw(setup bill last_bill)) {
2020 $new->set($_, $old->get($_));
2023 $error = $new->insert( allow_pkgpart => $same_pkgpart );
2026 $error ||= $old->transfer($new);
2028 if ( $error and $error > 0 ) {
2029 # no reason why this should ever fail, but still...
2030 $error = "Unable to transfer all services from supplemental package ".
2034 $dbh->rollback if $oldAutoCommit;
2037 push @new_supp_pkgs, $new;
2039 } # if !$opt->{'cust_pkg'}
2040 # because if there is one, then supplemental packages would already
2041 # have been created for it.
2043 #Good to go, cancel old package. Notify 'cancel' of whether to credit
2045 #Don't allow billing the package (preceding period packages and/or
2046 #outstanding usage) if we are keeping dates (i.e. location changing),
2047 #because the new package will be billed for the same date range.
2048 #Supplemental packages are also canceled here.
2050 # during scheduled changes, avoid canceling the package we just
2052 $self->set('change_to_pkgnum' => '');
2054 $error = $self->cancel(
2056 unused_credit => $unused_credit,
2057 nobill => $keep_dates,
2058 change_custnum => ( $self->custnum != $custnum ? $custnum : '' ),
2061 $dbh->rollback if $oldAutoCommit;
2065 if ( $conf->exists('cust_pkg-change_pkgpart-bill_now') ) {
2067 my $error = $cust_pkg->cust_main->bill(
2068 'pkg_list' => [ $cust_pkg, @new_supp_pkgs ]
2071 $dbh->rollback if $oldAutoCommit;
2076 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2082 =item change_later OPTION => VALUE...
2084 Schedule a package change for a later date. This actually orders the new
2085 package immediately, but sets its start date for a future date, and sets
2086 the current package to expire on the same date.
2088 If the package is already scheduled for a change, this can be called with
2089 'start_date' to change the scheduled date, or with pkgpart and/or
2090 locationnum to modify the package change. To cancel the scheduled change
2091 entirely, see C<abort_change>.
2099 The date for the package change. Required, and must be in the future.
2107 The pkgpart. locationnum, and quantity of the new package, with the same
2108 meaning as in C<change>.
2116 my $opt = ref($_[0]) ? shift : { @_ };
2118 my $oldAutoCommit = $FS::UID::AutoCommit;
2119 local $FS::UID::AutoCommit = 0;
2122 my $cust_main = $self->cust_main;
2124 my $date = delete $opt->{'start_date'} or return 'start_date required';
2126 if ( $date <= time ) {
2127 $dbh->rollback if $oldAutoCommit;
2128 return "start_date $date is in the past";
2133 if ( $self->change_to_pkgnum ) {
2134 my $change_to = FS::cust_pkg->by_key($self->change_to_pkgnum);
2135 my $new_pkgpart = $opt->{'pkgpart'}
2136 if $opt->{'pkgpart'} and $opt->{'pkgpart'} != $change_to->pkgpart;
2137 my $new_locationnum = $opt->{'locationnum'}
2138 if $opt->{'locationnum'} and $opt->{'locationnum'} != $change_to->locationnum;
2139 my $new_quantity = $opt->{'quantity'}
2140 if $opt->{'quantity'} and $opt->{'quantity'} != $change_to->quantity;
2141 if ( $new_pkgpart or $new_locationnum or $new_quantity ) {
2142 # it hasn't been billed yet, so in principle we could just edit
2143 # it in place (w/o a package change), but that's bad form.
2144 # So change the package according to the new options...
2145 my $err_or_pkg = $change_to->change(%$opt);
2146 if ( ref $err_or_pkg ) {
2147 # Then set that package up for a future start.
2148 $self->set('change_to_pkgnum', $err_or_pkg->pkgnum);
2149 $self->set('expire', $date); # in case it's different
2150 $err_or_pkg->set('start_date', $date);
2151 $err_or_pkg->set('change_date', '');
2152 $err_or_pkg->set('change_pkgnum', '');
2154 $error = $self->replace ||
2155 $err_or_pkg->replace ||
2156 $change_to->cancel ||
2159 $error = $err_or_pkg;
2161 } else { # change the start date only.
2162 $self->set('expire', $date);
2163 $change_to->set('start_date', $date);
2164 $error = $self->replace || $change_to->replace;
2167 $dbh->rollback if $oldAutoCommit;
2170 $dbh->commit if $oldAutoCommit;
2173 } # if $self->change_to_pkgnum
2175 my $new_pkgpart = $opt->{'pkgpart'}
2176 if $opt->{'pkgpart'} and $opt->{'pkgpart'} != $self->pkgpart;
2177 my $new_locationnum = $opt->{'locationnum'}
2178 if $opt->{'locationnum'} and $opt->{'locationnum'} != $self->locationnum;
2179 my $new_quantity = $opt->{'quantity'}
2180 if $opt->{'quantity'} and $opt->{'quantity'} != $self->quantity;
2182 return '' unless $new_pkgpart or $new_locationnum or $new_quantity; # wouldn't do anything
2184 # allow $opt->{'locationnum'} = '' to specifically set it to null
2185 # (i.e. customer default location)
2186 $opt->{'locationnum'} = $self->locationnum if !exists($opt->{'locationnum'});
2188 my $new = FS::cust_pkg->new( {
2189 custnum => $self->custnum,
2190 locationnum => $opt->{'locationnum'},
2191 start_date => $date,
2192 map { $_ => ( $opt->{$_} || $self->$_() ) }
2193 qw( pkgpart quantity refnum salesnum )
2195 $error = $new->insert('change' => 1,
2196 'allow_pkgpart' => ($new_pkgpart ? 0 : 1));
2198 $self->set('change_to_pkgnum', $new->pkgnum);
2199 $self->set('expire', $date);
2200 $error = $self->replace;
2203 $dbh->rollback if $oldAutoCommit;
2205 $dbh->commit if $oldAutoCommit;
2213 Cancels a future package change scheduled by C<change_later>.
2219 my $pkgnum = $self->change_to_pkgnum;
2220 my $change_to = FS::cust_pkg->by_key($pkgnum) if $pkgnum;
2223 $error = $change_to->cancel || $change_to->delete;
2224 return $error if $error;
2226 $self->set('change_to_pkgnum', '');
2227 $self->set('expire', '');
2231 =item set_quantity QUANTITY
2233 Change the package's quantity field. This is one of the few package properties
2234 that can safely be changed without canceling and reordering the package
2235 (because it doesn't affect tax eligibility). Returns an error or an
2242 $self = $self->replace_old; # just to make sure
2243 $self->quantity(shift);
2247 =item set_salesnum SALESNUM
2249 Change the package's salesnum (sales person) field. This is one of the few
2250 package properties that can safely be changed without canceling and reordering
2251 the package (because it doesn't affect tax eligibility). Returns an error or
2258 $self = $self->replace_old; # just to make sure
2259 $self->salesnum(shift);
2261 # XXX this should probably reassign any credit that's already been given
2264 =item modify_charge OPTIONS
2266 Change the properties of a one-time charge. Currently the only properties
2267 that can be changed this way are those that have no impact on billing
2269 - pkg: the package description
2270 - classnum: the package class
2271 - additional: arrayref of additional invoice details to add to this package
2273 If you pass 'adjust_commission' => 1, and the classnum changes, and there are
2274 commission credits linked to this charge, they will be recalculated.
2281 my $part_pkg = $self->part_pkg;
2282 my $pkgnum = $self->pkgnum;
2285 my $oldAutoCommit = $FS::UID::AutoCommit;
2286 local $FS::UID::AutoCommit = 0;
2288 return "Can't use modify_charge except on one-time charges"
2289 unless $part_pkg->freq eq '0';
2291 if ( length($opt{'pkg'}) and $part_pkg->pkg ne $opt{'pkg'} ) {
2292 $part_pkg->set('pkg', $opt{'pkg'});
2295 my %pkg_opt = $part_pkg->options;
2296 if ( ref($opt{'additional'}) ) {
2297 delete $pkg_opt{$_} foreach grep /^additional/, keys %pkg_opt;
2299 for ( $i = 0; exists($opt{'additional'}->[$i]); $i++ ) {
2300 $pkg_opt{ "additional_info$i" } = $opt{'additional'}->[$i];
2302 $pkg_opt{'additional_count'} = $i if $i > 0;
2306 if ( exists($opt{'classnum'}) and $part_pkg->classnum ne $opt{'classnum'} ) {
2308 $old_classnum = $part_pkg->classnum;
2309 $part_pkg->set('classnum', $opt{'classnum'});
2312 my $error = $part_pkg->replace( options => \%pkg_opt );
2313 return $error if $error;
2315 if (defined $old_classnum) {
2316 # fix invoice grouping records
2317 my $old_catname = $old_classnum
2318 ? FS::pkg_class->by_key($old_classnum)->categoryname
2320 my $new_catname = $opt{'classnum'}
2321 ? $part_pkg->pkg_class->categoryname
2323 if ( $old_catname ne $new_catname ) {
2324 foreach my $cust_bill_pkg ($self->cust_bill_pkg) {
2325 # (there should only be one...)
2326 my @display = qsearch( 'cust_bill_pkg_display', {
2327 'billpkgnum' => $cust_bill_pkg->billpkgnum,
2328 'section' => $old_catname,
2330 foreach (@display) {
2331 $_->set('section', $new_catname);
2332 $error = $_->replace;
2334 $dbh->rollback if $oldAutoCommit;
2338 } # foreach $cust_bill_pkg
2341 if ( $opt{'adjust_commission'} ) {
2342 # fix commission credits...tricky.
2343 foreach my $cust_event ($self->cust_event) {
2344 my $part_event = $cust_event->part_event;
2345 foreach my $table (qw(sales agent)) {
2347 "FS::part_event::Action::Mixin::credit_${table}_pkg_class";
2348 my $credit = qsearchs('cust_credit', {
2349 'eventnum' => $cust_event->eventnum,
2351 if ( $part_event->isa($class) ) {
2352 # Yes, this results in current commission rates being applied
2353 # retroactively to a one-time charge. For accounting purposes
2354 # there ought to be some kind of time limit on doing this.
2355 my $amount = $part_event->_calc_credit($self);
2356 if ( $credit and $credit->amount ne $amount ) {
2357 # Void the old credit.
2358 $error = $credit->void('Package class changed');
2360 $dbh->rollback if $oldAutoCommit;
2361 return "$error (adjusting commission credit)";
2364 # redo the event action to recreate the credit.
2366 eval { $part_event->do_action( $self, $cust_event ) };
2368 $dbh->rollback if $oldAutoCommit;
2371 } # if $part_event->isa($class)
2373 } # foreach $cust_event
2374 } # if $opt{'adjust_commission'}
2375 } # if defined $old_classnum
2377 $dbh->commit if $oldAutoCommit;
2383 use Storable 'thaw';
2386 sub process_bulk_cust_pkg {
2388 my $param = thaw(decode_base64(shift));
2389 warn Dumper($param) if $DEBUG;
2391 my $old_part_pkg = qsearchs('part_pkg',
2392 { pkgpart => $param->{'old_pkgpart'} });
2393 my $new_part_pkg = qsearchs('part_pkg',
2394 { pkgpart => $param->{'new_pkgpart'} });
2395 die "Must select a new package type\n" unless $new_part_pkg;
2396 #my $keep_dates = $param->{'keep_dates'} || 0;
2397 my $keep_dates = 1; # there is no good reason to turn this off
2399 local $SIG{HUP} = 'IGNORE';
2400 local $SIG{INT} = 'IGNORE';
2401 local $SIG{QUIT} = 'IGNORE';
2402 local $SIG{TERM} = 'IGNORE';
2403 local $SIG{TSTP} = 'IGNORE';
2404 local $SIG{PIPE} = 'IGNORE';
2406 my $oldAutoCommit = $FS::UID::AutoCommit;
2407 local $FS::UID::AutoCommit = 0;
2410 my @cust_pkgs = qsearch('cust_pkg', { 'pkgpart' => $param->{'old_pkgpart'} } );
2413 foreach my $old_cust_pkg ( @cust_pkgs ) {
2415 $job->update_statustext(int(100*$i/(scalar @cust_pkgs)));
2416 if ( $old_cust_pkg->getfield('cancel') ) {
2417 warn '[process_bulk_cust_pkg ] skipping canceled pkgnum '.
2418 $old_cust_pkg->pkgnum."\n"
2422 warn '[process_bulk_cust_pkg] changing pkgnum '.$old_cust_pkg->pkgnum."\n"
2424 my $error = $old_cust_pkg->change(
2425 'pkgpart' => $param->{'new_pkgpart'},
2426 'keep_dates' => $keep_dates
2428 if ( !ref($error) ) { # change returns the cust_pkg on success
2430 die "Error changing pkgnum ".$old_cust_pkg->pkgnum.": '$error'\n";
2433 $dbh->commit if $oldAutoCommit;
2439 Returns the last bill date, or if there is no last bill date, the setup date.
2440 Useful for billing metered services.
2446 return $self->setfield('last_bill', $_[0]) if @_;
2447 return $self->getfield('last_bill') if $self->getfield('last_bill');
2448 my $cust_bill_pkg = qsearchs('cust_bill_pkg', { 'pkgnum' => $self->pkgnum,
2449 'edate' => $self->bill, } );
2450 $cust_bill_pkg ? $cust_bill_pkg->sdate : $self->setup || 0;
2453 =item last_cust_pkg_reason ACTION
2455 Returns the most recent ACTION FS::cust_pkg_reason associated with the package.
2456 Returns false if there is no reason or the package is not currenly ACTION'd
2457 ACTION is one of adjourn, susp, cancel, or expire.
2461 sub last_cust_pkg_reason {
2462 my ( $self, $action ) = ( shift, shift );
2463 my $date = $self->get($action);
2465 'table' => 'cust_pkg_reason',
2466 'hashref' => { 'pkgnum' => $self->pkgnum,
2467 'action' => substr(uc($action), 0, 1),
2470 'order_by' => 'ORDER BY num DESC LIMIT 1',
2474 =item last_reason ACTION
2476 Returns the most recent ACTION FS::reason associated with the package.
2477 Returns false if there is no reason or the package is not currenly ACTION'd
2478 ACTION is one of adjourn, susp, cancel, or expire.
2483 my $cust_pkg_reason = shift->last_cust_pkg_reason(@_);
2484 $cust_pkg_reason->reason
2485 if $cust_pkg_reason;
2490 Returns the definition for this billing item, as an FS::part_pkg object (see
2497 return $self->{'_pkgpart'} if $self->{'_pkgpart'};
2498 cluck "cust_pkg->part_pkg called" if $DEBUG > 1;
2499 qsearchs( 'part_pkg', { 'pkgpart' => $self->pkgpart } );
2504 Returns the cancelled package this package was changed from, if any.
2510 return '' unless $self->change_pkgnum;
2511 qsearchs('cust_pkg', { 'pkgnum' => $self->change_pkgnum } );
2514 =item change_cust_main
2516 Returns the customter this package was detached to, if any.
2520 sub change_cust_main {
2522 return '' unless $self->change_custnum;
2523 qsearchs('cust_main', { 'custnum' => $self->change_custnum } );
2528 Calls the I<calc_setup> of the FS::part_pkg object associated with this billing
2535 $self->part_pkg->calc_setup($self, @_);
2540 Calls the I<calc_recur> of the FS::part_pkg object associated with this billing
2547 $self->part_pkg->calc_recur($self, @_);
2552 Calls the I<base_recur> of the FS::part_pkg object associated with this billing
2559 $self->part_pkg->base_recur($self, @_);
2564 Calls the I<calc_remain> of the FS::part_pkg object associated with this
2571 $self->part_pkg->calc_remain($self, @_);
2576 Calls the I<calc_cancel> of the FS::part_pkg object associated with this
2583 $self->part_pkg->calc_cancel($self, @_);
2588 Returns any invoice line items for this package (see L<FS::cust_bill_pkg>).
2594 qsearch( 'cust_bill_pkg', { 'pkgnum' => $self->pkgnum } );
2597 =item cust_pkg_detail [ DETAILTYPE ]
2599 Returns any customer package details for this package (see
2600 L<FS::cust_pkg_detail>).
2602 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
2606 sub cust_pkg_detail {
2608 my %hash = ( 'pkgnum' => $self->pkgnum );
2609 $hash{detailtype} = shift if @_;
2611 'table' => 'cust_pkg_detail',
2612 'hashref' => \%hash,
2613 'order_by' => 'ORDER BY weight, pkgdetailnum',
2617 =item set_cust_pkg_detail DETAILTYPE [ DETAIL, DETAIL, ... ]
2619 Sets customer package details for this package (see L<FS::cust_pkg_detail>).
2621 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
2623 If there is an error, returns the error, otherwise returns false.
2627 sub set_cust_pkg_detail {
2628 my( $self, $detailtype, @details ) = @_;
2630 local $SIG{HUP} = 'IGNORE';
2631 local $SIG{INT} = 'IGNORE';
2632 local $SIG{QUIT} = 'IGNORE';
2633 local $SIG{TERM} = 'IGNORE';
2634 local $SIG{TSTP} = 'IGNORE';
2635 local $SIG{PIPE} = 'IGNORE';
2637 my $oldAutoCommit = $FS::UID::AutoCommit;
2638 local $FS::UID::AutoCommit = 0;
2641 foreach my $current ( $self->cust_pkg_detail($detailtype) ) {
2642 my $error = $current->delete;
2644 $dbh->rollback if $oldAutoCommit;
2645 return "error removing old detail: $error";
2649 foreach my $detail ( @details ) {
2650 my $cust_pkg_detail = new FS::cust_pkg_detail {
2651 'pkgnum' => $self->pkgnum,
2652 'detailtype' => $detailtype,
2653 'detail' => $detail,
2655 my $error = $cust_pkg_detail->insert;
2657 $dbh->rollback if $oldAutoCommit;
2658 return "error adding new detail: $error";
2663 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2670 Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.
2674 #false laziness w/cust_bill.pm
2678 'table' => 'cust_event',
2679 'addl_from' => 'JOIN part_event USING ( eventpart )',
2680 'hashref' => { 'tablenum' => $self->pkgnum },
2681 'extra_sql' => " AND eventtable = 'cust_pkg' ",
2685 =item num_cust_event
2687 Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.
2691 #false laziness w/cust_bill.pm
2692 sub num_cust_event {
2695 "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
2696 " WHERE tablenum = ? AND eventtable = 'cust_pkg'";
2697 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
2698 $sth->execute($self->pkgnum) or die $sth->errstr. " executing $sql";
2699 $sth->fetchrow_arrayref->[0];
2702 =item cust_svc [ SVCPART ] (old, deprecated usage)
2704 =item cust_svc [ OPTION => VALUE ... ] (current usage)
2706 Returns the services for this package, as FS::cust_svc objects (see
2707 L<FS::cust_svc>). Available options are svcpart and svcdb. If either is
2708 spcififed, returns only the matching services.
2715 return () unless $self->num_cust_svc(@_);
2718 if ( @_ && $_[0] =~ /^\d+/ ) {
2719 $opt{svcpart} = shift;
2720 } elsif ( @_ && ref($_[0]) eq 'HASH' ) {
2727 'table' => 'cust_svc',
2728 'hashref' => { 'pkgnum' => $self->pkgnum },
2730 if ( $opt{svcpart} ) {
2731 $search{hashref}->{svcpart} = $opt{'svcpart'};
2733 if ( $opt{'svcdb'} ) {
2734 $search{addl_from} = ' LEFT JOIN part_svc USING ( svcpart ) ';
2735 $search{extra_sql} = ' AND svcdb = '. dbh->quote( $opt{'svcdb'} );
2738 cluck "cust_pkg->cust_svc called" if $DEBUG > 2;
2740 #if ( $self->{'_svcnum'} ) {
2741 # values %{ $self->{'_svcnum'}->cache };
2743 $self->_sort_cust_svc( [ qsearch(\%search) ] );
2748 =item overlimit [ SVCPART ]
2750 Returns the services for this package which have exceeded their
2751 usage limit as FS::cust_svc objects (see L<FS::cust_svc>). If a svcpart
2752 is specified, return only the matching services.
2758 return () unless $self->num_cust_svc(@_);
2759 grep { $_->overlimit } $self->cust_svc(@_);
2762 =item h_cust_svc END_TIMESTAMP [ START_TIMESTAMP ] [ MODE ]
2764 Returns historical services for this package created before END TIMESTAMP and
2765 (optionally) not cancelled before START_TIMESTAMP, as FS::h_cust_svc objects
2766 (see L<FS::h_cust_svc>). If MODE is 'I' (for 'invoice'), services with the
2767 I<pkg_svc.hidden> flag will be omitted.
2773 warn "$me _h_cust_svc called on $self\n"
2776 my ($end, $start, $mode) = @_;
2777 my @cust_svc = $self->_sort_cust_svc(
2778 [ qsearch( 'h_cust_svc',
2779 { 'pkgnum' => $self->pkgnum, },
2780 FS::h_cust_svc->sql_h_search(@_),
2783 if ( defined($mode) && $mode eq 'I' ) {
2784 my %hidden_svcpart = map { $_->svcpart => $_->hidden } $self->part_svc;
2785 return grep { !$hidden_svcpart{$_->svcpart} } @cust_svc;
2791 sub _sort_cust_svc {
2792 my( $self, $arrayref ) = @_;
2795 sub ($$) { my ($a, $b) = @_; $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] };
2797 my %pkg_svc = map { $_->svcpart => $_ }
2798 qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
2803 my $pkg_svc = $pkg_svc{ $_->svcpart } || '';
2805 $pkg_svc ? $pkg_svc->primary_svc : '',
2806 $pkg_svc ? $pkg_svc->quantity : 0,
2813 =item num_cust_svc [ SVCPART ] (old, deprecated usage)
2815 =item num_cust_svc [ OPTION => VALUE ... ] (current usage)
2817 Returns the number of services for this package. Available options are svcpart
2818 and svcdb. If either is spcififed, returns only the matching services.
2825 return $self->{'_num_cust_svc'}
2827 && exists($self->{'_num_cust_svc'})
2828 && $self->{'_num_cust_svc'} =~ /\d/;
2830 cluck "cust_pkg->num_cust_svc called, _num_cust_svc:".$self->{'_num_cust_svc'}
2834 if ( @_ && $_[0] =~ /^\d+/ ) {
2835 $opt{svcpart} = shift;
2836 } elsif ( @_ && ref($_[0]) eq 'HASH' ) {
2842 my $select = 'SELECT COUNT(*) FROM cust_svc ';
2843 my $where = ' WHERE pkgnum = ? ';
2844 my @param = ($self->pkgnum);
2846 if ( $opt{'svcpart'} ) {
2847 $where .= ' AND svcpart = ? ';
2848 push @param, $opt{'svcpart'};
2850 if ( $opt{'svcdb'} ) {
2851 $select .= ' LEFT JOIN part_svc USING ( svcpart ) ';
2852 $where .= ' AND svcdb = ? ';
2853 push @param, $opt{'svcdb'};
2856 my $sth = dbh->prepare("$select $where") or die dbh->errstr;
2857 $sth->execute(@param) or die $sth->errstr;
2858 $sth->fetchrow_arrayref->[0];
2861 =item available_part_svc
2863 Returns a list of FS::part_svc objects representing services included in this
2864 package but not yet provisioned. Each FS::part_svc object also has an extra
2865 field, I<num_avail>, which specifies the number of available services.
2869 sub available_part_svc {
2872 my $pkg_quantity = $self->quantity || 1;
2874 grep { $_->num_avail > 0 }
2876 my $part_svc = $_->part_svc;
2877 $part_svc->{'Hash'}{'num_avail'} = #evil encapsulation-breaking
2878 $pkg_quantity * $_->quantity - $self->num_cust_svc($_->svcpart);
2880 # more evil encapsulation breakage
2881 if($part_svc->{'Hash'}{'num_avail'} > 0) {
2882 my @exports = $part_svc->part_export_did;
2883 $part_svc->{'Hash'}{'can_get_dids'} = scalar(@exports);
2888 $self->part_pkg->pkg_svc;
2891 =item part_svc [ OPTION => VALUE ... ]
2893 Returns a list of FS::part_svc objects representing provisioned and available
2894 services included in this package. Each FS::part_svc object also has the
2895 following extra fields:
2899 =item num_cust_svc (count)
2901 =item num_avail (quantity - count)
2903 =item cust_pkg_svc (services) - array reference containing the provisioned services, as cust_svc objects
2907 Accepts one option: summarize_size. If specified and non-zero, will omit the
2908 extra cust_pkg_svc option for objects where num_cust_svc is this size or
2914 #label -> ($cust_svc->label)[1]
2920 my $pkg_quantity = $self->quantity || 1;
2922 #XXX some sort of sort order besides numeric by svcpart...
2923 my @part_svc = sort { $a->svcpart <=> $b->svcpart } map {
2925 my $part_svc = $pkg_svc->part_svc;
2926 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
2927 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #more evil
2928 $part_svc->{'Hash'}{'num_avail'} =
2929 max( 0, $pkg_quantity * $pkg_svc->quantity - $num_cust_svc );
2930 $part_svc->{'Hash'}{'cust_pkg_svc'} =
2931 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : []
2932 unless exists($opt{summarize_size}) && $opt{summarize_size} > 0
2933 && $num_cust_svc >= $opt{summarize_size};
2934 $part_svc->{'Hash'}{'hidden'} = $pkg_svc->hidden;
2936 } $self->part_pkg->pkg_svc;
2939 push @part_svc, map {
2941 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
2942 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #speak no evail
2943 $part_svc->{'Hash'}{'num_avail'} = 0; #0-$num_cust_svc ?
2944 $part_svc->{'Hash'}{'cust_pkg_svc'} =
2945 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : [];
2947 } $self->extra_part_svc;
2953 =item extra_part_svc
2955 Returns a list of FS::part_svc objects corresponding to services in this
2956 package which are still provisioned but not (any longer) available in the
2961 sub extra_part_svc {
2964 my $pkgnum = $self->pkgnum;
2965 #my $pkgpart = $self->pkgpart;
2968 # 'table' => 'part_svc',
2971 # "WHERE 0 = ( SELECT COUNT(*) FROM pkg_svc
2972 # WHERE pkg_svc.svcpart = part_svc.svcpart
2973 # AND pkg_svc.pkgpart = ?
2976 # AND 0 < ( SELECT COUNT(*) FROM cust_svc
2977 # LEFT JOIN cust_pkg USING ( pkgnum )
2978 # WHERE cust_svc.svcpart = part_svc.svcpart
2981 # 'extra_param' => [ [$self->pkgpart=>'int'], [$self->pkgnum=>'int'] ],
2984 #seems to benchmark slightly faster... (or did?)
2986 my @pkgparts = map $_->pkgpart, $self->part_pkg->self_and_svc_linked;
2987 my $pkgparts = join(',', @pkgparts);
2990 #'select' => 'DISTINCT ON (svcpart) part_svc.*',
2991 #MySQL doesn't grok DISINCT ON
2992 'select' => 'DISTINCT part_svc.*',
2993 'table' => 'part_svc',
2995 "LEFT JOIN pkg_svc ON ( pkg_svc.svcpart = part_svc.svcpart
2996 AND pkg_svc.pkgpart IN ($pkgparts)
2999 LEFT JOIN cust_svc ON ( cust_svc.svcpart = part_svc.svcpart )
3000 LEFT JOIN cust_pkg USING ( pkgnum )
3003 'extra_sql' => "WHERE pkgsvcnum IS NULL AND cust_pkg.pkgnum = ? ",
3004 'extra_param' => [ [$self->pkgnum=>'int'] ],
3010 Returns a short status string for this package, currently:
3014 =item not yet billed
3016 =item one-time charge
3031 my $freq = length($self->freq) ? $self->freq : $self->part_pkg->freq;
3033 return 'cancelled' if $self->get('cancel');
3034 return 'suspended' if $self->susp;
3035 return 'not yet billed' unless $self->setup;
3036 return 'one-time charge' if $freq =~ /^(0|$)/;
3040 =item ucfirst_status
3042 Returns the status with the first character capitalized.
3046 sub ucfirst_status {
3047 ucfirst(shift->status);
3052 Class method that returns the list of possible status strings for packages
3053 (see L<the status method|/status>). For example:
3055 @statuses = FS::cust_pkg->statuses();
3059 tie my %statuscolor, 'Tie::IxHash',
3060 'not yet billed' => '009999', #teal? cyan?
3061 'one-time charge' => '000000',
3062 'active' => '00CC00',
3063 'suspended' => 'FF9900',
3064 'cancelled' => 'FF0000',
3068 my $self = shift; #could be class...
3069 #grep { $_ !~ /^(not yet billed)$/ } #this is a dumb status anyway
3070 # # mayble split btw one-time vs. recur
3076 Returns a hex triplet color string for this package's status.
3082 $statuscolor{$self->status};
3087 Returns a label for this package. (Currently "pkgnum: pkg - comment" or
3088 "pkg - comment" depending on user preference).
3094 my $label = $self->part_pkg->pkg_comment( 'nopkgpart' => 1 );
3095 $label = $self->pkgnum. ": $label"
3096 if $FS::CurrentUser::CurrentUser->option('show_pkgnum');
3100 =item pkg_label_long
3102 Returns a long label for this package, adding the primary service's label to
3107 sub pkg_label_long {
3109 my $label = $self->pkg_label;
3110 my $cust_svc = $self->primary_cust_svc;
3111 $label .= ' ('. ($cust_svc->label)[1]. ')' if $cust_svc;
3117 Returns a customer-localized label for this package.
3123 $self->part_pkg->pkg_locale( $self->cust_main->locale );
3126 =item primary_cust_svc
3128 Returns a primary service (as FS::cust_svc object) if one can be identified.
3132 #for labeling purposes - might not 100% match up with part_pkg->svcpart's idea
3134 sub primary_cust_svc {
3137 my @cust_svc = $self->cust_svc;
3139 return '' unless @cust_svc; #no serivces - irrelevant then
3141 return $cust_svc[0] if scalar(@cust_svc) == 1; #always return a single service
3143 # primary service as specified in the package definition
3144 # or exactly one service definition with quantity one
3145 my $svcpart = $self->part_pkg->svcpart;
3146 @cust_svc = grep { $_->svcpart == $svcpart } @cust_svc;
3147 return $cust_svc[0] if scalar(@cust_svc) == 1;
3149 #couldn't identify one thing..
3155 Returns a list of lists, calling the label method for all services
3156 (see L<FS::cust_svc>) of this billing item.
3162 map { [ $_->label ] } $self->cust_svc;
3165 =item h_labels END_TIMESTAMP [ START_TIMESTAMP ] [ MODE ]
3167 Like the labels method, but returns historical information on services that
3168 were active as of END_TIMESTAMP and (optionally) not cancelled before
3169 START_TIMESTAMP. If MODE is 'I' (for 'invoice'), services with the
3170 I<pkg_svc.hidden> flag will be omitted.
3172 Returns a list of lists, calling the label method for all (historical) services
3173 (see L<FS::h_cust_svc>) of this billing item.
3179 warn "$me _h_labels called on $self\n"
3181 map { [ $_->label(@_) ] } $self->h_cust_svc(@_);
3186 Like labels, except returns a simple flat list, and shortens long
3187 (currently >5 or the cust_bill-max_same_services configuration value) lists of
3188 identical services to one line that lists the service label and the number of
3189 individual services rather than individual items.
3194 shift->_labels_short( 'labels', @_ );
3197 =item h_labels_short END_TIMESTAMP [ START_TIMESTAMP ]
3199 Like h_labels, except returns a simple flat list, and shortens long
3200 (currently >5 or the cust_bill-max_same_services configuration value) lists of
3201 identical services to one line that lists the service label and the number of
3202 individual services rather than individual items.
3206 sub h_labels_short {
3207 shift->_labels_short( 'h_labels', @_ );
3211 my( $self, $method ) = ( shift, shift );
3213 warn "$me _labels_short called on $self with $method method\n"
3216 my $conf = new FS::Conf;
3217 my $max_same_services = $conf->config('cust_bill-max_same_services') || 5;
3219 warn "$me _labels_short populating \%labels\n"
3223 #tie %labels, 'Tie::IxHash';
3224 push @{ $labels{$_->[0]} }, $_->[1]
3225 foreach $self->$method(@_);
3227 warn "$me _labels_short populating \@labels\n"
3231 foreach my $label ( keys %labels ) {
3233 my @values = grep { ! $seen{$_}++ } @{ $labels{$label} };
3234 my $num = scalar(@values);
3235 warn "$me _labels_short $num items for $label\n"
3238 if ( $num > $max_same_services ) {
3239 warn "$me _labels_short more than $max_same_services, so summarizing\n"
3241 push @labels, "$label ($num)";
3243 if ( $conf->exists('cust_bill-consolidate_services') ) {
3244 warn "$me _labels_short consolidating services\n"
3246 # push @labels, "$label: ". join(', ', @values);
3248 my $detail = "$label: ";
3249 $detail .= shift(@values). ', '
3251 && ( length($detail.$values[0]) < 78 || $detail eq "$label: " );
3253 push @labels, $detail;
3255 warn "$me _labels_short done consolidating services\n"
3258 warn "$me _labels_short adding service data\n"
3260 push @labels, map { "$label: $_" } @values;
3271 Returns the parent customer object (see L<FS::cust_main>).
3277 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
3282 Returns the balance for this specific package, when using
3283 experimental package balance.
3289 $self->cust_main->balance_pkgnum( $self->pkgnum );
3292 #these subs are in location_Mixin.pm now... unfortunately the POD doesn't mixin
3296 Returns the location object, if any (see L<FS::cust_location>).
3298 =item cust_location_or_main
3300 If this package is associated with a location, returns the locaiton (see
3301 L<FS::cust_location>), otherwise returns the customer (see L<FS::cust_main>).
3303 =item location_label [ OPTION => VALUE ... ]
3305 Returns the label of the location object (see L<FS::cust_location>).
3309 #end of subs in location_Mixin.pm now... unfortunately the POD doesn't mixin
3311 =item tax_locationnum
3313 Returns the foreign key to a L<FS::cust_location> object for calculating
3314 tax on this package, as determined by the C<tax-pkg_address> and
3315 C<tax-ship_address> configuration flags.
3319 sub tax_locationnum {
3321 my $conf = FS::Conf->new;
3322 if ( $conf->exists('tax-pkg_address') ) {
3323 return $self->locationnum;
3325 elsif ( $conf->exists('tax-ship_address') ) {
3326 return $self->cust_main->ship_locationnum;
3329 return $self->cust_main->bill_locationnum;
3335 Returns the L<FS::cust_location> object for tax_locationnum.
3341 FS::cust_location->by_key( $self->tax_locationnum )
3344 =item seconds_since TIMESTAMP
3346 Returns the number of seconds all accounts (see L<FS::svc_acct>) in this
3347 package have been online since TIMESTAMP, according to the session monitor.
3349 TIMESTAMP is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
3350 L<Time::Local> and L<Date::Parse> for conversion functions.
3355 my($self, $since) = @_;
3358 foreach my $cust_svc (
3359 grep { $_->part_svc->svcdb eq 'svc_acct' } $self->cust_svc
3361 $seconds += $cust_svc->seconds_since($since);
3368 =item seconds_since_sqlradacct TIMESTAMP_START TIMESTAMP_END
3370 Returns the numbers of seconds all accounts (see L<FS::svc_acct>) in this
3371 package have been online between TIMESTAMP_START (inclusive) and TIMESTAMP_END
3374 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
3375 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
3381 sub seconds_since_sqlradacct {
3382 my($self, $start, $end) = @_;
3386 foreach my $cust_svc (
3388 my $part_svc = $_->part_svc;
3389 $part_svc->svcdb eq 'svc_acct'
3390 && scalar($part_svc->part_export_usage);
3393 $seconds += $cust_svc->seconds_since_sqlradacct($start, $end);
3400 =item attribute_since_sqlradacct TIMESTAMP_START TIMESTAMP_END ATTRIBUTE
3402 Returns the sum of the given attribute for all accounts (see L<FS::svc_acct>)
3403 in this package for sessions ending between TIMESTAMP_START (inclusive) and
3407 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
3408 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
3413 sub attribute_since_sqlradacct {
3414 my($self, $start, $end, $attrib) = @_;
3418 foreach my $cust_svc (
3420 my $part_svc = $_->part_svc;
3421 $part_svc->svcdb eq 'svc_acct'
3422 && scalar($part_svc->part_export_usage);
3425 $sum += $cust_svc->attribute_since_sqlradacct($start, $end, $attrib);
3437 my( $self, $value ) = @_;
3438 if ( defined($value) ) {
3439 $self->setfield('quantity', $value);
3441 $self->getfield('quantity') || 1;
3444 =item transfer DEST_PKGNUM | DEST_CUST_PKG, [ OPTION => VALUE ... ]
3446 Transfers as many services as possible from this package to another package.
3448 The destination package can be specified by pkgnum by passing an FS::cust_pkg
3449 object. The destination package must already exist.
3451 Services are moved only if the destination allows services with the correct
3452 I<svcpart> (not svcdb), unless the B<change_svcpart> option is set true. Use
3453 this option with caution! No provision is made for export differences
3454 between the old and new service definitions. Probably only should be used
3455 when your exports for all service definitions of a given svcdb are identical.
3456 (attempt a transfer without it first, to move all possible svcpart-matching
3459 Any services that can't be moved remain in the original package.
3461 Returns an error, if there is one; otherwise, returns the number of services
3462 that couldn't be moved.
3467 my ($self, $dest_pkgnum, %opt) = @_;
3473 if (ref ($dest_pkgnum) eq 'FS::cust_pkg') {
3474 $dest = $dest_pkgnum;
3475 $dest_pkgnum = $dest->pkgnum;
3477 $dest = qsearchs('cust_pkg', { pkgnum => $dest_pkgnum });
3480 return ('Package does not exist: '.$dest_pkgnum) unless $dest;
3482 foreach my $pkg_svc ( $dest->part_pkg->pkg_svc ) {
3483 $target{$pkg_svc->svcpart} = $pkg_svc->quantity;
3486 foreach my $cust_svc ($dest->cust_svc) {
3487 $target{$cust_svc->svcpart}--;
3490 my %svcpart2svcparts = ();
3491 if ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
3492 warn "change_svcpart option received, creating alternates list\n" if $DEBUG;
3493 foreach my $svcpart ( map { $_->svcpart } $self->cust_svc ) {
3494 next if exists $svcpart2svcparts{$svcpart};
3495 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
3496 $svcpart2svcparts{$svcpart} = [
3498 sort { $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] }
3500 my $pkg_svc = qsearchs( 'pkg_svc', { 'pkgpart' => $dest->pkgpart,
3501 'svcpart' => $_ } );
3503 $pkg_svc ? $pkg_svc->primary_svc : '',
3504 $pkg_svc ? $pkg_svc->quantity : 0,
3508 grep { $_ != $svcpart }
3510 qsearch('part_svc', { 'svcdb' => $part_svc->svcdb } )
3512 warn "alternates for svcpart $svcpart: ".
3513 join(', ', @{$svcpart2svcparts{$svcpart}}). "\n"
3518 foreach my $cust_svc ($self->cust_svc) {
3519 if($target{$cust_svc->svcpart} > 0
3520 or $FS::cust_svc::ignore_quantity) { # maybe should be a 'force' option
3521 $target{$cust_svc->svcpart}--;
3522 my $new = new FS::cust_svc { $cust_svc->hash };
3523 $new->pkgnum($dest_pkgnum);
3524 my $error = $new->replace($cust_svc);
3525 return $error if $error;
3526 } elsif ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
3528 warn "looking for alternates for svcpart ". $cust_svc->svcpart. "\n";
3529 warn "alternates to consider: ".
3530 join(', ', @{$svcpart2svcparts{$cust_svc->svcpart}}). "\n";
3532 my @alternate = grep {
3533 warn "considering alternate svcpart $_: ".
3534 "$target{$_} available in new package\n"
3537 } @{$svcpart2svcparts{$cust_svc->svcpart}};
3539 warn "alternate(s) found\n" if $DEBUG;
3540 my $change_svcpart = $alternate[0];
3541 $target{$change_svcpart}--;
3542 my $new = new FS::cust_svc { $cust_svc->hash };
3543 $new->svcpart($change_svcpart);
3544 $new->pkgnum($dest_pkgnum);
3545 my $error = $new->replace($cust_svc);
3546 return $error if $error;
3557 =item grab_svcnums SVCNUM, SVCNUM ...
3559 Change the pkgnum for the provided services to this packages. If there is an
3560 error, returns the error, otherwise returns false.
3568 local $SIG{HUP} = 'IGNORE';
3569 local $SIG{INT} = 'IGNORE';
3570 local $SIG{QUIT} = 'IGNORE';
3571 local $SIG{TERM} = 'IGNORE';
3572 local $SIG{TSTP} = 'IGNORE';
3573 local $SIG{PIPE} = 'IGNORE';
3575 my $oldAutoCommit = $FS::UID::AutoCommit;
3576 local $FS::UID::AutoCommit = 0;
3579 foreach my $svcnum (@svcnum) {
3580 my $cust_svc = qsearchs('cust_svc', { svcnum=>$svcnum } ) or do {
3581 $dbh->rollback if $oldAutoCommit;
3582 return "unknown svcnum $svcnum";
3584 $cust_svc->pkgnum( $self->pkgnum );
3585 my $error = $cust_svc->replace;
3587 $dbh->rollback if $oldAutoCommit;
3592 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3599 This method is deprecated. See the I<depend_jobnum> option to the insert and
3600 order_pkgs methods in FS::cust_main for a better way to defer provisioning.
3607 local $SIG{HUP} = 'IGNORE';
3608 local $SIG{INT} = 'IGNORE';
3609 local $SIG{QUIT} = 'IGNORE';
3610 local $SIG{TERM} = 'IGNORE';
3611 local $SIG{TSTP} = 'IGNORE';
3612 local $SIG{PIPE} = 'IGNORE';
3614 my $oldAutoCommit = $FS::UID::AutoCommit;
3615 local $FS::UID::AutoCommit = 0;
3618 foreach my $cust_svc ( $self->cust_svc ) {
3619 #false laziness w/svc_Common::insert
3620 my $svc_x = $cust_svc->svc_x;
3621 foreach my $part_export ( $cust_svc->part_svc->part_export ) {
3622 my $error = $part_export->export_insert($svc_x);
3624 $dbh->rollback if $oldAutoCommit;
3630 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3635 =item export_pkg_change OLD_CUST_PKG
3637 Calls the "pkg_change" export action for all services attached to this package.
3641 sub export_pkg_change {
3642 my( $self, $old ) = ( shift, shift );
3644 local $SIG{HUP} = 'IGNORE';
3645 local $SIG{INT} = 'IGNORE';
3646 local $SIG{QUIT} = 'IGNORE';
3647 local $SIG{TERM} = 'IGNORE';
3648 local $SIG{TSTP} = 'IGNORE';
3649 local $SIG{PIPE} = 'IGNORE';
3651 my $oldAutoCommit = $FS::UID::AutoCommit;
3652 local $FS::UID::AutoCommit = 0;
3655 foreach my $svc_x ( map $_->svc_x, $self->cust_svc ) {
3656 my $error = $svc_x->export('pkg_change', $self, $old);
3658 $dbh->rollback if $oldAutoCommit;
3663 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3670 Associates this package with a (suspension or cancellation) reason (see
3671 L<FS::cust_pkg_reason>, possibly inserting a new reason on the fly (see
3674 Available options are:
3680 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.
3684 the access_user (see L<FS::access_user>) providing the reason
3692 the action (cancel, susp, adjourn, expire) associated with the reason
3696 If there is an error, returns the error, otherwise returns false.
3701 my ($self, %options) = @_;
3703 my $otaker = $options{reason_otaker} ||
3704 $FS::CurrentUser::CurrentUser->username;
3707 if ( $options{'reason'} =~ /^(\d+)$/ ) {
3711 } elsif ( ref($options{'reason'}) ) {
3713 return 'Enter a new reason (or select an existing one)'
3714 unless $options{'reason'}->{'reason'} !~ /^\s*$/;
3716 my $reason = new FS::reason({
3717 'reason_type' => $options{'reason'}->{'typenum'},
3718 'reason' => $options{'reason'}->{'reason'},
3720 my $error = $reason->insert;
3721 return $error if $error;
3723 $reasonnum = $reason->reasonnum;
3726 return "Unparsable reason: ". $options{'reason'};
3729 my $cust_pkg_reason =
3730 new FS::cust_pkg_reason({ 'pkgnum' => $self->pkgnum,
3731 'reasonnum' => $reasonnum,
3732 'otaker' => $otaker,
3733 'action' => substr(uc($options{'action'}),0,1),
3734 'date' => $options{'date'}
3739 $cust_pkg_reason->insert;
3742 =item insert_discount
3744 Associates this package with a discount (see L<FS::cust_pkg_discount>, possibly
3745 inserting a new discount on the fly (see L<FS::discount>).
3747 Available options are:
3755 If there is an error, returns the error, otherwise returns false.
3759 sub insert_discount {
3760 #my ($self, %options) = @_;
3763 my $cust_pkg_discount = new FS::cust_pkg_discount {
3764 'pkgnum' => $self->pkgnum,
3765 'discountnum' => $self->discountnum,
3767 'end_date' => '', #XXX
3768 #for the create a new discount case
3769 '_type' => $self->discountnum__type,
3770 'amount' => $self->discountnum_amount,
3771 'percent' => $self->discountnum_percent,
3772 'months' => $self->discountnum_months,
3773 'setup' => $self->discountnum_setup,
3774 #'disabled' => $self->discountnum_disabled,
3777 $cust_pkg_discount->insert;
3780 =item set_usage USAGE_VALUE_HASHREF
3782 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
3783 to which they should be set (see L<FS::svc_acct>). Currently seconds,
3784 upbytes, downbytes, and totalbytes are appropriate keys.
3786 All svc_accts which are part of this package have their values reset.
3791 my ($self, $valueref, %opt) = @_;
3793 #only svc_acct can set_usage for now
3794 foreach my $cust_svc ( $self->cust_svc( 'svcdb'=>'svc_acct' ) ) {
3795 my $svc_x = $cust_svc->svc_x;
3796 $svc_x->set_usage($valueref, %opt)
3797 if $svc_x->can("set_usage");
3801 =item recharge USAGE_VALUE_HASHREF
3803 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
3804 to which they should be set (see L<FS::svc_acct>). Currently seconds,
3805 upbytes, downbytes, and totalbytes are appropriate keys.
3807 All svc_accts which are part of this package have their values incremented.
3812 my ($self, $valueref) = @_;
3814 #only svc_acct can set_usage for now
3815 foreach my $cust_svc ( $self->cust_svc( 'svcdb'=>'svc_acct' ) ) {
3816 my $svc_x = $cust_svc->svc_x;
3817 $svc_x->recharge($valueref)
3818 if $svc_x->can("recharge");
3822 =item cust_pkg_discount
3826 sub cust_pkg_discount {
3828 qsearch('cust_pkg_discount', { 'pkgnum' => $self->pkgnum } );
3831 =item cust_pkg_discount_active
3835 sub cust_pkg_discount_active {
3837 grep { $_->status eq 'active' } $self->cust_pkg_discount;
3840 =item cust_pkg_usage
3842 Returns a list of all voice usage counters attached to this package.
3846 sub cust_pkg_usage {
3848 qsearch('cust_pkg_usage', { pkgnum => $self->pkgnum });
3851 =item apply_usage OPTIONS
3853 Takes the following options:
3854 - cdr: a call detail record (L<FS::cdr>)
3855 - rate_detail: the rate determined for this call (L<FS::rate_detail>)
3856 - minutes: the maximum number of minutes to be charged
3858 Finds available usage minutes for a call of this class, and subtracts
3859 up to that many minutes from the usage pool. If the usage pool is empty,
3860 and the C<cdr-minutes_priority> global config option is set, minutes may
3861 be taken from other calls as well. Either way, an allocation record will
3862 be created (L<FS::cdr_cust_pkg_usage>) and this method will return the
3863 number of minutes of usage applied to the call.
3868 my ($self, %opt) = @_;
3869 my $cdr = $opt{cdr};
3870 my $rate_detail = $opt{rate_detail};
3871 my $minutes = $opt{minutes};
3872 my $classnum = $rate_detail->classnum;
3873 my $pkgnum = $self->pkgnum;
3874 my $custnum = $self->custnum;
3876 local $SIG{HUP} = 'IGNORE';
3877 local $SIG{INT} = 'IGNORE';
3878 local $SIG{QUIT} = 'IGNORE';
3879 local $SIG{TERM} = 'IGNORE';
3880 local $SIG{TSTP} = 'IGNORE';
3881 local $SIG{PIPE} = 'IGNORE';
3883 my $oldAutoCommit = $FS::UID::AutoCommit;
3884 local $FS::UID::AutoCommit = 0;
3886 my $order = FS::Conf->new->config('cdr-minutes_priority');
3890 $is_classnum = ' part_pkg_usage_class.classnum = '.$classnum;
3892 $is_classnum = ' part_pkg_usage_class.classnum IS NULL';
3894 my @usage_recs = qsearch({
3895 'table' => 'cust_pkg_usage',
3896 'addl_from' => ' JOIN part_pkg_usage USING (pkgusagepart)'.
3897 ' JOIN cust_pkg USING (pkgnum)'.
3898 ' JOIN part_pkg_usage_class USING (pkgusagepart)',
3899 'select' => 'cust_pkg_usage.*',
3900 'extra_sql' => " WHERE ( cust_pkg.pkgnum = $pkgnum OR ".
3901 " ( cust_pkg.custnum = $custnum AND ".
3902 " part_pkg_usage.shared IS NOT NULL ) ) AND ".
3903 $is_classnum . ' AND '.
3904 " cust_pkg_usage.minutes > 0",
3905 'order_by' => " ORDER BY priority ASC",
3908 my $orig_minutes = $minutes;
3910 while (!$error and $minutes > 0 and @usage_recs) {
3911 my $cust_pkg_usage = shift @usage_recs;
3912 $cust_pkg_usage->select_for_update;
3913 my $cdr_cust_pkg_usage = FS::cdr_cust_pkg_usage->new({
3914 pkgusagenum => $cust_pkg_usage->pkgusagenum,
3915 acctid => $cdr->acctid,
3916 minutes => min($cust_pkg_usage->minutes, $minutes),
3918 $cust_pkg_usage->set('minutes',
3919 sprintf('%.0f', $cust_pkg_usage->minutes - $cdr_cust_pkg_usage->minutes)
3921 $error = $cust_pkg_usage->replace || $cdr_cust_pkg_usage->insert;
3922 $minutes -= $cdr_cust_pkg_usage->minutes;
3924 if ( $order and $minutes > 0 and !$error ) {
3925 # then try to steal minutes from another call
3927 'table' => 'cdr_cust_pkg_usage',
3928 'addl_from' => ' JOIN cust_pkg_usage USING (pkgusagenum)'.
3929 ' JOIN part_pkg_usage USING (pkgusagepart)'.
3930 ' JOIN cust_pkg USING (pkgnum)'.
3931 ' JOIN part_pkg_usage_class USING (pkgusagepart)'.
3932 ' JOIN cdr USING (acctid)',
3933 'select' => 'cdr_cust_pkg_usage.*',
3934 'extra_sql' => " WHERE cdr.freesidestatus = 'rated' AND ".
3935 " ( cust_pkg.pkgnum = $pkgnum OR ".
3936 " ( cust_pkg.custnum = $custnum AND ".
3937 " part_pkg_usage.shared IS NOT NULL ) ) AND ".
3938 " part_pkg_usage_class.classnum = $classnum",
3939 'order_by' => ' ORDER BY part_pkg_usage.priority ASC',
3941 if ( $order eq 'time' ) {
3942 # find CDRs that are using minutes, but have a later startdate
3944 my $startdate = $cdr->startdate;
3945 if ($startdate !~ /^\d+$/) {
3946 die "bad cdr startdate '$startdate'";
3948 $search{'extra_sql'} .= " AND cdr.startdate > $startdate";
3949 # minimize needless reshuffling
3950 $search{'order_by'} .= ', cdr.startdate DESC';
3952 # XXX may not work correctly with rate_time schedules. Could
3953 # fix this by storing ratedetailnum in cdr_cust_pkg_usage, I
3955 $search{'addl_from'} .=
3956 ' JOIN rate_detail'.
3957 ' ON (cdr.rated_ratedetailnum = rate_detail.ratedetailnum)';
3958 if ( $order eq 'rate_high' ) {
3959 $search{'extra_sql'} .= ' AND rate_detail.min_charge < '.
3960 $rate_detail->min_charge;
3961 $search{'order_by'} .= ', rate_detail.min_charge ASC';
3962 } elsif ( $order eq 'rate_low' ) {
3963 $search{'extra_sql'} .= ' AND rate_detail.min_charge > '.
3964 $rate_detail->min_charge;
3965 $search{'order_by'} .= ', rate_detail.min_charge DESC';
3967 # this should really never happen
3968 die "invalid cdr-minutes_priority value '$order'\n";
3971 my @cdr_usage_recs = qsearch(\%search);
3973 while (!$error and @cdr_usage_recs and $minutes > 0) {
3974 my $cdr_cust_pkg_usage = shift @cdr_usage_recs;
3975 my $cust_pkg_usage = $cdr_cust_pkg_usage->cust_pkg_usage;
3976 my $old_cdr = $cdr_cust_pkg_usage->cdr;
3977 $reproc_cdrs{$old_cdr->acctid} = $old_cdr;
3978 $cdr_cust_pkg_usage->select_for_update;
3979 $old_cdr->select_for_update;
3980 $cust_pkg_usage->select_for_update;
3981 # in case someone else stole the usage from this CDR
3982 # while waiting for the lock...
3983 next if $old_cdr->acctid != $cdr_cust_pkg_usage->acctid;
3984 # steal the usage allocation and flag the old CDR for reprocessing
3985 $cdr_cust_pkg_usage->set('acctid', $cdr->acctid);
3986 # if the allocation is more minutes than we need, adjust it...
3987 my $delta = $cdr_cust_pkg_usage->minutes - $minutes;
3989 $cdr_cust_pkg_usage->set('minutes', $minutes);
3990 $cust_pkg_usage->set('minutes', $cust_pkg_usage->minutes + $delta);
3991 $error = $cust_pkg_usage->replace;
3993 #warn 'CDR '.$cdr->acctid . ' stealing allocation '.$cdr_cust_pkg_usage->cdrusagenum.' from CDR '.$old_cdr->acctid."\n";
3994 $error ||= $cdr_cust_pkg_usage->replace;
3995 # deduct the stolen minutes
3996 $minutes -= $cdr_cust_pkg_usage->minutes;
3998 # after all minute-stealing is done, reset the affected CDRs
3999 foreach (values %reproc_cdrs) {
4000 $error ||= $_->set_status('');
4001 # XXX or should we just call $cdr->rate right here?
4002 # it's not like we can create a loop this way, since the min_charge
4003 # or call time has to go monotonically in one direction.
4004 # we COULD get some very deep recursions going, though...
4006 } # if $order and $minutes
4009 die "error applying included minutes\npkgnum ".$self->pkgnum.", class $classnum, acctid ".$cdr->acctid."\n$error\n"
4011 $dbh->commit if $oldAutoCommit;
4012 return $orig_minutes - $minutes;
4016 =item supplemental_pkgs
4018 Returns a list of all packages supplemental to this one.
4022 sub supplemental_pkgs {
4024 qsearch('cust_pkg', { 'main_pkgnum' => $self->pkgnum });
4029 Returns the package that this one is supplemental to, if any.
4035 if ( $self->main_pkgnum ) {
4036 return FS::cust_pkg->by_key($self->main_pkgnum);
4043 =head1 CLASS METHODS
4049 Returns an SQL expression identifying recurring packages.
4053 sub recurring_sql { "
4054 '0' != ( select freq from part_pkg
4055 where cust_pkg.pkgpart = part_pkg.pkgpart )
4060 Returns an SQL expression identifying one-time packages.
4065 '0' = ( select freq from part_pkg
4066 where cust_pkg.pkgpart = part_pkg.pkgpart )
4071 Returns an SQL expression identifying ordered packages (recurring packages not
4077 $_[0]->recurring_sql. " AND ". $_[0]->not_yet_billed_sql;
4082 Returns an SQL expression identifying active packages.
4087 $_[0]->recurring_sql. "
4088 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
4089 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4090 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
4093 =item not_yet_billed_sql
4095 Returns an SQL expression identifying packages which have not yet been billed.
4099 sub not_yet_billed_sql { "
4100 ( cust_pkg.setup IS NULL OR cust_pkg.setup = 0 )
4101 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4102 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
4107 Returns an SQL expression identifying inactive packages (one-time packages
4108 that are otherwise unsuspended/uncancelled).
4112 sub inactive_sql { "
4113 ". $_[0]->onetime_sql(). "
4114 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
4115 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4116 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
4122 Returns an SQL expression identifying suspended packages.
4126 sub suspended_sql { susp_sql(@_); }
4128 #$_[0]->recurring_sql(). ' AND '.
4130 ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4131 AND cust_pkg.susp IS NOT NULL AND cust_pkg.susp != 0
4138 Returns an SQL exprression identifying cancelled packages.
4142 sub cancelled_sql { cancel_sql(@_); }
4144 #$_[0]->recurring_sql(). ' AND '.
4145 "cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0";
4150 Returns an SQL expression to give the package status as a string.
4156 WHEN cust_pkg.cancel IS NOT NULL THEN 'cancelled'
4157 WHEN cust_pkg.susp IS NOT NULL THEN 'suspended'
4158 WHEN cust_pkg.setup IS NULL THEN 'not yet billed'
4159 WHEN ".onetime_sql()." THEN 'one-time charge'
4164 =item search HASHREF
4168 Returns a qsearch hash expression to search for parameters specified in HASHREF.
4169 Valid parameters are
4177 active, inactive, suspended, cancel (or cancelled)
4181 active, inactive, suspended, one-time charge, inactive, cancel (or cancelled)
4185 boolean selects custom packages
4191 pkgpart or arrayref or hashref of pkgparts
4195 arrayref of beginning and ending epoch date
4199 arrayref of beginning and ending epoch date
4203 arrayref of beginning and ending epoch date
4207 arrayref of beginning and ending epoch date
4211 arrayref of beginning and ending epoch date
4215 arrayref of beginning and ending epoch date
4219 arrayref of beginning and ending epoch date
4223 pkgnum or APKG_pkgnum
4227 a value suited to passing to FS::UI::Web::cust_header
4231 specifies the user for agent virtualization
4235 boolean; if true, returns only packages with more than 0 FCC phone lines.
4237 =item state, country
4239 Limit to packages with a service location in the specified state and country.
4240 For FCC 477 reporting, mostly.
4247 my ($class, $params) = @_;
4254 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
4256 "cust_main.agentnum = $1";
4263 if ( $params->{'cust_status'} =~ /^([a-z]+)$/ ) {
4264 push @where, FS::cust_main->cust_status_sql . " = '$1' ";
4268 # parse customer sales person
4271 if ( $params->{'cust_main_salesnum'} =~ /^(\d+)$/ ) {
4272 push @where, ($1 > 0) ? "cust_main.salesnum = $1"
4273 : 'cust_main.salesnum IS NULL';
4278 # parse sales person
4281 if ( $params->{'salesnum'} =~ /^(\d+)$/ ) {
4282 push @where, ($1 > 0) ? "cust_pkg.salesnum = $1"
4283 : 'cust_pkg.salesnum IS NULL';
4290 if ( $params->{'custnum'} =~ /^(\d+)$/ and $1 ) {
4292 "cust_pkg.custnum = $1";
4299 if ( $params->{'pkgbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
4301 "cust_pkg.pkgbatch = '$1'";
4308 if ( $params->{'magic'} eq 'active'
4309 || $params->{'status'} eq 'active' ) {
4311 push @where, FS::cust_pkg->active_sql();
4313 } elsif ( $params->{'magic'} =~ /^not[ _]yet[ _]billed$/
4314 || $params->{'status'} =~ /^not[ _]yet[ _]billed$/ ) {
4316 push @where, FS::cust_pkg->not_yet_billed_sql();
4318 } elsif ( $params->{'magic'} =~ /^(one-time charge|inactive)/
4319 || $params->{'status'} =~ /^(one-time charge|inactive)/ ) {
4321 push @where, FS::cust_pkg->inactive_sql();
4323 } elsif ( $params->{'magic'} eq 'suspended'
4324 || $params->{'status'} eq 'suspended' ) {
4326 push @where, FS::cust_pkg->suspended_sql();
4328 } elsif ( $params->{'magic'} =~ /^cancell?ed$/
4329 || $params->{'status'} =~ /^cancell?ed$/ ) {
4331 push @where, FS::cust_pkg->cancelled_sql();
4336 # parse package class
4339 if ( exists($params->{'classnum'}) ) {
4342 if ( ref($params->{'classnum'}) ) {
4344 if ( ref($params->{'classnum'}) eq 'HASH' ) {
4345 @classnum = grep $params->{'classnum'}{$_}, keys %{ $params->{'classnum'} };
4346 } elsif ( ref($params->{'classnum'}) eq 'ARRAY' ) {
4347 @classnum = @{ $params->{'classnum'} };
4349 die 'unhandled classnum ref '. $params->{'classnum'};
4353 } elsif ( $params->{'classnum'} =~ /^(\d*)$/ && $1 ne '0' ) {
4360 my @nums = grep $_, @classnum;
4361 push @c_where, 'part_pkg.classnum IN ('. join(',',@nums). ')' if @nums;
4362 my $null = scalar( grep { $_ eq '' } @classnum );
4363 push @c_where, 'part_pkg.classnum IS NULL' if $null;
4365 if ( scalar(@c_where) == 1 ) {
4366 push @where, @c_where;
4367 } elsif ( @c_where ) {
4368 push @where, ' ( '. join(' OR ', @c_where). ' ) ';
4377 # parse package report options
4380 my @report_option = ();
4381 if ( exists($params->{'report_option'}) ) {
4382 if ( ref($params->{'report_option'}) eq 'ARRAY' ) {
4383 @report_option = @{ $params->{'report_option'} };
4384 } elsif ( $params->{'report_option'} =~ /^([,\d]*)$/ ) {
4385 @report_option = split(',', $1);
4390 if (@report_option) {
4391 # this will result in the empty set for the dangling comma case as it should
4393 map{ "0 < ( SELECT count(*) FROM part_pkg_option
4394 WHERE part_pkg_option.pkgpart = part_pkg.pkgpart
4395 AND optionname = 'report_option_$_'
4396 AND optionvalue = '1' )"
4400 foreach my $any ( grep /^report_option_any/, keys %$params ) {
4402 my @report_option_any = ();
4403 if ( ref($params->{$any}) eq 'ARRAY' ) {
4404 @report_option_any = @{ $params->{$any} };
4405 } elsif ( $params->{$any} =~ /^([,\d]*)$/ ) {
4406 @report_option_any = split(',', $1);
4409 if (@report_option_any) {
4410 # this will result in the empty set for the dangling comma case as it should
4411 push @where, ' ( '. join(' OR ',
4412 map{ "0 < ( SELECT count(*) FROM part_pkg_option
4413 WHERE part_pkg_option.pkgpart = part_pkg.pkgpart
4414 AND optionname = 'report_option_$_'
4415 AND optionvalue = '1' )"
4416 } @report_option_any
4426 push @where, "part_pkg.custom = 'Y'" if $params->{custom};
4432 push @where, "(part_pkg.fcc_ds0s > 0 OR pkg_class.fcc_ds0s > 0)"
4433 if $params->{fcc_line};
4439 if ( exists($params->{'censustract'}) ) {
4440 $params->{'censustract'} =~ /^([.\d]*)$/;
4441 my $censustract = "cust_location.censustract = '$1'";
4442 $censustract .= ' OR cust_location.censustract is NULL' unless $1;
4443 push @where, "( $censustract )";
4447 # parse censustract2
4449 if ( exists($params->{'censustract2'})
4450 && $params->{'censustract2'} =~ /^(\d*)$/
4454 push @where, "cust_location.censustract LIKE '$1%'";
4457 "( cust_location.censustract = '' OR cust_location.censustract IS NULL )";
4462 # parse country/state
4464 for (qw(state country)) { # parsing rules are the same for these
4465 if ( exists($params->{$_})
4466 && uc($params->{$_}) =~ /^([A-Z]{2})$/ )
4468 # XXX post-2.3 only--before that, state/country may be in cust_main
4469 push @where, "cust_location.$_ = '$1'";
4477 if ( ref($params->{'pkgpart'}) ) {
4480 if ( ref($params->{'pkgpart'}) eq 'HASH' ) {
4481 @pkgpart = grep $params->{'pkgpart'}{$_}, keys %{ $params->{'pkgpart'} };
4482 } elsif ( ref($params->{'pkgpart'}) eq 'ARRAY' ) {
4483 @pkgpart = @{ $params->{'pkgpart'} };
4485 die 'unhandled pkgpart ref '. $params->{'pkgpart'};
4488 @pkgpart = grep /^(\d+)$/, @pkgpart;
4490 push @where, 'pkgpart IN ('. join(',', @pkgpart). ')' if scalar(@pkgpart);
4492 } elsif ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
4493 push @where, "pkgpart = $1";
4502 #false laziness w/report_cust_pkg.html
4505 'one-time charge' => { 'last_bill'=>1, 'bill'=>1, 'adjourn'=>1, 'susp'=>1, 'expire'=>1, 'cancel'=>1, },
4506 'active' => { 'susp'=>1, 'cancel'=>1 },
4507 'suspended' => { 'cancel' => 1 },
4512 if( exists($params->{'active'} ) ) {
4513 # This overrides all the other date-related fields
4514 my($beginning, $ending) = @{$params->{'active'}};
4516 "cust_pkg.setup IS NOT NULL",
4517 "cust_pkg.setup <= $ending",
4518 "(cust_pkg.cancel IS NULL OR cust_pkg.cancel >= $beginning )",
4519 "NOT (".FS::cust_pkg->onetime_sql . ")";
4522 foreach my $field (qw( setup last_bill bill adjourn susp expire contract_end change_date cancel )) {
4524 next unless exists($params->{$field});
4526 my($beginning, $ending) = @{$params->{$field}};
4528 next if $beginning == 0 && $ending == 4294967295;
4531 "cust_pkg.$field IS NOT NULL",
4532 "cust_pkg.$field >= $beginning",
4533 "cust_pkg.$field <= $ending";
4535 $orderby ||= "ORDER BY cust_pkg.$field";
4540 $orderby ||= 'ORDER BY bill';
4543 # parse magic, legacy, etc.
4546 if ( $params->{'magic'} &&
4547 $params->{'magic'} =~ /^(active|inactive|suspended|cancell?ed)$/
4550 $orderby = 'ORDER BY pkgnum';
4552 if ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
4553 push @where, "pkgpart = $1";
4556 } elsif ( $params->{'query'} eq 'pkgnum' ) {
4558 $orderby = 'ORDER BY pkgnum';
4560 } elsif ( $params->{'query'} eq 'APKG_pkgnum' ) {
4562 $orderby = 'ORDER BY pkgnum';
4565 SELECT count(*) FROM pkg_svc
4566 WHERE pkg_svc.pkgpart = cust_pkg.pkgpart
4567 AND pkg_svc.quantity > ( SELECT count(*) FROM cust_svc
4568 WHERE cust_svc.pkgnum = cust_pkg.pkgnum
4569 AND cust_svc.svcpart = pkg_svc.svcpart
4576 # setup queries, links, subs, etc. for the search
4579 # here is the agent virtualization
4580 if ($params->{CurrentUser}) {
4582 qsearchs('access_user', { username => $params->{CurrentUser} });
4585 push @where, $access_user->agentnums_sql('table'=>'cust_main');
4590 push @where, $FS::CurrentUser::CurrentUser->agentnums_sql('table'=>'cust_main');
4593 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
4595 my $addl_from = 'LEFT JOIN part_pkg USING ( pkgpart ) '.
4596 'LEFT JOIN pkg_class ON ( part_pkg.classnum = pkg_class.classnum ) '.
4597 'LEFT JOIN cust_location USING ( locationnum ) '.
4598 FS::UI::Web::join_cust_main('cust_pkg', 'cust_pkg');
4602 if ( $params->{'select_zip5'} ) {
4603 my $zip = 'cust_location.zip';
4605 $select = "DISTINCT substr($zip,1,5) as zip";
4606 $orderby = "ORDER BY substr($zip,1,5)";
4607 $count_query = "SELECT COUNT( DISTINCT substr($zip,1,5) )";
4609 $select = join(', ',
4611 ( map "part_pkg.$_", qw( pkg freq ) ),
4612 'pkg_class.classname',
4613 'cust_main.custnum AS cust_main_custnum',
4614 FS::UI::Web::cust_sql_fields(
4615 $params->{'cust_fields'}
4618 $count_query = 'SELECT COUNT(*)';
4621 $count_query .= " FROM cust_pkg $addl_from $extra_sql";
4624 'table' => 'cust_pkg',
4626 'select' => $select,
4627 'extra_sql' => $extra_sql,
4628 'order_by' => $orderby,
4629 'addl_from' => $addl_from,
4630 'count_query' => $count_query,
4637 Returns a list of two package counts. The first is a count of packages
4638 based on the supplied criteria and the second is the count of residential
4639 packages with those same criteria. Criteria are specified as in the search
4645 my ($class, $params) = @_;
4647 my $sql_query = $class->search( $params );
4649 my $count_sql = delete($sql_query->{'count_query'});
4650 $count_sql =~ s/ FROM/,count(CASE WHEN cust_main.company IS NULL OR cust_main.company = '' THEN 1 END) FROM/
4651 or die "couldn't parse count_sql";
4653 my $count_sth = dbh->prepare($count_sql)
4654 or die "Error preparing $count_sql: ". dbh->errstr;
4656 or die "Error executing $count_sql: ". $count_sth->errstr;
4657 my $count_arrayref = $count_sth->fetchrow_arrayref;
4659 return ( @$count_arrayref );
4663 =item tax_locationnum_sql
4665 Returns an SQL expression for the tax location for a package, based
4666 on the settings of 'tax-pkg_address' and 'tax-ship_address'.
4670 sub tax_locationnum_sql {
4671 my $conf = FS::Conf->new;
4672 if ( $conf->exists('tax-pkg_address') ) {
4673 'cust_pkg.locationnum';
4675 elsif ( $conf->exists('tax-ship_address') ) {
4676 'cust_main.ship_locationnum';
4679 'cust_main.bill_locationnum';
4685 Returns a list: the first item is an SQL fragment identifying matching
4686 packages/customers via location (taking into account shipping and package
4687 address taxation, if enabled), and subsequent items are the parameters to
4688 substitute for the placeholders in that fragment.
4693 my($class, %opt) = @_;
4694 my $ornull = $opt{'ornull'};
4696 my $conf = new FS::Conf;
4698 # '?' placeholders in _location_sql_where
4699 my $x = $ornull ? 3 : 2;
4710 if ( $conf->exists('tax-ship_address') ) {
4713 ( ( ship_last IS NULL OR ship_last = '' )
4714 AND ". _location_sql_where('cust_main', '', $ornull ). "
4716 OR ( ship_last IS NOT NULL AND ship_last != ''
4717 AND ". _location_sql_where('cust_main', 'ship_', $ornull ). "
4720 # AND payby != 'COMP'
4722 @main_param = ( @bill_param, @bill_param );
4726 $main_where = _location_sql_where('cust_main'); # AND payby != 'COMP'
4727 @main_param = @bill_param;
4733 if ( $conf->exists('tax-pkg_address') ) {
4735 my $loc_where = _location_sql_where( 'cust_location', '', $ornull );
4738 ( cust_pkg.locationnum IS NULL AND $main_where )
4739 OR ( cust_pkg.locationnum IS NOT NULL AND $loc_where )
4742 @param = ( @main_param, @bill_param );
4746 $where = $main_where;
4747 @param = @main_param;
4755 #subroutine, helper for location_sql
4756 sub _location_sql_where {
4758 my $prefix = @_ ? shift : '';
4759 my $ornull = @_ ? shift : '';
4761 # $ornull = $ornull ? " OR ( ? IS NULL AND $table.${prefix}county IS NULL ) " : '';
4763 $ornull = $ornull ? ' OR ? IS NULL ' : '';
4765 my $or_empty_city = " OR ( ? = '' AND $table.${prefix}city IS NULL )";
4766 my $or_empty_county = " OR ( ? = '' AND $table.${prefix}county IS NULL )";
4767 my $or_empty_state = " OR ( ? = '' AND $table.${prefix}state IS NULL )";
4769 my $text = (driver_name =~ /^mysql/i) ? 'char' : 'text';
4771 # ( $table.${prefix}city = ? $or_empty_city $ornull )
4773 ( $table.district = ? OR ? = '' OR CAST(? AS $text) IS NULL )
4774 AND ( $table.${prefix}city = ? OR ? = '' OR CAST(? AS $text) IS NULL )
4775 AND ( $table.${prefix}county = ? $or_empty_county $ornull )
4776 AND ( $table.${prefix}state = ? $or_empty_state $ornull )
4777 AND $table.${prefix}country = ?
4782 my( $self, $what ) = @_;
4784 my $what_show_zero = $what. '_show_zero';
4785 length($self->$what_show_zero())
4786 ? ($self->$what_show_zero() eq 'Y')
4787 : $self->part_pkg->$what_show_zero();
4794 =item order CUSTNUM, PKGPARTS_ARYREF, [ REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF [ REFNUM ] ] ]
4796 CUSTNUM is a customer (see L<FS::cust_main>)
4798 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
4799 L<FS::part_pkg>) to order for this customer. Duplicates are of course
4802 REMOVE_PKGNUMS is an optional list of pkgnums specifying the billing items to
4803 remove for this customer. The services (see L<FS::cust_svc>) are moved to the
4804 new billing items. An error is returned if this is not possible (see
4805 L<FS::pkg_svc>). An empty arrayref is equivalent to not specifying this
4808 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
4809 newly-created cust_pkg objects.
4811 REFNUM, if specified, will specify the FS::pkg_referral record to be created
4812 and inserted. Multiple FS::pkg_referral records can be created by
4813 setting I<refnum> to an array reference of refnums or a hash reference with
4814 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
4815 record will be created corresponding to cust_main.refnum.
4820 my ($custnum, $pkgparts, $remove_pkgnum, $return_cust_pkg, $refnum) = @_;
4822 my $conf = new FS::Conf;
4824 # Transactionize this whole mess
4825 local $SIG{HUP} = 'IGNORE';
4826 local $SIG{INT} = 'IGNORE';
4827 local $SIG{QUIT} = 'IGNORE';
4828 local $SIG{TERM} = 'IGNORE';
4829 local $SIG{TSTP} = 'IGNORE';
4830 local $SIG{PIPE} = 'IGNORE';
4832 my $oldAutoCommit = $FS::UID::AutoCommit;
4833 local $FS::UID::AutoCommit = 0;
4837 # my $cust_main = qsearchs('cust_main', { custnum => $custnum });
4838 # return "Customer not found: $custnum" unless $cust_main;
4840 warn "$me order: pkgnums to remove: ". join(',', @$remove_pkgnum). "\n"
4843 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
4846 my $change = scalar(@old_cust_pkg) != 0;
4849 if ( scalar(@old_cust_pkg) == 1 && scalar(@$pkgparts) == 1 ) {
4851 warn "$me order: changing pkgnum ". $old_cust_pkg[0]->pkgnum.
4852 " to pkgpart ". $pkgparts->[0]. "\n"
4855 my $err_or_cust_pkg =
4856 $old_cust_pkg[0]->change( 'pkgpart' => $pkgparts->[0],
4857 'refnum' => $refnum,
4860 unless (ref($err_or_cust_pkg)) {
4861 $dbh->rollback if $oldAutoCommit;
4862 return $err_or_cust_pkg;
4865 push @$return_cust_pkg, $err_or_cust_pkg;
4866 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4871 # Create the new packages.
4872 foreach my $pkgpart (@$pkgparts) {
4874 warn "$me order: inserting pkgpart $pkgpart\n" if $DEBUG;
4876 my $cust_pkg = new FS::cust_pkg { custnum => $custnum,
4877 pkgpart => $pkgpart,
4881 $error = $cust_pkg->insert( 'change' => $change );
4882 push @$return_cust_pkg, $cust_pkg;
4884 foreach my $link ($cust_pkg->part_pkg->supp_part_pkg_link) {
4885 my $supp_pkg = FS::cust_pkg->new({
4886 custnum => $custnum,
4887 pkgpart => $link->dst_pkgpart,
4889 main_pkgnum => $cust_pkg->pkgnum,
4892 $error ||= $supp_pkg->insert( 'change' => $change );
4893 push @$return_cust_pkg, $supp_pkg;
4897 $dbh->rollback if $oldAutoCommit;
4902 # $return_cust_pkg now contains refs to all of the newly
4905 # Transfer services and cancel old packages.
4906 foreach my $old_pkg (@old_cust_pkg) {
4908 warn "$me order: transferring services from pkgnum ". $old_pkg->pkgnum. "\n"
4911 foreach my $new_pkg (@$return_cust_pkg) {
4912 $error = $old_pkg->transfer($new_pkg);
4913 if ($error and $error == 0) {
4914 # $old_pkg->transfer failed.
4915 $dbh->rollback if $oldAutoCommit;
4920 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
4921 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
4922 foreach my $new_pkg (@$return_cust_pkg) {
4923 $error = $old_pkg->transfer($new_pkg, 'change_svcpart'=>1 );
4924 if ($error and $error == 0) {
4925 # $old_pkg->transfer failed.
4926 $dbh->rollback if $oldAutoCommit;
4933 # Transfers were successful, but we went through all of the
4934 # new packages and still had services left on the old package.
4935 # We can't cancel the package under the circumstances, so abort.
4936 $dbh->rollback if $oldAutoCommit;
4937 return "Unable to transfer all services from package ".$old_pkg->pkgnum;
4939 $error = $old_pkg->cancel( quiet=>1 );
4945 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4949 =item bulk_change PKGPARTS_ARYREF, REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF ]
4951 A bulk change method to change packages for multiple customers.
4953 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
4954 L<FS::part_pkg>) to order for each customer. Duplicates are of course
4957 REMOVE_PKGNUMS is an list of pkgnums specifying the billing items to
4958 replace. The services (see L<FS::cust_svc>) are moved to the
4959 new billing items. An error is returned if this is not possible (see
4962 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
4963 newly-created cust_pkg objects.
4968 my ($pkgparts, $remove_pkgnum, $return_cust_pkg) = @_;
4970 # Transactionize this whole mess
4971 local $SIG{HUP} = 'IGNORE';
4972 local $SIG{INT} = 'IGNORE';
4973 local $SIG{QUIT} = 'IGNORE';
4974 local $SIG{TERM} = 'IGNORE';
4975 local $SIG{TSTP} = 'IGNORE';
4976 local $SIG{PIPE} = 'IGNORE';
4978 my $oldAutoCommit = $FS::UID::AutoCommit;
4979 local $FS::UID::AutoCommit = 0;
4983 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
4986 while(scalar(@old_cust_pkg)) {
4988 my $custnum = $old_cust_pkg[0]->custnum;
4989 my (@remove) = map { $_->pkgnum }
4990 grep { $_->custnum == $custnum } @old_cust_pkg;
4991 @old_cust_pkg = grep { $_->custnum != $custnum } @old_cust_pkg;
4993 my $error = order $custnum, $pkgparts, \@remove, \@return;
4995 push @errors, $error
4997 push @$return_cust_pkg, @return;
5000 if (scalar(@errors)) {
5001 $dbh->rollback if $oldAutoCommit;
5002 return join(' / ', @errors);
5005 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5009 # Used by FS::Upgrade to migrate to a new database.
5010 sub _upgrade_data { # class method
5011 my ($class, %opts) = @_;
5012 $class->_upgrade_otaker(%opts);
5014 # RT#10139, bug resulting in contract_end being set when it shouldn't
5015 'UPDATE cust_pkg SET contract_end = NULL WHERE contract_end = -1',
5016 # RT#10830, bad calculation of prorate date near end of year
5017 # the date range for bill is December 2009, and we move it forward
5018 # one year if it's before the previous bill date (which it should
5020 'UPDATE cust_pkg SET bill = bill + (365*24*60*60) WHERE bill < last_bill
5021 AND bill > 1259654400 AND bill < 1262332800 AND (SELECT plan FROM part_pkg
5022 WHERE part_pkg.pkgpart = cust_pkg.pkgpart) = \'prorate\'',
5023 # RT6628, add order_date to cust_pkg
5024 'update cust_pkg set order_date = (select history_date from h_cust_pkg
5025 where h_cust_pkg.pkgnum = cust_pkg.pkgnum and
5026 history_action = \'insert\') where order_date is null',
5028 foreach my $sql (@statements) {
5029 my $sth = dbh->prepare($sql);
5030 $sth->execute or die $sth->errstr;
5038 sub order is not OO. Perhaps it should be moved to FS::cust_main and made so?
5040 In sub order, the @pkgparts array (passed by reference) is clobbered.
5042 Also in sub order, no money is adjusted. Once FS::part_pkg defines a standard
5043 method to pass dates to the recur_prog expression, it should do so.
5045 FS::svc_acct, FS::svc_domain, FS::svc_www, FS::svc_ip and FS::svc_forward are
5046 loaded via 'use' at compile time, rather than via 'require' in sub { setup,
5047 suspend, unsuspend, cancel } because they use %FS::UID::callback to load
5048 configuration values. Probably need a subroutine which decides what to do
5049 based on whether or not we've fetched the user yet, rather than a hash. See
5050 FS::UID and the TODO.
5052 Now that things are transactional should the check in the insert method be
5057 L<FS::Record>, L<FS::cust_main>, L<FS::part_pkg>, L<FS::cust_svc>,
5058 L<FS::pkg_svc>, schema.html from the base documentation