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 );
8 use Scalar::Util qw( blessed );
9 use List::Util qw(min max);
11 use Time::Local qw( timelocal timelocal_nocheck );
13 use FS::UID qw( dbh driver_name );
14 use FS::Misc qw( send_email );
15 use FS::Record qw( qsearch qsearchs fields );
21 use FS::cust_location;
23 use FS::cust_bill_pkg;
24 use FS::cust_pkg_detail;
25 use FS::cust_pkg_usage;
26 use FS::cdr_cust_pkg_usage;
31 use FS::cust_pkg_reason;
33 use FS::cust_pkg_discount;
40 # need to 'use' these instead of 'require' in sub { cancel, suspend, unsuspend,
42 # because they load configuration by setting FS::UID::callback (see TODO)
48 # for sending cancel emails in sub cancel
51 our ($disable_agentcheck, $DEBUG, $me, $import) = (0, 0, '[FS::cust_pkg]', 0);
53 our $upgrade = 0; #go away after setup+start dates cleaned up for old customers
57 my ( $hashref, $cache ) = @_;
58 #if ( $hashref->{'pkgpart'} ) {
59 if ( $hashref->{'pkg'} ) {
60 # #@{ $self->{'_pkgnum'} } = ();
61 # my $subcache = $cache->subcache('pkgpart', 'part_pkg');
62 # $self->{'_pkgpart'} = $subcache;
63 # #push @{ $self->{'_pkgnum'} },
64 # FS::part_pkg->new_or_cached($hashref, $subcache);
65 $self->{'_pkgpart'} = FS::part_pkg->new($hashref);
67 if ( exists $hashref->{'svcnum'} ) {
68 #@{ $self->{'_pkgnum'} } = ();
69 my $subcache = $cache->subcache('svcnum', 'cust_svc', $hashref->{pkgnum});
70 $self->{'_svcnum'} = $subcache;
71 #push @{ $self->{'_pkgnum'} },
72 FS::cust_svc->new_or_cached($hashref, $subcache) if $hashref->{svcnum};
78 FS::cust_pkg - Object methods for cust_pkg objects
84 $record = new FS::cust_pkg \%hash;
85 $record = new FS::cust_pkg { 'column' => 'value' };
87 $error = $record->insert;
89 $error = $new_record->replace($old_record);
91 $error = $record->delete;
93 $error = $record->check;
95 $error = $record->cancel;
97 $error = $record->suspend;
99 $error = $record->unsuspend;
101 $part_pkg = $record->part_pkg;
103 @labels = $record->labels;
105 $seconds = $record->seconds_since($timestamp);
107 $error = FS::cust_pkg::order( $custnum, \@pkgparts );
108 $error = FS::cust_pkg::order( $custnum, \@pkgparts, \@remove_pkgnums ] );
112 An FS::cust_pkg object represents a customer billing item. FS::cust_pkg
113 inherits from FS::Record. The following fields are currently supported:
119 Primary key (assigned automatically for new billing items)
123 Customer (see L<FS::cust_main>)
127 Billing item definition (see L<FS::part_pkg>)
131 Optional link to package location (see L<FS::location>)
135 date package was ordered (also remains same on changes)
147 date (next bill date)
175 order taker (see L<FS::access_user>)
179 If this field is set to 1, disables the automatic
180 unsuspension of this package when using the B<unsuspendauto> config option.
184 If not set, defaults to 1
188 Date of change from previous package
198 =item change_locationnum
206 The pkgnum of the package that this package is supplemental to, if any.
210 The package link (L<FS::part_pkg_link>) that defines this supplemental
211 package, if it is one.
213 =item change_to_pkgnum
215 The pkgnum of the package this one will be "changed to" in the future
216 (on its expiration date).
220 Note: setup, last_bill, bill, adjourn, susp, expire, cancel and change_date
221 are specified as UNIX timestamps; see L<perlfunc/"time">. Also see
222 L<Time::Local> and L<Date::Parse> for conversion functions.
230 Create a new billing item. To add the item to the database, see L<"insert">.
234 sub table { 'cust_pkg'; }
235 sub cust_linked { $_[0]->cust_main_custnum || $_[0]->custnum }
236 sub cust_unlinked_msg {
238 "WARNING: can't find cust_main.custnum ". $self->custnum.
239 ' (cust_pkg.pkgnum '. $self->pkgnum. ')';
242 =item insert [ OPTION => VALUE ... ]
244 Adds this billing item to the database ("Orders" the item). If there is an
245 error, returns the error, otherwise returns false.
247 If the additional field I<promo_code> is defined instead of I<pkgpart>, it
248 will be used to look up the package definition and agent restrictions will be
251 If the additional field I<refnum> is defined, an FS::pkg_referral record will
252 be created and inserted. Multiple FS::pkg_referral records can be created by
253 setting I<refnum> to an array reference of refnums or a hash reference with
254 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
255 record will be created corresponding to cust_main.refnum.
257 The following options are available:
263 If set true, supresses actions that should only be taken for new package
264 orders. (Currently this includes: intro periods when delay_setup is on.)
268 cust_pkg_option records will be created
272 a ticket will be added to this customer with this subject
276 an optional queue name for ticket additions
280 Don't check the legality of the package definition. This should be used
281 when performing a package change that doesn't change the pkgpart (i.e.
289 my( $self, %options ) = @_;
292 $error = $self->check_pkgpart unless $options{'allow_pkgpart'};
293 return $error if $error;
295 my $part_pkg = $self->part_pkg;
298 # if the package def says to start only on the first of the month:
299 if ( $part_pkg->option('start_1st', 1) && !$self->start_date ) {
300 my ($sec,$min,$hour,$mday,$mon,$year) = (localtime(time) )[0,1,2,3,4,5];
301 $mon += 1 unless $mday == 1;
302 until ( $mon < 12 ) { $mon -= 12; $year++; }
303 $self->start_date( timelocal_nocheck(0,0,0,1,$mon,$year) );
306 # set up any automatic expire/adjourn/contract_end timers
307 # based on the start date
308 foreach my $action ( qw(expire adjourn contract_end) ) {
309 my $months = $part_pkg->option("${action}_months",1);
310 if($months and !$self->$action) {
311 my $start = $self->start_date || $self->setup || time;
312 $self->$action( $part_pkg->add_freq($start, $months) );
316 # if this package has "free days" and delayed setup fee, tehn
317 # set start date that many days in the future.
318 # (this should have been set in the UI, but enforce it here)
319 if ( ! $options{'change'}
320 && ( my $free_days = $part_pkg->option('free_days',1) )
321 && $part_pkg->option('delay_setup',1)
322 #&& ! $self->start_date
325 $self->start_date( $part_pkg->default_start_date );
329 # set order date unless it was specified as part of an import
330 $self->order_date(time) unless $import && $self->order_date;
332 local $SIG{HUP} = 'IGNORE';
333 local $SIG{INT} = 'IGNORE';
334 local $SIG{QUIT} = 'IGNORE';
335 local $SIG{TERM} = 'IGNORE';
336 local $SIG{TSTP} = 'IGNORE';
337 local $SIG{PIPE} = 'IGNORE';
339 my $oldAutoCommit = $FS::UID::AutoCommit;
340 local $FS::UID::AutoCommit = 0;
343 $error = $self->SUPER::insert($options{options} ? %{$options{options}} : ());
345 $dbh->rollback if $oldAutoCommit;
349 $self->refnum($self->cust_main->refnum) unless $self->refnum;
350 $self->refnum( [ $self->refnum ] ) unless ref($self->refnum);
351 $self->process_m2m( 'link_table' => 'pkg_referral',
352 'target_table' => 'part_referral',
353 'params' => $self->refnum,
356 if ( $self->discountnum ) {
357 my $error = $self->insert_discount();
359 $dbh->rollback if $oldAutoCommit;
364 my $conf = new FS::Conf;
366 if ( ! $import && $conf->config('ticket_system') && $options{ticket_subject} ) {
368 #this init stuff is still inefficient, but at least its limited to
369 # the small number (any?) folks using ticket emailing on pkg order
372 # use lib ( "/opt/rt3/local/lib", "/opt/rt3/lib" );
379 use FS::TicketSystem;
380 FS::TicketSystem->init();
382 my $q = new RT::Queue($RT::SystemUser);
383 $q->Load($options{ticket_queue}) if $options{ticket_queue};
384 my $t = new RT::Ticket($RT::SystemUser);
385 my $mime = new MIME::Entity;
386 $mime->build( Type => 'text/plain', Data => $options{ticket_subject} );
387 $t->Create( $options{ticket_queue} ? (Queue => $q) : (),
388 Subject => $options{ticket_subject},
391 $t->AddLink( Type => 'MemberOf',
392 Target => 'freeside://freeside/cust_main/'. $self->custnum,
396 if (! $import && $conf->config('welcome_letter') && $self->cust_main->num_pkgs == 1) {
397 my $queue = new FS::queue {
398 'job' => 'FS::cust_main::queueable_print',
400 $error = $queue->insert(
401 'custnum' => $self->custnum,
402 'template' => 'welcome_letter',
406 warn "can't send welcome letter: $error";
411 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
418 This method now works but you probably shouldn't use it.
420 You don't want to delete packages, because there would then be no record
421 the customer ever purchased the package. Instead, see the cancel method and
422 hide cancelled packages.
429 local $SIG{HUP} = 'IGNORE';
430 local $SIG{INT} = 'IGNORE';
431 local $SIG{QUIT} = 'IGNORE';
432 local $SIG{TERM} = 'IGNORE';
433 local $SIG{TSTP} = 'IGNORE';
434 local $SIG{PIPE} = 'IGNORE';
436 my $oldAutoCommit = $FS::UID::AutoCommit;
437 local $FS::UID::AutoCommit = 0;
440 foreach my $cust_pkg_discount ($self->cust_pkg_discount) {
441 my $error = $cust_pkg_discount->delete;
443 $dbh->rollback if $oldAutoCommit;
447 #cust_bill_pkg_discount?
449 foreach my $cust_pkg_detail ($self->cust_pkg_detail) {
450 my $error = $cust_pkg_detail->delete;
452 $dbh->rollback if $oldAutoCommit;
457 foreach my $cust_pkg_reason (
459 'table' => 'cust_pkg_reason',
460 'hashref' => { 'pkgnum' => $self->pkgnum },
464 my $error = $cust_pkg_reason->delete;
466 $dbh->rollback if $oldAutoCommit;
473 my $error = $self->SUPER::delete(@_);
475 $dbh->rollback if $oldAutoCommit;
479 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
485 =item replace [ OLD_RECORD ] [ HASHREF | OPTION => VALUE ... ]
487 Replaces the OLD_RECORD with this one in the database. If there is an error,
488 returns the error, otherwise returns false.
490 Currently, custnum, setup, bill, adjourn, susp, expire, and cancel may be changed.
492 Changing pkgpart may have disasterous effects. See the order subroutine.
494 setup and bill are normally updated by calling the bill method of a customer
495 object (see L<FS::cust_main>).
497 suspend is normally updated by the suspend and unsuspend methods.
499 cancel is normally updated by the cancel method (and also the order subroutine
502 Available options are:
508 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.
512 the access_user (see L<FS::access_user>) providing the reason
516 hashref of keys and values - cust_pkg_option records will be created, updated or removed as appopriate
525 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
530 ( ref($_[0]) eq 'HASH' )
534 #return "Can't (yet?) change pkgpart!" if $old->pkgpart != $new->pkgpart;
535 #return "Can't change otaker!" if $old->otaker ne $new->otaker;
538 #return "Can't change setup once it exists!"
539 # if $old->getfield('setup') &&
540 # $old->getfield('setup') != $new->getfield('setup');
542 #some logic for bill, susp, cancel?
544 local($disable_agentcheck) = 1 if $old->pkgpart == $new->pkgpart;
546 local $SIG{HUP} = 'IGNORE';
547 local $SIG{INT} = 'IGNORE';
548 local $SIG{QUIT} = 'IGNORE';
549 local $SIG{TERM} = 'IGNORE';
550 local $SIG{TSTP} = 'IGNORE';
551 local $SIG{PIPE} = 'IGNORE';
553 my $oldAutoCommit = $FS::UID::AutoCommit;
554 local $FS::UID::AutoCommit = 0;
557 foreach my $method ( qw(adjourn expire) ) { # How many reasons?
558 if ($options->{'reason'} && $new->$method && $old->$method ne $new->$method) {
559 my $error = $new->insert_reason(
560 'reason' => $options->{'reason'},
561 'date' => $new->$method,
563 'reason_otaker' => $options->{'reason_otaker'},
566 dbh->rollback if $oldAutoCommit;
567 return "Error inserting cust_pkg_reason: $error";
572 #save off and freeze RADIUS attributes for any associated svc_acct records
574 if ( $old->part_pkg->is_prepaid || $new->part_pkg->is_prepaid ) {
576 #also check for specific exports?
577 # to avoid spurious modify export events
578 @svc_acct = map { $_->svc_x }
579 grep { $_->part_svc->svcdb eq 'svc_acct' }
582 $_->snapshot foreach @svc_acct;
586 my $error = $new->export_pkg_change($old)
587 || $new->SUPER::replace( $old,
589 ? $options->{options}
593 $dbh->rollback if $oldAutoCommit;
597 #for prepaid packages,
598 #trigger export of new RADIUS Expiration attribute when cust_pkg.bill changes
599 foreach my $old_svc_acct ( @svc_acct ) {
600 my $new_svc_acct = new FS::svc_acct { $old_svc_acct->hash };
602 $new_svc_acct->replace( $old_svc_acct,
603 'depend_jobnum' => $options->{depend_jobnum},
606 $dbh->rollback if $oldAutoCommit;
611 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
618 Checks all fields to make sure this is a valid billing item. If there is an
619 error, returns the error, otherwise returns false. Called by the insert and
627 if ( !$self->locationnum or $self->locationnum == -1 ) {
628 $self->set('locationnum', $self->cust_main->ship_locationnum);
632 $self->ut_numbern('pkgnum')
633 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum')
634 || $self->ut_numbern('pkgpart')
635 || $self->ut_foreign_keyn('contactnum', 'contact', 'contactnum' )
636 || $self->ut_foreign_keyn('locationnum', 'cust_location', 'locationnum')
637 || $self->ut_foreign_keyn('salesnum', 'sales', 'salesnum')
638 || $self->ut_numbern('quantity')
639 || $self->ut_numbern('start_date')
640 || $self->ut_numbern('setup')
641 || $self->ut_numbern('bill')
642 || $self->ut_numbern('susp')
643 || $self->ut_numbern('cancel')
644 || $self->ut_numbern('adjourn')
645 || $self->ut_numbern('resume')
646 || $self->ut_numbern('expire')
647 || $self->ut_numbern('dundate')
648 || $self->ut_enum('no_auto', [ '', 'Y' ])
649 || $self->ut_enum('waive_setup', [ '', 'Y' ])
650 || $self->ut_numbern('agent_pkgid')
651 || $self->ut_enum('recur_show_zero', [ '', 'Y', 'N', ])
652 || $self->ut_enum('setup_show_zero', [ '', 'Y', 'N', ])
653 || $self->ut_foreign_keyn('main_pkgnum', 'cust_pkg', 'pkgnum')
654 || $self->ut_foreign_keyn('pkglinknum', 'part_pkg_link', 'pkglinknum')
655 || $self->ut_foreign_keyn('change_to_pkgnum', 'cust_pkg', 'pkgnum')
657 return $error if $error;
659 return "A package with both start date (future start) and setup date (already started) will never bill"
660 if $self->start_date && $self->setup && ! $upgrade;
662 return "A future unsuspend date can only be set for a package with a suspend date"
663 if $self->resume and !$self->susp and !$self->adjourn;
665 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
667 if ( $self->dbdef_table->column('manual_flag') ) {
668 $self->manual_flag('') if $self->manual_flag eq ' ';
669 $self->manual_flag =~ /^([01]?)$/
670 or return "Illegal manual_flag ". $self->manual_flag;
671 $self->manual_flag($1);
679 Check the pkgpart to make sure it's allowed with the reg_code and/or
680 promo_code of the package (if present) and with the customer's agent.
681 Called from C<insert>, unless we are doing a package change that doesn't
689 # my $error = $self->ut_numbern('pkgpart'); # already done
692 if ( $self->reg_code ) {
694 unless ( grep { $self->pkgpart == $_->pkgpart }
695 map { $_->reg_code_pkg }
696 qsearchs( 'reg_code', { 'code' => $self->reg_code,
697 'agentnum' => $self->cust_main->agentnum })
699 return "Unknown registration code";
702 } elsif ( $self->promo_code ) {
705 qsearchs('part_pkg', {
706 'pkgpart' => $self->pkgpart,
707 'promo_code' => { op=>'ILIKE', value=>$self->promo_code },
709 return 'Unknown promotional code' unless $promo_part_pkg;
713 unless ( $disable_agentcheck ) {
715 qsearchs( 'agent', { 'agentnum' => $self->cust_main->agentnum } );
716 return "agent ". $agent->agentnum. ':'. $agent->agent.
717 " can't purchase pkgpart ". $self->pkgpart
718 unless $agent->pkgpart_hashref->{ $self->pkgpart }
719 || $agent->agentnum == $self->part_pkg->agentnum;
722 $error = $self->ut_foreign_key('pkgpart', 'part_pkg', 'pkgpart' );
723 return $error if $error;
731 =item cancel [ OPTION => VALUE ... ]
733 Cancels and removes all services (see L<FS::cust_svc> and L<FS::part_svc>)
734 in this package, then cancels the package itself (sets the cancel field to
737 Available options are:
741 =item quiet - can be set true to supress email cancellation notices.
743 =item time - can be set to cancel the package based on a specific future or
744 historical date. Using time ensures that the remaining amount is calculated
745 correctly. Note however that this is an immediate cancel and just changes
746 the date. You are PROBABLY looking to expire the account instead of using
749 =item reason - can be set to a cancellation reason (see L<FS:reason>),
750 either a reasonnum of an existing reason, or passing a hashref will create
751 a new reason. The hashref should have the following keys: typenum - Reason
752 type (see L<FS::reason_type>, reason - Text of the new reason.
754 =item date - can be set to a unix style timestamp to specify when to
757 =item nobill - can be set true to skip billing if it might otherwise be done.
759 =item unused_credit - can be set to 1 to credit the remaining time, or 0 to
760 not credit it. This must be set (by change()) when changing the package
761 to a different pkgpart or location, and probably shouldn't be in any other
762 case. If it's not set, the 'unused_credit_cancel' part_pkg option will
767 If there is an error, returns the error, otherwise returns false.
772 my( $self, %options ) = @_;
775 # pass all suspend/cancel actions to the main package
776 if ( $self->main_pkgnum and !$options{'from_main'} ) {
777 return $self->main_pkg->cancel(%options);
780 my $conf = new FS::Conf;
782 warn "cust_pkg::cancel called with options".
783 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
786 local $SIG{HUP} = 'IGNORE';
787 local $SIG{INT} = 'IGNORE';
788 local $SIG{QUIT} = 'IGNORE';
789 local $SIG{TERM} = 'IGNORE';
790 local $SIG{TSTP} = 'IGNORE';
791 local $SIG{PIPE} = 'IGNORE';
793 my $oldAutoCommit = $FS::UID::AutoCommit;
794 local $FS::UID::AutoCommit = 0;
797 my $old = $self->select_for_update;
799 if ( $old->get('cancel') || $self->get('cancel') ) {
800 dbh->rollback if $oldAutoCommit;
801 return ""; # no error
804 # XXX possibly set cancel_time to the expire date?
805 my $cancel_time = $options{'time'} || time;
806 my $date = $options{'date'} if $options{'date'}; # expire/cancel later
807 $date = '' if ($date && $date <= $cancel_time); # complain instead?
809 #race condition: usage could be ongoing until unprovisioned
810 #resolved by performing a change package instead (which unprovisions) and
812 if ( !$options{nobill} && !$date ) {
813 # && $conf->exists('bill_usage_on_cancel') ) { #calc_cancel checks this
814 my $copy = $self->new({$self->hash});
816 $copy->cust_main->bill( 'pkg_list' => [ $copy ],
818 'time' => $cancel_time );
819 warn "Error billing during cancel, custnum ".
820 #$self->cust_main->custnum. ": $error"
825 if ( $options{'reason'} ) {
826 $error = $self->insert_reason( 'reason' => $options{'reason'},
827 'action' => $date ? 'expire' : 'cancel',
828 'date' => $date ? $date : $cancel_time,
829 'reason_otaker' => $options{'reason_otaker'},
832 dbh->rollback if $oldAutoCommit;
833 return "Error inserting cust_pkg_reason: $error";
837 my %svc_cancel_opt = ();
838 $svc_cancel_opt{'date'} = $date if $date;
839 foreach my $cust_svc (
842 sort { $a->[1] <=> $b->[1] }
843 map { [ $_, $_->svc_x ? $_->svc_x->table_info->{'cancel_weight'} : -1 ]; }
844 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
846 my $part_svc = $cust_svc->part_svc;
847 next if ( defined($part_svc) and $part_svc->preserve );
848 my $error = $cust_svc->cancel( %svc_cancel_opt );
851 $dbh->rollback if $oldAutoCommit;
852 return 'Error '. ($svc_cancel_opt{'date'} ? 'expiring' : 'canceling' ).
858 # credit remaining time if appropriate
860 if ( exists($options{'unused_credit'}) ) {
861 $do_credit = $options{'unused_credit'};
864 $do_credit = $self->part_pkg->option('unused_credit_cancel', 1);
867 my $error = $self->credit_remaining('cancel', $cancel_time);
869 $dbh->rollback if $oldAutoCommit;
876 my %hash = $self->hash;
878 $hash{'expire'} = $date;
880 $hash{'cancel'} = $cancel_time;
882 $hash{'change_custnum'} = $options{'change_custnum'};
884 my $new = new FS::cust_pkg ( \%hash );
885 $error = $new->replace( $self, options => { $self->options } );
886 if ( $self->change_to_pkgnum ) {
887 my $change_to = FS::cust_pkg->by_key($self->change_to_pkgnum);
888 $error ||= $change_to->cancel || $change_to->delete;
891 $dbh->rollback if $oldAutoCommit;
895 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
896 $error = $supp_pkg->cancel(%options, 'from_main' => 1);
898 $dbh->rollback if $oldAutoCommit;
899 return "canceling supplemental pkg#".$supp_pkg->pkgnum.": $error";
903 foreach my $usage ( $self->cust_pkg_usage ) {
904 $error = $usage->delete;
906 $dbh->rollback if $oldAutoCommit;
907 return "deleting usage pools: $error";
911 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
912 return '' if $date; #no errors
914 my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ } $self->cust_main->invoicing_list;
915 if ( !$options{'quiet'} &&
916 $conf->exists('emailcancel', $self->cust_main->agentnum) &&
918 my $msgnum = $conf->config('cancel_msgnum', $self->cust_main->agentnum);
921 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum });
922 $error = $msg_template->send( 'cust_main' => $self->cust_main,
927 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
928 'to' => \@invoicing_list,
929 'subject' => ( $conf->config('cancelsubject') || 'Cancellation Notice' ),
930 'body' => [ map "$_\n", $conf->config('cancelmessage') ],
933 #should this do something on errors?
940 =item cancel_if_expired [ NOW_TIMESTAMP ]
942 Cancels this package if its expire date has been reached.
946 sub cancel_if_expired {
948 my $time = shift || time;
949 return '' unless $self->expire && $self->expire <= $time;
950 my $error = $self->cancel;
952 return "Error cancelling expired pkg ". $self->pkgnum. " for custnum ".
953 $self->custnum. ": $error";
960 "Un-cancels" this package: Orders a new package with the same custnum, pkgpart,
961 locationnum, (other fields?). Attempts to re-provision cancelled services
962 using history information (errors at this stage are not fatal).
964 cust_pkg: pass a scalar reference, will be filled in with the new cust_pkg object
966 svc_fatal: service provisioning errors are fatal
968 svc_errors: pass an array reference, will be filled in with any provisioning errors
970 main_pkgnum: link the package as a supplemental package of this one. For
976 my( $self, %options ) = @_;
978 #in case you try do do $uncancel-date = $cust_pkg->uncacel
979 return '' unless $self->get('cancel');
981 if ( $self->main_pkgnum and !$options{'main_pkgnum'} ) {
982 return $self->main_pkg->uncancel(%options);
989 local $SIG{HUP} = 'IGNORE';
990 local $SIG{INT} = 'IGNORE';
991 local $SIG{QUIT} = 'IGNORE';
992 local $SIG{TERM} = 'IGNORE';
993 local $SIG{TSTP} = 'IGNORE';
994 local $SIG{PIPE} = 'IGNORE';
996 my $oldAutoCommit = $FS::UID::AutoCommit;
997 local $FS::UID::AutoCommit = 0;
1001 # insert the new package
1004 my $cust_pkg = new FS::cust_pkg {
1005 last_bill => ( $options{'last_bill'} || $self->get('last_bill') ),
1006 bill => ( $options{'bill'} || $self->get('bill') ),
1008 uncancel_pkgnum => $self->pkgnum,
1009 main_pkgnum => ($options{'main_pkgnum'} || ''),
1010 map { $_ => $self->get($_) } qw(
1011 custnum pkgpart locationnum
1013 susp adjourn resume expire start_date contract_end dundate
1014 change_date change_pkgpart change_locationnum
1015 manual_flag no_auto quantity agent_pkgid recur_show_zero setup_show_zero
1019 my $error = $cust_pkg->insert(
1020 'change' => 1, #supresses any referral credit to a referring customer
1021 'allow_pkgpart' => 1, # allow this even if the package def is disabled
1024 $dbh->rollback if $oldAutoCommit;
1032 #find historical services within this timeframe before the package cancel
1033 # (incompatible with "time" option to cust_pkg->cancel?)
1034 my $fuzz = 2 * 60; #2 minutes? too much? (might catch separate unprovision)
1035 # too little? (unprovisioing export delay?)
1036 my($end, $start) = ( $self->get('cancel'), $self->get('cancel') - $fuzz );
1037 my @h_cust_svc = $self->h_cust_svc( $end, $start );
1040 foreach my $h_cust_svc (@h_cust_svc) {
1041 my $h_svc_x = $h_cust_svc->h_svc_x( $end, $start );
1042 #next unless $h_svc_x; #should this happen?
1043 (my $table = $h_svc_x->table) =~ s/^h_//;
1044 require "FS/$table.pm";
1045 my $class = "FS::$table";
1046 my $svc_x = $class->new( {
1047 'pkgnum' => $cust_pkg->pkgnum,
1048 'svcpart' => $h_cust_svc->svcpart,
1049 map { $_ => $h_svc_x->get($_) } fields($table)
1053 if ( $h_svc_x->isa('FS::h_svc_Radius_Mixin') ) {
1054 $svc_x->usergroup( [ $h_svc_x->h_usergroup($end, $start) ] );
1057 my $svc_error = $svc_x->insert;
1059 if ( $options{svc_fatal} ) {
1060 $dbh->rollback if $oldAutoCommit;
1063 # if we've failed to insert the svc_x object, svc_Common->insert
1064 # will have removed the cust_svc already. if not, then both records
1065 # were inserted but we failed for some other reason (export, most
1066 # likely). in that case, report the error and delete the records.
1067 push @svc_errors, $svc_error;
1068 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svc_x->svcnum });
1070 # except if export_insert failed, export_delete probably won't be
1072 local $FS::svc_Common::noexport_hack = 1;
1073 my $cleanup_error = $svc_x->delete; # also deletes cust_svc
1074 if ( $cleanup_error ) { # and if THAT fails, then run away
1075 $dbh->rollback if $oldAutoCommit;
1076 return $cleanup_error;
1081 } #foreach $h_cust_svc
1083 #these are pretty rare, but should handle them
1084 # - dsl_device (mac addresses)
1085 # - phone_device (mac addresses)
1086 # - dsl_note (ikano notes)
1087 # - domain_record (i.e. restore DNS information w/domains)
1088 # - inventory_item(?) (inventory w/un-cancelling service?)
1089 # - nas (svc_broaband nas stuff)
1090 #this stuff is unused in the wild afaik
1091 # - mailinglistmember
1093 # - svc_domain.parent_svcnum?
1094 # - acct_snarf (ancient mail fetching config)
1095 # - cgp_rule (communigate)
1096 # - cust_svc_option (used by our Tron stuff)
1097 # - acct_rt_transaction (used by our time worked stuff)
1100 # also move over any services that didn't unprovision at cancellation
1103 foreach my $cust_svc ( qsearch('cust_svc', { pkgnum => $self->pkgnum } ) ) {
1104 $cust_svc->pkgnum( $cust_pkg->pkgnum );
1105 my $error = $cust_svc->replace;
1107 $dbh->rollback if $oldAutoCommit;
1113 # Uncancel any supplemental packages, and make them supplemental to the
1117 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1119 $error = $supp_pkg->uncancel(%options, 'main_pkgnum' => $cust_pkg->pkgnum);
1121 $dbh->rollback if $oldAutoCommit;
1122 return "canceling supplemental pkg#".$supp_pkg->pkgnum.": $error";
1130 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1132 ${ $options{cust_pkg} } = $cust_pkg if ref($options{cust_pkg});
1133 @{ $options{svc_errors} } = @svc_errors if ref($options{svc_errors});
1140 Cancels any pending expiration (sets the expire field to null).
1142 If there is an error, returns the error, otherwise returns false.
1147 my( $self, %options ) = @_;
1150 local $SIG{HUP} = 'IGNORE';
1151 local $SIG{INT} = 'IGNORE';
1152 local $SIG{QUIT} = 'IGNORE';
1153 local $SIG{TERM} = 'IGNORE';
1154 local $SIG{TSTP} = 'IGNORE';
1155 local $SIG{PIPE} = 'IGNORE';
1157 my $oldAutoCommit = $FS::UID::AutoCommit;
1158 local $FS::UID::AutoCommit = 0;
1161 my $old = $self->select_for_update;
1163 my $pkgnum = $old->pkgnum;
1164 if ( $old->get('cancel') || $self->get('cancel') ) {
1165 dbh->rollback if $oldAutoCommit;
1166 return "Can't unexpire cancelled package $pkgnum";
1167 # or at least it's pointless
1170 unless ( $old->get('expire') && $self->get('expire') ) {
1171 dbh->rollback if $oldAutoCommit;
1172 return ""; # no error
1175 my %hash = $self->hash;
1176 $hash{'expire'} = '';
1177 my $new = new FS::cust_pkg ( \%hash );
1178 $error = $new->replace( $self, options => { $self->options } );
1180 $dbh->rollback if $oldAutoCommit;
1184 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1190 =item suspend [ OPTION => VALUE ... ]
1192 Suspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
1193 package, then suspends the package itself (sets the susp field to now).
1195 Available options are:
1199 =item reason - can be set to a cancellation reason (see L<FS:reason>),
1200 either a reasonnum of an existing reason, or passing a hashref will create
1201 a new reason. The hashref should have the following keys:
1202 - typenum - Reason type (see L<FS::reason_type>
1203 - reason - Text of the new reason.
1205 =item date - can be set to a unix style timestamp to specify when to
1208 =item time - can be set to override the current time, for calculation
1209 of final invoices or unused-time credits
1211 =item resume_date - can be set to a time when the package should be
1212 unsuspended. This may be more convenient than calling C<unsuspend()>
1215 =item from_main - allows a supplemental package to be suspended, rather
1216 than redirecting the method call to its main package. For internal use.
1220 If there is an error, returns the error, otherwise returns false.
1225 my( $self, %options ) = @_;
1228 # pass all suspend/cancel actions to the main package
1229 if ( $self->main_pkgnum and !$options{'from_main'} ) {
1230 return $self->main_pkg->suspend(%options);
1233 local $SIG{HUP} = 'IGNORE';
1234 local $SIG{INT} = 'IGNORE';
1235 local $SIG{QUIT} = 'IGNORE';
1236 local $SIG{TERM} = 'IGNORE';
1237 local $SIG{TSTP} = 'IGNORE';
1238 local $SIG{PIPE} = 'IGNORE';
1240 my $oldAutoCommit = $FS::UID::AutoCommit;
1241 local $FS::UID::AutoCommit = 0;
1244 my $old = $self->select_for_update;
1246 my $pkgnum = $old->pkgnum;
1247 if ( $old->get('cancel') || $self->get('cancel') ) {
1248 dbh->rollback if $oldAutoCommit;
1249 return "Can't suspend cancelled package $pkgnum";
1252 if ( $old->get('susp') || $self->get('susp') ) {
1253 dbh->rollback if $oldAutoCommit;
1254 return ""; # no error # complain on adjourn?
1257 my $suspend_time = $options{'time'} || time;
1258 my $date = $options{date} if $options{date}; # adjourn/suspend later
1259 $date = '' if ($date && $date <= $suspend_time); # complain instead?
1261 if ( $date && $old->get('expire') && $old->get('expire') < $date ) {
1262 dbh->rollback if $oldAutoCommit;
1263 return "Package $pkgnum expires before it would be suspended.";
1266 # some false laziness with sub cancel
1267 if ( !$options{nobill} && !$date &&
1268 $self->part_pkg->option('bill_suspend_as_cancel',1) ) {
1269 # kind of a kludge--'bill_suspend_as_cancel' to avoid having to
1270 # make the entire cust_main->bill path recognize 'suspend' and
1271 # 'cancel' separately.
1272 warn "Billing $pkgnum on suspension (at $suspend_time)\n" if $DEBUG;
1273 my $copy = $self->new({$self->hash});
1275 $copy->cust_main->bill( 'pkg_list' => [ $copy ],
1277 'time' => $suspend_time );
1278 warn "Error billing during suspend, custnum ".
1279 #$self->cust_main->custnum. ": $error"
1284 if ( $options{'reason'} ) {
1285 $error = $self->insert_reason( 'reason' => $options{'reason'},
1286 'action' => $date ? 'adjourn' : 'suspend',
1287 'date' => $date ? $date : $suspend_time,
1288 'reason_otaker' => $options{'reason_otaker'},
1291 dbh->rollback if $oldAutoCommit;
1292 return "Error inserting cust_pkg_reason: $error";
1296 my %hash = $self->hash;
1298 $hash{'adjourn'} = $date;
1300 $hash{'susp'} = $suspend_time;
1303 my $resume_date = $options{'resume_date'} || 0;
1304 if ( $resume_date > ($date || $suspend_time) ) {
1305 $hash{'resume'} = $resume_date;
1308 $options{options} ||= {};
1310 my $new = new FS::cust_pkg ( \%hash );
1311 $error = $new->replace( $self, options => { $self->options,
1312 %{ $options{options} },
1316 $dbh->rollback if $oldAutoCommit;
1321 # credit remaining time if appropriate
1322 if ( $self->part_pkg->option('unused_credit_suspend', 1) ) {
1323 my $error = $self->credit_remaining('suspend', $suspend_time);
1325 $dbh->rollback if $oldAutoCommit;
1332 foreach my $cust_svc (
1333 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
1335 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
1337 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
1338 $dbh->rollback if $oldAutoCommit;
1339 return "Illegal svcdb value in part_svc!";
1342 require "FS/$svcdb.pm";
1344 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
1346 $error = $svc->suspend;
1348 $dbh->rollback if $oldAutoCommit;
1351 my( $label, $value ) = $cust_svc->label;
1352 push @labels, "$label: $value";
1356 my $conf = new FS::Conf;
1357 if ( $conf->config('suspend_email_admin') ) {
1359 my $error = send_email(
1360 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
1361 #invoice_from ??? well as good as any
1362 'to' => $conf->config('suspend_email_admin'),
1363 'subject' => 'FREESIDE NOTIFICATION: Customer package suspended',
1365 "This is an automatic message from your Freeside installation\n",
1366 "informing you that the following customer package has been suspended:\n",
1368 'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
1369 'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
1370 ( map { "Service : $_\n" } @labels ),
1375 warn "WARNING: can't send suspension admin email (suspending anyway): ".
1383 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1384 $error = $supp_pkg->suspend(%options, 'from_main' => 1);
1386 $dbh->rollback if $oldAutoCommit;
1387 return "suspending supplemental pkg#".$supp_pkg->pkgnum.": $error";
1391 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1396 =item credit_remaining MODE TIME
1398 Generate a credit for this package for the time remaining in the current
1399 billing period. MODE is either "suspend" or "cancel" (determines the
1400 credit type). TIME is the time of suspension/cancellation. Both arguments
1405 sub credit_remaining {
1406 # Add a credit for remaining service
1407 my ($self, $mode, $time) = @_;
1408 die 'credit_remaining requires suspend or cancel'
1409 unless $mode eq 'suspend' or $mode eq 'cancel';
1410 die 'no suspend/cancel time' unless $time > 0;
1412 my $conf = FS::Conf->new;
1413 my $reason_type = $conf->config($mode.'_credit_type');
1415 my $last_bill = $self->getfield('last_bill') || 0;
1416 my $next_bill = $self->getfield('bill') || 0;
1417 if ( $last_bill > 0 # the package has been billed
1418 and $next_bill > 0 # the package has a next bill date
1419 and $next_bill >= $time # which is in the future
1421 my $remaining_value = $self->calc_remain('time' => $time);
1422 if ( $remaining_value > 0 ) {
1423 warn "Crediting for $remaining_value on package ".$self->pkgnum."\n"
1425 my $error = $self->cust_main->credit(
1427 'Credit for unused time on '. $self->part_pkg->pkg,
1428 'reason_type' => $reason_type,
1430 return "Error crediting customer \$$remaining_value for unused time".
1431 " on ". $self->part_pkg->pkg. ": $error"
1433 } #if $remaining_value
1434 } #if $last_bill, etc.
1438 =item unsuspend [ OPTION => VALUE ... ]
1440 Unsuspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
1441 package, then unsuspends the package itself (clears the susp field and the
1442 adjourn field if it is in the past). If the suspend reason includes an
1443 unsuspension package, that package will be ordered.
1445 Available options are:
1451 Can be set to a date to unsuspend the package in the future (the 'resume'
1454 =item adjust_next_bill
1456 Can be set true to adjust the next bill date forward by
1457 the amount of time the account was inactive. This was set true by default
1458 in the past (from 1.4.2 and 1.5.0pre6 through 1.7.0), but now needs to be
1459 explicitly requested with this option or in the price plan.
1463 If there is an error, returns the error, otherwise returns false.
1468 my( $self, %opt ) = @_;
1471 # pass all suspend/cancel actions to the main package
1472 if ( $self->main_pkgnum and !$opt{'from_main'} ) {
1473 return $self->main_pkg->unsuspend(%opt);
1476 local $SIG{HUP} = 'IGNORE';
1477 local $SIG{INT} = 'IGNORE';
1478 local $SIG{QUIT} = 'IGNORE';
1479 local $SIG{TERM} = 'IGNORE';
1480 local $SIG{TSTP} = 'IGNORE';
1481 local $SIG{PIPE} = 'IGNORE';
1483 my $oldAutoCommit = $FS::UID::AutoCommit;
1484 local $FS::UID::AutoCommit = 0;
1487 my $old = $self->select_for_update;
1489 my $pkgnum = $old->pkgnum;
1490 if ( $old->get('cancel') || $self->get('cancel') ) {
1491 $dbh->rollback if $oldAutoCommit;
1492 return "Can't unsuspend cancelled package $pkgnum";
1495 unless ( $old->get('susp') && $self->get('susp') ) {
1496 $dbh->rollback if $oldAutoCommit;
1497 return ""; # no error # complain instead?
1500 my $date = $opt{'date'};
1501 if ( $date and $date > time ) { # return an error if $date <= time?
1503 if ( $old->get('expire') && $old->get('expire') < $date ) {
1504 $dbh->rollback if $oldAutoCommit;
1505 return "Package $pkgnum expires before it would be unsuspended.";
1508 my $new = new FS::cust_pkg { $self->hash };
1509 $new->set('resume', $date);
1510 $error = $new->replace($self, options => $self->options);
1513 $dbh->rollback if $oldAutoCommit;
1517 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1525 foreach my $cust_svc (
1526 qsearch('cust_svc',{'pkgnum'=> $self->pkgnum } )
1528 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
1530 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
1531 $dbh->rollback if $oldAutoCommit;
1532 return "Illegal svcdb value in part_svc!";
1535 require "FS/$svcdb.pm";
1537 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
1539 $error = $svc->unsuspend;
1541 $dbh->rollback if $oldAutoCommit;
1544 my( $label, $value ) = $cust_svc->label;
1545 push @labels, "$label: $value";
1550 my $cust_pkg_reason = $self->last_cust_pkg_reason('susp');
1551 my $reason = $cust_pkg_reason ? $cust_pkg_reason->reason : '';
1553 my %hash = $self->hash;
1554 my $inactive = time - $hash{'susp'};
1556 my $conf = new FS::Conf;
1558 if ( $inactive > 0 &&
1559 ( $hash{'bill'} || $hash{'setup'} ) &&
1560 ( $opt{'adjust_next_bill'} ||
1561 $conf->exists('unsuspend-always_adjust_next_bill_date') ||
1562 $self->part_pkg->option('unsuspend_adjust_bill', 1) )
1565 $hash{'bill'} = ( $hash{'bill'} || $hash{'setup'} ) + $inactive;
1570 $hash{'adjourn'} = '' if $hash{'adjourn'} and $hash{'adjourn'} < time;
1571 $hash{'resume'} = '' if !$hash{'adjourn'};
1572 my $new = new FS::cust_pkg ( \%hash );
1573 $error = $new->replace( $self, options => { $self->options } );
1575 $dbh->rollback if $oldAutoCommit;
1581 if ( $reason && $reason->unsuspend_pkgpart ) {
1582 my $part_pkg = FS::part_pkg->by_key($reason->unsuspend_pkgpart)
1583 or $error = "Unsuspend package definition ".$reason->unsuspend_pkgpart.
1585 my $start_date = $self->cust_main->next_bill_date
1586 if $reason->unsuspend_hold;
1589 $unsusp_pkg = FS::cust_pkg->new({
1590 'custnum' => $self->custnum,
1591 'pkgpart' => $reason->unsuspend_pkgpart,
1592 'start_date' => $start_date,
1593 'locationnum' => $self->locationnum,
1594 # discount? probably not...
1597 $error ||= $self->cust_main->order_pkg( 'cust_pkg' => $unsusp_pkg );
1601 $dbh->rollback if $oldAutoCommit;
1606 if ( $conf->config('unsuspend_email_admin') ) {
1608 my $error = send_email(
1609 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
1610 #invoice_from ??? well as good as any
1611 'to' => $conf->config('unsuspend_email_admin'),
1612 'subject' => 'FREESIDE NOTIFICATION: Customer package unsuspended', 'body' => [
1613 "This is an automatic message from your Freeside installation\n",
1614 "informing you that the following customer package has been unsuspended:\n",
1616 'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
1617 'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
1618 ( map { "Service : $_\n" } @labels ),
1620 "An unsuspension fee was charged: ".
1621 $unsusp_pkg->part_pkg->pkg_comment."\n"
1628 warn "WARNING: can't send unsuspension admin email (unsuspending anyway): ".
1634 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1635 $error = $supp_pkg->unsuspend(%opt, 'from_main' => 1);
1637 $dbh->rollback if $oldAutoCommit;
1638 return "unsuspending supplemental pkg#".$supp_pkg->pkgnum.": $error";
1642 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1649 Cancels any pending suspension (sets the adjourn field to null).
1651 If there is an error, returns the error, otherwise returns false.
1656 my( $self, %options ) = @_;
1659 local $SIG{HUP} = 'IGNORE';
1660 local $SIG{INT} = 'IGNORE';
1661 local $SIG{QUIT} = 'IGNORE';
1662 local $SIG{TERM} = 'IGNORE';
1663 local $SIG{TSTP} = 'IGNORE';
1664 local $SIG{PIPE} = 'IGNORE';
1666 my $oldAutoCommit = $FS::UID::AutoCommit;
1667 local $FS::UID::AutoCommit = 0;
1670 my $old = $self->select_for_update;
1672 my $pkgnum = $old->pkgnum;
1673 if ( $old->get('cancel') || $self->get('cancel') ) {
1674 dbh->rollback if $oldAutoCommit;
1675 return "Can't unadjourn cancelled package $pkgnum";
1676 # or at least it's pointless
1679 if ( $old->get('susp') || $self->get('susp') ) {
1680 dbh->rollback if $oldAutoCommit;
1681 return "Can't unadjourn suspended package $pkgnum";
1682 # perhaps this is arbitrary
1685 unless ( $old->get('adjourn') && $self->get('adjourn') ) {
1686 dbh->rollback if $oldAutoCommit;
1687 return ""; # no error
1690 my %hash = $self->hash;
1691 $hash{'adjourn'} = '';
1692 $hash{'resume'} = '';
1693 my $new = new FS::cust_pkg ( \%hash );
1694 $error = $new->replace( $self, options => { $self->options } );
1696 $dbh->rollback if $oldAutoCommit;
1700 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1707 =item change HASHREF | OPTION => VALUE ...
1709 Changes this package: cancels it and creates a new one, with a different
1710 pkgpart or locationnum or both. All services are transferred to the new
1711 package (no change will be made if this is not possible).
1713 Options may be passed as a list of key/value pairs or as a hash reference.
1720 New locationnum, to change the location for this package.
1724 New FS::cust_location object, to create a new location and assign it
1729 New FS::cust_main object, to create a new customer and assign the new package
1734 New pkgpart (see L<FS::part_pkg>).
1738 New refnum (see L<FS::part_referral>).
1742 New quantity; if unspecified, the new package will have the same quantity
1747 "New" (existing) FS::cust_pkg object. The package's services and other
1748 attributes will be transferred to this package.
1752 Set to true to transfer billing dates (start_date, setup, last_bill, bill,
1753 susp, adjourn, cancel, expire, and contract_end) to the new package.
1755 =item unprotect_svcs
1757 Normally, change() will rollback and return an error if some services
1758 can't be transferred (also see the I<cust_pkg-change_svcpart> config option).
1759 If unprotect_svcs is true, this method will transfer as many services as
1760 it can and then unconditionally cancel the old package.
1764 At least one of locationnum, cust_location, pkgpart, refnum, cust_main, or
1765 cust_pkg must be specified (otherwise, what's the point?)
1767 Returns either the new FS::cust_pkg object or a scalar error.
1771 my $err_or_new_cust_pkg = $old_cust_pkg->change
1775 #some false laziness w/order
1778 my $opt = ref($_[0]) ? shift : { @_ };
1780 my $conf = new FS::Conf;
1782 # Transactionize this whole mess
1783 local $SIG{HUP} = 'IGNORE';
1784 local $SIG{INT} = 'IGNORE';
1785 local $SIG{QUIT} = 'IGNORE';
1786 local $SIG{TERM} = 'IGNORE';
1787 local $SIG{TSTP} = 'IGNORE';
1788 local $SIG{PIPE} = 'IGNORE';
1790 my $oldAutoCommit = $FS::UID::AutoCommit;
1791 local $FS::UID::AutoCommit = 0;
1800 $hash{'setup'} = $time if $self->setup;
1802 $hash{'change_date'} = $time;
1803 $hash{"change_$_"} = $self->$_()
1804 foreach qw( pkgnum pkgpart locationnum );
1806 if ( $opt->{'cust_location'} ) {
1807 $error = $opt->{'cust_location'}->find_or_insert;
1809 $dbh->rollback if $oldAutoCommit;
1810 return "inserting cust_location (transaction rolled back): $error";
1812 $opt->{'locationnum'} = $opt->{'cust_location'}->locationnum;
1815 if ( $opt->{'cust_pkg'} ) {
1816 # treat changing to a package with a different pkgpart as a
1817 # pkgpart change (because it is)
1818 $opt->{'pkgpart'} = $opt->{'cust_pkg'}->pkgpart;
1821 # whether to override pkgpart checking on the new package
1822 my $same_pkgpart = 1;
1823 if ( $opt->{'pkgpart'} and ( $opt->{'pkgpart'} != $self->pkgpart ) ) {
1827 my $unused_credit = 0;
1828 my $keep_dates = $opt->{'keep_dates'};
1829 # Special case. If the pkgpart is changing, and the customer is
1830 # going to be credited for remaining time, don't keep setup, bill,
1831 # or last_bill dates, and DO pass the flag to cancel() to credit
1833 if ( $opt->{'pkgpart'}
1834 and $opt->{'pkgpart'} != $self->pkgpart
1835 and $self->part_pkg->option('unused_credit_change', 1) ) {
1838 $hash{$_} = '' foreach qw(setup bill last_bill);
1841 if ( $keep_dates ) {
1842 foreach my $date ( qw(setup bill last_bill susp adjourn cancel expire
1843 resume start_date contract_end ) ) {
1844 $hash{$date} = $self->getfield($date);
1848 # allow $opt->{'locationnum'} = '' to specifically set it to null
1849 # (i.e. customer default location)
1850 $opt->{'locationnum'} = $self->locationnum if !exists($opt->{'locationnum'});
1852 # usually this doesn't matter. the two cases where it does are:
1853 # 1. unused_credit_change + pkgpart change + setup fee on the new package
1855 # 2. (more importantly) changing a package before it's billed
1856 $hash{'waive_setup'} = $self->waive_setup;
1858 my $custnum = $self->custnum;
1859 if ( $opt->{cust_main} ) {
1860 my $cust_main = $opt->{cust_main};
1861 unless ( $cust_main->custnum ) {
1862 my $error = $cust_main->insert( @{ $opt->{cust_main_insert_args}||[] } );
1864 $dbh->rollback if $oldAutoCommit;
1865 return "inserting cust_main (transaction rolled back): $error";
1868 $custnum = $cust_main->custnum;
1871 $hash{'contactnum'} = $opt->{'contactnum'} if $opt->{'contactnum'};
1874 if ( $opt->{'cust_pkg'} ) {
1875 # The target package already exists; update it to show that it was
1876 # changed from this package.
1877 $cust_pkg = $opt->{'cust_pkg'};
1879 foreach ( qw( pkgnum pkgpart locationnum ) ) {
1880 $cust_pkg->set("change_$_", $self->get($_));
1882 $cust_pkg->set('change_date', $time);
1883 $error = $cust_pkg->replace;
1886 # Create the new package.
1887 $cust_pkg = new FS::cust_pkg {
1888 custnum => $custnum,
1889 locationnum => $opt->{'locationnum'},
1890 ( map { $_ => ( $opt->{$_} || $self->$_() ) }
1891 qw( pkgpart quantity refnum salesnum )
1895 $error = $cust_pkg->insert( 'change' => 1,
1896 'allow_pkgpart' => $same_pkgpart );
1899 $dbh->rollback if $oldAutoCommit;
1903 # Transfer services and cancel old package.
1905 $error = $self->transfer($cust_pkg);
1906 if ($error and $error == 0) {
1907 # $old_pkg->transfer failed.
1908 $dbh->rollback if $oldAutoCommit;
1912 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
1913 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
1914 $error = $self->transfer($cust_pkg, 'change_svcpart'=>1 );
1915 if ($error and $error == 0) {
1916 # $old_pkg->transfer failed.
1917 $dbh->rollback if $oldAutoCommit;
1922 # We set unprotect_svcs when executing a "future package change". It's
1923 # not a user-interactive operation, so returning an error means the
1924 # package change will just fail. Rather than have that happen, we'll
1925 # let leftover services be deleted.
1926 if ($error > 0 and !$opt->{'unprotect_svcs'}) {
1927 # Transfers were successful, but we still had services left on the old
1928 # package. We can't change the package under this circumstances, so abort.
1929 $dbh->rollback if $oldAutoCommit;
1930 return "Unable to transfer all services from package ". $self->pkgnum;
1933 #reset usage if changing pkgpart
1934 # AND usage rollover is off (otherwise adds twice, now and at package bill)
1935 if ($self->pkgpart != $cust_pkg->pkgpart) {
1936 my $part_pkg = $cust_pkg->part_pkg;
1937 $error = $part_pkg->reset_usage($cust_pkg, $part_pkg->is_prepaid
1941 if $part_pkg->can('reset_usage') && ! $part_pkg->option('usage_rollover',1);
1944 $dbh->rollback if $oldAutoCommit;
1945 return "Error setting usage values: $error";
1948 # if NOT changing pkgpart, transfer any usage pools over
1949 foreach my $usage ($self->cust_pkg_usage) {
1950 $usage->set('pkgnum', $cust_pkg->pkgnum);
1951 $error = $usage->replace;
1953 $dbh->rollback if $oldAutoCommit;
1954 return "Error transferring usage pools: $error";
1959 # transfer discounts, if we're not changing pkgpart
1960 if ( $same_pkgpart ) {
1961 foreach my $old_discount ($self->cust_pkg_discount_active) {
1962 # don't remove the old discount, we may still need to bill that package.
1963 my $new_discount = new FS::cust_pkg_discount {
1964 'pkgnum' => $cust_pkg->pkgnum,
1965 'discountnum' => $old_discount->discountnum,
1966 'months_used' => $old_discount->months_used,
1968 $error = $new_discount->insert;
1970 $dbh->rollback if $oldAutoCommit;
1971 return "Error transferring discounts: $error";
1976 # transfer (copy) invoice details
1977 foreach my $detail ($self->cust_pkg_detail) {
1978 my $new_detail = FS::cust_pkg_detail->new({ $detail->hash });
1979 $new_detail->set('pkgdetailnum', '');
1980 $new_detail->set('pkgnum', $cust_pkg->pkgnum);
1981 $error = $new_detail->insert;
1983 $dbh->rollback if $oldAutoCommit;
1984 return "Error transferring package notes: $error";
1990 if ( !$opt->{'cust_pkg'} ) {
1991 # Order any supplemental packages.
1992 my $part_pkg = $cust_pkg->part_pkg;
1993 my @old_supp_pkgs = $self->supplemental_pkgs;
1994 foreach my $link ($part_pkg->supp_part_pkg_link) {
1996 foreach (@old_supp_pkgs) {
1997 if ($_->pkgpart == $link->dst_pkgpart) {
1999 $_->pkgpart(0); # so that it can't match more than once
2003 # false laziness with FS::cust_main::Packages::order_pkg
2004 my $new = FS::cust_pkg->new({
2005 pkgpart => $link->dst_pkgpart,
2006 pkglinknum => $link->pkglinknum,
2007 custnum => $custnum,
2008 main_pkgnum => $cust_pkg->pkgnum,
2009 locationnum => $cust_pkg->locationnum,
2010 start_date => $cust_pkg->start_date,
2011 order_date => $cust_pkg->order_date,
2012 expire => $cust_pkg->expire,
2013 adjourn => $cust_pkg->adjourn,
2014 contract_end => $cust_pkg->contract_end,
2015 refnum => $cust_pkg->refnum,
2016 discountnum => $cust_pkg->discountnum,
2017 waive_setup => $cust_pkg->waive_setup,
2019 if ( $old and $opt->{'keep_dates'} ) {
2020 foreach (qw(setup bill last_bill)) {
2021 $new->set($_, $old->get($_));
2024 $error = $new->insert( allow_pkgpart => $same_pkgpart );
2027 $error ||= $old->transfer($new);
2029 if ( $error and $error > 0 ) {
2030 # no reason why this should ever fail, but still...
2031 $error = "Unable to transfer all services from supplemental package ".
2035 $dbh->rollback if $oldAutoCommit;
2038 push @new_supp_pkgs, $new;
2040 } # if !$opt->{'cust_pkg'}
2041 # because if there is one, then supplemental packages would already
2042 # have been created for it.
2044 #Good to go, cancel old package. Notify 'cancel' of whether to credit
2046 #Don't allow billing the package (preceding period packages and/or
2047 #outstanding usage) if we are keeping dates (i.e. location changing),
2048 #because the new package will be billed for the same date range.
2049 #Supplemental packages are also canceled here.
2051 # during scheduled changes, avoid canceling the package we just
2053 $self->set('change_to_pkgnum' => '');
2055 $error = $self->cancel(
2057 unused_credit => $unused_credit,
2058 nobill => $keep_dates,
2059 change_custnum => ( $self->custnum != $custnum ? $custnum : '' ),
2062 $dbh->rollback if $oldAutoCommit;
2066 if ( $conf->exists('cust_pkg-change_pkgpart-bill_now') ) {
2068 my $error = $cust_pkg->cust_main->bill(
2069 'pkg_list' => [ $cust_pkg, @new_supp_pkgs ]
2072 $dbh->rollback if $oldAutoCommit;
2077 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2083 =item change_later OPTION => VALUE...
2085 Schedule a package change for a later date. This actually orders the new
2086 package immediately, but sets its start date for a future date, and sets
2087 the current package to expire on the same date.
2089 If the package is already scheduled for a change, this can be called with
2090 'start_date' to change the scheduled date, or with pkgpart and/or
2091 locationnum to modify the package change. To cancel the scheduled change
2092 entirely, see C<abort_change>.
2100 The date for the package change. Required, and must be in the future.
2108 The pkgpart. locationnum, and quantity of the new package, with the same
2109 meaning as in C<change>.
2117 my $opt = ref($_[0]) ? shift : { @_ };
2119 my $oldAutoCommit = $FS::UID::AutoCommit;
2120 local $FS::UID::AutoCommit = 0;
2123 my $cust_main = $self->cust_main;
2125 my $date = delete $opt->{'start_date'} or return 'start_date required';
2127 if ( $date <= time ) {
2128 $dbh->rollback if $oldAutoCommit;
2129 return "start_date $date is in the past";
2134 if ( $self->change_to_pkgnum ) {
2135 my $change_to = FS::cust_pkg->by_key($self->change_to_pkgnum);
2136 my $new_pkgpart = $opt->{'pkgpart'}
2137 if $opt->{'pkgpart'} and $opt->{'pkgpart'} != $change_to->pkgpart;
2138 my $new_locationnum = $opt->{'locationnum'}
2139 if $opt->{'locationnum'} and $opt->{'locationnum'} != $change_to->locationnum;
2140 my $new_quantity = $opt->{'quantity'}
2141 if $opt->{'quantity'} and $opt->{'quantity'} != $change_to->quantity;
2142 if ( $new_pkgpart or $new_locationnum or $new_quantity ) {
2143 # it hasn't been billed yet, so in principle we could just edit
2144 # it in place (w/o a package change), but that's bad form.
2145 # So change the package according to the new options...
2146 my $err_or_pkg = $change_to->change(%$opt);
2147 if ( ref $err_or_pkg ) {
2148 # Then set that package up for a future start.
2149 $self->set('change_to_pkgnum', $err_or_pkg->pkgnum);
2150 $self->set('expire', $date); # in case it's different
2151 $err_or_pkg->set('start_date', $date);
2152 $err_or_pkg->set('change_date', '');
2153 $err_or_pkg->set('change_pkgnum', '');
2155 $error = $self->replace ||
2156 $err_or_pkg->replace ||
2157 $change_to->cancel ||
2160 $error = $err_or_pkg;
2162 } else { # change the start date only.
2163 $self->set('expire', $date);
2164 $change_to->set('start_date', $date);
2165 $error = $self->replace || $change_to->replace;
2168 $dbh->rollback if $oldAutoCommit;
2171 $dbh->commit if $oldAutoCommit;
2174 } # if $self->change_to_pkgnum
2176 my $new_pkgpart = $opt->{'pkgpart'}
2177 if $opt->{'pkgpart'} and $opt->{'pkgpart'} != $self->pkgpart;
2178 my $new_locationnum = $opt->{'locationnum'}
2179 if $opt->{'locationnum'} and $opt->{'locationnum'} != $self->locationnum;
2180 my $new_quantity = $opt->{'quantity'}
2181 if $opt->{'quantity'} and $opt->{'quantity'} != $self->quantity;
2183 return '' unless $new_pkgpart or $new_locationnum or $new_quantity; # wouldn't do anything
2185 # allow $opt->{'locationnum'} = '' to specifically set it to null
2186 # (i.e. customer default location)
2187 $opt->{'locationnum'} = $self->locationnum if !exists($opt->{'locationnum'});
2189 my $new = FS::cust_pkg->new( {
2190 custnum => $self->custnum,
2191 locationnum => $opt->{'locationnum'},
2192 start_date => $date,
2193 map { $_ => ( $opt->{$_} || $self->$_() ) }
2194 qw( pkgpart quantity refnum salesnum )
2196 $error = $new->insert('change' => 1,
2197 'allow_pkgpart' => ($new_pkgpart ? 0 : 1));
2199 $self->set('change_to_pkgnum', $new->pkgnum);
2200 $self->set('expire', $date);
2201 $error = $self->replace;
2204 $dbh->rollback if $oldAutoCommit;
2206 $dbh->commit if $oldAutoCommit;
2214 Cancels a future package change scheduled by C<change_later>.
2220 my $pkgnum = $self->change_to_pkgnum;
2221 my $change_to = FS::cust_pkg->by_key($pkgnum) if $pkgnum;
2224 $error = $change_to->cancel || $change_to->delete;
2225 return $error if $error;
2227 $self->set('change_to_pkgnum', '');
2228 $self->set('expire', '');
2232 =item set_quantity QUANTITY
2234 Change the package's quantity field. This is one of the few package properties
2235 that can safely be changed without canceling and reordering the package
2236 (because it doesn't affect tax eligibility). Returns an error or an
2243 $self = $self->replace_old; # just to make sure
2244 $self->quantity(shift);
2248 =item set_salesnum SALESNUM
2250 Change the package's salesnum (sales person) field. This is one of the few
2251 package properties that can safely be changed without canceling and reordering
2252 the package (because it doesn't affect tax eligibility). Returns an error or
2259 $self = $self->replace_old; # just to make sure
2260 $self->salesnum(shift);
2262 # XXX this should probably reassign any credit that's already been given
2265 =item modify_charge OPTIONS
2267 Change the properties of a one-time charge. Currently the only properties
2268 that can be changed this way are those that have no impact on billing
2270 - pkg: the package description
2271 - classnum: the package class
2272 - additional: arrayref of additional invoice details to add to this package
2274 If you pass 'adjust_commission' => 1, and the classnum changes, and there are
2275 commission credits linked to this charge, they will be recalculated.
2282 my $part_pkg = $self->part_pkg;
2283 my $pkgnum = $self->pkgnum;
2286 my $oldAutoCommit = $FS::UID::AutoCommit;
2287 local $FS::UID::AutoCommit = 0;
2289 return "Can't use modify_charge except on one-time charges"
2290 unless $part_pkg->freq eq '0';
2292 if ( length($opt{'pkg'}) and $part_pkg->pkg ne $opt{'pkg'} ) {
2293 $part_pkg->set('pkg', $opt{'pkg'});
2296 my %pkg_opt = $part_pkg->options;
2297 if ( ref($opt{'additional'}) ) {
2298 delete $pkg_opt{$_} foreach grep /^additional/, keys %pkg_opt;
2300 for ( $i = 0; exists($opt{'additional'}->[$i]); $i++ ) {
2301 $pkg_opt{ "additional_info$i" } = $opt{'additional'}->[$i];
2303 $pkg_opt{'additional_count'} = $i if $i > 0;
2307 if ( exists($opt{'classnum'}) and $part_pkg->classnum ne $opt{'classnum'} ) {
2309 $old_classnum = $part_pkg->classnum;
2310 $part_pkg->set('classnum', $opt{'classnum'});
2313 my $error = $part_pkg->replace( options => \%pkg_opt );
2314 return $error if $error;
2316 if (defined $old_classnum) {
2317 # fix invoice grouping records
2318 my $old_catname = $old_classnum
2319 ? FS::pkg_class->by_key($old_classnum)->categoryname
2321 my $new_catname = $opt{'classnum'}
2322 ? $part_pkg->pkg_class->categoryname
2324 if ( $old_catname ne $new_catname ) {
2325 foreach my $cust_bill_pkg ($self->cust_bill_pkg) {
2326 # (there should only be one...)
2327 my @display = qsearch( 'cust_bill_pkg_display', {
2328 'billpkgnum' => $cust_bill_pkg->billpkgnum,
2329 'section' => $old_catname,
2331 foreach (@display) {
2332 $_->set('section', $new_catname);
2333 $error = $_->replace;
2335 $dbh->rollback if $oldAutoCommit;
2339 } # foreach $cust_bill_pkg
2342 if ( $opt{'adjust_commission'} ) {
2343 # fix commission credits...tricky.
2344 foreach my $cust_event ($self->cust_event) {
2345 my $part_event = $cust_event->part_event;
2346 foreach my $table (qw(sales agent)) {
2348 "FS::part_event::Action::Mixin::credit_${table}_pkg_class";
2349 my $credit = qsearchs('cust_credit', {
2350 'eventnum' => $cust_event->eventnum,
2352 if ( $part_event->isa($class) ) {
2353 # Yes, this results in current commission rates being applied
2354 # retroactively to a one-time charge. For accounting purposes
2355 # there ought to be some kind of time limit on doing this.
2356 my $amount = $part_event->_calc_credit($self);
2357 if ( $credit and $credit->amount ne $amount ) {
2358 # Void the old credit.
2359 $error = $credit->void('Package class changed');
2361 $dbh->rollback if $oldAutoCommit;
2362 return "$error (adjusting commission credit)";
2365 # redo the event action to recreate the credit.
2367 eval { $part_event->do_action( $self, $cust_event ) };
2369 $dbh->rollback if $oldAutoCommit;
2372 } # if $part_event->isa($class)
2374 } # foreach $cust_event
2375 } # if $opt{'adjust_commission'}
2376 } # if defined $old_classnum
2378 $dbh->commit if $oldAutoCommit;
2384 use Storable 'thaw';
2387 sub process_bulk_cust_pkg {
2389 my $param = thaw(decode_base64(shift));
2390 warn Dumper($param) if $DEBUG;
2392 my $old_part_pkg = qsearchs('part_pkg',
2393 { pkgpart => $param->{'old_pkgpart'} });
2394 my $new_part_pkg = qsearchs('part_pkg',
2395 { pkgpart => $param->{'new_pkgpart'} });
2396 die "Must select a new package type\n" unless $new_part_pkg;
2397 #my $keep_dates = $param->{'keep_dates'} || 0;
2398 my $keep_dates = 1; # there is no good reason to turn this off
2400 local $SIG{HUP} = 'IGNORE';
2401 local $SIG{INT} = 'IGNORE';
2402 local $SIG{QUIT} = 'IGNORE';
2403 local $SIG{TERM} = 'IGNORE';
2404 local $SIG{TSTP} = 'IGNORE';
2405 local $SIG{PIPE} = 'IGNORE';
2407 my $oldAutoCommit = $FS::UID::AutoCommit;
2408 local $FS::UID::AutoCommit = 0;
2411 my @cust_pkgs = qsearch('cust_pkg', { 'pkgpart' => $param->{'old_pkgpart'} } );
2414 foreach my $old_cust_pkg ( @cust_pkgs ) {
2416 $job->update_statustext(int(100*$i/(scalar @cust_pkgs)));
2417 if ( $old_cust_pkg->getfield('cancel') ) {
2418 warn '[process_bulk_cust_pkg ] skipping canceled pkgnum '.
2419 $old_cust_pkg->pkgnum."\n"
2423 warn '[process_bulk_cust_pkg] changing pkgnum '.$old_cust_pkg->pkgnum."\n"
2425 my $error = $old_cust_pkg->change(
2426 'pkgpart' => $param->{'new_pkgpart'},
2427 'keep_dates' => $keep_dates
2429 if ( !ref($error) ) { # change returns the cust_pkg on success
2431 die "Error changing pkgnum ".$old_cust_pkg->pkgnum.": '$error'\n";
2434 $dbh->commit if $oldAutoCommit;
2440 Returns the last bill date, or if there is no last bill date, the setup date.
2441 Useful for billing metered services.
2447 return $self->setfield('last_bill', $_[0]) if @_;
2448 return $self->getfield('last_bill') if $self->getfield('last_bill');
2449 my $cust_bill_pkg = qsearchs('cust_bill_pkg', { 'pkgnum' => $self->pkgnum,
2450 'edate' => $self->bill, } );
2451 $cust_bill_pkg ? $cust_bill_pkg->sdate : $self->setup || 0;
2454 =item last_cust_pkg_reason ACTION
2456 Returns the most recent ACTION FS::cust_pkg_reason associated with the package.
2457 Returns false if there is no reason or the package is not currenly ACTION'd
2458 ACTION is one of adjourn, susp, cancel, or expire.
2462 sub last_cust_pkg_reason {
2463 my ( $self, $action ) = ( shift, shift );
2464 my $date = $self->get($action);
2466 'table' => 'cust_pkg_reason',
2467 'hashref' => { 'pkgnum' => $self->pkgnum,
2468 'action' => substr(uc($action), 0, 1),
2471 'order_by' => 'ORDER BY num DESC LIMIT 1',
2475 =item last_reason ACTION
2477 Returns the most recent ACTION FS::reason associated with the package.
2478 Returns false if there is no reason or the package is not currenly ACTION'd
2479 ACTION is one of adjourn, susp, cancel, or expire.
2484 my $cust_pkg_reason = shift->last_cust_pkg_reason(@_);
2485 $cust_pkg_reason->reason
2486 if $cust_pkg_reason;
2491 Returns the definition for this billing item, as an FS::part_pkg object (see
2498 return $self->{'_pkgpart'} if $self->{'_pkgpart'};
2499 cluck "cust_pkg->part_pkg called" if $DEBUG > 1;
2500 qsearchs( 'part_pkg', { 'pkgpart' => $self->pkgpart } );
2505 Returns the cancelled package this package was changed from, if any.
2511 return '' unless $self->change_pkgnum;
2512 qsearchs('cust_pkg', { 'pkgnum' => $self->change_pkgnum } );
2515 =item change_cust_main
2517 Returns the customter this package was detached to, if any.
2521 sub change_cust_main {
2523 return '' unless $self->change_custnum;
2524 qsearchs('cust_main', { 'custnum' => $self->change_custnum } );
2529 Calls the I<calc_setup> of the FS::part_pkg object associated with this billing
2536 $self->part_pkg->calc_setup($self, @_);
2541 Calls the I<calc_recur> of the FS::part_pkg object associated with this billing
2548 $self->part_pkg->calc_recur($self, @_);
2553 Calls the I<base_setup> of the FS::part_pkg object associated with this billing
2560 $self->part_pkg->base_setup($self, @_);
2565 Calls the I<base_recur> of the FS::part_pkg object associated with this billing
2572 $self->part_pkg->base_recur($self, @_);
2577 Calls the I<calc_remain> of the FS::part_pkg object associated with this
2584 $self->part_pkg->calc_remain($self, @_);
2589 Calls the I<calc_cancel> of the FS::part_pkg object associated with this
2596 $self->part_pkg->calc_cancel($self, @_);
2601 Returns any invoice line items for this package (see L<FS::cust_bill_pkg>).
2607 qsearch( 'cust_bill_pkg', { 'pkgnum' => $self->pkgnum } );
2610 =item cust_pkg_detail [ DETAILTYPE ]
2612 Returns any customer package details for this package (see
2613 L<FS::cust_pkg_detail>).
2615 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
2619 sub cust_pkg_detail {
2621 my %hash = ( 'pkgnum' => $self->pkgnum );
2622 $hash{detailtype} = shift if @_;
2624 'table' => 'cust_pkg_detail',
2625 'hashref' => \%hash,
2626 'order_by' => 'ORDER BY weight, pkgdetailnum',
2630 =item set_cust_pkg_detail DETAILTYPE [ DETAIL, DETAIL, ... ]
2632 Sets customer package details for this package (see L<FS::cust_pkg_detail>).
2634 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
2636 If there is an error, returns the error, otherwise returns false.
2640 sub set_cust_pkg_detail {
2641 my( $self, $detailtype, @details ) = @_;
2643 local $SIG{HUP} = 'IGNORE';
2644 local $SIG{INT} = 'IGNORE';
2645 local $SIG{QUIT} = 'IGNORE';
2646 local $SIG{TERM} = 'IGNORE';
2647 local $SIG{TSTP} = 'IGNORE';
2648 local $SIG{PIPE} = 'IGNORE';
2650 my $oldAutoCommit = $FS::UID::AutoCommit;
2651 local $FS::UID::AutoCommit = 0;
2654 foreach my $current ( $self->cust_pkg_detail($detailtype) ) {
2655 my $error = $current->delete;
2657 $dbh->rollback if $oldAutoCommit;
2658 return "error removing old detail: $error";
2662 foreach my $detail ( @details ) {
2663 my $cust_pkg_detail = new FS::cust_pkg_detail {
2664 'pkgnum' => $self->pkgnum,
2665 'detailtype' => $detailtype,
2666 'detail' => $detail,
2668 my $error = $cust_pkg_detail->insert;
2670 $dbh->rollback if $oldAutoCommit;
2671 return "error adding new detail: $error";
2676 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2683 Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.
2687 #false laziness w/cust_bill.pm
2691 'table' => 'cust_event',
2692 'addl_from' => 'JOIN part_event USING ( eventpart )',
2693 'hashref' => { 'tablenum' => $self->pkgnum },
2694 'extra_sql' => " AND eventtable = 'cust_pkg' ",
2698 =item num_cust_event
2700 Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.
2704 #false laziness w/cust_bill.pm
2705 sub num_cust_event {
2708 "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
2709 " WHERE tablenum = ? AND eventtable = 'cust_pkg'";
2710 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
2711 $sth->execute($self->pkgnum) or die $sth->errstr. " executing $sql";
2712 $sth->fetchrow_arrayref->[0];
2715 =item part_pkg_currency_option OPTIONNAME
2717 Returns a two item list consisting of the currency of this customer, if any,
2718 and a value for the provided option. If the customer has a currency, the value
2719 is the option value the given name and the currency (see
2720 L<FS::part_pkg_currency>). Otherwise, if the customer has no currency, is the
2721 regular option value for the given name (see L<FS::part_pkg_option>).
2725 sub part_pkg_currency_option {
2726 my( $self, $optionname ) = @_;
2727 my $part_pkg = $self->part_pkg;
2728 if ( my $currency = $self->cust_main->currency ) {
2729 ($currency, $part_pkg->part_pkg_currency_option($currency, $optionname) );
2731 ('', $part_pkg->option($optionname) );
2735 =item cust_svc [ SVCPART ] (old, deprecated usage)
2737 =item cust_svc [ OPTION => VALUE ... ] (current usage)
2739 =item cust_svc_unsorted [ OPTION => VALUE ... ]
2741 Returns the services for this package, as FS::cust_svc objects (see
2742 L<FS::cust_svc>). Available options are svcpart and svcdb. If either is
2743 spcififed, returns only the matching services.
2745 As an optimization, use the cust_svc_unsorted version if you are not displaying
2752 cluck "cust_pkg->cust_svc called" if $DEBUG > 2;
2753 $self->_sort_cust_svc( $self->cust_svc_unsorted_arrayref );
2756 sub cust_svc_unsorted {
2758 @{ $self->cust_svc_unsorted_arrayref };
2761 sub cust_svc_unsorted_arrayref {
2764 return () unless $self->num_cust_svc(@_);
2767 if ( @_ && $_[0] =~ /^\d+/ ) {
2768 $opt{svcpart} = shift;
2769 } elsif ( @_ && ref($_[0]) eq 'HASH' ) {
2776 'table' => 'cust_svc',
2777 'hashref' => { 'pkgnum' => $self->pkgnum },
2779 if ( $opt{svcpart} ) {
2780 $search{hashref}->{svcpart} = $opt{'svcpart'};
2782 if ( $opt{'svcdb'} ) {
2783 $search{addl_from} = ' LEFT JOIN part_svc USING ( svcpart ) ';
2784 $search{extra_sql} = ' AND svcdb = '. dbh->quote( $opt{'svcdb'} );
2787 [ qsearch(\%search) ];
2791 =item overlimit [ SVCPART ]
2793 Returns the services for this package which have exceeded their
2794 usage limit as FS::cust_svc objects (see L<FS::cust_svc>). If a svcpart
2795 is specified, return only the matching services.
2801 return () unless $self->num_cust_svc(@_);
2802 grep { $_->overlimit } $self->cust_svc(@_);
2805 =item h_cust_svc END_TIMESTAMP [ START_TIMESTAMP ] [ MODE ]
2807 Returns historical services for this package created before END TIMESTAMP and
2808 (optionally) not cancelled before START_TIMESTAMP, as FS::h_cust_svc objects
2809 (see L<FS::h_cust_svc>). If MODE is 'I' (for 'invoice'), services with the
2810 I<pkg_svc.hidden> flag will be omitted.
2816 warn "$me _h_cust_svc called on $self\n"
2819 my ($end, $start, $mode) = @_;
2820 my @cust_svc = $self->_sort_cust_svc(
2821 [ qsearch( 'h_cust_svc',
2822 { 'pkgnum' => $self->pkgnum, },
2823 FS::h_cust_svc->sql_h_search(@_),
2826 if ( defined($mode) && $mode eq 'I' ) {
2827 my %hidden_svcpart = map { $_->svcpart => $_->hidden } $self->part_svc;
2828 return grep { !$hidden_svcpart{$_->svcpart} } @cust_svc;
2834 sub _sort_cust_svc {
2835 my( $self, $arrayref ) = @_;
2838 sub ($$) { my ($a, $b) = @_; $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] };
2840 my %pkg_svc = map { $_->svcpart => $_ }
2841 qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
2846 my $pkg_svc = $pkg_svc{ $_->svcpart } || '';
2848 $pkg_svc ? $pkg_svc->primary_svc : '',
2849 $pkg_svc ? $pkg_svc->quantity : 0,
2856 =item num_cust_svc [ SVCPART ] (old, deprecated usage)
2858 =item num_cust_svc [ OPTION => VALUE ... ] (current usage)
2860 Returns the number of services for this package. Available options are svcpart
2861 and svcdb. If either is spcififed, returns only the matching services.
2868 return $self->{'_num_cust_svc'}
2870 && exists($self->{'_num_cust_svc'})
2871 && $self->{'_num_cust_svc'} =~ /\d/;
2873 cluck "cust_pkg->num_cust_svc called, _num_cust_svc:".$self->{'_num_cust_svc'}
2877 if ( @_ && $_[0] =~ /^\d+/ ) {
2878 $opt{svcpart} = shift;
2879 } elsif ( @_ && ref($_[0]) eq 'HASH' ) {
2885 my $select = 'SELECT COUNT(*) FROM cust_svc ';
2886 my $where = ' WHERE pkgnum = ? ';
2887 my @param = ($self->pkgnum);
2889 if ( $opt{'svcpart'} ) {
2890 $where .= ' AND svcpart = ? ';
2891 push @param, $opt{'svcpart'};
2893 if ( $opt{'svcdb'} ) {
2894 $select .= ' LEFT JOIN part_svc USING ( svcpart ) ';
2895 $where .= ' AND svcdb = ? ';
2896 push @param, $opt{'svcdb'};
2899 my $sth = dbh->prepare("$select $where") or die dbh->errstr;
2900 $sth->execute(@param) or die $sth->errstr;
2901 $sth->fetchrow_arrayref->[0];
2904 =item available_part_svc
2906 Returns a list of FS::part_svc objects representing services included in this
2907 package but not yet provisioned. Each FS::part_svc object also has an extra
2908 field, I<num_avail>, which specifies the number of available services.
2912 sub available_part_svc {
2915 my $pkg_quantity = $self->quantity || 1;
2917 grep { $_->num_avail > 0 }
2919 my $part_svc = $_->part_svc;
2920 $part_svc->{'Hash'}{'num_avail'} = #evil encapsulation-breaking
2921 $pkg_quantity * $_->quantity - $self->num_cust_svc($_->svcpart);
2923 # more evil encapsulation breakage
2924 if($part_svc->{'Hash'}{'num_avail'} > 0) {
2925 my @exports = $part_svc->part_export_did;
2926 $part_svc->{'Hash'}{'can_get_dids'} = scalar(@exports);
2931 $self->part_pkg->pkg_svc;
2934 =item part_svc [ OPTION => VALUE ... ]
2936 Returns a list of FS::part_svc objects representing provisioned and available
2937 services included in this package. Each FS::part_svc object also has the
2938 following extra fields:
2942 =item num_cust_svc (count)
2944 =item num_avail (quantity - count)
2946 =item cust_pkg_svc (services) - array reference containing the provisioned services, as cust_svc objects
2950 Accepts one option: summarize_size. If specified and non-zero, will omit the
2951 extra cust_pkg_svc option for objects where num_cust_svc is this size or
2957 #label -> ($cust_svc->label)[1]
2963 my $pkg_quantity = $self->quantity || 1;
2965 #XXX some sort of sort order besides numeric by svcpart...
2966 my @part_svc = sort { $a->svcpart <=> $b->svcpart } map {
2968 my $part_svc = $pkg_svc->part_svc;
2969 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
2970 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #more evil
2971 $part_svc->{'Hash'}{'num_avail'} =
2972 max( 0, $pkg_quantity * $pkg_svc->quantity - $num_cust_svc );
2973 $part_svc->{'Hash'}{'cust_pkg_svc'} =
2974 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : []
2975 unless exists($opt{summarize_size}) && $opt{summarize_size} > 0
2976 && $num_cust_svc >= $opt{summarize_size};
2977 $part_svc->{'Hash'}{'hidden'} = $pkg_svc->hidden;
2979 } $self->part_pkg->pkg_svc;
2982 push @part_svc, map {
2984 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
2985 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #speak no evail
2986 $part_svc->{'Hash'}{'num_avail'} = 0; #0-$num_cust_svc ?
2987 $part_svc->{'Hash'}{'cust_pkg_svc'} =
2988 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : [];
2990 } $self->extra_part_svc;
2996 =item extra_part_svc
2998 Returns a list of FS::part_svc objects corresponding to services in this
2999 package which are still provisioned but not (any longer) available in the
3004 sub extra_part_svc {
3007 my $pkgnum = $self->pkgnum;
3008 #my $pkgpart = $self->pkgpart;
3011 # 'table' => 'part_svc',
3014 # "WHERE 0 = ( SELECT COUNT(*) FROM pkg_svc
3015 # WHERE pkg_svc.svcpart = part_svc.svcpart
3016 # AND pkg_svc.pkgpart = ?
3019 # AND 0 < ( SELECT COUNT(*) FROM cust_svc
3020 # LEFT JOIN cust_pkg USING ( pkgnum )
3021 # WHERE cust_svc.svcpart = part_svc.svcpart
3024 # 'extra_param' => [ [$self->pkgpart=>'int'], [$self->pkgnum=>'int'] ],
3027 #seems to benchmark slightly faster... (or did?)
3029 my @pkgparts = map $_->pkgpart, $self->part_pkg->self_and_svc_linked;
3030 my $pkgparts = join(',', @pkgparts);
3033 #'select' => 'DISTINCT ON (svcpart) part_svc.*',
3034 #MySQL doesn't grok DISINCT ON
3035 'select' => 'DISTINCT part_svc.*',
3036 'table' => 'part_svc',
3038 "LEFT JOIN pkg_svc ON ( pkg_svc.svcpart = part_svc.svcpart
3039 AND pkg_svc.pkgpart IN ($pkgparts)
3042 LEFT JOIN cust_svc ON ( cust_svc.svcpart = part_svc.svcpart )
3043 LEFT JOIN cust_pkg USING ( pkgnum )
3046 'extra_sql' => "WHERE pkgsvcnum IS NULL AND cust_pkg.pkgnum = ? ",
3047 'extra_param' => [ [$self->pkgnum=>'int'] ],
3053 Returns a short status string for this package, currently:
3057 =item not yet billed
3059 =item one-time charge
3074 my $freq = length($self->freq) ? $self->freq : $self->part_pkg->freq;
3076 return 'cancelled' if $self->get('cancel');
3077 return 'suspended' if $self->susp;
3078 return 'not yet billed' unless $self->setup;
3079 return 'one-time charge' if $freq =~ /^(0|$)/;
3083 =item ucfirst_status
3085 Returns the status with the first character capitalized.
3089 sub ucfirst_status {
3090 ucfirst(shift->status);
3095 Class method that returns the list of possible status strings for packages
3096 (see L<the status method|/status>). For example:
3098 @statuses = FS::cust_pkg->statuses();
3102 tie my %statuscolor, 'Tie::IxHash',
3103 'not yet billed' => '009999', #teal? cyan?
3104 'one-time charge' => '000000',
3105 'active' => '00CC00',
3106 'suspended' => 'FF9900',
3107 'cancelled' => 'FF0000',
3111 my $self = shift; #could be class...
3112 #grep { $_ !~ /^(not yet billed)$/ } #this is a dumb status anyway
3113 # # mayble split btw one-time vs. recur
3119 Returns a hex triplet color string for this package's status.
3125 $statuscolor{$self->status};
3130 Returns a label for this package. (Currently "pkgnum: pkg - comment" or
3131 "pkg - comment" depending on user preference).
3137 my $label = $self->part_pkg->pkg_comment( 'nopkgpart' => 1 );
3138 $label = $self->pkgnum. ": $label"
3139 if $FS::CurrentUser::CurrentUser->option('show_pkgnum');
3143 =item pkg_label_long
3145 Returns a long label for this package, adding the primary service's label to
3150 sub pkg_label_long {
3152 my $label = $self->pkg_label;
3153 my $cust_svc = $self->primary_cust_svc;
3154 $label .= ' ('. ($cust_svc->label)[1]. ')' if $cust_svc;
3160 Returns a customer-localized label for this package.
3166 $self->part_pkg->pkg_locale( $self->cust_main->locale );
3169 =item primary_cust_svc
3171 Returns a primary service (as FS::cust_svc object) if one can be identified.
3175 #for labeling purposes - might not 100% match up with part_pkg->svcpart's idea
3177 sub primary_cust_svc {
3180 my @cust_svc = $self->cust_svc;
3182 return '' unless @cust_svc; #no serivces - irrelevant then
3184 return $cust_svc[0] if scalar(@cust_svc) == 1; #always return a single service
3186 # primary service as specified in the package definition
3187 # or exactly one service definition with quantity one
3188 my $svcpart = $self->part_pkg->svcpart;
3189 @cust_svc = grep { $_->svcpart == $svcpart } @cust_svc;
3190 return $cust_svc[0] if scalar(@cust_svc) == 1;
3192 #couldn't identify one thing..
3198 Returns a list of lists, calling the label method for all services
3199 (see L<FS::cust_svc>) of this billing item.
3205 map { [ $_->label ] } $self->cust_svc;
3208 =item h_labels END_TIMESTAMP [ START_TIMESTAMP ] [ MODE ]
3210 Like the labels method, but returns historical information on services that
3211 were active as of END_TIMESTAMP and (optionally) not cancelled before
3212 START_TIMESTAMP. If MODE is 'I' (for 'invoice'), services with the
3213 I<pkg_svc.hidden> flag will be omitted.
3215 Returns a list of lists, calling the label method for all (historical) services
3216 (see L<FS::h_cust_svc>) of this billing item.
3222 warn "$me _h_labels called on $self\n"
3224 map { [ $_->label(@_) ] } $self->h_cust_svc(@_);
3229 Like labels, except returns a simple flat list, and shortens long
3230 (currently >5 or the cust_bill-max_same_services configuration value) lists of
3231 identical services to one line that lists the service label and the number of
3232 individual services rather than individual items.
3237 shift->_labels_short( 'labels', @_ );
3240 =item h_labels_short END_TIMESTAMP [ START_TIMESTAMP ]
3242 Like h_labels, except returns a simple flat list, and shortens long
3243 (currently >5 or the cust_bill-max_same_services configuration value) lists of
3244 identical services to one line that lists the service label and the number of
3245 individual services rather than individual items.
3249 sub h_labels_short {
3250 shift->_labels_short( 'h_labels', @_ );
3254 my( $self, $method ) = ( shift, shift );
3256 warn "$me _labels_short called on $self with $method method\n"
3259 my $conf = new FS::Conf;
3260 my $max_same_services = $conf->config('cust_bill-max_same_services') || 5;
3262 warn "$me _labels_short populating \%labels\n"
3266 #tie %labels, 'Tie::IxHash';
3267 push @{ $labels{$_->[0]} }, $_->[1]
3268 foreach $self->$method(@_);
3270 warn "$me _labels_short populating \@labels\n"
3274 foreach my $label ( keys %labels ) {
3276 my @values = grep { ! $seen{$_}++ } @{ $labels{$label} };
3277 my $num = scalar(@values);
3278 warn "$me _labels_short $num items for $label\n"
3281 if ( $num > $max_same_services ) {
3282 warn "$me _labels_short more than $max_same_services, so summarizing\n"
3284 push @labels, "$label ($num)";
3286 if ( $conf->exists('cust_bill-consolidate_services') ) {
3287 warn "$me _labels_short consolidating services\n"
3289 # push @labels, "$label: ". join(', ', @values);
3291 my $detail = "$label: ";
3292 $detail .= shift(@values). ', '
3294 && ( length($detail.$values[0]) < 78 || $detail eq "$label: " );
3296 push @labels, $detail;
3298 warn "$me _labels_short done consolidating services\n"
3301 warn "$me _labels_short adding service data\n"
3303 push @labels, map { "$label: $_" } @values;
3314 Returns the parent customer object (see L<FS::cust_main>).
3320 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
3325 Returns the balance for this specific package, when using
3326 experimental package balance.
3332 $self->cust_main->balance_pkgnum( $self->pkgnum );
3335 #these subs are in location_Mixin.pm now... unfortunately the POD doesn't mixin
3339 Returns the location object, if any (see L<FS::cust_location>).
3341 =item cust_location_or_main
3343 If this package is associated with a location, returns the locaiton (see
3344 L<FS::cust_location>), otherwise returns the customer (see L<FS::cust_main>).
3346 =item location_label [ OPTION => VALUE ... ]
3348 Returns the label of the location object (see L<FS::cust_location>).
3352 #end of subs in location_Mixin.pm now... unfortunately the POD doesn't mixin
3354 =item tax_locationnum
3356 Returns the foreign key to a L<FS::cust_location> object for calculating
3357 tax on this package, as determined by the C<tax-pkg_address> and
3358 C<tax-ship_address> configuration flags.
3362 sub tax_locationnum {
3364 my $conf = FS::Conf->new;
3365 if ( $conf->exists('tax-pkg_address') ) {
3366 return $self->locationnum;
3368 elsif ( $conf->exists('tax-ship_address') ) {
3369 return $self->cust_main->ship_locationnum;
3372 return $self->cust_main->bill_locationnum;
3378 Returns the L<FS::cust_location> object for tax_locationnum.
3384 FS::cust_location->by_key( $self->tax_locationnum )
3387 =item seconds_since TIMESTAMP
3389 Returns the number of seconds all accounts (see L<FS::svc_acct>) in this
3390 package have been online since TIMESTAMP, according to the session monitor.
3392 TIMESTAMP is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
3393 L<Time::Local> and L<Date::Parse> for conversion functions.
3398 my($self, $since) = @_;
3401 foreach my $cust_svc (
3402 grep { $_->part_svc->svcdb eq 'svc_acct' } $self->cust_svc
3404 $seconds += $cust_svc->seconds_since($since);
3411 =item seconds_since_sqlradacct TIMESTAMP_START TIMESTAMP_END
3413 Returns the numbers of seconds all accounts (see L<FS::svc_acct>) in this
3414 package have been online between TIMESTAMP_START (inclusive) and TIMESTAMP_END
3417 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
3418 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
3424 sub seconds_since_sqlradacct {
3425 my($self, $start, $end) = @_;
3429 foreach my $cust_svc (
3431 my $part_svc = $_->part_svc;
3432 $part_svc->svcdb eq 'svc_acct'
3433 && scalar($part_svc->part_export_usage);
3436 $seconds += $cust_svc->seconds_since_sqlradacct($start, $end);
3443 =item attribute_since_sqlradacct TIMESTAMP_START TIMESTAMP_END ATTRIBUTE
3445 Returns the sum of the given attribute for all accounts (see L<FS::svc_acct>)
3446 in this package for sessions ending between TIMESTAMP_START (inclusive) and
3450 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
3451 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
3456 sub attribute_since_sqlradacct {
3457 my($self, $start, $end, $attrib) = @_;
3461 foreach my $cust_svc (
3463 my $part_svc = $_->part_svc;
3464 scalar($part_svc->part_export_usage);
3467 $sum += $cust_svc->attribute_since_sqlradacct($start, $end, $attrib);
3479 my( $self, $value ) = @_;
3480 if ( defined($value) ) {
3481 $self->setfield('quantity', $value);
3483 $self->getfield('quantity') || 1;
3486 =item transfer DEST_PKGNUM | DEST_CUST_PKG, [ OPTION => VALUE ... ]
3488 Transfers as many services as possible from this package to another package.
3490 The destination package can be specified by pkgnum by passing an FS::cust_pkg
3491 object. The destination package must already exist.
3493 Services are moved only if the destination allows services with the correct
3494 I<svcpart> (not svcdb), unless the B<change_svcpart> option is set true. Use
3495 this option with caution! No provision is made for export differences
3496 between the old and new service definitions. Probably only should be used
3497 when your exports for all service definitions of a given svcdb are identical.
3498 (attempt a transfer without it first, to move all possible svcpart-matching
3501 Any services that can't be moved remain in the original package.
3503 Returns an error, if there is one; otherwise, returns the number of services
3504 that couldn't be moved.
3509 my ($self, $dest_pkgnum, %opt) = @_;
3515 if (ref ($dest_pkgnum) eq 'FS::cust_pkg') {
3516 $dest = $dest_pkgnum;
3517 $dest_pkgnum = $dest->pkgnum;
3519 $dest = qsearchs('cust_pkg', { pkgnum => $dest_pkgnum });
3522 return ('Package does not exist: '.$dest_pkgnum) unless $dest;
3524 foreach my $pkg_svc ( $dest->part_pkg->pkg_svc ) {
3525 $target{$pkg_svc->svcpart} = $pkg_svc->quantity;
3528 foreach my $cust_svc ($dest->cust_svc) {
3529 $target{$cust_svc->svcpart}--;
3532 my %svcpart2svcparts = ();
3533 if ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
3534 warn "change_svcpart option received, creating alternates list\n" if $DEBUG;
3535 foreach my $svcpart ( map { $_->svcpart } $self->cust_svc ) {
3536 next if exists $svcpart2svcparts{$svcpart};
3537 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
3538 $svcpart2svcparts{$svcpart} = [
3540 sort { $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] }
3542 my $pkg_svc = qsearchs( 'pkg_svc', { 'pkgpart' => $dest->pkgpart,
3543 'svcpart' => $_ } );
3545 $pkg_svc ? $pkg_svc->primary_svc : '',
3546 $pkg_svc ? $pkg_svc->quantity : 0,
3550 grep { $_ != $svcpart }
3552 qsearch('part_svc', { 'svcdb' => $part_svc->svcdb } )
3554 warn "alternates for svcpart $svcpart: ".
3555 join(', ', @{$svcpart2svcparts{$svcpart}}). "\n"
3560 foreach my $cust_svc ($self->cust_svc) {
3561 if($target{$cust_svc->svcpart} > 0
3562 or $FS::cust_svc::ignore_quantity) { # maybe should be a 'force' option
3563 $target{$cust_svc->svcpart}--;
3564 my $new = new FS::cust_svc { $cust_svc->hash };
3565 $new->pkgnum($dest_pkgnum);
3566 my $error = $new->replace($cust_svc);
3567 return $error if $error;
3568 } elsif ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
3570 warn "looking for alternates for svcpart ". $cust_svc->svcpart. "\n";
3571 warn "alternates to consider: ".
3572 join(', ', @{$svcpart2svcparts{$cust_svc->svcpart}}). "\n";
3574 my @alternate = grep {
3575 warn "considering alternate svcpart $_: ".
3576 "$target{$_} available in new package\n"
3579 } @{$svcpart2svcparts{$cust_svc->svcpart}};
3581 warn "alternate(s) found\n" if $DEBUG;
3582 my $change_svcpart = $alternate[0];
3583 $target{$change_svcpart}--;
3584 my $new = new FS::cust_svc { $cust_svc->hash };
3585 $new->svcpart($change_svcpart);
3586 $new->pkgnum($dest_pkgnum);
3587 my $error = $new->replace($cust_svc);
3588 return $error if $error;
3599 =item grab_svcnums SVCNUM, SVCNUM ...
3601 Change the pkgnum for the provided services to this packages. If there is an
3602 error, returns the error, otherwise returns false.
3610 local $SIG{HUP} = 'IGNORE';
3611 local $SIG{INT} = 'IGNORE';
3612 local $SIG{QUIT} = 'IGNORE';
3613 local $SIG{TERM} = 'IGNORE';
3614 local $SIG{TSTP} = 'IGNORE';
3615 local $SIG{PIPE} = 'IGNORE';
3617 my $oldAutoCommit = $FS::UID::AutoCommit;
3618 local $FS::UID::AutoCommit = 0;
3621 foreach my $svcnum (@svcnum) {
3622 my $cust_svc = qsearchs('cust_svc', { svcnum=>$svcnum } ) or do {
3623 $dbh->rollback if $oldAutoCommit;
3624 return "unknown svcnum $svcnum";
3626 $cust_svc->pkgnum( $self->pkgnum );
3627 my $error = $cust_svc->replace;
3629 $dbh->rollback if $oldAutoCommit;
3634 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3641 This method is deprecated. See the I<depend_jobnum> option to the insert and
3642 order_pkgs methods in FS::cust_main for a better way to defer provisioning.
3646 #looks like this is still used by the order_pkg and change_pkg methods in
3647 # ClientAPI/MyAccount, need to look into those before removing
3651 local $SIG{HUP} = 'IGNORE';
3652 local $SIG{INT} = 'IGNORE';
3653 local $SIG{QUIT} = 'IGNORE';
3654 local $SIG{TERM} = 'IGNORE';
3655 local $SIG{TSTP} = 'IGNORE';
3656 local $SIG{PIPE} = 'IGNORE';
3658 my $oldAutoCommit = $FS::UID::AutoCommit;
3659 local $FS::UID::AutoCommit = 0;
3662 foreach my $cust_svc ( $self->cust_svc ) {
3663 #false laziness w/svc_Common::insert
3664 my $svc_x = $cust_svc->svc_x;
3665 foreach my $part_export ( $cust_svc->part_svc->part_export ) {
3666 my $error = $part_export->export_insert($svc_x);
3668 $dbh->rollback if $oldAutoCommit;
3674 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3679 =item export_pkg_change OLD_CUST_PKG
3681 Calls the "pkg_change" export action for all services attached to this package.
3685 sub export_pkg_change {
3686 my( $self, $old ) = ( shift, shift );
3688 local $SIG{HUP} = 'IGNORE';
3689 local $SIG{INT} = 'IGNORE';
3690 local $SIG{QUIT} = 'IGNORE';
3691 local $SIG{TERM} = 'IGNORE';
3692 local $SIG{TSTP} = 'IGNORE';
3693 local $SIG{PIPE} = 'IGNORE';
3695 my $oldAutoCommit = $FS::UID::AutoCommit;
3696 local $FS::UID::AutoCommit = 0;
3699 foreach my $svc_x ( map $_->svc_x, $self->cust_svc ) {
3700 my $error = $svc_x->export('pkg_change', $self, $old);
3702 $dbh->rollback if $oldAutoCommit;
3707 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3714 Associates this package with a (suspension or cancellation) reason (see
3715 L<FS::cust_pkg_reason>, possibly inserting a new reason on the fly (see
3718 Available options are:
3724 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.
3728 the access_user (see L<FS::access_user>) providing the reason
3736 the action (cancel, susp, adjourn, expire) associated with the reason
3740 If there is an error, returns the error, otherwise returns false.
3745 my ($self, %options) = @_;
3747 my $otaker = $options{reason_otaker} ||
3748 $FS::CurrentUser::CurrentUser->username;
3751 if ( $options{'reason'} =~ /^(\d+)$/ ) {
3755 } elsif ( ref($options{'reason'}) ) {
3757 return 'Enter a new reason (or select an existing one)'
3758 unless $options{'reason'}->{'reason'} !~ /^\s*$/;
3760 my $reason = new FS::reason({
3761 'reason_type' => $options{'reason'}->{'typenum'},
3762 'reason' => $options{'reason'}->{'reason'},
3764 my $error = $reason->insert;
3765 return $error if $error;
3767 $reasonnum = $reason->reasonnum;
3770 return "Unparsable reason: ". $options{'reason'};
3773 my $cust_pkg_reason =
3774 new FS::cust_pkg_reason({ 'pkgnum' => $self->pkgnum,
3775 'reasonnum' => $reasonnum,
3776 'otaker' => $otaker,
3777 'action' => substr(uc($options{'action'}),0,1),
3778 'date' => $options{'date'}
3783 $cust_pkg_reason->insert;
3786 =item insert_discount
3788 Associates this package with a discount (see L<FS::cust_pkg_discount>, possibly
3789 inserting a new discount on the fly (see L<FS::discount>).
3791 Available options are:
3799 If there is an error, returns the error, otherwise returns false.
3803 sub insert_discount {
3804 #my ($self, %options) = @_;
3807 my $cust_pkg_discount = new FS::cust_pkg_discount {
3808 'pkgnum' => $self->pkgnum,
3809 'discountnum' => $self->discountnum,
3811 'end_date' => '', #XXX
3812 #for the create a new discount case
3813 '_type' => $self->discountnum__type,
3814 'amount' => $self->discountnum_amount,
3815 'percent' => $self->discountnum_percent,
3816 'months' => $self->discountnum_months,
3817 'setup' => $self->discountnum_setup,
3818 #'disabled' => $self->discountnum_disabled,
3821 $cust_pkg_discount->insert;
3824 =item set_usage USAGE_VALUE_HASHREF
3826 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
3827 to which they should be set (see L<FS::svc_acct>). Currently seconds,
3828 upbytes, downbytes, and totalbytes are appropriate keys.
3830 All svc_accts which are part of this package have their values reset.
3835 my ($self, $valueref, %opt) = @_;
3837 #only svc_acct can set_usage for now
3838 foreach my $cust_svc ( $self->cust_svc( 'svcdb'=>'svc_acct' ) ) {
3839 my $svc_x = $cust_svc->svc_x;
3840 $svc_x->set_usage($valueref, %opt)
3841 if $svc_x->can("set_usage");
3845 =item recharge USAGE_VALUE_HASHREF
3847 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
3848 to which they should be set (see L<FS::svc_acct>). Currently seconds,
3849 upbytes, downbytes, and totalbytes are appropriate keys.
3851 All svc_accts which are part of this package have their values incremented.
3856 my ($self, $valueref) = @_;
3858 #only svc_acct can set_usage for now
3859 foreach my $cust_svc ( $self->cust_svc( 'svcdb'=>'svc_acct' ) ) {
3860 my $svc_x = $cust_svc->svc_x;
3861 $svc_x->recharge($valueref)
3862 if $svc_x->can("recharge");
3866 =item cust_pkg_discount
3870 sub cust_pkg_discount {
3872 qsearch('cust_pkg_discount', { 'pkgnum' => $self->pkgnum } );
3875 =item cust_pkg_discount_active
3879 sub cust_pkg_discount_active {
3881 grep { $_->status eq 'active' } $self->cust_pkg_discount;
3884 =item cust_pkg_usage
3886 Returns a list of all voice usage counters attached to this package.
3890 sub cust_pkg_usage {
3892 qsearch('cust_pkg_usage', { pkgnum => $self->pkgnum });
3895 =item apply_usage OPTIONS
3897 Takes the following options:
3898 - cdr: a call detail record (L<FS::cdr>)
3899 - rate_detail: the rate determined for this call (L<FS::rate_detail>)
3900 - minutes: the maximum number of minutes to be charged
3902 Finds available usage minutes for a call of this class, and subtracts
3903 up to that many minutes from the usage pool. If the usage pool is empty,
3904 and the C<cdr-minutes_priority> global config option is set, minutes may
3905 be taken from other calls as well. Either way, an allocation record will
3906 be created (L<FS::cdr_cust_pkg_usage>) and this method will return the
3907 number of minutes of usage applied to the call.
3912 my ($self, %opt) = @_;
3913 my $cdr = $opt{cdr};
3914 my $rate_detail = $opt{rate_detail};
3915 my $minutes = $opt{minutes};
3916 my $classnum = $rate_detail->classnum;
3917 my $pkgnum = $self->pkgnum;
3918 my $custnum = $self->custnum;
3920 local $SIG{HUP} = 'IGNORE';
3921 local $SIG{INT} = 'IGNORE';
3922 local $SIG{QUIT} = 'IGNORE';
3923 local $SIG{TERM} = 'IGNORE';
3924 local $SIG{TSTP} = 'IGNORE';
3925 local $SIG{PIPE} = 'IGNORE';
3927 my $oldAutoCommit = $FS::UID::AutoCommit;
3928 local $FS::UID::AutoCommit = 0;
3930 my $order = FS::Conf->new->config('cdr-minutes_priority');
3934 $is_classnum = ' part_pkg_usage_class.classnum = '.$classnum;
3936 $is_classnum = ' part_pkg_usage_class.classnum IS NULL';
3938 my @usage_recs = qsearch({
3939 'table' => 'cust_pkg_usage',
3940 'addl_from' => ' JOIN part_pkg_usage USING (pkgusagepart)'.
3941 ' JOIN cust_pkg USING (pkgnum)'.
3942 ' JOIN part_pkg_usage_class USING (pkgusagepart)',
3943 'select' => 'cust_pkg_usage.*',
3944 'extra_sql' => " WHERE ( cust_pkg.pkgnum = $pkgnum OR ".
3945 " ( cust_pkg.custnum = $custnum AND ".
3946 " part_pkg_usage.shared IS NOT NULL ) ) AND ".
3947 $is_classnum . ' AND '.
3948 " cust_pkg_usage.minutes > 0",
3949 'order_by' => " ORDER BY priority ASC",
3952 my $orig_minutes = $minutes;
3954 while (!$error and $minutes > 0 and @usage_recs) {
3955 my $cust_pkg_usage = shift @usage_recs;
3956 $cust_pkg_usage->select_for_update;
3957 my $cdr_cust_pkg_usage = FS::cdr_cust_pkg_usage->new({
3958 pkgusagenum => $cust_pkg_usage->pkgusagenum,
3959 acctid => $cdr->acctid,
3960 minutes => min($cust_pkg_usage->minutes, $minutes),
3962 $cust_pkg_usage->set('minutes',
3963 sprintf('%.0f', $cust_pkg_usage->minutes - $cdr_cust_pkg_usage->minutes)
3965 $error = $cust_pkg_usage->replace || $cdr_cust_pkg_usage->insert;
3966 $minutes -= $cdr_cust_pkg_usage->minutes;
3968 if ( $order and $minutes > 0 and !$error ) {
3969 # then try to steal minutes from another call
3971 'table' => 'cdr_cust_pkg_usage',
3972 'addl_from' => ' JOIN cust_pkg_usage USING (pkgusagenum)'.
3973 ' JOIN part_pkg_usage USING (pkgusagepart)'.
3974 ' JOIN cust_pkg USING (pkgnum)'.
3975 ' JOIN part_pkg_usage_class USING (pkgusagepart)'.
3976 ' JOIN cdr USING (acctid)',
3977 'select' => 'cdr_cust_pkg_usage.*',
3978 'extra_sql' => " WHERE cdr.freesidestatus = 'rated' AND ".
3979 " ( cust_pkg.pkgnum = $pkgnum OR ".
3980 " ( cust_pkg.custnum = $custnum AND ".
3981 " part_pkg_usage.shared IS NOT NULL ) ) AND ".
3982 " part_pkg_usage_class.classnum = $classnum",
3983 'order_by' => ' ORDER BY part_pkg_usage.priority ASC',
3985 if ( $order eq 'time' ) {
3986 # find CDRs that are using minutes, but have a later startdate
3988 my $startdate = $cdr->startdate;
3989 if ($startdate !~ /^\d+$/) {
3990 die "bad cdr startdate '$startdate'";
3992 $search{'extra_sql'} .= " AND cdr.startdate > $startdate";
3993 # minimize needless reshuffling
3994 $search{'order_by'} .= ', cdr.startdate DESC';
3996 # XXX may not work correctly with rate_time schedules. Could
3997 # fix this by storing ratedetailnum in cdr_cust_pkg_usage, I
3999 $search{'addl_from'} .=
4000 ' JOIN rate_detail'.
4001 ' ON (cdr.rated_ratedetailnum = rate_detail.ratedetailnum)';
4002 if ( $order eq 'rate_high' ) {
4003 $search{'extra_sql'} .= ' AND rate_detail.min_charge < '.
4004 $rate_detail->min_charge;
4005 $search{'order_by'} .= ', rate_detail.min_charge ASC';
4006 } elsif ( $order eq 'rate_low' ) {
4007 $search{'extra_sql'} .= ' AND rate_detail.min_charge > '.
4008 $rate_detail->min_charge;
4009 $search{'order_by'} .= ', rate_detail.min_charge DESC';
4011 # this should really never happen
4012 die "invalid cdr-minutes_priority value '$order'\n";
4015 my @cdr_usage_recs = qsearch(\%search);
4017 while (!$error and @cdr_usage_recs and $minutes > 0) {
4018 my $cdr_cust_pkg_usage = shift @cdr_usage_recs;
4019 my $cust_pkg_usage = $cdr_cust_pkg_usage->cust_pkg_usage;
4020 my $old_cdr = $cdr_cust_pkg_usage->cdr;
4021 $reproc_cdrs{$old_cdr->acctid} = $old_cdr;
4022 $cdr_cust_pkg_usage->select_for_update;
4023 $old_cdr->select_for_update;
4024 $cust_pkg_usage->select_for_update;
4025 # in case someone else stole the usage from this CDR
4026 # while waiting for the lock...
4027 next if $old_cdr->acctid != $cdr_cust_pkg_usage->acctid;
4028 # steal the usage allocation and flag the old CDR for reprocessing
4029 $cdr_cust_pkg_usage->set('acctid', $cdr->acctid);
4030 # if the allocation is more minutes than we need, adjust it...
4031 my $delta = $cdr_cust_pkg_usage->minutes - $minutes;
4033 $cdr_cust_pkg_usage->set('minutes', $minutes);
4034 $cust_pkg_usage->set('minutes', $cust_pkg_usage->minutes + $delta);
4035 $error = $cust_pkg_usage->replace;
4037 #warn 'CDR '.$cdr->acctid . ' stealing allocation '.$cdr_cust_pkg_usage->cdrusagenum.' from CDR '.$old_cdr->acctid."\n";
4038 $error ||= $cdr_cust_pkg_usage->replace;
4039 # deduct the stolen minutes
4040 $minutes -= $cdr_cust_pkg_usage->minutes;
4042 # after all minute-stealing is done, reset the affected CDRs
4043 foreach (values %reproc_cdrs) {
4044 $error ||= $_->set_status('');
4045 # XXX or should we just call $cdr->rate right here?
4046 # it's not like we can create a loop this way, since the min_charge
4047 # or call time has to go monotonically in one direction.
4048 # we COULD get some very deep recursions going, though...
4050 } # if $order and $minutes
4053 die "error applying included minutes\npkgnum ".$self->pkgnum.", class $classnum, acctid ".$cdr->acctid."\n$error\n"
4055 $dbh->commit if $oldAutoCommit;
4056 return $orig_minutes - $minutes;
4060 =item supplemental_pkgs
4062 Returns a list of all packages supplemental to this one.
4066 sub supplemental_pkgs {
4068 qsearch('cust_pkg', { 'main_pkgnum' => $self->pkgnum });
4073 Returns the package that this one is supplemental to, if any.
4079 if ( $self->main_pkgnum ) {
4080 return FS::cust_pkg->by_key($self->main_pkgnum);
4087 =head1 CLASS METHODS
4093 Returns an SQL expression identifying recurring packages.
4097 sub recurring_sql { "
4098 '0' != ( select freq from part_pkg
4099 where cust_pkg.pkgpart = part_pkg.pkgpart )
4104 Returns an SQL expression identifying one-time packages.
4109 '0' = ( select freq from part_pkg
4110 where cust_pkg.pkgpart = part_pkg.pkgpart )
4115 Returns an SQL expression identifying ordered packages (recurring packages not
4121 $_[0]->recurring_sql. " AND ". $_[0]->not_yet_billed_sql;
4126 Returns an SQL expression identifying active packages.
4131 $_[0]->recurring_sql. "
4132 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
4133 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4134 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
4137 =item not_yet_billed_sql
4139 Returns an SQL expression identifying packages which have not yet been billed.
4143 sub not_yet_billed_sql { "
4144 ( cust_pkg.setup IS NULL OR cust_pkg.setup = 0 )
4145 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4146 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
4151 Returns an SQL expression identifying inactive packages (one-time packages
4152 that are otherwise unsuspended/uncancelled).
4156 sub inactive_sql { "
4157 ". $_[0]->onetime_sql(). "
4158 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
4159 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4160 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
4166 Returns an SQL expression identifying suspended packages.
4170 sub suspended_sql { susp_sql(@_); }
4172 #$_[0]->recurring_sql(). ' AND '.
4174 ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4175 AND cust_pkg.susp IS NOT NULL AND cust_pkg.susp != 0
4182 Returns an SQL exprression identifying cancelled packages.
4186 sub cancelled_sql { cancel_sql(@_); }
4188 #$_[0]->recurring_sql(). ' AND '.
4189 "cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0";
4194 Returns an SQL expression to give the package status as a string.
4200 WHEN cust_pkg.cancel IS NOT NULL THEN 'cancelled'
4201 WHEN cust_pkg.susp IS NOT NULL THEN 'suspended'
4202 WHEN cust_pkg.setup IS NULL THEN 'not yet billed'
4203 WHEN ".onetime_sql()." THEN 'one-time charge'
4208 =item search HASHREF
4212 Returns a qsearch hash expression to search for parameters specified in HASHREF.
4213 Valid parameters are
4221 active, inactive, suspended, cancel (or cancelled)
4225 active, inactive, suspended, one-time charge, inactive, cancel (or cancelled)
4229 boolean selects custom packages
4235 pkgpart or arrayref or hashref of pkgparts
4239 arrayref of beginning and ending epoch date
4243 arrayref of beginning and ending epoch date
4247 arrayref of beginning and ending epoch date
4251 arrayref of beginning and ending epoch date
4255 arrayref of beginning and ending epoch date
4259 arrayref of beginning and ending epoch date
4263 arrayref of beginning and ending epoch date
4267 pkgnum or APKG_pkgnum
4271 a value suited to passing to FS::UI::Web::cust_header
4275 specifies the user for agent virtualization
4279 boolean; if true, returns only packages with more than 0 FCC phone lines.
4281 =item state, country
4283 Limit to packages with a service location in the specified state and country.
4284 For FCC 477 reporting, mostly.
4288 Limit to packages whose service locations are the same as the customer's
4289 default service location.
4291 =item location_nocust
4293 Limit to packages whose service locations are not the customer's default
4296 =item location_census
4298 Limit to packages whose service locations have census tracts.
4300 =item location_nocensus
4302 Limit to packages whose service locations do not have a census tract.
4304 =item location_geocode
4306 Limit to packages whose locations have geocodes.
4308 =item location_geocode
4310 Limit to packages whose locations do not have geocodes.
4317 my ($class, $params) = @_;
4324 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
4326 "cust_main.agentnum = $1";
4333 if ( $params->{'cust_status'} =~ /^([a-z]+)$/ ) {
4334 push @where, FS::cust_main->cust_status_sql . " = '$1' ";
4338 # parse customer sales person
4341 if ( $params->{'cust_main_salesnum'} =~ /^(\d+)$/ ) {
4342 push @where, ($1 > 0) ? "cust_main.salesnum = $1"
4343 : 'cust_main.salesnum IS NULL';
4348 # parse sales person
4351 if ( $params->{'salesnum'} =~ /^(\d+)$/ ) {
4352 push @where, ($1 > 0) ? "cust_pkg.salesnum = $1"
4353 : 'cust_pkg.salesnum IS NULL';
4360 if ( $params->{'custnum'} =~ /^(\d+)$/ and $1 ) {
4362 "cust_pkg.custnum = $1";
4369 if ( $params->{'pkgbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
4371 "cust_pkg.pkgbatch = '$1'";
4378 if ( $params->{'magic'} eq 'active'
4379 || $params->{'status'} eq 'active' ) {
4381 push @where, FS::cust_pkg->active_sql();
4383 } elsif ( $params->{'magic'} =~ /^not[ _]yet[ _]billed$/
4384 || $params->{'status'} =~ /^not[ _]yet[ _]billed$/ ) {
4386 push @where, FS::cust_pkg->not_yet_billed_sql();
4388 } elsif ( $params->{'magic'} =~ /^(one-time charge|inactive)/
4389 || $params->{'status'} =~ /^(one-time charge|inactive)/ ) {
4391 push @where, FS::cust_pkg->inactive_sql();
4393 } elsif ( $params->{'magic'} eq 'suspended'
4394 || $params->{'status'} eq 'suspended' ) {
4396 push @where, FS::cust_pkg->suspended_sql();
4398 } elsif ( $params->{'magic'} =~ /^cancell?ed$/
4399 || $params->{'status'} =~ /^cancell?ed$/ ) {
4401 push @where, FS::cust_pkg->cancelled_sql();
4406 # parse package class
4409 if ( exists($params->{'classnum'}) ) {
4412 if ( ref($params->{'classnum'}) ) {
4414 if ( ref($params->{'classnum'}) eq 'HASH' ) {
4415 @classnum = grep $params->{'classnum'}{$_}, keys %{ $params->{'classnum'} };
4416 } elsif ( ref($params->{'classnum'}) eq 'ARRAY' ) {
4417 @classnum = @{ $params->{'classnum'} };
4419 die 'unhandled classnum ref '. $params->{'classnum'};
4423 } elsif ( $params->{'classnum'} =~ /^(\d*)$/ && $1 ne '0' ) {
4430 my @nums = grep $_, @classnum;
4431 push @c_where, 'part_pkg.classnum IN ('. join(',',@nums). ')' if @nums;
4432 my $null = scalar( grep { $_ eq '' } @classnum );
4433 push @c_where, 'part_pkg.classnum IS NULL' if $null;
4435 if ( scalar(@c_where) == 1 ) {
4436 push @where, @c_where;
4437 } elsif ( @c_where ) {
4438 push @where, ' ( '. join(' OR ', @c_where). ' ) ';
4447 # parse package report options
4450 my @report_option = ();
4451 if ( exists($params->{'report_option'}) ) {
4452 if ( ref($params->{'report_option'}) eq 'ARRAY' ) {
4453 @report_option = @{ $params->{'report_option'} };
4454 } elsif ( $params->{'report_option'} =~ /^([,\d]*)$/ ) {
4455 @report_option = split(',', $1);
4460 if (@report_option) {
4461 # this will result in the empty set for the dangling comma case as it should
4463 map{ "0 < ( SELECT count(*) FROM part_pkg_option
4464 WHERE part_pkg_option.pkgpart = part_pkg.pkgpart
4465 AND optionname = 'report_option_$_'
4466 AND optionvalue = '1' )"
4470 foreach my $any ( grep /^report_option_any/, keys %$params ) {
4472 my @report_option_any = ();
4473 if ( ref($params->{$any}) eq 'ARRAY' ) {
4474 @report_option_any = @{ $params->{$any} };
4475 } elsif ( $params->{$any} =~ /^([,\d]*)$/ ) {
4476 @report_option_any = split(',', $1);
4479 if (@report_option_any) {
4480 # this will result in the empty set for the dangling comma case as it should
4481 push @where, ' ( '. join(' OR ',
4482 map{ "0 < ( SELECT count(*) FROM part_pkg_option
4483 WHERE part_pkg_option.pkgpart = part_pkg.pkgpart
4484 AND optionname = 'report_option_$_'
4485 AND optionvalue = '1' )"
4486 } @report_option_any
4496 push @where, "part_pkg.custom = 'Y'" if $params->{custom};
4502 push @where, "(part_pkg.fcc_ds0s > 0 OR pkg_class.fcc_ds0s > 0)"
4503 if $params->{fcc_line};
4509 if ( exists($params->{'censustract'}) ) {
4510 $params->{'censustract'} =~ /^([.\d]*)$/;
4511 my $censustract = "cust_location.censustract = '$1'";
4512 $censustract .= ' OR cust_location.censustract is NULL' unless $1;
4513 push @where, "( $censustract )";
4517 # parse censustract2
4519 if ( exists($params->{'censustract2'})
4520 && $params->{'censustract2'} =~ /^(\d*)$/
4524 push @where, "cust_location.censustract LIKE '$1%'";
4527 "( cust_location.censustract = '' OR cust_location.censustract IS NULL )";
4532 # parse country/state
4534 for (qw(state country)) { # parsing rules are the same for these
4535 if ( exists($params->{$_})
4536 && uc($params->{$_}) =~ /^([A-Z]{2})$/ )
4538 # XXX post-2.3 only--before that, state/country may be in cust_main
4539 push @where, "cust_location.$_ = '$1'";
4546 if ( $params->{location_cust} xor $params->{location_nocust} ) {
4547 my $op = $params->{location_cust} ? '=' : '!=';
4548 push @where, "cust_location.locationnum $op cust_main.ship_locationnum";
4550 if ( $params->{location_census} xor $params->{location_nocensus} ) {
4551 my $op = $params->{location_census} ? "IS NOT NULL" : "IS NULL";
4552 push @where, "cust_location.censustract $op";
4554 if ( $params->{location_geocode} xor $params->{location_nogeocode} ) {
4555 my $op = $params->{location_geocode} ? "IS NOT NULL" : "IS NULL";
4556 push @where, "cust_location.geocode $op";
4563 if ( ref($params->{'pkgpart'}) ) {
4566 if ( ref($params->{'pkgpart'}) eq 'HASH' ) {
4567 @pkgpart = grep $params->{'pkgpart'}{$_}, keys %{ $params->{'pkgpart'} };
4568 } elsif ( ref($params->{'pkgpart'}) eq 'ARRAY' ) {
4569 @pkgpart = @{ $params->{'pkgpart'} };
4571 die 'unhandled pkgpart ref '. $params->{'pkgpart'};
4574 @pkgpart = grep /^(\d+)$/, @pkgpart;
4576 push @where, 'pkgpart IN ('. join(',', @pkgpart). ')' if scalar(@pkgpart);
4578 } elsif ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
4579 push @where, "pkgpart = $1";
4588 #false laziness w/report_cust_pkg.html
4591 'one-time charge' => { 'last_bill'=>1, 'bill'=>1, 'adjourn'=>1, 'susp'=>1, 'expire'=>1, 'cancel'=>1, },
4592 'active' => { 'susp'=>1, 'cancel'=>1 },
4593 'suspended' => { 'cancel' => 1 },
4598 if( exists($params->{'active'} ) ) {
4599 # This overrides all the other date-related fields
4600 my($beginning, $ending) = @{$params->{'active'}};
4602 "cust_pkg.setup IS NOT NULL",
4603 "cust_pkg.setup <= $ending",
4604 "(cust_pkg.cancel IS NULL OR cust_pkg.cancel >= $beginning )",
4605 "NOT (".FS::cust_pkg->onetime_sql . ")";
4608 foreach my $field (qw( setup last_bill bill adjourn susp expire contract_end change_date cancel )) {
4610 next unless exists($params->{$field});
4612 my($beginning, $ending) = @{$params->{$field}};
4614 next if $beginning == 0 && $ending == 4294967295;
4617 "cust_pkg.$field IS NOT NULL",
4618 "cust_pkg.$field >= $beginning",
4619 "cust_pkg.$field <= $ending";
4621 $orderby ||= "ORDER BY cust_pkg.$field";
4626 $orderby ||= 'ORDER BY bill';
4629 # parse magic, legacy, etc.
4632 if ( $params->{'magic'} &&
4633 $params->{'magic'} =~ /^(active|inactive|suspended|cancell?ed)$/
4636 $orderby = 'ORDER BY pkgnum';
4638 if ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
4639 push @where, "pkgpart = $1";
4642 } elsif ( $params->{'query'} eq 'pkgnum' ) {
4644 $orderby = 'ORDER BY pkgnum';
4646 } elsif ( $params->{'query'} eq 'APKG_pkgnum' ) {
4648 $orderby = 'ORDER BY pkgnum';
4651 SELECT count(*) FROM pkg_svc
4652 WHERE pkg_svc.pkgpart = cust_pkg.pkgpart
4653 AND pkg_svc.quantity > ( SELECT count(*) FROM cust_svc
4654 WHERE cust_svc.pkgnum = cust_pkg.pkgnum
4655 AND cust_svc.svcpart = pkg_svc.svcpart
4662 # setup queries, links, subs, etc. for the search
4665 # here is the agent virtualization
4666 if ($params->{CurrentUser}) {
4668 qsearchs('access_user', { username => $params->{CurrentUser} });
4671 push @where, $access_user->agentnums_sql('table'=>'cust_main');
4676 push @where, $FS::CurrentUser::CurrentUser->agentnums_sql('table'=>'cust_main');
4679 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
4681 my $addl_from = 'LEFT JOIN part_pkg USING ( pkgpart ) '.
4682 'LEFT JOIN pkg_class ON ( part_pkg.classnum = pkg_class.classnum ) '.
4683 'LEFT JOIN cust_location USING ( locationnum ) '.
4684 FS::UI::Web::join_cust_main('cust_pkg', 'cust_pkg');
4688 if ( $params->{'select_zip5'} ) {
4689 my $zip = 'cust_location.zip';
4691 $select = "DISTINCT substr($zip,1,5) as zip";
4692 $orderby = "ORDER BY substr($zip,1,5)";
4693 $count_query = "SELECT COUNT( DISTINCT substr($zip,1,5) )";
4695 $select = join(', ',
4697 ( map "part_pkg.$_", qw( pkg freq ) ),
4698 'pkg_class.classname',
4699 'cust_main.custnum AS cust_main_custnum',
4700 FS::UI::Web::cust_sql_fields(
4701 $params->{'cust_fields'}
4704 $count_query = 'SELECT COUNT(*)';
4707 $count_query .= " FROM cust_pkg $addl_from $extra_sql";
4710 'table' => 'cust_pkg',
4712 'select' => $select,
4713 'extra_sql' => $extra_sql,
4714 'order_by' => $orderby,
4715 'addl_from' => $addl_from,
4716 'count_query' => $count_query,
4723 Returns a list of two package counts. The first is a count of packages
4724 based on the supplied criteria and the second is the count of residential
4725 packages with those same criteria. Criteria are specified as in the search
4731 my ($class, $params) = @_;
4733 my $sql_query = $class->search( $params );
4735 my $count_sql = delete($sql_query->{'count_query'});
4736 $count_sql =~ s/ FROM/,count(CASE WHEN cust_main.company IS NULL OR cust_main.company = '' THEN 1 END) FROM/
4737 or die "couldn't parse count_sql";
4739 my $count_sth = dbh->prepare($count_sql)
4740 or die "Error preparing $count_sql: ". dbh->errstr;
4742 or die "Error executing $count_sql: ". $count_sth->errstr;
4743 my $count_arrayref = $count_sth->fetchrow_arrayref;
4745 return ( @$count_arrayref );
4749 =item tax_locationnum_sql
4751 Returns an SQL expression for the tax location for a package, based
4752 on the settings of 'tax-pkg_address' and 'tax-ship_address'.
4756 sub tax_locationnum_sql {
4757 my $conf = FS::Conf->new;
4758 if ( $conf->exists('tax-pkg_address') ) {
4759 'cust_pkg.locationnum';
4761 elsif ( $conf->exists('tax-ship_address') ) {
4762 'cust_main.ship_locationnum';
4765 'cust_main.bill_locationnum';
4771 Returns a list: the first item is an SQL fragment identifying matching
4772 packages/customers via location (taking into account shipping and package
4773 address taxation, if enabled), and subsequent items are the parameters to
4774 substitute for the placeholders in that fragment.
4779 my($class, %opt) = @_;
4780 my $ornull = $opt{'ornull'};
4782 my $conf = new FS::Conf;
4784 # '?' placeholders in _location_sql_where
4785 my $x = $ornull ? 3 : 2;
4796 if ( $conf->exists('tax-ship_address') ) {
4799 ( ( ship_last IS NULL OR ship_last = '' )
4800 AND ". _location_sql_where('cust_main', '', $ornull ). "
4802 OR ( ship_last IS NOT NULL AND ship_last != ''
4803 AND ". _location_sql_where('cust_main', 'ship_', $ornull ). "
4806 # AND payby != 'COMP'
4808 @main_param = ( @bill_param, @bill_param );
4812 $main_where = _location_sql_where('cust_main'); # AND payby != 'COMP'
4813 @main_param = @bill_param;
4819 if ( $conf->exists('tax-pkg_address') ) {
4821 my $loc_where = _location_sql_where( 'cust_location', '', $ornull );
4824 ( cust_pkg.locationnum IS NULL AND $main_where )
4825 OR ( cust_pkg.locationnum IS NOT NULL AND $loc_where )
4828 @param = ( @main_param, @bill_param );
4832 $where = $main_where;
4833 @param = @main_param;
4841 #subroutine, helper for location_sql
4842 sub _location_sql_where {
4844 my $prefix = @_ ? shift : '';
4845 my $ornull = @_ ? shift : '';
4847 # $ornull = $ornull ? " OR ( ? IS NULL AND $table.${prefix}county IS NULL ) " : '';
4849 $ornull = $ornull ? ' OR ? IS NULL ' : '';
4851 my $or_empty_city = " OR ( ? = '' AND $table.${prefix}city IS NULL )";
4852 my $or_empty_county = " OR ( ? = '' AND $table.${prefix}county IS NULL )";
4853 my $or_empty_state = " OR ( ? = '' AND $table.${prefix}state IS NULL )";
4855 my $text = (driver_name =~ /^mysql/i) ? 'char' : 'text';
4857 # ( $table.${prefix}city = ? $or_empty_city $ornull )
4859 ( $table.district = ? OR ? = '' OR CAST(? AS $text) IS NULL )
4860 AND ( $table.${prefix}city = ? OR ? = '' OR CAST(? AS $text) IS NULL )
4861 AND ( $table.${prefix}county = ? $or_empty_county $ornull )
4862 AND ( $table.${prefix}state = ? $or_empty_state $ornull )
4863 AND $table.${prefix}country = ?
4868 my( $self, $what ) = @_;
4870 my $what_show_zero = $what. '_show_zero';
4871 length($self->$what_show_zero())
4872 ? ($self->$what_show_zero() eq 'Y')
4873 : $self->part_pkg->$what_show_zero();
4880 =item order CUSTNUM, PKGPARTS_ARYREF, [ REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF [ REFNUM ] ] ]
4882 CUSTNUM is a customer (see L<FS::cust_main>)
4884 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
4885 L<FS::part_pkg>) to order for this customer. Duplicates are of course
4888 REMOVE_PKGNUMS is an optional list of pkgnums specifying the billing items to
4889 remove for this customer. The services (see L<FS::cust_svc>) are moved to the
4890 new billing items. An error is returned if this is not possible (see
4891 L<FS::pkg_svc>). An empty arrayref is equivalent to not specifying this
4894 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
4895 newly-created cust_pkg objects.
4897 REFNUM, if specified, will specify the FS::pkg_referral record to be created
4898 and inserted. Multiple FS::pkg_referral records can be created by
4899 setting I<refnum> to an array reference of refnums or a hash reference with
4900 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
4901 record will be created corresponding to cust_main.refnum.
4906 my ($custnum, $pkgparts, $remove_pkgnum, $return_cust_pkg, $refnum) = @_;
4908 my $conf = new FS::Conf;
4910 # Transactionize this whole mess
4911 local $SIG{HUP} = 'IGNORE';
4912 local $SIG{INT} = 'IGNORE';
4913 local $SIG{QUIT} = 'IGNORE';
4914 local $SIG{TERM} = 'IGNORE';
4915 local $SIG{TSTP} = 'IGNORE';
4916 local $SIG{PIPE} = 'IGNORE';
4918 my $oldAutoCommit = $FS::UID::AutoCommit;
4919 local $FS::UID::AutoCommit = 0;
4923 # my $cust_main = qsearchs('cust_main', { custnum => $custnum });
4924 # return "Customer not found: $custnum" unless $cust_main;
4926 warn "$me order: pkgnums to remove: ". join(',', @$remove_pkgnum). "\n"
4929 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
4932 my $change = scalar(@old_cust_pkg) != 0;
4935 if ( scalar(@old_cust_pkg) == 1 && scalar(@$pkgparts) == 1 ) {
4937 warn "$me order: changing pkgnum ". $old_cust_pkg[0]->pkgnum.
4938 " to pkgpart ". $pkgparts->[0]. "\n"
4941 my $err_or_cust_pkg =
4942 $old_cust_pkg[0]->change( 'pkgpart' => $pkgparts->[0],
4943 'refnum' => $refnum,
4946 unless (ref($err_or_cust_pkg)) {
4947 $dbh->rollback if $oldAutoCommit;
4948 return $err_or_cust_pkg;
4951 push @$return_cust_pkg, $err_or_cust_pkg;
4952 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4957 # Create the new packages.
4958 foreach my $pkgpart (@$pkgparts) {
4960 warn "$me order: inserting pkgpart $pkgpart\n" if $DEBUG;
4962 my $cust_pkg = new FS::cust_pkg { custnum => $custnum,
4963 pkgpart => $pkgpart,
4967 $error = $cust_pkg->insert( 'change' => $change );
4968 push @$return_cust_pkg, $cust_pkg;
4970 foreach my $link ($cust_pkg->part_pkg->supp_part_pkg_link) {
4971 my $supp_pkg = FS::cust_pkg->new({
4972 custnum => $custnum,
4973 pkgpart => $link->dst_pkgpart,
4975 main_pkgnum => $cust_pkg->pkgnum,
4978 $error ||= $supp_pkg->insert( 'change' => $change );
4979 push @$return_cust_pkg, $supp_pkg;
4983 $dbh->rollback if $oldAutoCommit;
4988 # $return_cust_pkg now contains refs to all of the newly
4991 # Transfer services and cancel old packages.
4992 foreach my $old_pkg (@old_cust_pkg) {
4994 warn "$me order: transferring services from pkgnum ". $old_pkg->pkgnum. "\n"
4997 foreach my $new_pkg (@$return_cust_pkg) {
4998 $error = $old_pkg->transfer($new_pkg);
4999 if ($error and $error == 0) {
5000 # $old_pkg->transfer failed.
5001 $dbh->rollback if $oldAutoCommit;
5006 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
5007 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
5008 foreach my $new_pkg (@$return_cust_pkg) {
5009 $error = $old_pkg->transfer($new_pkg, 'change_svcpart'=>1 );
5010 if ($error and $error == 0) {
5011 # $old_pkg->transfer failed.
5012 $dbh->rollback if $oldAutoCommit;
5019 # Transfers were successful, but we went through all of the
5020 # new packages and still had services left on the old package.
5021 # We can't cancel the package under the circumstances, so abort.
5022 $dbh->rollback if $oldAutoCommit;
5023 return "Unable to transfer all services from package ".$old_pkg->pkgnum;
5025 $error = $old_pkg->cancel( quiet=>1 );
5031 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5035 =item bulk_change PKGPARTS_ARYREF, REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF ]
5037 A bulk change method to change packages for multiple customers.
5039 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
5040 L<FS::part_pkg>) to order for each customer. Duplicates are of course
5043 REMOVE_PKGNUMS is an list of pkgnums specifying the billing items to
5044 replace. The services (see L<FS::cust_svc>) are moved to the
5045 new billing items. An error is returned if this is not possible (see
5048 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
5049 newly-created cust_pkg objects.
5054 my ($pkgparts, $remove_pkgnum, $return_cust_pkg) = @_;
5056 # Transactionize this whole mess
5057 local $SIG{HUP} = 'IGNORE';
5058 local $SIG{INT} = 'IGNORE';
5059 local $SIG{QUIT} = 'IGNORE';
5060 local $SIG{TERM} = 'IGNORE';
5061 local $SIG{TSTP} = 'IGNORE';
5062 local $SIG{PIPE} = 'IGNORE';
5064 my $oldAutoCommit = $FS::UID::AutoCommit;
5065 local $FS::UID::AutoCommit = 0;
5069 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
5072 while(scalar(@old_cust_pkg)) {
5074 my $custnum = $old_cust_pkg[0]->custnum;
5075 my (@remove) = map { $_->pkgnum }
5076 grep { $_->custnum == $custnum } @old_cust_pkg;
5077 @old_cust_pkg = grep { $_->custnum != $custnum } @old_cust_pkg;
5079 my $error = order $custnum, $pkgparts, \@remove, \@return;
5081 push @errors, $error
5083 push @$return_cust_pkg, @return;
5086 if (scalar(@errors)) {
5087 $dbh->rollback if $oldAutoCommit;
5088 return join(' / ', @errors);
5091 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5095 # Used by FS::Upgrade to migrate to a new database.
5096 sub _upgrade_data { # class method
5097 my ($class, %opts) = @_;
5098 $class->_upgrade_otaker(%opts);
5100 # RT#10139, bug resulting in contract_end being set when it shouldn't
5101 'UPDATE cust_pkg SET contract_end = NULL WHERE contract_end = -1',
5102 # RT#10830, bad calculation of prorate date near end of year
5103 # the date range for bill is December 2009, and we move it forward
5104 # one year if it's before the previous bill date (which it should
5106 'UPDATE cust_pkg SET bill = bill + (365*24*60*60) WHERE bill < last_bill
5107 AND bill > 1259654400 AND bill < 1262332800 AND (SELECT plan FROM part_pkg
5108 WHERE part_pkg.pkgpart = cust_pkg.pkgpart) = \'prorate\'',
5109 # RT6628, add order_date to cust_pkg
5110 'update cust_pkg set order_date = (select history_date from h_cust_pkg
5111 where h_cust_pkg.pkgnum = cust_pkg.pkgnum and
5112 history_action = \'insert\') where order_date is null',
5114 foreach my $sql (@statements) {
5115 my $sth = dbh->prepare($sql);
5116 $sth->execute or die $sth->errstr;
5124 sub order is not OO. Perhaps it should be moved to FS::cust_main and made so?
5126 In sub order, the @pkgparts array (passed by reference) is clobbered.
5128 Also in sub order, no money is adjusted. Once FS::part_pkg defines a standard
5129 method to pass dates to the recur_prog expression, it should do so.
5131 FS::svc_acct, FS::svc_domain, FS::svc_www, FS::svc_ip and FS::svc_forward are
5132 loaded via 'use' at compile time, rather than via 'require' in sub { setup,
5133 suspend, unsuspend, cancel } because they use %FS::UID::callback to load
5134 configuration values. Probably need a subroutine which decides what to do
5135 based on whether or not we've fetched the user yet, rather than a hash. See
5136 FS::UID and the TODO.
5138 Now that things are transactional should the check in the insert method be
5143 L<FS::Record>, L<FS::cust_main>, L<FS::part_pkg>, L<FS::cust_svc>,
5144 L<FS::pkg_svc>, schema.html from the base documentation