2 use base qw( FS::otaker_Mixin FS::cust_main_Mixin FS::Sales_Mixin
3 FS::contact_Mixin FS::location_Mixin
4 FS::m2m_Common FS::option_Common );
7 use vars qw( $disable_agentcheck $DEBUG $me $upgrade );
9 use Scalar::Util qw( blessed );
10 use List::Util qw(min max);
12 use Time::Local qw( timelocal timelocal_nocheck );
14 use FS::UID qw( getotaker dbh driver_name );
15 use FS::Misc qw( send_email );
16 use FS::Record qw( qsearch qsearchs fields );
22 use FS::cust_location;
24 use FS::cust_bill_pkg;
25 use FS::cust_pkg_detail;
26 use FS::cust_pkg_usage;
27 use FS::cdr_cust_pkg_usage;
32 use FS::cust_pkg_reason;
34 use FS::cust_pkg_discount;
41 # need to 'use' these instead of 'require' in sub { cancel, suspend, unsuspend,
43 # because they load configuration by setting FS::UID::callback (see TODO)
49 # for sending cancel emails in sub cancel
53 $me = '[FS::cust_pkg]';
55 $disable_agentcheck = 0;
57 $upgrade = 0; #go away after setup+start dates cleaned up for old customers
61 my ( $hashref, $cache ) = @_;
62 #if ( $hashref->{'pkgpart'} ) {
63 if ( $hashref->{'pkg'} ) {
64 # #@{ $self->{'_pkgnum'} } = ();
65 # my $subcache = $cache->subcache('pkgpart', 'part_pkg');
66 # $self->{'_pkgpart'} = $subcache;
67 # #push @{ $self->{'_pkgnum'} },
68 # FS::part_pkg->new_or_cached($hashref, $subcache);
69 $self->{'_pkgpart'} = FS::part_pkg->new($hashref);
71 if ( exists $hashref->{'svcnum'} ) {
72 #@{ $self->{'_pkgnum'} } = ();
73 my $subcache = $cache->subcache('svcnum', 'cust_svc', $hashref->{pkgnum});
74 $self->{'_svcnum'} = $subcache;
75 #push @{ $self->{'_pkgnum'} },
76 FS::cust_svc->new_or_cached($hashref, $subcache) if $hashref->{svcnum};
82 FS::cust_pkg - Object methods for cust_pkg objects
88 $record = new FS::cust_pkg \%hash;
89 $record = new FS::cust_pkg { 'column' => 'value' };
91 $error = $record->insert;
93 $error = $new_record->replace($old_record);
95 $error = $record->delete;
97 $error = $record->check;
99 $error = $record->cancel;
101 $error = $record->suspend;
103 $error = $record->unsuspend;
105 $part_pkg = $record->part_pkg;
107 @labels = $record->labels;
109 $seconds = $record->seconds_since($timestamp);
111 $error = FS::cust_pkg::order( $custnum, \@pkgparts );
112 $error = FS::cust_pkg::order( $custnum, \@pkgparts, \@remove_pkgnums ] );
116 An FS::cust_pkg object represents a customer billing item. FS::cust_pkg
117 inherits from FS::Record. The following fields are currently supported:
123 Primary key (assigned automatically for new billing items)
127 Customer (see L<FS::cust_main>)
131 Billing item definition (see L<FS::part_pkg>)
135 Optional link to package location (see L<FS::location>)
139 date package was ordered (also remains same on changes)
151 date (next bill date)
179 order taker (see L<FS::access_user>)
183 If this field is set to 1, disables the automatic
184 unsuspension of this package when using the B<unsuspendauto> config option.
188 If not set, defaults to 1
192 Date of change from previous package
202 =item change_locationnum
210 The pkgnum of the package that this package is supplemental to, if any.
214 The package link (L<FS::part_pkg_link>) that defines this supplemental
215 package, if it is one.
217 =item change_to_pkgnum
219 The pkgnum of the package this one will be "changed to" in the future
220 (on its expiration date).
224 Note: setup, last_bill, bill, adjourn, susp, expire, cancel and change_date
225 are specified as UNIX timestamps; see L<perlfunc/"time">. Also see
226 L<Time::Local> and L<Date::Parse> for conversion functions.
234 Create a new billing item. To add the item to the database, see L<"insert">.
238 sub table { 'cust_pkg'; }
239 sub cust_linked { $_[0]->cust_main_custnum || $_[0]->custnum }
240 sub cust_unlinked_msg {
242 "WARNING: can't find cust_main.custnum ". $self->custnum.
243 ' (cust_pkg.pkgnum '. $self->pkgnum. ')';
246 =item insert [ OPTION => VALUE ... ]
248 Adds this billing item to the database ("Orders" the item). If there is an
249 error, returns the error, otherwise returns false.
251 If the additional field I<promo_code> is defined instead of I<pkgpart>, it
252 will be used to look up the package definition and agent restrictions will be
255 If the additional field I<refnum> is defined, an FS::pkg_referral record will
256 be created and inserted. Multiple FS::pkg_referral records can be created by
257 setting I<refnum> to an array reference of refnums or a hash reference with
258 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
259 record will be created corresponding to cust_main.refnum.
261 The following options are available:
267 If set true, supresses actions that should only be taken for new package
268 orders. (Currently this includes: intro periods when delay_setup is on,
269 auto-adding a 1st start date, auto-adding expiration/adjourn/contract_end dates)
273 cust_pkg_option records will be created
277 a ticket will be added to this customer with this subject
281 an optional queue name for ticket additions
285 Don't check the legality of the package definition. This should be used
286 when performing a package change that doesn't change the pkgpart (i.e.
294 my( $self, %options ) = @_;
297 $error = $self->check_pkgpart unless $options{'allow_pkgpart'};
298 return $error if $error;
300 my $part_pkg = $self->part_pkg;
302 if ( ! $options{'change'} ) {
304 # if the package def says to start only on the first of the month:
305 if ( $part_pkg->option('start_1st', 1) && !$self->start_date ) {
306 my ($sec,$min,$hour,$mday,$mon,$year) = (localtime(time) )[0,1,2,3,4,5];
307 $mon += 1 unless $mday == 1;
308 until ( $mon < 12 ) { $mon -= 12; $year++; }
309 $self->start_date( timelocal_nocheck(0,0,0,1,$mon,$year) );
312 # set up any automatic expire/adjourn/contract_end timers
313 # based on the start date
314 foreach my $action ( qw(expire adjourn contract_end) ) {
315 my $months = $part_pkg->option("${action}_months",1);
316 if($months and !$self->$action) {
317 my $start = $self->start_date || $self->setup || time;
318 $self->$action( $part_pkg->add_freq($start, $months) );
322 # if this package has "free days" and delayed setup fee, then
323 # set start date that many days in the future.
324 # (this should have been set in the UI, but enforce it here)
325 if ( ! $options{'change'}
326 && $part_pkg->option('free_days',1)
327 && $part_pkg->option('delay_setup',1)
328 #&& ! $self->start_date
331 $self->start_date( $part_pkg->default_start_date );
336 # set order date unless this was previously a different package
337 $self->order_date(time) unless $self->change_pkgnum;
339 local $SIG{HUP} = 'IGNORE';
340 local $SIG{INT} = 'IGNORE';
341 local $SIG{QUIT} = 'IGNORE';
342 local $SIG{TERM} = 'IGNORE';
343 local $SIG{TSTP} = 'IGNORE';
344 local $SIG{PIPE} = 'IGNORE';
346 my $oldAutoCommit = $FS::UID::AutoCommit;
347 local $FS::UID::AutoCommit = 0;
350 $error = $self->SUPER::insert($options{options} ? %{$options{options}} : ());
352 $dbh->rollback if $oldAutoCommit;
356 $self->refnum($self->cust_main->refnum) unless $self->refnum;
357 $self->refnum( [ $self->refnum ] ) unless ref($self->refnum);
358 $self->process_m2m( 'link_table' => 'pkg_referral',
359 'target_table' => 'part_referral',
360 'params' => $self->refnum,
363 if ( $self->discountnum ) {
364 my $error = $self->insert_discount();
366 $dbh->rollback if $oldAutoCommit;
371 my $conf = new FS::Conf;
373 if ( $conf->config('ticket_system') && $options{ticket_subject} ) {
375 #this init stuff is still inefficient, but at least its limited to
376 # the small number (any?) folks using ticket emailing on pkg order
379 # use lib ( "/opt/rt3/local/lib", "/opt/rt3/lib" );
386 use FS::TicketSystem;
387 FS::TicketSystem->init();
389 my $q = new RT::Queue($RT::SystemUser);
390 $q->Load($options{ticket_queue}) if $options{ticket_queue};
391 my $t = new RT::Ticket($RT::SystemUser);
392 my $mime = new MIME::Entity;
393 $mime->build( Type => 'text/plain', Data => $options{ticket_subject} );
394 $t->Create( $options{ticket_queue} ? (Queue => $q) : (),
395 Subject => $options{ticket_subject},
398 $t->AddLink( Type => 'MemberOf',
399 Target => 'freeside://freeside/cust_main/'. $self->custnum,
403 if ($conf->config('welcome_letter') && $self->cust_main->num_pkgs == 1) {
404 my $queue = new FS::queue {
405 'job' => 'FS::cust_main::queueable_print',
407 $error = $queue->insert(
408 'custnum' => $self->custnum,
409 'template' => 'welcome_letter',
413 warn "can't send welcome letter: $error";
418 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
425 This method now works but you probably shouldn't use it.
427 You don't want to delete packages, because there would then be no record
428 the customer ever purchased the package. Instead, see the cancel method and
429 hide cancelled packages.
436 local $SIG{HUP} = 'IGNORE';
437 local $SIG{INT} = 'IGNORE';
438 local $SIG{QUIT} = 'IGNORE';
439 local $SIG{TERM} = 'IGNORE';
440 local $SIG{TSTP} = 'IGNORE';
441 local $SIG{PIPE} = 'IGNORE';
443 my $oldAutoCommit = $FS::UID::AutoCommit;
444 local $FS::UID::AutoCommit = 0;
447 foreach my $cust_pkg_discount ($self->cust_pkg_discount) {
448 my $error = $cust_pkg_discount->delete;
450 $dbh->rollback if $oldAutoCommit;
454 #cust_bill_pkg_discount?
456 foreach my $cust_pkg_detail ($self->cust_pkg_detail) {
457 my $error = $cust_pkg_detail->delete;
459 $dbh->rollback if $oldAutoCommit;
464 foreach my $cust_pkg_reason (
466 'table' => 'cust_pkg_reason',
467 'hashref' => { 'pkgnum' => $self->pkgnum },
471 my $error = $cust_pkg_reason->delete;
473 $dbh->rollback if $oldAutoCommit;
480 my $error = $self->SUPER::delete(@_);
482 $dbh->rollback if $oldAutoCommit;
486 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
492 =item replace [ OLD_RECORD ] [ HASHREF | OPTION => VALUE ... ]
494 Replaces the OLD_RECORD with this one in the database. If there is an error,
495 returns the error, otherwise returns false.
497 Currently, custnum, setup, bill, adjourn, susp, expire, and cancel may be changed.
499 Changing pkgpart may have disasterous effects. See the order subroutine.
501 setup and bill are normally updated by calling the bill method of a customer
502 object (see L<FS::cust_main>).
504 suspend is normally updated by the suspend and unsuspend methods.
506 cancel is normally updated by the cancel method (and also the order subroutine
509 Available options are:
515 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.
519 the access_user (see L<FS::access_user>) providing the reason
523 hashref of keys and values - cust_pkg_option records will be created, updated or removed as appopriate
532 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
537 ( ref($_[0]) eq 'HASH' )
541 #return "Can't (yet?) change pkgpart!" if $old->pkgpart != $new->pkgpart;
542 #return "Can't change otaker!" if $old->otaker ne $new->otaker;
545 #return "Can't change setup once it exists!"
546 # if $old->getfield('setup') &&
547 # $old->getfield('setup') != $new->getfield('setup');
549 #some logic for bill, susp, cancel?
551 local($disable_agentcheck) = 1 if $old->pkgpart == $new->pkgpart;
553 local $SIG{HUP} = 'IGNORE';
554 local $SIG{INT} = 'IGNORE';
555 local $SIG{QUIT} = 'IGNORE';
556 local $SIG{TERM} = 'IGNORE';
557 local $SIG{TSTP} = 'IGNORE';
558 local $SIG{PIPE} = 'IGNORE';
560 my $oldAutoCommit = $FS::UID::AutoCommit;
561 local $FS::UID::AutoCommit = 0;
564 foreach my $method ( qw(adjourn expire) ) { # How many reasons?
565 if ($options->{'reason'} && $new->$method && $old->$method ne $new->$method) {
566 my $error = $new->insert_reason(
567 'reason' => $options->{'reason'},
568 'date' => $new->$method,
570 'reason_otaker' => $options->{'reason_otaker'},
573 dbh->rollback if $oldAutoCommit;
574 return "Error inserting cust_pkg_reason: $error";
579 #save off and freeze RADIUS attributes for any associated svc_acct records
581 if ( $old->part_pkg->is_prepaid || $new->part_pkg->is_prepaid ) {
583 #also check for specific exports?
584 # to avoid spurious modify export events
585 @svc_acct = map { $_->svc_x }
586 grep { $_->part_svc->svcdb eq 'svc_acct' }
589 $_->snapshot foreach @svc_acct;
593 my $error = $new->export_pkg_change($old)
594 || $new->SUPER::replace( $old,
596 ? $options->{options}
600 $dbh->rollback if $oldAutoCommit;
604 #for prepaid packages,
605 #trigger export of new RADIUS Expiration attribute when cust_pkg.bill changes
606 foreach my $old_svc_acct ( @svc_acct ) {
607 my $new_svc_acct = new FS::svc_acct { $old_svc_acct->hash };
609 $new_svc_acct->replace( $old_svc_acct,
610 'depend_jobnum' => $options->{depend_jobnum},
613 $dbh->rollback if $oldAutoCommit;
618 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
625 Checks all fields to make sure this is a valid billing item. If there is an
626 error, returns the error, otherwise returns false. Called by the insert and
634 if ( !$self->locationnum or $self->locationnum == -1 ) {
635 $self->set('locationnum', $self->cust_main->ship_locationnum);
639 $self->ut_numbern('pkgnum')
640 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum')
641 || $self->ut_numbern('pkgpart')
642 || $self->ut_foreign_keyn('contactnum', 'contact', 'contactnum' )
643 || $self->ut_foreign_keyn('locationnum', 'cust_location', 'locationnum')
644 || $self->ut_foreign_keyn('salesnum', 'sales', 'salesnum')
645 || $self->ut_numbern('quantity')
646 || $self->ut_numbern('start_date')
647 || $self->ut_numbern('setup')
648 || $self->ut_numbern('bill')
649 || $self->ut_numbern('susp')
650 || $self->ut_numbern('cancel')
651 || $self->ut_numbern('adjourn')
652 || $self->ut_numbern('resume')
653 || $self->ut_numbern('expire')
654 || $self->ut_numbern('dundate')
655 || $self->ut_enum('no_auto', [ '', 'Y' ])
656 || $self->ut_enum('waive_setup', [ '', 'Y' ])
657 || $self->ut_numbern('agent_pkgid')
658 || $self->ut_enum('recur_show_zero', [ '', 'Y', 'N', ])
659 || $self->ut_enum('setup_show_zero', [ '', 'Y', 'N', ])
660 || $self->ut_foreign_keyn('main_pkgnum', 'cust_pkg', 'pkgnum')
661 || $self->ut_foreign_keyn('pkglinknum', 'part_pkg_link', 'pkglinknum')
662 || $self->ut_foreign_keyn('change_to_pkgnum', 'cust_pkg', 'pkgnum')
664 return $error if $error;
666 return "A package with both start date (future start) and setup date (already started) will never bill"
667 if $self->start_date && $self->setup && ! $upgrade;
669 return "A future unsuspend date can only be set for a package with a suspend date"
670 if $self->resume and !$self->susp and !$self->adjourn;
672 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
674 if ( $self->dbdef_table->column('manual_flag') ) {
675 $self->manual_flag('') if $self->manual_flag eq ' ';
676 $self->manual_flag =~ /^([01]?)$/
677 or return "Illegal manual_flag ". $self->manual_flag;
678 $self->manual_flag($1);
686 Check the pkgpart to make sure it's allowed with the reg_code and/or
687 promo_code of the package (if present) and with the customer's agent.
688 Called from C<insert>, unless we are doing a package change that doesn't
696 # my $error = $self->ut_numbern('pkgpart'); # already done
699 if ( $self->reg_code ) {
701 unless ( grep { $self->pkgpart == $_->pkgpart }
702 map { $_->reg_code_pkg }
703 qsearchs( 'reg_code', { 'code' => $self->reg_code,
704 'agentnum' => $self->cust_main->agentnum })
706 return "Unknown registration code";
709 } elsif ( $self->promo_code ) {
712 qsearchs('part_pkg', {
713 'pkgpart' => $self->pkgpart,
714 'promo_code' => { op=>'ILIKE', value=>$self->promo_code },
716 return 'Unknown promotional code' unless $promo_part_pkg;
720 unless ( $disable_agentcheck ) {
722 qsearchs( 'agent', { 'agentnum' => $self->cust_main->agentnum } );
723 return "agent ". $agent->agentnum. ':'. $agent->agent.
724 " can't purchase pkgpart ". $self->pkgpart
725 unless $agent->pkgpart_hashref->{ $self->pkgpart }
726 || $agent->agentnum == $self->part_pkg->agentnum;
729 $error = $self->ut_foreign_key('pkgpart', 'part_pkg', 'pkgpart' );
730 return $error if $error;
738 =item cancel [ OPTION => VALUE ... ]
740 Cancels and removes all services (see L<FS::cust_svc> and L<FS::part_svc>)
741 in this package, then cancels the package itself (sets the cancel field to
744 Available options are:
748 =item quiet - can be set true to supress email cancellation notices.
750 =item time - can be set to cancel the package based on a specific future or
751 historical date. Using time ensures that the remaining amount is calculated
752 correctly. Note however that this is an immediate cancel and just changes
753 the date. You are PROBABLY looking to expire the account instead of using
756 =item reason - can be set to a cancellation reason (see L<FS:reason>),
757 either a reasonnum of an existing reason, or passing a hashref will create
758 a new reason. The hashref should have the following keys: typenum - Reason
759 type (see L<FS::reason_type>, reason - Text of the new reason.
761 =item date - can be set to a unix style timestamp to specify when to
764 =item nobill - can be set true to skip billing if it might otherwise be done.
766 =item unused_credit - can be set to 1 to credit the remaining time, or 0 to
767 not credit it. This must be set (by change()) when changing the package
768 to a different pkgpart or location, and probably shouldn't be in any other
769 case. If it's not set, the 'unused_credit_cancel' part_pkg option will
774 If there is an error, returns the error, otherwise returns false.
779 my( $self, %options ) = @_;
782 # pass all suspend/cancel actions to the main package
783 if ( $self->main_pkgnum and !$options{'from_main'} ) {
784 return $self->main_pkg->cancel(%options);
787 my $conf = new FS::Conf;
789 warn "cust_pkg::cancel called with options".
790 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
793 local $SIG{HUP} = 'IGNORE';
794 local $SIG{INT} = 'IGNORE';
795 local $SIG{QUIT} = 'IGNORE';
796 local $SIG{TERM} = 'IGNORE';
797 local $SIG{TSTP} = 'IGNORE';
798 local $SIG{PIPE} = 'IGNORE';
800 my $oldAutoCommit = $FS::UID::AutoCommit;
801 local $FS::UID::AutoCommit = 0;
804 my $old = $self->select_for_update;
806 if ( $old->get('cancel') || $self->get('cancel') ) {
807 dbh->rollback if $oldAutoCommit;
808 return ""; # no error
811 # XXX possibly set cancel_time to the expire date?
812 my $cancel_time = $options{'time'} || time;
813 my $date = $options{'date'} if $options{'date'}; # expire/cancel later
814 $date = '' if ($date && $date <= $cancel_time); # complain instead?
816 #race condition: usage could be ongoing until unprovisioned
817 #resolved by performing a change package instead (which unprovisions) and
819 if ( !$options{nobill} && !$date ) {
820 # && $conf->exists('bill_usage_on_cancel') ) { #calc_cancel checks this
821 my $copy = $self->new({$self->hash});
823 $copy->cust_main->bill( 'pkg_list' => [ $copy ],
825 'time' => $cancel_time );
826 warn "Error billing during cancel, custnum ".
827 #$self->cust_main->custnum. ": $error"
832 if ( $options{'reason'} ) {
833 $error = $self->insert_reason( 'reason' => $options{'reason'},
834 'action' => $date ? 'expire' : 'cancel',
835 'date' => $date ? $date : $cancel_time,
836 'reason_otaker' => $options{'reason_otaker'},
839 dbh->rollback if $oldAutoCommit;
840 return "Error inserting cust_pkg_reason: $error";
844 my %svc_cancel_opt = ();
845 $svc_cancel_opt{'date'} = $date if $date;
846 foreach my $cust_svc (
849 sort { $a->[1] <=> $b->[1] }
850 map { [ $_, $_->svc_x ? $_->svc_x->table_info->{'cancel_weight'} : -1 ]; }
851 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
853 my $part_svc = $cust_svc->part_svc;
854 next if ( defined($part_svc) and $part_svc->preserve );
855 my $error = $cust_svc->cancel( %svc_cancel_opt );
858 $dbh->rollback if $oldAutoCommit;
859 return 'Error '. ($svc_cancel_opt{'date'} ? 'expiring' : 'canceling' ).
865 # credit remaining time if appropriate
867 if ( exists($options{'unused_credit'}) ) {
868 $do_credit = $options{'unused_credit'};
871 $do_credit = $self->part_pkg->option('unused_credit_cancel', 1);
874 my $error = $self->credit_remaining('cancel', $cancel_time);
876 $dbh->rollback if $oldAutoCommit;
883 my %hash = $self->hash;
885 $hash{'expire'} = $date;
887 $hash{'cancel'} = $cancel_time;
889 $hash{'change_custnum'} = $options{'change_custnum'};
891 my $new = new FS::cust_pkg ( \%hash );
892 $error = $new->replace( $self, options => { $self->options } );
893 if ( $self->change_to_pkgnum ) {
894 my $change_to = FS::cust_pkg->by_key($self->change_to_pkgnum);
895 $error ||= $change_to->cancel || $change_to->delete;
898 $dbh->rollback if $oldAutoCommit;
902 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
903 $error = $supp_pkg->cancel(%options, 'from_main' => 1);
905 $dbh->rollback if $oldAutoCommit;
906 return "canceling supplemental pkg#".$supp_pkg->pkgnum.": $error";
910 foreach my $usage ( $self->cust_pkg_usage ) {
911 $error = $usage->delete;
913 $dbh->rollback if $oldAutoCommit;
914 return "deleting usage pools: $error";
918 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
919 return '' if $date; #no errors
921 my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ } $self->cust_main->invoicing_list;
922 if ( !$options{'quiet'} &&
923 $conf->exists('emailcancel', $self->cust_main->agentnum) &&
925 my $msgnum = $conf->config('cancel_msgnum', $self->cust_main->agentnum);
928 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum });
929 $error = $msg_template->send( 'cust_main' => $self->cust_main,
934 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
935 'to' => \@invoicing_list,
936 'subject' => ( $conf->config('cancelsubject') || 'Cancellation Notice' ),
937 'body' => [ map "$_\n", $conf->config('cancelmessage') ],
940 #should this do something on errors?
947 =item cancel_if_expired [ NOW_TIMESTAMP ]
949 Cancels this package if its expire date has been reached.
953 sub cancel_if_expired {
955 my $time = shift || time;
956 return '' unless $self->expire && $self->expire <= $time;
957 my $error = $self->cancel;
959 return "Error cancelling expired pkg ". $self->pkgnum. " for custnum ".
960 $self->custnum. ": $error";
967 "Un-cancels" this package: Orders a new package with the same custnum, pkgpart,
968 locationnum, (other fields?). Attempts to re-provision cancelled services
969 using history information (errors at this stage are not fatal).
971 cust_pkg: pass a scalar reference, will be filled in with the new cust_pkg object
973 svc_fatal: service provisioning errors are fatal
975 svc_errors: pass an array reference, will be filled in with any provisioning errors
977 main_pkgnum: link the package as a supplemental package of this one. For
983 my( $self, %options ) = @_;
985 #in case you try do do $uncancel-date = $cust_pkg->uncacel
986 return '' unless $self->get('cancel');
988 if ( $self->main_pkgnum and !$options{'main_pkgnum'} ) {
989 return $self->main_pkg->uncancel(%options);
996 local $SIG{HUP} = 'IGNORE';
997 local $SIG{INT} = 'IGNORE';
998 local $SIG{QUIT} = 'IGNORE';
999 local $SIG{TERM} = 'IGNORE';
1000 local $SIG{TSTP} = 'IGNORE';
1001 local $SIG{PIPE} = 'IGNORE';
1003 my $oldAutoCommit = $FS::UID::AutoCommit;
1004 local $FS::UID::AutoCommit = 0;
1008 # insert the new package
1011 my $cust_pkg = new FS::cust_pkg {
1012 last_bill => ( $options{'last_bill'} || $self->get('last_bill') ),
1013 bill => ( $options{'bill'} || $self->get('bill') ),
1015 uncancel_pkgnum => $self->pkgnum,
1016 main_pkgnum => ($options{'main_pkgnum'} || ''),
1017 map { $_ => $self->get($_) } qw(
1018 custnum pkgpart locationnum
1020 susp adjourn resume expire start_date contract_end dundate
1021 change_date change_pkgpart change_locationnum
1022 manual_flag no_auto quantity agent_pkgid recur_show_zero setup_show_zero
1026 my $error = $cust_pkg->insert(
1027 'change' => 1, #supresses any referral credit to a referring customer
1028 'allow_pkgpart' => 1, # allow this even if the package def is disabled
1031 $dbh->rollback if $oldAutoCommit;
1039 #find historical services within this timeframe before the package cancel
1040 # (incompatible with "time" option to cust_pkg->cancel?)
1041 my $fuzz = 2 * 60; #2 minutes? too much? (might catch separate unprovision)
1042 # too little? (unprovisioing export delay?)
1043 my($end, $start) = ( $self->get('cancel'), $self->get('cancel') - $fuzz );
1044 my @h_cust_svc = $self->h_cust_svc( $end, $start );
1047 foreach my $h_cust_svc (@h_cust_svc) {
1048 my $h_svc_x = $h_cust_svc->h_svc_x( $end, $start );
1049 #next unless $h_svc_x; #should this happen?
1050 (my $table = $h_svc_x->table) =~ s/^h_//;
1051 require "FS/$table.pm";
1052 my $class = "FS::$table";
1053 my $svc_x = $class->new( {
1054 'pkgnum' => $cust_pkg->pkgnum,
1055 'svcpart' => $h_cust_svc->svcpart,
1056 map { $_ => $h_svc_x->get($_) } fields($table)
1060 if ( $h_svc_x->isa('FS::h_svc_Radius_Mixin') ) {
1061 $svc_x->usergroup( [ $h_svc_x->h_usergroup($end, $start) ] );
1064 my $svc_error = $svc_x->insert;
1066 if ( $options{svc_fatal} ) {
1067 $dbh->rollback if $oldAutoCommit;
1070 # if we've failed to insert the svc_x object, svc_Common->insert
1071 # will have removed the cust_svc already. if not, then both records
1072 # were inserted but we failed for some other reason (export, most
1073 # likely). in that case, report the error and delete the records.
1074 push @svc_errors, $svc_error;
1075 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svc_x->svcnum });
1077 # except if export_insert failed, export_delete probably won't be
1079 local $FS::svc_Common::noexport_hack = 1;
1080 my $cleanup_error = $svc_x->delete; # also deletes cust_svc
1081 if ( $cleanup_error ) { # and if THAT fails, then run away
1082 $dbh->rollback if $oldAutoCommit;
1083 return $cleanup_error;
1088 } #foreach $h_cust_svc
1090 #these are pretty rare, but should handle them
1091 # - dsl_device (mac addresses)
1092 # - phone_device (mac addresses)
1093 # - dsl_note (ikano notes)
1094 # - domain_record (i.e. restore DNS information w/domains)
1095 # - inventory_item(?) (inventory w/un-cancelling service?)
1096 # - nas (svc_broaband nas stuff)
1097 #this stuff is unused in the wild afaik
1098 # - mailinglistmember
1100 # - svc_domain.parent_svcnum?
1101 # - acct_snarf (ancient mail fetching config)
1102 # - cgp_rule (communigate)
1103 # - cust_svc_option (used by our Tron stuff)
1104 # - acct_rt_transaction (used by our time worked stuff)
1107 # also move over any services that didn't unprovision at cancellation
1110 foreach my $cust_svc ( qsearch('cust_svc', { pkgnum => $self->pkgnum } ) ) {
1111 $cust_svc->pkgnum( $cust_pkg->pkgnum );
1112 my $error = $cust_svc->replace;
1114 $dbh->rollback if $oldAutoCommit;
1120 # Uncancel any supplemental packages, and make them supplemental to the
1124 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1126 $error = $supp_pkg->uncancel(%options, 'main_pkgnum' => $cust_pkg->pkgnum);
1128 $dbh->rollback if $oldAutoCommit;
1129 return "canceling supplemental pkg#".$supp_pkg->pkgnum.": $error";
1137 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1139 ${ $options{cust_pkg} } = $cust_pkg if ref($options{cust_pkg});
1140 @{ $options{svc_errors} } = @svc_errors if ref($options{svc_errors});
1147 Cancels any pending expiration (sets the expire field to null).
1149 If there is an error, returns the error, otherwise returns false.
1154 my( $self, %options ) = @_;
1157 local $SIG{HUP} = 'IGNORE';
1158 local $SIG{INT} = 'IGNORE';
1159 local $SIG{QUIT} = 'IGNORE';
1160 local $SIG{TERM} = 'IGNORE';
1161 local $SIG{TSTP} = 'IGNORE';
1162 local $SIG{PIPE} = 'IGNORE';
1164 my $oldAutoCommit = $FS::UID::AutoCommit;
1165 local $FS::UID::AutoCommit = 0;
1168 my $old = $self->select_for_update;
1170 my $pkgnum = $old->pkgnum;
1171 if ( $old->get('cancel') || $self->get('cancel') ) {
1172 dbh->rollback if $oldAutoCommit;
1173 return "Can't unexpire cancelled package $pkgnum";
1174 # or at least it's pointless
1177 unless ( $old->get('expire') && $self->get('expire') ) {
1178 dbh->rollback if $oldAutoCommit;
1179 return ""; # no error
1182 my %hash = $self->hash;
1183 $hash{'expire'} = '';
1184 my $new = new FS::cust_pkg ( \%hash );
1185 $error = $new->replace( $self, options => { $self->options } );
1187 $dbh->rollback if $oldAutoCommit;
1191 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1197 =item suspend [ OPTION => VALUE ... ]
1199 Suspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
1200 package, then suspends the package itself (sets the susp field to now).
1202 Available options are:
1206 =item reason - can be set to a cancellation reason (see L<FS:reason>),
1207 either a reasonnum of an existing reason, or passing a hashref will create
1208 a new reason. The hashref should have the following keys:
1209 - typenum - Reason type (see L<FS::reason_type>
1210 - reason - Text of the new reason.
1212 =item date - can be set to a unix style timestamp to specify when to
1215 =item time - can be set to override the current time, for calculation
1216 of final invoices or unused-time credits
1218 =item resume_date - can be set to a time when the package should be
1219 unsuspended. This may be more convenient than calling C<unsuspend()>
1222 =item from_main - allows a supplemental package to be suspended, rather
1223 than redirecting the method call to its main package. For internal use.
1227 If there is an error, returns the error, otherwise returns false.
1232 my( $self, %options ) = @_;
1235 # pass all suspend/cancel actions to the main package
1236 if ( $self->main_pkgnum and !$options{'from_main'} ) {
1237 return $self->main_pkg->suspend(%options);
1240 local $SIG{HUP} = 'IGNORE';
1241 local $SIG{INT} = 'IGNORE';
1242 local $SIG{QUIT} = 'IGNORE';
1243 local $SIG{TERM} = 'IGNORE';
1244 local $SIG{TSTP} = 'IGNORE';
1245 local $SIG{PIPE} = 'IGNORE';
1247 my $oldAutoCommit = $FS::UID::AutoCommit;
1248 local $FS::UID::AutoCommit = 0;
1251 my $old = $self->select_for_update;
1253 my $pkgnum = $old->pkgnum;
1254 if ( $old->get('cancel') || $self->get('cancel') ) {
1255 dbh->rollback if $oldAutoCommit;
1256 return "Can't suspend cancelled package $pkgnum";
1259 if ( $old->get('susp') || $self->get('susp') ) {
1260 dbh->rollback if $oldAutoCommit;
1261 return ""; # no error # complain on adjourn?
1264 my $suspend_time = $options{'time'} || time;
1265 my $date = $options{date} if $options{date}; # adjourn/suspend later
1266 $date = '' if ($date && $date <= $suspend_time); # complain instead?
1268 if ( $date && $old->get('expire') && $old->get('expire') < $date ) {
1269 dbh->rollback if $oldAutoCommit;
1270 return "Package $pkgnum expires before it would be suspended.";
1273 # some false laziness with sub cancel
1274 if ( !$options{nobill} && !$date &&
1275 $self->part_pkg->option('bill_suspend_as_cancel',1) ) {
1276 # kind of a kludge--'bill_suspend_as_cancel' to avoid having to
1277 # make the entire cust_main->bill path recognize 'suspend' and
1278 # 'cancel' separately.
1279 warn "Billing $pkgnum on suspension (at $suspend_time)\n" if $DEBUG;
1280 my $copy = $self->new({$self->hash});
1282 $copy->cust_main->bill( 'pkg_list' => [ $copy ],
1284 'time' => $suspend_time );
1285 warn "Error billing during suspend, custnum ".
1286 #$self->cust_main->custnum. ": $error"
1291 if ( $options{'reason'} ) {
1292 $error = $self->insert_reason( 'reason' => $options{'reason'},
1293 'action' => $date ? 'adjourn' : 'suspend',
1294 'date' => $date ? $date : $suspend_time,
1295 'reason_otaker' => $options{'reason_otaker'},
1298 dbh->rollback if $oldAutoCommit;
1299 return "Error inserting cust_pkg_reason: $error";
1303 my %hash = $self->hash;
1305 $hash{'adjourn'} = $date;
1307 $hash{'susp'} = $suspend_time;
1310 my $resume_date = $options{'resume_date'} || 0;
1311 if ( $resume_date > ($date || $suspend_time) ) {
1312 $hash{'resume'} = $resume_date;
1315 $options{options} ||= {};
1317 my $new = new FS::cust_pkg ( \%hash );
1318 $error = $new->replace( $self, options => { $self->options,
1319 %{ $options{options} },
1323 $dbh->rollback if $oldAutoCommit;
1328 # credit remaining time if appropriate
1329 if ( $self->part_pkg->option('unused_credit_suspend', 1) ) {
1330 my $error = $self->credit_remaining('suspend', $suspend_time);
1332 $dbh->rollback if $oldAutoCommit;
1339 foreach my $cust_svc (
1340 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
1342 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
1344 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
1345 $dbh->rollback if $oldAutoCommit;
1346 return "Illegal svcdb value in part_svc!";
1349 require "FS/$svcdb.pm";
1351 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
1353 $error = $svc->suspend;
1355 $dbh->rollback if $oldAutoCommit;
1358 my( $label, $value ) = $cust_svc->label;
1359 push @labels, "$label: $value";
1363 my $conf = new FS::Conf;
1364 if ( $conf->config('suspend_email_admin') ) {
1366 my $error = send_email(
1367 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
1368 #invoice_from ??? well as good as any
1369 'to' => $conf->config('suspend_email_admin'),
1370 'subject' => 'FREESIDE NOTIFICATION: Customer package suspended',
1372 "This is an automatic message from your Freeside installation\n",
1373 "informing you that the following customer package has been suspended:\n",
1375 'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
1376 'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
1377 ( map { "Service : $_\n" } @labels ),
1382 warn "WARNING: can't send suspension admin email (suspending anyway): ".
1390 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1391 $error = $supp_pkg->suspend(%options, 'from_main' => 1);
1393 $dbh->rollback if $oldAutoCommit;
1394 return "suspending supplemental pkg#".$supp_pkg->pkgnum.": $error";
1398 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1403 =item credit_remaining MODE TIME
1405 Generate a credit for this package for the time remaining in the current
1406 billing period. MODE is either "suspend" or "cancel" (determines the
1407 credit type). TIME is the time of suspension/cancellation. Both arguments
1412 sub credit_remaining {
1413 # Add a credit for remaining service
1414 my ($self, $mode, $time) = @_;
1415 die 'credit_remaining requires suspend or cancel'
1416 unless $mode eq 'suspend' or $mode eq 'cancel';
1417 die 'no suspend/cancel time' unless $time > 0;
1419 my $conf = FS::Conf->new;
1420 my $reason_type = $conf->config($mode.'_credit_type');
1422 my $last_bill = $self->getfield('last_bill') || 0;
1423 my $next_bill = $self->getfield('bill') || 0;
1424 if ( $last_bill > 0 # the package has been billed
1425 and $next_bill > 0 # the package has a next bill date
1426 and $next_bill >= $time # which is in the future
1428 my $remaining_value = $self->calc_remain('time' => $time);
1429 if ( $remaining_value > 0 ) {
1430 warn "Crediting for $remaining_value on package ".$self->pkgnum."\n"
1432 my $error = $self->cust_main->credit(
1434 'Credit for unused time on '. $self->part_pkg->pkg,
1435 'reason_type' => $reason_type,
1437 return "Error crediting customer \$$remaining_value for unused time".
1438 " on ". $self->part_pkg->pkg. ": $error"
1440 } #if $remaining_value
1441 } #if $last_bill, etc.
1445 =item unsuspend [ OPTION => VALUE ... ]
1447 Unsuspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
1448 package, then unsuspends the package itself (clears the susp field and the
1449 adjourn field if it is in the past). If the suspend reason includes an
1450 unsuspension package, that package will be ordered.
1452 Available options are:
1458 Can be set to a date to unsuspend the package in the future (the 'resume'
1461 =item adjust_next_bill
1463 Can be set true to adjust the next bill date forward by
1464 the amount of time the account was inactive. This was set true by default
1465 in the past (from 1.4.2 and 1.5.0pre6 through 1.7.0), but now needs to be
1466 explicitly requested with this option or in the price plan.
1470 If there is an error, returns the error, otherwise returns false.
1475 my( $self, %opt ) = @_;
1478 # pass all suspend/cancel actions to the main package
1479 if ( $self->main_pkgnum and !$opt{'from_main'} ) {
1480 return $self->main_pkg->unsuspend(%opt);
1483 local $SIG{HUP} = 'IGNORE';
1484 local $SIG{INT} = 'IGNORE';
1485 local $SIG{QUIT} = 'IGNORE';
1486 local $SIG{TERM} = 'IGNORE';
1487 local $SIG{TSTP} = 'IGNORE';
1488 local $SIG{PIPE} = 'IGNORE';
1490 my $oldAutoCommit = $FS::UID::AutoCommit;
1491 local $FS::UID::AutoCommit = 0;
1494 my $old = $self->select_for_update;
1496 my $pkgnum = $old->pkgnum;
1497 if ( $old->get('cancel') || $self->get('cancel') ) {
1498 $dbh->rollback if $oldAutoCommit;
1499 return "Can't unsuspend cancelled package $pkgnum";
1502 unless ( $old->get('susp') && $self->get('susp') ) {
1503 $dbh->rollback if $oldAutoCommit;
1504 return ""; # no error # complain instead?
1507 my $date = $opt{'date'};
1508 if ( $date and $date > time ) { # return an error if $date <= time?
1510 if ( $old->get('expire') && $old->get('expire') < $date ) {
1511 $dbh->rollback if $oldAutoCommit;
1512 return "Package $pkgnum expires before it would be unsuspended.";
1515 my $new = new FS::cust_pkg { $self->hash };
1516 $new->set('resume', $date);
1517 $error = $new->replace($self, options => $self->options);
1520 $dbh->rollback if $oldAutoCommit;
1524 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1532 foreach my $cust_svc (
1533 qsearch('cust_svc',{'pkgnum'=> $self->pkgnum } )
1535 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
1537 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
1538 $dbh->rollback if $oldAutoCommit;
1539 return "Illegal svcdb value in part_svc!";
1542 require "FS/$svcdb.pm";
1544 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
1546 $error = $svc->unsuspend;
1548 $dbh->rollback if $oldAutoCommit;
1551 my( $label, $value ) = $cust_svc->label;
1552 push @labels, "$label: $value";
1557 my $cust_pkg_reason = $self->last_cust_pkg_reason('susp');
1558 my $reason = $cust_pkg_reason ? $cust_pkg_reason->reason : '';
1560 my %hash = $self->hash;
1561 my $inactive = time - $hash{'susp'};
1563 my $conf = new FS::Conf;
1565 if ( $inactive > 0 &&
1566 ( $hash{'bill'} || $hash{'setup'} ) &&
1567 ( $opt{'adjust_next_bill'} ||
1568 $conf->exists('unsuspend-always_adjust_next_bill_date') ||
1569 $self->part_pkg->option('unsuspend_adjust_bill', 1) )
1572 $hash{'bill'} = ( $hash{'bill'} || $hash{'setup'} ) + $inactive;
1577 $hash{'adjourn'} = '' if $hash{'adjourn'} and $hash{'adjourn'} < time;
1578 $hash{'resume'} = '' if !$hash{'adjourn'};
1579 my $new = new FS::cust_pkg ( \%hash );
1580 $error = $new->replace( $self, options => { $self->options } );
1582 $dbh->rollback if $oldAutoCommit;
1588 if ( $reason && $reason->unsuspend_pkgpart ) {
1589 my $part_pkg = FS::part_pkg->by_key($reason->unsuspend_pkgpart)
1590 or $error = "Unsuspend package definition ".$reason->unsuspend_pkgpart.
1592 my $start_date = $self->cust_main->next_bill_date
1593 if $reason->unsuspend_hold;
1596 $unsusp_pkg = FS::cust_pkg->new({
1597 'custnum' => $self->custnum,
1598 'pkgpart' => $reason->unsuspend_pkgpart,
1599 'start_date' => $start_date,
1600 'locationnum' => $self->locationnum,
1601 # discount? probably not...
1604 $error ||= $self->cust_main->order_pkg( 'cust_pkg' => $unsusp_pkg );
1608 $dbh->rollback if $oldAutoCommit;
1613 if ( $conf->config('unsuspend_email_admin') ) {
1615 my $error = send_email(
1616 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
1617 #invoice_from ??? well as good as any
1618 'to' => $conf->config('unsuspend_email_admin'),
1619 'subject' => 'FREESIDE NOTIFICATION: Customer package unsuspended', 'body' => [
1620 "This is an automatic message from your Freeside installation\n",
1621 "informing you that the following customer package has been unsuspended:\n",
1623 'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
1624 'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
1625 ( map { "Service : $_\n" } @labels ),
1627 "An unsuspension fee was charged: ".
1628 $unsusp_pkg->part_pkg->pkg_comment."\n"
1635 warn "WARNING: can't send unsuspension admin email (unsuspending anyway): ".
1641 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1642 $error = $supp_pkg->unsuspend(%opt, 'from_main' => 1);
1644 $dbh->rollback if $oldAutoCommit;
1645 return "unsuspending supplemental pkg#".$supp_pkg->pkgnum.": $error";
1649 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1656 Cancels any pending suspension (sets the adjourn field to null).
1658 If there is an error, returns the error, otherwise returns false.
1663 my( $self, %options ) = @_;
1666 local $SIG{HUP} = 'IGNORE';
1667 local $SIG{INT} = 'IGNORE';
1668 local $SIG{QUIT} = 'IGNORE';
1669 local $SIG{TERM} = 'IGNORE';
1670 local $SIG{TSTP} = 'IGNORE';
1671 local $SIG{PIPE} = 'IGNORE';
1673 my $oldAutoCommit = $FS::UID::AutoCommit;
1674 local $FS::UID::AutoCommit = 0;
1677 my $old = $self->select_for_update;
1679 my $pkgnum = $old->pkgnum;
1680 if ( $old->get('cancel') || $self->get('cancel') ) {
1681 dbh->rollback if $oldAutoCommit;
1682 return "Can't unadjourn cancelled package $pkgnum";
1683 # or at least it's pointless
1686 if ( $old->get('susp') || $self->get('susp') ) {
1687 dbh->rollback if $oldAutoCommit;
1688 return "Can't unadjourn suspended package $pkgnum";
1689 # perhaps this is arbitrary
1692 unless ( $old->get('adjourn') && $self->get('adjourn') ) {
1693 dbh->rollback if $oldAutoCommit;
1694 return ""; # no error
1697 my %hash = $self->hash;
1698 $hash{'adjourn'} = '';
1699 $hash{'resume'} = '';
1700 my $new = new FS::cust_pkg ( \%hash );
1701 $error = $new->replace( $self, options => { $self->options } );
1703 $dbh->rollback if $oldAutoCommit;
1707 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1714 =item change HASHREF | OPTION => VALUE ...
1716 Changes this package: cancels it and creates a new one, with a different
1717 pkgpart or locationnum or both. All services are transferred to the new
1718 package (no change will be made if this is not possible).
1720 Options may be passed as a list of key/value pairs or as a hash reference.
1727 New locationnum, to change the location for this package.
1731 New FS::cust_location object, to create a new location and assign it
1736 New FS::cust_main object, to create a new customer and assign the new package
1741 New pkgpart (see L<FS::part_pkg>).
1745 New refnum (see L<FS::part_referral>).
1749 New quantity; if unspecified, the new package will have the same quantity
1754 "New" (existing) FS::cust_pkg object. The package's services and other
1755 attributes will be transferred to this package.
1759 Set to true to transfer billing dates (start_date, setup, last_bill, bill,
1760 susp, adjourn, cancel, expire, and contract_end) to the new package.
1762 =item unprotect_svcs
1764 Normally, change() will rollback and return an error if some services
1765 can't be transferred (also see the I<cust_pkg-change_svcpart> config option).
1766 If unprotect_svcs is true, this method will transfer as many services as
1767 it can and then unconditionally cancel the old package.
1771 At least one of locationnum, cust_location, pkgpart, refnum, cust_main, or
1772 cust_pkg must be specified (otherwise, what's the point?)
1774 Returns either the new FS::cust_pkg object or a scalar error.
1778 my $err_or_new_cust_pkg = $old_cust_pkg->change
1782 #some false laziness w/order
1785 my $opt = ref($_[0]) ? shift : { @_ };
1787 my $conf = new FS::Conf;
1789 # Transactionize this whole mess
1790 local $SIG{HUP} = 'IGNORE';
1791 local $SIG{INT} = 'IGNORE';
1792 local $SIG{QUIT} = 'IGNORE';
1793 local $SIG{TERM} = 'IGNORE';
1794 local $SIG{TSTP} = 'IGNORE';
1795 local $SIG{PIPE} = 'IGNORE';
1797 my $oldAutoCommit = $FS::UID::AutoCommit;
1798 local $FS::UID::AutoCommit = 0;
1807 $hash{'setup'} = $time if $self->setup;
1809 $hash{'change_date'} = $time;
1810 $hash{"change_$_"} = $self->$_()
1811 foreach qw( pkgnum pkgpart locationnum );
1813 if ( $opt->{'cust_location'} ) {
1814 $error = $opt->{'cust_location'}->find_or_insert;
1816 $dbh->rollback if $oldAutoCommit;
1817 return "creating location record: $error";
1819 $opt->{'locationnum'} = $opt->{'cust_location'}->locationnum;
1822 if ( $opt->{'cust_pkg'} ) {
1823 # treat changing to a package with a different pkgpart as a
1824 # pkgpart change (because it is)
1825 $opt->{'pkgpart'} = $opt->{'cust_pkg'}->pkgpart;
1828 # whether to override pkgpart checking on the new package
1829 my $same_pkgpart = 1;
1830 if ( $opt->{'pkgpart'} and ( $opt->{'pkgpart'} != $self->pkgpart ) ) {
1834 my $unused_credit = 0;
1835 my $keep_dates = $opt->{'keep_dates'};
1836 # Special case. If the pkgpart is changing, and the customer is
1837 # going to be credited for remaining time, don't keep setup, bill,
1838 # or last_bill dates, and DO pass the flag to cancel() to credit
1840 if ( $opt->{'pkgpart'}
1841 and $opt->{'pkgpart'} != $self->pkgpart
1842 and $self->part_pkg->option('unused_credit_change', 1) ) {
1845 $hash{$_} = '' foreach qw(setup bill last_bill);
1848 if ( $keep_dates ) {
1849 foreach my $date ( qw(setup bill last_bill susp adjourn cancel expire
1850 resume start_date contract_end ) ) {
1851 $hash{$date} = $self->getfield($date);
1854 # always keep this date, regardless of anything
1855 # (the date of the package change is in a different field)
1856 $hash{'order_date'} = $self->getfield('order_date');
1858 # allow $opt->{'locationnum'} = '' to specifically set it to null
1859 # (i.e. customer default location)
1860 $opt->{'locationnum'} = $self->locationnum if !exists($opt->{'locationnum'});
1862 # usually this doesn't matter. the two cases where it does are:
1863 # 1. unused_credit_change + pkgpart change + setup fee on the new package
1865 # 2. (more importantly) changing a package before it's billed
1866 $hash{'waive_setup'} = $self->waive_setup;
1868 my $custnum = $self->custnum;
1869 if ( $opt->{cust_main} ) {
1870 my $cust_main = $opt->{cust_main};
1871 unless ( $cust_main->custnum ) {
1872 my $error = $cust_main->insert( @{ $opt->{cust_main_insert_args}||[] } );
1874 $dbh->rollback if $oldAutoCommit;
1875 return "inserting customer record: $error";
1878 $custnum = $cust_main->custnum;
1881 $hash{'contactnum'} = $opt->{'contactnum'} if $opt->{'contactnum'};
1884 if ( $opt->{'cust_pkg'} ) {
1885 # The target package already exists; update it to show that it was
1886 # changed from this package.
1887 $cust_pkg = $opt->{'cust_pkg'};
1889 foreach ( qw( pkgnum pkgpart locationnum ) ) {
1890 $cust_pkg->set("change_$_", $self->get($_));
1892 $cust_pkg->set('change_date', $time);
1893 $error = $cust_pkg->replace;
1896 # Create the new package.
1897 $cust_pkg = new FS::cust_pkg {
1898 custnum => $custnum,
1899 locationnum => $opt->{'locationnum'},
1900 ( map { $_ => ( $opt->{$_} || $self->$_() ) }
1901 qw( pkgpart quantity refnum salesnum )
1905 $error = $cust_pkg->insert( 'change' => 1,
1906 'allow_pkgpart' => $same_pkgpart );
1909 $dbh->rollback if $oldAutoCommit;
1910 return "inserting new package: $error";
1913 # Transfer services and cancel old package.
1915 $error = $self->transfer($cust_pkg);
1916 if ($error and $error == 0) {
1917 # $old_pkg->transfer failed.
1918 $dbh->rollback if $oldAutoCommit;
1919 return "transferring $error";
1922 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
1923 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
1924 $error = $self->transfer($cust_pkg, 'change_svcpart'=>1 );
1925 if ($error and $error == 0) {
1926 # $old_pkg->transfer failed.
1927 $dbh->rollback if $oldAutoCommit;
1928 return "converting $error";
1932 # We set unprotect_svcs when executing a "future package change". It's
1933 # not a user-interactive operation, so returning an error means the
1934 # package change will just fail. Rather than have that happen, we'll
1935 # let leftover services be deleted.
1936 if ($error > 0 and !$opt->{'unprotect_svcs'}) {
1937 # Transfers were successful, but we still had services left on the old
1938 # package. We can't change the package under this circumstances, so abort.
1939 $dbh->rollback if $oldAutoCommit;
1940 return "unable to transfer all services";
1943 #reset usage if changing pkgpart
1944 # AND usage rollover is off (otherwise adds twice, now and at package bill)
1945 if ($self->pkgpart != $cust_pkg->pkgpart) {
1946 my $part_pkg = $cust_pkg->part_pkg;
1947 $error = $part_pkg->reset_usage($cust_pkg, $part_pkg->is_prepaid
1951 if $part_pkg->can('reset_usage') && ! $part_pkg->option('usage_rollover',1);
1954 $dbh->rollback if $oldAutoCommit;
1955 return "setting usage values: $error";
1958 # if NOT changing pkgpart, transfer any usage pools over
1959 foreach my $usage ($self->cust_pkg_usage) {
1960 $usage->set('pkgnum', $cust_pkg->pkgnum);
1961 $error = $usage->replace;
1963 $dbh->rollback if $oldAutoCommit;
1964 return "transferring usage pools: $error";
1969 # transfer discounts, if we're not changing pkgpart
1970 if ( $same_pkgpart ) {
1971 foreach my $old_discount ($self->cust_pkg_discount_active) {
1972 # don't remove the old discount, we may still need to bill that package.
1973 my $new_discount = new FS::cust_pkg_discount {
1974 'pkgnum' => $cust_pkg->pkgnum,
1975 'discountnum' => $old_discount->discountnum,
1976 'months_used' => $old_discount->months_used,
1978 $error = $new_discount->insert;
1980 $dbh->rollback if $oldAutoCommit;
1981 return "transferring discounts: $error";
1986 # transfer (copy) invoice details
1987 foreach my $detail ($self->cust_pkg_detail) {
1988 my $new_detail = FS::cust_pkg_detail->new({ $detail->hash });
1989 $new_detail->set('pkgdetailnum', '');
1990 $new_detail->set('pkgnum', $cust_pkg->pkgnum);
1991 $error = $new_detail->insert;
1993 $dbh->rollback if $oldAutoCommit;
1994 return "transferring package notes: $error";
2000 if ( !$opt->{'cust_pkg'} ) {
2001 # Order any supplemental packages.
2002 my $part_pkg = $cust_pkg->part_pkg;
2003 my @old_supp_pkgs = $self->supplemental_pkgs;
2004 foreach my $link ($part_pkg->supp_part_pkg_link) {
2006 foreach (@old_supp_pkgs) {
2007 if ($_->pkgpart == $link->dst_pkgpart) {
2009 $_->pkgpart(0); # so that it can't match more than once
2013 # false laziness with FS::cust_main::Packages::order_pkg
2014 my $new = FS::cust_pkg->new({
2015 pkgpart => $link->dst_pkgpart,
2016 pkglinknum => $link->pkglinknum,
2017 custnum => $custnum,
2018 main_pkgnum => $cust_pkg->pkgnum,
2019 locationnum => $cust_pkg->locationnum,
2020 start_date => $cust_pkg->start_date,
2021 order_date => $cust_pkg->order_date,
2022 expire => $cust_pkg->expire,
2023 adjourn => $cust_pkg->adjourn,
2024 contract_end => $cust_pkg->contract_end,
2025 refnum => $cust_pkg->refnum,
2026 discountnum => $cust_pkg->discountnum,
2027 waive_setup => $cust_pkg->waive_setup,
2029 if ( $old and $opt->{'keep_dates'} ) {
2030 foreach (qw(setup bill last_bill)) {
2031 $new->set($_, $old->get($_));
2034 $error = $new->insert( allow_pkgpart => $same_pkgpart );
2037 $error ||= $old->transfer($new);
2039 if ( $error and $error > 0 ) {
2040 # no reason why this should ever fail, but still...
2041 $error = "Unable to transfer all services from supplemental package ".
2045 $dbh->rollback if $oldAutoCommit;
2048 push @new_supp_pkgs, $new;
2050 } # if !$opt->{'cust_pkg'}
2051 # because if there is one, then supplemental packages would already
2052 # have been created for it.
2054 #Good to go, cancel old package. Notify 'cancel' of whether to credit
2056 #Don't allow billing the package (preceding period packages and/or
2057 #outstanding usage) if we are keeping dates (i.e. location changing),
2058 #because the new package will be billed for the same date range.
2059 #Supplemental packages are also canceled here.
2061 # during scheduled changes, avoid canceling the package we just
2063 $self->set('change_to_pkgnum' => '');
2065 $error = $self->cancel(
2067 unused_credit => $unused_credit,
2068 nobill => $keep_dates,
2069 change_custnum => ( $self->custnum != $custnum ? $custnum : '' ),
2072 $dbh->rollback if $oldAutoCommit;
2073 return "canceling old package: $error";
2076 if ( $conf->exists('cust_pkg-change_pkgpart-bill_now') ) {
2078 my $error = $cust_pkg->cust_main->bill(
2079 'pkg_list' => [ $cust_pkg, @new_supp_pkgs ]
2082 $dbh->rollback if $oldAutoCommit;
2083 return "billing new package: $error";
2087 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2093 =item change_later OPTION => VALUE...
2095 Schedule a package change for a later date. This actually orders the new
2096 package immediately, but sets its start date for a future date, and sets
2097 the current package to expire on the same date.
2099 If the package is already scheduled for a change, this can be called with
2100 'start_date' to change the scheduled date, or with pkgpart and/or
2101 locationnum to modify the package change. To cancel the scheduled change
2102 entirely, see C<abort_change>.
2110 The date for the package change. Required, and must be in the future.
2118 The pkgpart. locationnum, and quantity of the new package, with the same
2119 meaning as in C<change>.
2127 my $opt = ref($_[0]) ? shift : { @_ };
2129 my $oldAutoCommit = $FS::UID::AutoCommit;
2130 local $FS::UID::AutoCommit = 0;
2133 my $cust_main = $self->cust_main;
2135 my $date = delete $opt->{'start_date'} or return 'start_date required';
2137 if ( $date <= time ) {
2138 $dbh->rollback if $oldAutoCommit;
2139 return "start_date $date is in the past";
2144 if ( $self->change_to_pkgnum ) {
2145 my $change_to = FS::cust_pkg->by_key($self->change_to_pkgnum);
2146 my $new_pkgpart = $opt->{'pkgpart'}
2147 if $opt->{'pkgpart'} and $opt->{'pkgpart'} != $change_to->pkgpart;
2148 my $new_locationnum = $opt->{'locationnum'}
2149 if $opt->{'locationnum'} and $opt->{'locationnum'} != $change_to->locationnum;
2150 my $new_quantity = $opt->{'quantity'}
2151 if $opt->{'quantity'} and $opt->{'quantity'} != $change_to->quantity;
2152 if ( $new_pkgpart or $new_locationnum or $new_quantity ) {
2153 # it hasn't been billed yet, so in principle we could just edit
2154 # it in place (w/o a package change), but that's bad form.
2155 # So change the package according to the new options...
2156 my $err_or_pkg = $change_to->change(%$opt);
2157 if ( ref $err_or_pkg ) {
2158 # Then set that package up for a future start.
2159 $self->set('change_to_pkgnum', $err_or_pkg->pkgnum);
2160 $self->set('expire', $date); # in case it's different
2161 $err_or_pkg->set('start_date', $date);
2162 $err_or_pkg->set('change_date', '');
2163 $err_or_pkg->set('change_pkgnum', '');
2165 $error = $self->replace ||
2166 $err_or_pkg->replace ||
2167 $change_to->cancel ||
2170 $error = $err_or_pkg;
2172 } else { # change the start date only.
2173 $self->set('expire', $date);
2174 $change_to->set('start_date', $date);
2175 $error = $self->replace || $change_to->replace;
2178 $dbh->rollback if $oldAutoCommit;
2181 $dbh->commit if $oldAutoCommit;
2184 } # if $self->change_to_pkgnum
2186 my $new_pkgpart = $opt->{'pkgpart'}
2187 if $opt->{'pkgpart'} and $opt->{'pkgpart'} != $self->pkgpart;
2188 my $new_locationnum = $opt->{'locationnum'}
2189 if $opt->{'locationnum'} and $opt->{'locationnum'} != $self->locationnum;
2190 my $new_quantity = $opt->{'quantity'}
2191 if $opt->{'quantity'} and $opt->{'quantity'} != $self->quantity;
2193 return '' unless $new_pkgpart or $new_locationnum or $new_quantity; # wouldn't do anything
2195 # allow $opt->{'locationnum'} = '' to specifically set it to null
2196 # (i.e. customer default location)
2197 $opt->{'locationnum'} = $self->locationnum if !exists($opt->{'locationnum'});
2199 my $new = FS::cust_pkg->new( {
2200 custnum => $self->custnum,
2201 locationnum => $opt->{'locationnum'},
2202 start_date => $date,
2203 map { $_ => ( $opt->{$_} || $self->$_() ) }
2204 qw( pkgpart quantity refnum salesnum )
2206 $error = $new->insert('change' => 1,
2207 'allow_pkgpart' => ($new_pkgpart ? 0 : 1));
2209 $self->set('change_to_pkgnum', $new->pkgnum);
2210 $self->set('expire', $date);
2211 $error = $self->replace;
2214 $dbh->rollback if $oldAutoCommit;
2216 $dbh->commit if $oldAutoCommit;
2224 Cancels a future package change scheduled by C<change_later>.
2230 my $pkgnum = $self->change_to_pkgnum;
2231 my $change_to = FS::cust_pkg->by_key($pkgnum) if $pkgnum;
2234 $error = $change_to->cancel || $change_to->delete;
2235 return $error if $error;
2237 $self->set('change_to_pkgnum', '');
2238 $self->set('expire', '');
2242 =item set_quantity QUANTITY
2244 Change the package's quantity field. This is one of the few package properties
2245 that can safely be changed without canceling and reordering the package
2246 (because it doesn't affect tax eligibility). Returns an error or an
2253 $self = $self->replace_old; # just to make sure
2254 $self->quantity(shift);
2258 =item set_salesnum SALESNUM
2260 Change the package's salesnum (sales person) field. This is one of the few
2261 package properties that can safely be changed without canceling and reordering
2262 the package (because it doesn't affect tax eligibility). Returns an error or
2269 $self = $self->replace_old; # just to make sure
2270 $self->salesnum(shift);
2272 # XXX this should probably reassign any credit that's already been given
2275 =item modify_charge OPTIONS
2277 Change the properties of a one-time charge. The following properties can
2278 be changed this way:
2279 - pkg: the package description
2280 - classnum: the package class
2281 - additional: arrayref of additional invoice details to add to this package
2283 and, I<if the charge has not yet been billed>:
2284 - start_date: the date when it will be billed
2285 - amount: the setup fee to be charged
2286 - quantity: the multiplier for the setup fee
2288 If you pass 'adjust_commission' => 1, and the classnum changes, and there are
2289 commission credits linked to this charge, they will be recalculated.
2296 my $part_pkg = $self->part_pkg;
2297 my $pkgnum = $self->pkgnum;
2300 my $oldAutoCommit = $FS::UID::AutoCommit;
2301 local $FS::UID::AutoCommit = 0;
2303 return "Can't use modify_charge except on one-time charges"
2304 unless $part_pkg->freq eq '0';
2306 if ( length($opt{'pkg'}) and $part_pkg->pkg ne $opt{'pkg'} ) {
2307 $part_pkg->set('pkg', $opt{'pkg'});
2310 my %pkg_opt = $part_pkg->options;
2311 if ( ref($opt{'additional'}) ) {
2312 delete $pkg_opt{$_} foreach grep /^additional/, keys %pkg_opt;
2314 for ( $i = 0; exists($opt{'additional'}->[$i]); $i++ ) {
2315 $pkg_opt{ "additional_info$i" } = $opt{'additional'}->[$i];
2317 $pkg_opt{'additional_count'} = $i if $i > 0;
2321 if ( exists($opt{'classnum'}) and $part_pkg->classnum ne $opt{'classnum'} )
2324 $old_classnum = $part_pkg->classnum;
2325 $part_pkg->set('classnum', $opt{'classnum'});
2328 if ( !$self->get('setup') ) {
2329 # not yet billed, so allow amount and quantity
2330 if ( exists($opt{'quantity'})
2331 and $opt{'quantity'} != $self->quantity
2332 and $opt{'quantity'} > 0 ) {
2334 $self->set('quantity', $opt{'quantity'});
2336 if ( exists($opt{'start_date'})
2337 and $opt{'start_date'} != $self->start_date ) {
2339 $self->set('start_date', $opt{'start_date'});
2341 if ($self->modified) { # for quantity or start_date change
2342 my $error = $self->replace;
2343 return $error if $error;
2346 if ( exists($opt{'amount'})
2347 and $part_pkg->option('setup_fee') != $opt{'amount'}
2348 and $opt{'amount'} > 0 ) {
2350 $pkg_opt{'setup_fee'} = $opt{'amount'};
2351 # standard for one-time charges is to set comment = (formatted) amount
2352 # update it to avoid confusion
2353 my $conf = FS::Conf->new;
2354 $part_pkg->set('comment',
2355 ($conf->config('money_char') || '$') .
2356 sprintf('%.2f', $opt{'amount'})
2359 } # else simply ignore them; the UI shouldn't allow editing the fields
2361 my $error = $part_pkg->replace( options => \%pkg_opt );
2363 $dbh->rollback if $oldAutoCommit;
2367 if (defined $old_classnum) {
2368 # fix invoice grouping records
2369 my $old_catname = $old_classnum
2370 ? FS::pkg_class->by_key($old_classnum)->categoryname
2372 my $new_catname = $opt{'classnum'}
2373 ? $part_pkg->pkg_class->categoryname
2375 if ( $old_catname ne $new_catname ) {
2376 foreach my $cust_bill_pkg ($self->cust_bill_pkg) {
2377 # (there should only be one...)
2378 my @display = qsearch( 'cust_bill_pkg_display', {
2379 'billpkgnum' => $cust_bill_pkg->billpkgnum,
2380 'section' => $old_catname,
2382 foreach (@display) {
2383 $_->set('section', $new_catname);
2384 $error = $_->replace;
2386 $dbh->rollback if $oldAutoCommit;
2390 } # foreach $cust_bill_pkg
2393 if ( $opt{'adjust_commission'} ) {
2394 # fix commission credits...tricky.
2395 foreach my $cust_event ($self->cust_event) {
2396 my $part_event = $cust_event->part_event;
2397 foreach my $table (qw(sales agent)) {
2399 "FS::part_event::Action::Mixin::credit_${table}_pkg_class";
2400 my $credit = qsearchs('cust_credit', {
2401 'eventnum' => $cust_event->eventnum,
2403 if ( $part_event->isa($class) ) {
2404 # Yes, this results in current commission rates being applied
2405 # retroactively to a one-time charge. For accounting purposes
2406 # there ought to be some kind of time limit on doing this.
2407 my $amount = $part_event->_calc_credit($self);
2408 if ( $credit and $credit->amount ne $amount ) {
2409 # Void the old credit.
2410 $error = $credit->void('Package class changed');
2412 $dbh->rollback if $oldAutoCommit;
2413 return "$error (adjusting commission credit)";
2416 # redo the event action to recreate the credit.
2418 eval { $part_event->do_action( $self, $cust_event ) };
2420 $dbh->rollback if $oldAutoCommit;
2423 } # if $part_event->isa($class)
2425 } # foreach $cust_event
2426 } # if $opt{'adjust_commission'}
2427 } # if defined $old_classnum
2429 $dbh->commit if $oldAutoCommit;
2435 use Storable 'thaw';
2438 sub process_bulk_cust_pkg {
2440 my $param = thaw(decode_base64(shift));
2441 warn Dumper($param) if $DEBUG;
2443 my $old_part_pkg = qsearchs('part_pkg',
2444 { pkgpart => $param->{'old_pkgpart'} });
2445 my $new_part_pkg = qsearchs('part_pkg',
2446 { pkgpart => $param->{'new_pkgpart'} });
2447 die "Must select a new package type\n" unless $new_part_pkg;
2448 #my $keep_dates = $param->{'keep_dates'} || 0;
2449 my $keep_dates = 1; # there is no good reason to turn this off
2451 local $SIG{HUP} = 'IGNORE';
2452 local $SIG{INT} = 'IGNORE';
2453 local $SIG{QUIT} = 'IGNORE';
2454 local $SIG{TERM} = 'IGNORE';
2455 local $SIG{TSTP} = 'IGNORE';
2456 local $SIG{PIPE} = 'IGNORE';
2458 my $oldAutoCommit = $FS::UID::AutoCommit;
2459 local $FS::UID::AutoCommit = 0;
2462 my @cust_pkgs = qsearch('cust_pkg', { 'pkgpart' => $param->{'old_pkgpart'} } );
2465 foreach my $old_cust_pkg ( @cust_pkgs ) {
2467 $job->update_statustext(int(100*$i/(scalar @cust_pkgs)));
2468 if ( $old_cust_pkg->getfield('cancel') ) {
2469 warn '[process_bulk_cust_pkg ] skipping canceled pkgnum '.
2470 $old_cust_pkg->pkgnum."\n"
2474 warn '[process_bulk_cust_pkg] changing pkgnum '.$old_cust_pkg->pkgnum."\n"
2476 my $error = $old_cust_pkg->change(
2477 'pkgpart' => $param->{'new_pkgpart'},
2478 'keep_dates' => $keep_dates
2480 if ( !ref($error) ) { # change returns the cust_pkg on success
2482 die "Error changing pkgnum ".$old_cust_pkg->pkgnum.": '$error'\n";
2485 $dbh->commit if $oldAutoCommit;
2491 Returns the last bill date, or if there is no last bill date, the setup date.
2492 Useful for billing metered services.
2498 return $self->setfield('last_bill', $_[0]) if @_;
2499 return $self->getfield('last_bill') if $self->getfield('last_bill');
2500 my $cust_bill_pkg = qsearchs('cust_bill_pkg', { 'pkgnum' => $self->pkgnum,
2501 'edate' => $self->bill, } );
2502 $cust_bill_pkg ? $cust_bill_pkg->sdate : $self->setup || 0;
2505 =item last_cust_pkg_reason ACTION
2507 Returns the most recent ACTION FS::cust_pkg_reason associated with the package.
2508 Returns false if there is no reason or the package is not currenly ACTION'd
2509 ACTION is one of adjourn, susp, cancel, or expire.
2513 sub last_cust_pkg_reason {
2514 my ( $self, $action ) = ( shift, shift );
2515 my $date = $self->get($action);
2517 'table' => 'cust_pkg_reason',
2518 'hashref' => { 'pkgnum' => $self->pkgnum,
2519 'action' => substr(uc($action), 0, 1),
2522 'order_by' => 'ORDER BY num DESC LIMIT 1',
2526 =item last_reason ACTION
2528 Returns the most recent ACTION FS::reason associated with the package.
2529 Returns false if there is no reason or the package is not currenly ACTION'd
2530 ACTION is one of adjourn, susp, cancel, or expire.
2535 my $cust_pkg_reason = shift->last_cust_pkg_reason(@_);
2536 $cust_pkg_reason->reason
2537 if $cust_pkg_reason;
2542 Returns the definition for this billing item, as an FS::part_pkg object (see
2549 return $self->{'_pkgpart'} if $self->{'_pkgpart'};
2550 cluck "cust_pkg->part_pkg called" if $DEBUG > 1;
2551 qsearchs( 'part_pkg', { 'pkgpart' => $self->pkgpart } );
2556 Returns the cancelled package this package was changed from, if any.
2562 return '' unless $self->change_pkgnum;
2563 qsearchs('cust_pkg', { 'pkgnum' => $self->change_pkgnum } );
2566 =item change_cust_main
2568 Returns the customter this package was detached to, if any.
2572 sub change_cust_main {
2574 return '' unless $self->change_custnum;
2575 qsearchs('cust_main', { 'custnum' => $self->change_custnum } );
2580 Calls the I<calc_setup> of the FS::part_pkg object associated with this billing
2587 $self->part_pkg->calc_setup($self, @_);
2592 Calls the I<calc_recur> of the FS::part_pkg object associated with this billing
2599 $self->part_pkg->calc_recur($self, @_);
2604 Calls the I<base_recur> of the FS::part_pkg object associated with this billing
2611 $self->part_pkg->base_recur($self, @_);
2616 Calls the I<calc_remain> of the FS::part_pkg object associated with this
2623 $self->part_pkg->calc_remain($self, @_);
2628 Calls the I<calc_cancel> of the FS::part_pkg object associated with this
2635 $self->part_pkg->calc_cancel($self, @_);
2640 Returns any invoice line items for this package (see L<FS::cust_bill_pkg>).
2646 qsearch( 'cust_bill_pkg', { 'pkgnum' => $self->pkgnum } );
2649 =item cust_pkg_detail [ DETAILTYPE ]
2651 Returns any customer package details for this package (see
2652 L<FS::cust_pkg_detail>).
2654 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
2658 sub cust_pkg_detail {
2660 my %hash = ( 'pkgnum' => $self->pkgnum );
2661 $hash{detailtype} = shift if @_;
2663 'table' => 'cust_pkg_detail',
2664 'hashref' => \%hash,
2665 'order_by' => 'ORDER BY weight, pkgdetailnum',
2669 =item set_cust_pkg_detail DETAILTYPE [ DETAIL, DETAIL, ... ]
2671 Sets customer package details for this package (see L<FS::cust_pkg_detail>).
2673 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
2675 If there is an error, returns the error, otherwise returns false.
2679 sub set_cust_pkg_detail {
2680 my( $self, $detailtype, @details ) = @_;
2682 local $SIG{HUP} = 'IGNORE';
2683 local $SIG{INT} = 'IGNORE';
2684 local $SIG{QUIT} = 'IGNORE';
2685 local $SIG{TERM} = 'IGNORE';
2686 local $SIG{TSTP} = 'IGNORE';
2687 local $SIG{PIPE} = 'IGNORE';
2689 my $oldAutoCommit = $FS::UID::AutoCommit;
2690 local $FS::UID::AutoCommit = 0;
2693 foreach my $current ( $self->cust_pkg_detail($detailtype) ) {
2694 my $error = $current->delete;
2696 $dbh->rollback if $oldAutoCommit;
2697 return "error removing old detail: $error";
2701 foreach my $detail ( @details ) {
2702 my $cust_pkg_detail = new FS::cust_pkg_detail {
2703 'pkgnum' => $self->pkgnum,
2704 'detailtype' => $detailtype,
2705 'detail' => $detail,
2707 my $error = $cust_pkg_detail->insert;
2709 $dbh->rollback if $oldAutoCommit;
2710 return "error adding new detail: $error";
2715 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2722 Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.
2726 #false laziness w/cust_bill.pm
2730 'table' => 'cust_event',
2731 'addl_from' => 'JOIN part_event USING ( eventpart )',
2732 'hashref' => { 'tablenum' => $self->pkgnum },
2733 'extra_sql' => " AND eventtable = 'cust_pkg' ",
2737 =item num_cust_event
2739 Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.
2743 #false laziness w/cust_bill.pm
2744 sub num_cust_event {
2747 "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
2748 " WHERE tablenum = ? AND eventtable = 'cust_pkg'";
2749 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
2750 $sth->execute($self->pkgnum) or die $sth->errstr. " executing $sql";
2751 $sth->fetchrow_arrayref->[0];
2754 =item cust_svc [ SVCPART ] (old, deprecated usage)
2756 =item cust_svc [ OPTION => VALUE ... ] (current usage)
2758 =item cust_svc_unsorted [ OPTION => VALUE ... ]
2760 Returns the services for this package, as FS::cust_svc objects (see
2761 L<FS::cust_svc>). Available options are svcpart and svcdb. If either is
2762 spcififed, returns only the matching services.
2764 As an optimization, use the cust_svc_unsorted version if you are not displaying
2771 cluck "cust_pkg->cust_svc called" if $DEBUG > 2;
2772 $self->_sort_cust_svc( $self->cust_svc_unsorted_arrayref(@_) );
2775 sub cust_svc_unsorted {
2777 @{ $self->cust_svc_unsorted_arrayref(@_) };
2780 sub cust_svc_unsorted_arrayref {
2783 return () unless $self->num_cust_svc(@_);
2786 if ( @_ && $_[0] =~ /^\d+/ ) {
2787 $opt{svcpart} = shift;
2788 } elsif ( @_ && ref($_[0]) eq 'HASH' ) {
2795 'table' => 'cust_svc',
2796 'hashref' => { 'pkgnum' => $self->pkgnum },
2798 if ( $opt{svcpart} ) {
2799 $search{hashref}->{svcpart} = $opt{'svcpart'};
2801 if ( $opt{'svcdb'} ) {
2802 $search{addl_from} = ' LEFT JOIN part_svc USING ( svcpart ) ';
2803 $search{extra_sql} = ' AND svcdb = '. dbh->quote( $opt{'svcdb'} );
2806 [ qsearch(\%search) ];
2810 =item overlimit [ SVCPART ]
2812 Returns the services for this package which have exceeded their
2813 usage limit as FS::cust_svc objects (see L<FS::cust_svc>). If a svcpart
2814 is specified, return only the matching services.
2820 return () unless $self->num_cust_svc(@_);
2821 grep { $_->overlimit } $self->cust_svc(@_);
2824 =item h_cust_svc END_TIMESTAMP [ START_TIMESTAMP ] [ MODE ]
2826 Returns historical services for this package created before END TIMESTAMP and
2827 (optionally) not cancelled before START_TIMESTAMP, as FS::h_cust_svc objects
2828 (see L<FS::h_cust_svc>). If MODE is 'I' (for 'invoice'), services with the
2829 I<pkg_svc.hidden> flag will be omitted.
2835 warn "$me _h_cust_svc called on $self\n"
2838 my ($end, $start, $mode) = @_;
2839 my @cust_svc = $self->_sort_cust_svc(
2840 [ qsearch( 'h_cust_svc',
2841 { 'pkgnum' => $self->pkgnum, },
2842 FS::h_cust_svc->sql_h_search(@_),
2845 if ( defined($mode) && $mode eq 'I' ) {
2846 my %hidden_svcpart = map { $_->svcpart => $_->hidden } $self->part_svc;
2847 return grep { !$hidden_svcpart{$_->svcpart} } @cust_svc;
2853 sub _sort_cust_svc {
2854 my( $self, $arrayref ) = @_;
2857 sub ($$) { my ($a, $b) = @_; $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] };
2859 my %pkg_svc = map { $_->svcpart => $_ }
2860 qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
2865 my $pkg_svc = $pkg_svc{ $_->svcpart } || '';
2867 $pkg_svc ? $pkg_svc->primary_svc : '',
2868 $pkg_svc ? $pkg_svc->quantity : 0,
2875 =item num_cust_svc [ SVCPART ] (old, deprecated usage)
2877 =item num_cust_svc [ OPTION => VALUE ... ] (current usage)
2879 Returns the number of services for this package. Available options are svcpart
2880 and svcdb. If either is spcififed, returns only the matching services.
2887 return $self->{'_num_cust_svc'}
2889 && exists($self->{'_num_cust_svc'})
2890 && $self->{'_num_cust_svc'} =~ /\d/;
2892 cluck "cust_pkg->num_cust_svc called, _num_cust_svc:".$self->{'_num_cust_svc'}
2896 if ( @_ && $_[0] =~ /^\d+/ ) {
2897 $opt{svcpart} = shift;
2898 } elsif ( @_ && ref($_[0]) eq 'HASH' ) {
2904 my $select = 'SELECT COUNT(*) FROM cust_svc ';
2905 my $where = ' WHERE pkgnum = ? ';
2906 my @param = ($self->pkgnum);
2908 if ( $opt{'svcpart'} ) {
2909 $where .= ' AND svcpart = ? ';
2910 push @param, $opt{'svcpart'};
2912 if ( $opt{'svcdb'} ) {
2913 $select .= ' LEFT JOIN part_svc USING ( svcpart ) ';
2914 $where .= ' AND svcdb = ? ';
2915 push @param, $opt{'svcdb'};
2918 my $sth = dbh->prepare("$select $where") or die dbh->errstr;
2919 $sth->execute(@param) or die $sth->errstr;
2920 $sth->fetchrow_arrayref->[0];
2923 =item available_part_svc
2925 Returns a list of FS::part_svc objects representing services included in this
2926 package but not yet provisioned. Each FS::part_svc object also has an extra
2927 field, I<num_avail>, which specifies the number of available services.
2931 sub available_part_svc {
2934 my $pkg_quantity = $self->quantity || 1;
2936 grep { $_->num_avail > 0 }
2938 my $part_svc = $_->part_svc;
2939 $part_svc->{'Hash'}{'num_avail'} = #evil encapsulation-breaking
2940 $pkg_quantity * $_->quantity - $self->num_cust_svc($_->svcpart);
2942 # more evil encapsulation breakage
2943 if($part_svc->{'Hash'}{'num_avail'} > 0) {
2944 my @exports = $part_svc->part_export_did;
2945 $part_svc->{'Hash'}{'can_get_dids'} = scalar(@exports);
2950 $self->part_pkg->pkg_svc;
2953 =item part_svc [ OPTION => VALUE ... ]
2955 Returns a list of FS::part_svc objects representing provisioned and available
2956 services included in this package. Each FS::part_svc object also has the
2957 following extra fields:
2961 =item num_cust_svc (count)
2963 =item num_avail (quantity - count)
2965 =item cust_pkg_svc (services) - array reference containing the provisioned services, as cust_svc objects
2969 Accepts one option: summarize_size. If specified and non-zero, will omit the
2970 extra cust_pkg_svc option for objects where num_cust_svc is this size or
2976 #label -> ($cust_svc->label)[1]
2982 my $pkg_quantity = $self->quantity || 1;
2984 #XXX some sort of sort order besides numeric by svcpart...
2985 my @part_svc = sort { $a->svcpart <=> $b->svcpart } map {
2987 my $part_svc = $pkg_svc->part_svc;
2988 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
2989 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #more evil
2990 $part_svc->{'Hash'}{'num_avail'} =
2991 max( 0, $pkg_quantity * $pkg_svc->quantity - $num_cust_svc );
2992 $part_svc->{'Hash'}{'cust_pkg_svc'} =
2993 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : []
2994 unless exists($opt{summarize_size}) && $opt{summarize_size} > 0
2995 && $num_cust_svc >= $opt{summarize_size};
2996 $part_svc->{'Hash'}{'hidden'} = $pkg_svc->hidden;
2998 } $self->part_pkg->pkg_svc;
3001 push @part_svc, map {
3003 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
3004 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #speak no evail
3005 $part_svc->{'Hash'}{'num_avail'} = 0; #0-$num_cust_svc ?
3006 $part_svc->{'Hash'}{'cust_pkg_svc'} =
3007 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : [];
3009 } $self->extra_part_svc;
3015 =item extra_part_svc
3017 Returns a list of FS::part_svc objects corresponding to services in this
3018 package which are still provisioned but not (any longer) available in the
3023 sub extra_part_svc {
3026 my $pkgnum = $self->pkgnum;
3027 #my $pkgpart = $self->pkgpart;
3030 # 'table' => 'part_svc',
3033 # "WHERE 0 = ( SELECT COUNT(*) FROM pkg_svc
3034 # WHERE pkg_svc.svcpart = part_svc.svcpart
3035 # AND pkg_svc.pkgpart = ?
3038 # AND 0 < ( SELECT COUNT(*) FROM cust_svc
3039 # LEFT JOIN cust_pkg USING ( pkgnum )
3040 # WHERE cust_svc.svcpart = part_svc.svcpart
3043 # 'extra_param' => [ [$self->pkgpart=>'int'], [$self->pkgnum=>'int'] ],
3046 #seems to benchmark slightly faster... (or did?)
3048 my @pkgparts = map $_->pkgpart, $self->part_pkg->self_and_svc_linked;
3049 my $pkgparts = join(',', @pkgparts);
3052 #'select' => 'DISTINCT ON (svcpart) part_svc.*',
3053 #MySQL doesn't grok DISINCT ON
3054 'select' => 'DISTINCT part_svc.*',
3055 'table' => 'part_svc',
3057 "LEFT JOIN pkg_svc ON ( pkg_svc.svcpart = part_svc.svcpart
3058 AND pkg_svc.pkgpart IN ($pkgparts)
3061 LEFT JOIN cust_svc ON ( cust_svc.svcpart = part_svc.svcpart )
3062 LEFT JOIN cust_pkg USING ( pkgnum )
3065 'extra_sql' => "WHERE pkgsvcnum IS NULL AND cust_pkg.pkgnum = ? ",
3066 'extra_param' => [ [$self->pkgnum=>'int'] ],
3072 Returns a short status string for this package, currently:
3076 =item not yet billed
3078 =item one-time charge
3093 my $freq = length($self->freq) ? $self->freq : $self->part_pkg->freq;
3095 return 'cancelled' if $self->get('cancel');
3096 return 'suspended' if $self->susp;
3097 return 'not yet billed' unless $self->setup;
3098 return 'one-time charge' if $freq =~ /^(0|$)/;
3102 =item ucfirst_status
3104 Returns the status with the first character capitalized.
3108 sub ucfirst_status {
3109 ucfirst(shift->status);
3114 Class method that returns the list of possible status strings for packages
3115 (see L<the status method|/status>). For example:
3117 @statuses = FS::cust_pkg->statuses();
3121 tie my %statuscolor, 'Tie::IxHash',
3122 'not yet billed' => '009999', #teal? cyan?
3123 'one-time charge' => '000000',
3124 'active' => '00CC00',
3125 'suspended' => 'FF9900',
3126 'cancelled' => 'FF0000',
3130 my $self = shift; #could be class...
3131 #grep { $_ !~ /^(not yet billed)$/ } #this is a dumb status anyway
3132 # # mayble split btw one-time vs. recur
3138 Returns a hex triplet color string for this package's status.
3144 $statuscolor{$self->status};
3149 Returns a label for this package. (Currently "pkgnum: pkg - comment" or
3150 "pkg - comment" depending on user preference).
3156 my $label = $self->part_pkg->pkg_comment( 'nopkgpart' => 1 );
3157 $label = $self->pkgnum. ": $label"
3158 if $FS::CurrentUser::CurrentUser->option('show_pkgnum');
3162 =item pkg_label_long
3164 Returns a long label for this package, adding the primary service's label to
3169 sub pkg_label_long {
3171 my $label = $self->pkg_label;
3172 my $cust_svc = $self->primary_cust_svc;
3173 $label .= ' ('. ($cust_svc->label)[1]. ')' if $cust_svc;
3179 Returns a customer-localized label for this package.
3185 $self->part_pkg->pkg_locale( $self->cust_main->locale );
3188 =item primary_cust_svc
3190 Returns a primary service (as FS::cust_svc object) if one can be identified.
3194 #for labeling purposes - might not 100% match up with part_pkg->svcpart's idea
3196 sub primary_cust_svc {
3199 my @cust_svc = $self->cust_svc;
3201 return '' unless @cust_svc; #no serivces - irrelevant then
3203 return $cust_svc[0] if scalar(@cust_svc) == 1; #always return a single service
3205 # primary service as specified in the package definition
3206 # or exactly one service definition with quantity one
3207 my $svcpart = $self->part_pkg->svcpart;
3208 @cust_svc = grep { $_->svcpart == $svcpart } @cust_svc;
3209 return $cust_svc[0] if scalar(@cust_svc) == 1;
3211 #couldn't identify one thing..
3217 Returns a list of lists, calling the label method for all services
3218 (see L<FS::cust_svc>) of this billing item.
3224 map { [ $_->label ] } $self->cust_svc;
3227 =item h_labels END_TIMESTAMP [ START_TIMESTAMP ] [ MODE ]
3229 Like the labels method, but returns historical information on services that
3230 were active as of END_TIMESTAMP and (optionally) not cancelled before
3231 START_TIMESTAMP. If MODE is 'I' (for 'invoice'), services with the
3232 I<pkg_svc.hidden> flag will be omitted.
3234 Returns a list of lists, calling the label method for all (historical) services
3235 (see L<FS::h_cust_svc>) of this billing item.
3241 warn "$me _h_labels called on $self\n"
3243 map { [ $_->label(@_) ] } $self->h_cust_svc(@_);
3248 Like labels, except returns a simple flat list, and shortens long
3249 (currently >5 or the cust_bill-max_same_services configuration value) lists of
3250 identical services to one line that lists the service label and the number of
3251 individual services rather than individual items.
3256 shift->_labels_short( 'labels', @_ );
3259 =item h_labels_short END_TIMESTAMP [ START_TIMESTAMP ]
3261 Like h_labels, except returns a simple flat list, and shortens long
3262 (currently >5 or the cust_bill-max_same_services configuration value) lists of
3263 identical services to one line that lists the service label and the number of
3264 individual services rather than individual items.
3268 sub h_labels_short {
3269 shift->_labels_short( 'h_labels', @_ );
3273 my( $self, $method ) = ( shift, shift );
3275 warn "$me _labels_short called on $self with $method method\n"
3278 my $conf = new FS::Conf;
3279 my $max_same_services = $conf->config('cust_bill-max_same_services') || 5;
3281 warn "$me _labels_short populating \%labels\n"
3285 #tie %labels, 'Tie::IxHash';
3286 push @{ $labels{$_->[0]} }, $_->[1]
3287 foreach $self->$method(@_);
3289 warn "$me _labels_short populating \@labels\n"
3293 foreach my $label ( keys %labels ) {
3295 my @values = grep { ! $seen{$_}++ } @{ $labels{$label} };
3296 my $num = scalar(@values);
3297 warn "$me _labels_short $num items for $label\n"
3300 if ( $num > $max_same_services ) {
3301 warn "$me _labels_short more than $max_same_services, so summarizing\n"
3303 push @labels, "$label ($num)";
3305 if ( $conf->exists('cust_bill-consolidate_services') ) {
3306 warn "$me _labels_short consolidating services\n"
3308 # push @labels, "$label: ". join(', ', @values);
3310 my $detail = "$label: ";
3311 $detail .= shift(@values). ', '
3313 && ( length($detail.$values[0]) < 78 || $detail eq "$label: " );
3315 push @labels, $detail;
3317 warn "$me _labels_short done consolidating services\n"
3320 warn "$me _labels_short adding service data\n"
3322 push @labels, map { "$label: $_" } @values;
3333 Returns the parent customer object (see L<FS::cust_main>).
3339 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
3344 Returns the balance for this specific package, when using
3345 experimental package balance.
3351 $self->cust_main->balance_pkgnum( $self->pkgnum );
3354 #these subs are in location_Mixin.pm now... unfortunately the POD doesn't mixin
3358 Returns the location object, if any (see L<FS::cust_location>).
3360 =item cust_location_or_main
3362 If this package is associated with a location, returns the locaiton (see
3363 L<FS::cust_location>), otherwise returns the customer (see L<FS::cust_main>).
3365 =item location_label [ OPTION => VALUE ... ]
3367 Returns the label of the location object (see L<FS::cust_location>).
3371 #end of subs in location_Mixin.pm now... unfortunately the POD doesn't mixin
3373 =item tax_locationnum
3375 Returns the foreign key to a L<FS::cust_location> object for calculating
3376 tax on this package, as determined by the C<tax-pkg_address> and
3377 C<tax-ship_address> configuration flags.
3381 sub tax_locationnum {
3383 my $conf = FS::Conf->new;
3384 if ( $conf->exists('tax-pkg_address') ) {
3385 return $self->locationnum;
3387 elsif ( $conf->exists('tax-ship_address') ) {
3388 return $self->cust_main->ship_locationnum;
3391 return $self->cust_main->bill_locationnum;
3397 Returns the L<FS::cust_location> object for tax_locationnum.
3403 FS::cust_location->by_key( $self->tax_locationnum )
3406 =item seconds_since TIMESTAMP
3408 Returns the number of seconds all accounts (see L<FS::svc_acct>) in this
3409 package have been online since TIMESTAMP, according to the session monitor.
3411 TIMESTAMP is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
3412 L<Time::Local> and L<Date::Parse> for conversion functions.
3417 my($self, $since) = @_;
3420 foreach my $cust_svc (
3421 grep { $_->part_svc->svcdb eq 'svc_acct' } $self->cust_svc
3423 $seconds += $cust_svc->seconds_since($since);
3430 =item seconds_since_sqlradacct TIMESTAMP_START TIMESTAMP_END
3432 Returns the numbers of seconds all accounts (see L<FS::svc_acct>) in this
3433 package have been online between TIMESTAMP_START (inclusive) and TIMESTAMP_END
3436 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
3437 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
3443 sub seconds_since_sqlradacct {
3444 my($self, $start, $end) = @_;
3448 foreach my $cust_svc (
3450 my $part_svc = $_->part_svc;
3451 $part_svc->svcdb eq 'svc_acct'
3452 && scalar($part_svc->part_export_usage);
3455 $seconds += $cust_svc->seconds_since_sqlradacct($start, $end);
3462 =item attribute_since_sqlradacct TIMESTAMP_START TIMESTAMP_END ATTRIBUTE
3464 Returns the sum of the given attribute for all accounts (see L<FS::svc_acct>)
3465 in this package for sessions ending between TIMESTAMP_START (inclusive) and
3469 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
3470 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
3475 sub attribute_since_sqlradacct {
3476 my($self, $start, $end, $attrib) = @_;
3480 foreach my $cust_svc (
3482 my $part_svc = $_->part_svc;
3483 scalar($part_svc->part_export_usage);
3486 $sum += $cust_svc->attribute_since_sqlradacct($start, $end, $attrib);
3498 my( $self, $value ) = @_;
3499 if ( defined($value) ) {
3500 $self->setfield('quantity', $value);
3502 $self->getfield('quantity') || 1;
3505 =item transfer DEST_PKGNUM | DEST_CUST_PKG, [ OPTION => VALUE ... ]
3507 Transfers as many services as possible from this package to another package.
3509 The destination package can be specified by pkgnum by passing an FS::cust_pkg
3510 object. The destination package must already exist.
3512 Services are moved only if the destination allows services with the correct
3513 I<svcpart> (not svcdb), unless the B<change_svcpart> option is set true. Use
3514 this option with caution! No provision is made for export differences
3515 between the old and new service definitions. Probably only should be used
3516 when your exports for all service definitions of a given svcdb are identical.
3517 (attempt a transfer without it first, to move all possible svcpart-matching
3520 Any services that can't be moved remain in the original package.
3522 Returns an error, if there is one; otherwise, returns the number of services
3523 that couldn't be moved.
3528 my ($self, $dest_pkgnum, %opt) = @_;
3534 if (ref ($dest_pkgnum) eq 'FS::cust_pkg') {
3535 $dest = $dest_pkgnum;
3536 $dest_pkgnum = $dest->pkgnum;
3538 $dest = qsearchs('cust_pkg', { pkgnum => $dest_pkgnum });
3541 return ('Package does not exist: '.$dest_pkgnum) unless $dest;
3543 foreach my $pkg_svc ( $dest->part_pkg->pkg_svc ) {
3544 $target{$pkg_svc->svcpart} = $pkg_svc->quantity;
3547 foreach my $cust_svc ($dest->cust_svc) {
3548 $target{$cust_svc->svcpart}--;
3551 my %svcpart2svcparts = ();
3552 if ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
3553 warn "change_svcpart option received, creating alternates list\n" if $DEBUG;
3554 foreach my $svcpart ( map { $_->svcpart } $self->cust_svc ) {
3555 next if exists $svcpart2svcparts{$svcpart};
3556 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
3557 $svcpart2svcparts{$svcpart} = [
3559 sort { $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] }
3561 my $pkg_svc = qsearchs( 'pkg_svc', { 'pkgpart' => $dest->pkgpart,
3562 'svcpart' => $_ } );
3564 $pkg_svc ? $pkg_svc->primary_svc : '',
3565 $pkg_svc ? $pkg_svc->quantity : 0,
3569 grep { $_ != $svcpart }
3571 qsearch('part_svc', { 'svcdb' => $part_svc->svcdb } )
3573 warn "alternates for svcpart $svcpart: ".
3574 join(', ', @{$svcpart2svcparts{$svcpart}}). "\n"
3580 foreach my $cust_svc ($self->cust_svc) {
3581 my $svcnum = $cust_svc->svcnum;
3582 if($target{$cust_svc->svcpart} > 0
3583 or $FS::cust_svc::ignore_quantity) { # maybe should be a 'force' option
3584 $target{$cust_svc->svcpart}--;
3585 my $new = new FS::cust_svc { $cust_svc->hash };
3586 $new->pkgnum($dest_pkgnum);
3587 $error = $new->replace($cust_svc);
3588 } elsif ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
3590 warn "looking for alternates for svcpart ". $cust_svc->svcpart. "\n";
3591 warn "alternates to consider: ".
3592 join(', ', @{$svcpart2svcparts{$cust_svc->svcpart}}). "\n";
3594 my @alternate = grep {
3595 warn "considering alternate svcpart $_: ".
3596 "$target{$_} available in new package\n"
3599 } @{$svcpart2svcparts{$cust_svc->svcpart}};
3601 warn "alternate(s) found\n" if $DEBUG;
3602 my $change_svcpart = $alternate[0];
3603 $target{$change_svcpart}--;
3604 my $new = new FS::cust_svc { $cust_svc->hash };
3605 $new->svcpart($change_svcpart);
3606 $new->pkgnum($dest_pkgnum);
3607 $error = $new->replace($cust_svc);
3615 my @label = $cust_svc->label;
3616 return "service $label[1]: $error";
3622 =item grab_svcnums SVCNUM, SVCNUM ...
3624 Change the pkgnum for the provided services to this packages. If there is an
3625 error, returns the error, otherwise returns false.
3633 local $SIG{HUP} = 'IGNORE';
3634 local $SIG{INT} = 'IGNORE';
3635 local $SIG{QUIT} = 'IGNORE';
3636 local $SIG{TERM} = 'IGNORE';
3637 local $SIG{TSTP} = 'IGNORE';
3638 local $SIG{PIPE} = 'IGNORE';
3640 my $oldAutoCommit = $FS::UID::AutoCommit;
3641 local $FS::UID::AutoCommit = 0;
3644 foreach my $svcnum (@svcnum) {
3645 my $cust_svc = qsearchs('cust_svc', { svcnum=>$svcnum } ) or do {
3646 $dbh->rollback if $oldAutoCommit;
3647 return "unknown svcnum $svcnum";
3649 $cust_svc->pkgnum( $self->pkgnum );
3650 my $error = $cust_svc->replace;
3652 $dbh->rollback if $oldAutoCommit;
3657 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3664 This method is deprecated. See the I<depend_jobnum> option to the insert and
3665 order_pkgs methods in FS::cust_main for a better way to defer provisioning.
3672 local $SIG{HUP} = 'IGNORE';
3673 local $SIG{INT} = 'IGNORE';
3674 local $SIG{QUIT} = 'IGNORE';
3675 local $SIG{TERM} = 'IGNORE';
3676 local $SIG{TSTP} = 'IGNORE';
3677 local $SIG{PIPE} = 'IGNORE';
3679 my $oldAutoCommit = $FS::UID::AutoCommit;
3680 local $FS::UID::AutoCommit = 0;
3683 foreach my $cust_svc ( $self->cust_svc ) {
3684 #false laziness w/svc_Common::insert
3685 my $svc_x = $cust_svc->svc_x;
3686 foreach my $part_export ( $cust_svc->part_svc->part_export ) {
3687 my $error = $part_export->export_insert($svc_x);
3689 $dbh->rollback if $oldAutoCommit;
3695 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3700 =item export_pkg_change OLD_CUST_PKG
3702 Calls the "pkg_change" export action for all services attached to this package.
3706 sub export_pkg_change {
3707 my( $self, $old ) = ( shift, shift );
3709 local $SIG{HUP} = 'IGNORE';
3710 local $SIG{INT} = 'IGNORE';
3711 local $SIG{QUIT} = 'IGNORE';
3712 local $SIG{TERM} = 'IGNORE';
3713 local $SIG{TSTP} = 'IGNORE';
3714 local $SIG{PIPE} = 'IGNORE';
3716 my $oldAutoCommit = $FS::UID::AutoCommit;
3717 local $FS::UID::AutoCommit = 0;
3720 foreach my $svc_x ( map $_->svc_x, $self->cust_svc ) {
3721 my $error = $svc_x->export('pkg_change', $self, $old);
3723 $dbh->rollback if $oldAutoCommit;
3728 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3735 Associates this package with a (suspension or cancellation) reason (see
3736 L<FS::cust_pkg_reason>, possibly inserting a new reason on the fly (see
3739 Available options are:
3745 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.
3749 the access_user (see L<FS::access_user>) providing the reason
3757 the action (cancel, susp, adjourn, expire) associated with the reason
3761 If there is an error, returns the error, otherwise returns false.
3766 my ($self, %options) = @_;
3768 my $otaker = $options{reason_otaker} ||
3769 $FS::CurrentUser::CurrentUser->username;
3772 if ( $options{'reason'} =~ /^(\d+)$/ ) {
3776 } elsif ( ref($options{'reason'}) ) {
3778 return 'Enter a new reason (or select an existing one)'
3779 unless $options{'reason'}->{'reason'} !~ /^\s*$/;
3781 my $reason = new FS::reason({
3782 'reason_type' => $options{'reason'}->{'typenum'},
3783 'reason' => $options{'reason'}->{'reason'},
3785 my $error = $reason->insert;
3786 return $error if $error;
3788 $reasonnum = $reason->reasonnum;
3791 return "Unparsable reason: ". $options{'reason'};
3794 my $cust_pkg_reason =
3795 new FS::cust_pkg_reason({ 'pkgnum' => $self->pkgnum,
3796 'reasonnum' => $reasonnum,
3797 'otaker' => $otaker,
3798 'action' => substr(uc($options{'action'}),0,1),
3799 'date' => $options{'date'}
3804 $cust_pkg_reason->insert;
3807 =item insert_discount
3809 Associates this package with a discount (see L<FS::cust_pkg_discount>, possibly
3810 inserting a new discount on the fly (see L<FS::discount>).
3812 Available options are:
3820 If there is an error, returns the error, otherwise returns false.
3824 sub insert_discount {
3825 #my ($self, %options) = @_;
3828 my $cust_pkg_discount = new FS::cust_pkg_discount {
3829 'pkgnum' => $self->pkgnum,
3830 'discountnum' => $self->discountnum,
3832 'end_date' => '', #XXX
3833 #for the create a new discount case
3834 '_type' => $self->discountnum__type,
3835 'amount' => $self->discountnum_amount,
3836 'percent' => $self->discountnum_percent,
3837 'months' => $self->discountnum_months,
3838 'setup' => $self->discountnum_setup,
3839 #'disabled' => $self->discountnum_disabled,
3842 $cust_pkg_discount->insert;
3845 =item set_usage 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 reset.
3856 my ($self, $valueref, %opt) = @_;
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->set_usage($valueref, %opt)
3862 if $svc_x->can("set_usage");
3866 =item recharge USAGE_VALUE_HASHREF
3868 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
3869 to which they should be set (see L<FS::svc_acct>). Currently seconds,
3870 upbytes, downbytes, and totalbytes are appropriate keys.
3872 All svc_accts which are part of this package have their values incremented.
3877 my ($self, $valueref) = @_;
3879 #only svc_acct can set_usage for now
3880 foreach my $cust_svc ( $self->cust_svc( 'svcdb'=>'svc_acct' ) ) {
3881 my $svc_x = $cust_svc->svc_x;
3882 $svc_x->recharge($valueref)
3883 if $svc_x->can("recharge");
3887 =item cust_pkg_discount
3891 sub cust_pkg_discount {
3893 qsearch('cust_pkg_discount', { 'pkgnum' => $self->pkgnum } );
3896 =item cust_pkg_discount_active
3900 sub cust_pkg_discount_active {
3902 grep { $_->status eq 'active' } $self->cust_pkg_discount;
3905 =item cust_pkg_usage
3907 Returns a list of all voice usage counters attached to this package.
3911 sub cust_pkg_usage {
3913 qsearch('cust_pkg_usage', { pkgnum => $self->pkgnum });
3916 =item apply_usage OPTIONS
3918 Takes the following options:
3919 - cdr: a call detail record (L<FS::cdr>)
3920 - rate_detail: the rate determined for this call (L<FS::rate_detail>)
3921 - minutes: the maximum number of minutes to be charged
3923 Finds available usage minutes for a call of this class, and subtracts
3924 up to that many minutes from the usage pool. If the usage pool is empty,
3925 and the C<cdr-minutes_priority> global config option is set, minutes may
3926 be taken from other calls as well. Either way, an allocation record will
3927 be created (L<FS::cdr_cust_pkg_usage>) and this method will return the
3928 number of minutes of usage applied to the call.
3933 my ($self, %opt) = @_;
3934 my $cdr = $opt{cdr};
3935 my $rate_detail = $opt{rate_detail};
3936 my $minutes = $opt{minutes};
3937 my $classnum = $rate_detail->classnum;
3938 my $pkgnum = $self->pkgnum;
3939 my $custnum = $self->custnum;
3941 local $SIG{HUP} = 'IGNORE';
3942 local $SIG{INT} = 'IGNORE';
3943 local $SIG{QUIT} = 'IGNORE';
3944 local $SIG{TERM} = 'IGNORE';
3945 local $SIG{TSTP} = 'IGNORE';
3946 local $SIG{PIPE} = 'IGNORE';
3948 my $oldAutoCommit = $FS::UID::AutoCommit;
3949 local $FS::UID::AutoCommit = 0;
3951 my $order = FS::Conf->new->config('cdr-minutes_priority');
3955 $is_classnum = ' part_pkg_usage_class.classnum = '.$classnum;
3957 $is_classnum = ' part_pkg_usage_class.classnum IS NULL';
3959 my @usage_recs = qsearch({
3960 'table' => 'cust_pkg_usage',
3961 'addl_from' => ' JOIN part_pkg_usage USING (pkgusagepart)'.
3962 ' JOIN cust_pkg USING (pkgnum)'.
3963 ' JOIN part_pkg_usage_class USING (pkgusagepart)',
3964 'select' => 'cust_pkg_usage.*',
3965 'extra_sql' => " WHERE ( cust_pkg.pkgnum = $pkgnum OR ".
3966 " ( cust_pkg.custnum = $custnum AND ".
3967 " part_pkg_usage.shared IS NOT NULL ) ) AND ".
3968 $is_classnum . ' AND '.
3969 " cust_pkg_usage.minutes > 0",
3970 'order_by' => " ORDER BY priority ASC",
3973 my $orig_minutes = $minutes;
3975 while (!$error and $minutes > 0 and @usage_recs) {
3976 my $cust_pkg_usage = shift @usage_recs;
3977 $cust_pkg_usage->select_for_update;
3978 my $cdr_cust_pkg_usage = FS::cdr_cust_pkg_usage->new({
3979 pkgusagenum => $cust_pkg_usage->pkgusagenum,
3980 acctid => $cdr->acctid,
3981 minutes => min($cust_pkg_usage->minutes, $minutes),
3983 $cust_pkg_usage->set('minutes',
3984 sprintf('%.0f', $cust_pkg_usage->minutes - $cdr_cust_pkg_usage->minutes)
3986 $error = $cust_pkg_usage->replace || $cdr_cust_pkg_usage->insert;
3987 $minutes -= $cdr_cust_pkg_usage->minutes;
3989 if ( $order and $minutes > 0 and !$error ) {
3990 # then try to steal minutes from another call
3992 'table' => 'cdr_cust_pkg_usage',
3993 'addl_from' => ' JOIN cust_pkg_usage USING (pkgusagenum)'.
3994 ' JOIN part_pkg_usage USING (pkgusagepart)'.
3995 ' JOIN cust_pkg USING (pkgnum)'.
3996 ' JOIN part_pkg_usage_class USING (pkgusagepart)'.
3997 ' JOIN cdr USING (acctid)',
3998 'select' => 'cdr_cust_pkg_usage.*',
3999 'extra_sql' => " WHERE cdr.freesidestatus = 'rated' AND ".
4000 " ( cust_pkg.pkgnum = $pkgnum OR ".
4001 " ( cust_pkg.custnum = $custnum AND ".
4002 " part_pkg_usage.shared IS NOT NULL ) ) AND ".
4003 " part_pkg_usage_class.classnum = $classnum",
4004 'order_by' => ' ORDER BY part_pkg_usage.priority ASC',
4006 if ( $order eq 'time' ) {
4007 # find CDRs that are using minutes, but have a later startdate
4009 my $startdate = $cdr->startdate;
4010 if ($startdate !~ /^\d+$/) {
4011 die "bad cdr startdate '$startdate'";
4013 $search{'extra_sql'} .= " AND cdr.startdate > $startdate";
4014 # minimize needless reshuffling
4015 $search{'order_by'} .= ', cdr.startdate DESC';
4017 # XXX may not work correctly with rate_time schedules. Could
4018 # fix this by storing ratedetailnum in cdr_cust_pkg_usage, I
4020 $search{'addl_from'} .=
4021 ' JOIN rate_detail'.
4022 ' ON (cdr.rated_ratedetailnum = rate_detail.ratedetailnum)';
4023 if ( $order eq 'rate_high' ) {
4024 $search{'extra_sql'} .= ' AND rate_detail.min_charge < '.
4025 $rate_detail->min_charge;
4026 $search{'order_by'} .= ', rate_detail.min_charge ASC';
4027 } elsif ( $order eq 'rate_low' ) {
4028 $search{'extra_sql'} .= ' AND rate_detail.min_charge > '.
4029 $rate_detail->min_charge;
4030 $search{'order_by'} .= ', rate_detail.min_charge DESC';
4032 # this should really never happen
4033 die "invalid cdr-minutes_priority value '$order'\n";
4036 my @cdr_usage_recs = qsearch(\%search);
4038 while (!$error and @cdr_usage_recs and $minutes > 0) {
4039 my $cdr_cust_pkg_usage = shift @cdr_usage_recs;
4040 my $cust_pkg_usage = $cdr_cust_pkg_usage->cust_pkg_usage;
4041 my $old_cdr = $cdr_cust_pkg_usage->cdr;
4042 $reproc_cdrs{$old_cdr->acctid} = $old_cdr;
4043 $cdr_cust_pkg_usage->select_for_update;
4044 $old_cdr->select_for_update;
4045 $cust_pkg_usage->select_for_update;
4046 # in case someone else stole the usage from this CDR
4047 # while waiting for the lock...
4048 next if $old_cdr->acctid != $cdr_cust_pkg_usage->acctid;
4049 # steal the usage allocation and flag the old CDR for reprocessing
4050 $cdr_cust_pkg_usage->set('acctid', $cdr->acctid);
4051 # if the allocation is more minutes than we need, adjust it...
4052 my $delta = $cdr_cust_pkg_usage->minutes - $minutes;
4054 $cdr_cust_pkg_usage->set('minutes', $minutes);
4055 $cust_pkg_usage->set('minutes', $cust_pkg_usage->minutes + $delta);
4056 $error = $cust_pkg_usage->replace;
4058 #warn 'CDR '.$cdr->acctid . ' stealing allocation '.$cdr_cust_pkg_usage->cdrusagenum.' from CDR '.$old_cdr->acctid."\n";
4059 $error ||= $cdr_cust_pkg_usage->replace;
4060 # deduct the stolen minutes
4061 $minutes -= $cdr_cust_pkg_usage->minutes;
4063 # after all minute-stealing is done, reset the affected CDRs
4064 foreach (values %reproc_cdrs) {
4065 $error ||= $_->set_status('');
4066 # XXX or should we just call $cdr->rate right here?
4067 # it's not like we can create a loop this way, since the min_charge
4068 # or call time has to go monotonically in one direction.
4069 # we COULD get some very deep recursions going, though...
4071 } # if $order and $minutes
4074 die "error applying included minutes\npkgnum ".$self->pkgnum.", class $classnum, acctid ".$cdr->acctid."\n$error\n"
4076 $dbh->commit if $oldAutoCommit;
4077 return $orig_minutes - $minutes;
4081 =item supplemental_pkgs
4083 Returns a list of all packages supplemental to this one.
4087 sub supplemental_pkgs {
4089 qsearch('cust_pkg', { 'main_pkgnum' => $self->pkgnum });
4094 Returns the package that this one is supplemental to, if any.
4100 if ( $self->main_pkgnum ) {
4101 return FS::cust_pkg->by_key($self->main_pkgnum);
4108 =head1 CLASS METHODS
4114 Returns an SQL expression identifying recurring packages.
4118 sub recurring_sql { "
4119 '0' != ( select freq from part_pkg
4120 where cust_pkg.pkgpart = part_pkg.pkgpart )
4125 Returns an SQL expression identifying one-time packages.
4130 '0' = ( select freq from part_pkg
4131 where cust_pkg.pkgpart = part_pkg.pkgpart )
4136 Returns an SQL expression identifying ordered packages (recurring packages not
4142 $_[0]->recurring_sql. " AND ". $_[0]->not_yet_billed_sql;
4147 Returns an SQL expression identifying active packages.
4152 $_[0]->recurring_sql. "
4153 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
4154 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4155 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
4158 =item not_yet_billed_sql
4160 Returns an SQL expression identifying packages which have not yet been billed.
4164 sub not_yet_billed_sql { "
4165 ( cust_pkg.setup IS NULL OR cust_pkg.setup = 0 )
4166 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4167 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
4172 Returns an SQL expression identifying inactive packages (one-time packages
4173 that are otherwise unsuspended/uncancelled).
4177 sub inactive_sql { "
4178 ". $_[0]->onetime_sql(). "
4179 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
4180 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4181 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
4187 Returns an SQL expression identifying suspended packages.
4191 sub suspended_sql { susp_sql(@_); }
4193 #$_[0]->recurring_sql(). ' AND '.
4195 ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4196 AND cust_pkg.susp IS NOT NULL AND cust_pkg.susp != 0
4203 Returns an SQL exprression identifying cancelled packages.
4207 sub cancelled_sql { cancel_sql(@_); }
4209 #$_[0]->recurring_sql(). ' AND '.
4210 "cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0";
4215 Returns an SQL expression to give the package status as a string.
4221 WHEN cust_pkg.cancel IS NOT NULL THEN 'cancelled'
4222 WHEN cust_pkg.susp IS NOT NULL THEN 'suspended'
4223 WHEN cust_pkg.setup IS NULL THEN 'not yet billed'
4224 WHEN ".onetime_sql()." THEN 'one-time charge'
4229 =item search HASHREF
4233 Returns a qsearch hash expression to search for parameters specified in HASHREF.
4234 Valid parameters are
4242 active, inactive, suspended, cancel (or cancelled)
4246 active, inactive, suspended, one-time charge, inactive, cancel (or cancelled)
4250 boolean selects custom packages
4256 pkgpart or arrayref or hashref of pkgparts
4260 arrayref of beginning and ending epoch date
4264 arrayref of beginning and ending epoch date
4268 arrayref of beginning and ending epoch date
4272 arrayref of beginning and ending epoch date
4276 arrayref of beginning and ending epoch date
4280 arrayref of beginning and ending epoch date
4284 arrayref of beginning and ending epoch date
4288 pkgnum or APKG_pkgnum
4292 a value suited to passing to FS::UI::Web::cust_header
4296 specifies the user for agent virtualization
4300 boolean; if true, returns only packages with more than 0 FCC phone lines.
4302 =item state, country
4304 Limit to packages with a service location in the specified state and country.
4305 For FCC 477 reporting, mostly.
4309 Limit to packages whose service locations are the same as the customer's
4310 default service location.
4312 =item location_nocust
4314 Limit to packages whose service locations are not the customer's default
4317 =item location_census
4319 Limit to packages whose service locations have census tracts.
4321 =item location_nocensus
4323 Limit to packages whose service locations do not have a census tract.
4325 =item location_geocode
4327 Limit to packages whose locations have geocodes.
4329 =item location_geocode
4331 Limit to packages whose locations do not have geocodes.
4338 my ($class, $params) = @_;
4345 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
4347 "cust_main.agentnum = $1";
4354 if ( $params->{'cust_status'} =~ /^([a-z]+)$/ ) {
4355 push @where, FS::cust_main->cust_status_sql . " = '$1' ";
4359 # parse customer sales person
4362 if ( $params->{'cust_main_salesnum'} =~ /^(\d+)$/ ) {
4363 push @where, ($1 > 0) ? "cust_main.salesnum = $1"
4364 : 'cust_main.salesnum IS NULL';
4369 # parse sales person
4372 if ( $params->{'salesnum'} =~ /^(\d+)$/ ) {
4373 push @where, ($1 > 0) ? "cust_pkg.salesnum = $1"
4374 : 'cust_pkg.salesnum IS NULL';
4381 if ( $params->{'custnum'} =~ /^(\d+)$/ and $1 ) {
4383 "cust_pkg.custnum = $1";
4390 if ( $params->{'pkgbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
4392 "cust_pkg.pkgbatch = '$1'";
4399 if ( $params->{'magic'} eq 'active'
4400 || $params->{'status'} eq 'active' ) {
4402 push @where, FS::cust_pkg->active_sql();
4404 } elsif ( $params->{'magic'} =~ /^not[ _]yet[ _]billed$/
4405 || $params->{'status'} =~ /^not[ _]yet[ _]billed$/ ) {
4407 push @where, FS::cust_pkg->not_yet_billed_sql();
4409 } elsif ( $params->{'magic'} =~ /^(one-time charge|inactive)/
4410 || $params->{'status'} =~ /^(one-time charge|inactive)/ ) {
4412 push @where, FS::cust_pkg->inactive_sql();
4414 } elsif ( $params->{'magic'} eq 'suspended'
4415 || $params->{'status'} eq 'suspended' ) {
4417 push @where, FS::cust_pkg->suspended_sql();
4419 } elsif ( $params->{'magic'} =~ /^cancell?ed$/
4420 || $params->{'status'} =~ /^cancell?ed$/ ) {
4422 push @where, FS::cust_pkg->cancelled_sql();
4427 # parse package class
4430 if ( exists($params->{'classnum'}) ) {
4433 if ( ref($params->{'classnum'}) ) {
4435 if ( ref($params->{'classnum'}) eq 'HASH' ) {
4436 @classnum = grep $params->{'classnum'}{$_}, keys %{ $params->{'classnum'} };
4437 } elsif ( ref($params->{'classnum'}) eq 'ARRAY' ) {
4438 @classnum = @{ $params->{'classnum'} };
4440 die 'unhandled classnum ref '. $params->{'classnum'};
4444 } elsif ( $params->{'classnum'} =~ /^(\d*)$/ && $1 ne '0' ) {
4451 my @nums = grep $_, @classnum;
4452 push @c_where, 'part_pkg.classnum IN ('. join(',',@nums). ')' if @nums;
4453 my $null = scalar( grep { $_ eq '' } @classnum );
4454 push @c_where, 'part_pkg.classnum IS NULL' if $null;
4456 if ( scalar(@c_where) == 1 ) {
4457 push @where, @c_where;
4458 } elsif ( @c_where ) {
4459 push @where, ' ( '. join(' OR ', @c_where). ' ) ';
4468 # parse package report options
4471 my @report_option = ();
4472 if ( exists($params->{'report_option'}) ) {
4473 if ( ref($params->{'report_option'}) eq 'ARRAY' ) {
4474 @report_option = @{ $params->{'report_option'} };
4475 } elsif ( $params->{'report_option'} =~ /^([,\d]*)$/ ) {
4476 @report_option = split(',', $1);
4481 if (@report_option) {
4482 # this will result in the empty set for the dangling comma case as it should
4484 map{ "0 < ( SELECT count(*) FROM part_pkg_option
4485 WHERE part_pkg_option.pkgpart = part_pkg.pkgpart
4486 AND optionname = 'report_option_$_'
4487 AND optionvalue = '1' )"
4491 foreach my $any ( grep /^report_option_any/, keys %$params ) {
4493 my @report_option_any = ();
4494 if ( ref($params->{$any}) eq 'ARRAY' ) {
4495 @report_option_any = @{ $params->{$any} };
4496 } elsif ( $params->{$any} =~ /^([,\d]*)$/ ) {
4497 @report_option_any = split(',', $1);
4500 if (@report_option_any) {
4501 # this will result in the empty set for the dangling comma case as it should
4502 push @where, ' ( '. join(' OR ',
4503 map{ "0 < ( SELECT count(*) FROM part_pkg_option
4504 WHERE part_pkg_option.pkgpart = part_pkg.pkgpart
4505 AND optionname = 'report_option_$_'
4506 AND optionvalue = '1' )"
4507 } @report_option_any
4517 push @where, "part_pkg.custom = 'Y'" if $params->{custom};
4523 push @where, "(part_pkg.fcc_ds0s > 0 OR pkg_class.fcc_ds0s > 0)"
4524 if $params->{fcc_line};
4530 if ( exists($params->{'censustract'}) ) {
4531 $params->{'censustract'} =~ /^([.\d]*)$/;
4532 my $censustract = "cust_location.censustract = '$1'";
4533 $censustract .= ' OR cust_location.censustract is NULL' unless $1;
4534 push @where, "( $censustract )";
4538 # parse censustract2
4540 if ( exists($params->{'censustract2'})
4541 && $params->{'censustract2'} =~ /^(\d*)$/
4545 push @where, "cust_location.censustract LIKE '$1%'";
4548 "( cust_location.censustract = '' OR cust_location.censustract IS NULL )";
4553 # parse country/state
4555 for (qw(state country)) { # parsing rules are the same for these
4556 if ( exists($params->{$_})
4557 && uc($params->{$_}) =~ /^([A-Z]{2})$/ )
4559 # XXX post-2.3 only--before that, state/country may be in cust_main
4560 push @where, "cust_location.$_ = '$1'";
4567 if ( $params->{location_cust} xor $params->{location_nocust} ) {
4568 my $op = $params->{location_cust} ? '=' : '!=';
4569 push @where, "cust_location.locationnum $op cust_main.ship_locationnum";
4571 if ( $params->{location_census} xor $params->{location_nocensus} ) {
4572 my $op = $params->{location_census} ? "IS NOT NULL" : "IS NULL";
4573 push @where, "cust_location.censustract $op";
4575 if ( $params->{location_geocode} xor $params->{location_nogeocode} ) {
4576 my $op = $params->{location_geocode} ? "IS NOT NULL" : "IS NULL";
4577 push @where, "cust_location.geocode $op";
4584 if ( ref($params->{'pkgpart'}) ) {
4587 if ( ref($params->{'pkgpart'}) eq 'HASH' ) {
4588 @pkgpart = grep $params->{'pkgpart'}{$_}, keys %{ $params->{'pkgpart'} };
4589 } elsif ( ref($params->{'pkgpart'}) eq 'ARRAY' ) {
4590 @pkgpart = @{ $params->{'pkgpart'} };
4592 die 'unhandled pkgpart ref '. $params->{'pkgpart'};
4595 @pkgpart = grep /^(\d+)$/, @pkgpart;
4597 push @where, 'pkgpart IN ('. join(',', @pkgpart). ')' if scalar(@pkgpart);
4599 } elsif ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
4600 push @where, "pkgpart = $1";
4609 #false laziness w/report_cust_pkg.html
4612 'one-time charge' => { 'last_bill'=>1, 'bill'=>1, 'adjourn'=>1, 'susp'=>1, 'expire'=>1, 'cancel'=>1, },
4613 'active' => { 'susp'=>1, 'cancel'=>1 },
4614 'suspended' => { 'cancel' => 1 },
4619 if( exists($params->{'active'} ) ) {
4620 # This overrides all the other date-related fields
4621 my($beginning, $ending) = @{$params->{'active'}};
4623 "cust_pkg.setup IS NOT NULL",
4624 "cust_pkg.setup <= $ending",
4625 "(cust_pkg.cancel IS NULL OR cust_pkg.cancel >= $beginning )",
4626 "NOT (".FS::cust_pkg->onetime_sql . ")";
4629 foreach my $field (qw( setup last_bill bill adjourn susp expire contract_end change_date cancel )) {
4631 next unless exists($params->{$field});
4633 my($beginning, $ending) = @{$params->{$field}};
4635 next if $beginning == 0 && $ending == 4294967295;
4638 "cust_pkg.$field IS NOT NULL",
4639 "cust_pkg.$field >= $beginning",
4640 "cust_pkg.$field <= $ending";
4642 $orderby ||= "ORDER BY cust_pkg.$field";
4647 $orderby ||= 'ORDER BY bill';
4650 # parse magic, legacy, etc.
4653 if ( $params->{'magic'} &&
4654 $params->{'magic'} =~ /^(active|inactive|suspended|cancell?ed)$/
4657 $orderby = 'ORDER BY pkgnum';
4659 if ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
4660 push @where, "pkgpart = $1";
4663 } elsif ( $params->{'query'} eq 'pkgnum' ) {
4665 $orderby = 'ORDER BY pkgnum';
4667 } elsif ( $params->{'query'} eq 'APKG_pkgnum' ) {
4669 $orderby = 'ORDER BY pkgnum';
4672 SELECT count(*) FROM pkg_svc
4673 WHERE pkg_svc.pkgpart = cust_pkg.pkgpart
4674 AND pkg_svc.quantity > ( SELECT count(*) FROM cust_svc
4675 WHERE cust_svc.pkgnum = cust_pkg.pkgnum
4676 AND cust_svc.svcpart = pkg_svc.svcpart
4683 # setup queries, links, subs, etc. for the search
4686 # here is the agent virtualization
4687 if ($params->{CurrentUser}) {
4689 qsearchs('access_user', { username => $params->{CurrentUser} });
4692 push @where, $access_user->agentnums_sql('table'=>'cust_main');
4697 push @where, $FS::CurrentUser::CurrentUser->agentnums_sql('table'=>'cust_main');
4700 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
4702 my $addl_from = 'LEFT JOIN part_pkg USING ( pkgpart ) '.
4703 'LEFT JOIN pkg_class ON ( part_pkg.classnum = pkg_class.classnum ) '.
4704 'LEFT JOIN cust_location USING ( locationnum ) '.
4705 FS::UI::Web::join_cust_main('cust_pkg', 'cust_pkg');
4709 if ( $params->{'select_zip5'} ) {
4710 my $zip = 'cust_location.zip';
4712 $select = "DISTINCT substr($zip,1,5) as zip";
4713 $orderby = "ORDER BY substr($zip,1,5)";
4714 $count_query = "SELECT COUNT( DISTINCT substr($zip,1,5) )";
4716 $select = join(', ',
4718 ( map "part_pkg.$_", qw( pkg freq ) ),
4719 'pkg_class.classname',
4720 'cust_main.custnum AS cust_main_custnum',
4721 FS::UI::Web::cust_sql_fields(
4722 $params->{'cust_fields'}
4725 $count_query = 'SELECT COUNT(*)';
4728 $count_query .= " FROM cust_pkg $addl_from $extra_sql";
4731 'table' => 'cust_pkg',
4733 'select' => $select,
4734 'extra_sql' => $extra_sql,
4735 'order_by' => $orderby,
4736 'addl_from' => $addl_from,
4737 'count_query' => $count_query,
4744 Returns a list of two package counts. The first is a count of packages
4745 based on the supplied criteria and the second is the count of residential
4746 packages with those same criteria. Criteria are specified as in the search
4752 my ($class, $params) = @_;
4754 my $sql_query = $class->search( $params );
4756 my $count_sql = delete($sql_query->{'count_query'});
4757 $count_sql =~ s/ FROM/,count(CASE WHEN cust_main.company IS NULL OR cust_main.company = '' THEN 1 END) FROM/
4758 or die "couldn't parse count_sql";
4760 my $count_sth = dbh->prepare($count_sql)
4761 or die "Error preparing $count_sql: ". dbh->errstr;
4763 or die "Error executing $count_sql: ". $count_sth->errstr;
4764 my $count_arrayref = $count_sth->fetchrow_arrayref;
4766 return ( @$count_arrayref );
4770 =item tax_locationnum_sql
4772 Returns an SQL expression for the tax location for a package, based
4773 on the settings of 'tax-pkg_address' and 'tax-ship_address'.
4777 sub tax_locationnum_sql {
4778 my $conf = FS::Conf->new;
4779 if ( $conf->exists('tax-pkg_address') ) {
4780 'cust_pkg.locationnum';
4782 elsif ( $conf->exists('tax-ship_address') ) {
4783 'cust_main.ship_locationnum';
4786 'cust_main.bill_locationnum';
4792 Returns a list: the first item is an SQL fragment identifying matching
4793 packages/customers via location (taking into account shipping and package
4794 address taxation, if enabled), and subsequent items are the parameters to
4795 substitute for the placeholders in that fragment.
4800 my($class, %opt) = @_;
4801 my $ornull = $opt{'ornull'};
4803 my $conf = new FS::Conf;
4805 # '?' placeholders in _location_sql_where
4806 my $x = $ornull ? 3 : 2;
4817 if ( $conf->exists('tax-ship_address') ) {
4820 ( ( ship_last IS NULL OR ship_last = '' )
4821 AND ". _location_sql_where('cust_main', '', $ornull ). "
4823 OR ( ship_last IS NOT NULL AND ship_last != ''
4824 AND ". _location_sql_where('cust_main', 'ship_', $ornull ). "
4827 # AND payby != 'COMP'
4829 @main_param = ( @bill_param, @bill_param );
4833 $main_where = _location_sql_where('cust_main'); # AND payby != 'COMP'
4834 @main_param = @bill_param;
4840 if ( $conf->exists('tax-pkg_address') ) {
4842 my $loc_where = _location_sql_where( 'cust_location', '', $ornull );
4845 ( cust_pkg.locationnum IS NULL AND $main_where )
4846 OR ( cust_pkg.locationnum IS NOT NULL AND $loc_where )
4849 @param = ( @main_param, @bill_param );
4853 $where = $main_where;
4854 @param = @main_param;
4862 #subroutine, helper for location_sql
4863 sub _location_sql_where {
4865 my $prefix = @_ ? shift : '';
4866 my $ornull = @_ ? shift : '';
4868 # $ornull = $ornull ? " OR ( ? IS NULL AND $table.${prefix}county IS NULL ) " : '';
4870 $ornull = $ornull ? ' OR ? IS NULL ' : '';
4872 my $or_empty_city = " OR ( ? = '' AND $table.${prefix}city IS NULL )";
4873 my $or_empty_county = " OR ( ? = '' AND $table.${prefix}county IS NULL )";
4874 my $or_empty_state = " OR ( ? = '' AND $table.${prefix}state IS NULL )";
4876 my $text = (driver_name =~ /^mysql/i) ? 'char' : 'text';
4878 # ( $table.${prefix}city = ? $or_empty_city $ornull )
4880 ( $table.district = ? OR ? = '' OR CAST(? AS $text) IS NULL )
4881 AND ( $table.${prefix}city = ? OR ? = '' OR CAST(? AS $text) IS NULL )
4882 AND ( $table.${prefix}county = ? $or_empty_county $ornull )
4883 AND ( $table.${prefix}state = ? $or_empty_state $ornull )
4884 AND $table.${prefix}country = ?
4889 my( $self, $what ) = @_;
4891 my $what_show_zero = $what. '_show_zero';
4892 length($self->$what_show_zero())
4893 ? ($self->$what_show_zero() eq 'Y')
4894 : $self->part_pkg->$what_show_zero();
4901 =item order CUSTNUM, PKGPARTS_ARYREF, [ REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF [ REFNUM ] ] ]
4903 CUSTNUM is a customer (see L<FS::cust_main>)
4905 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
4906 L<FS::part_pkg>) to order for this customer. Duplicates are of course
4909 REMOVE_PKGNUMS is an optional list of pkgnums specifying the billing items to
4910 remove for this customer. The services (see L<FS::cust_svc>) are moved to the
4911 new billing items. An error is returned if this is not possible (see
4912 L<FS::pkg_svc>). An empty arrayref is equivalent to not specifying this
4915 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
4916 newly-created cust_pkg objects.
4918 REFNUM, if specified, will specify the FS::pkg_referral record to be created
4919 and inserted. Multiple FS::pkg_referral records can be created by
4920 setting I<refnum> to an array reference of refnums or a hash reference with
4921 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
4922 record will be created corresponding to cust_main.refnum.
4927 my ($custnum, $pkgparts, $remove_pkgnum, $return_cust_pkg, $refnum) = @_;
4929 my $conf = new FS::Conf;
4931 # Transactionize this whole mess
4932 local $SIG{HUP} = 'IGNORE';
4933 local $SIG{INT} = 'IGNORE';
4934 local $SIG{QUIT} = 'IGNORE';
4935 local $SIG{TERM} = 'IGNORE';
4936 local $SIG{TSTP} = 'IGNORE';
4937 local $SIG{PIPE} = 'IGNORE';
4939 my $oldAutoCommit = $FS::UID::AutoCommit;
4940 local $FS::UID::AutoCommit = 0;
4944 # my $cust_main = qsearchs('cust_main', { custnum => $custnum });
4945 # return "Customer not found: $custnum" unless $cust_main;
4947 warn "$me order: pkgnums to remove: ". join(',', @$remove_pkgnum). "\n"
4950 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
4953 my $change = scalar(@old_cust_pkg) != 0;
4956 if ( scalar(@old_cust_pkg) == 1 && scalar(@$pkgparts) == 1 ) {
4958 warn "$me order: changing pkgnum ". $old_cust_pkg[0]->pkgnum.
4959 " to pkgpart ". $pkgparts->[0]. "\n"
4962 my $err_or_cust_pkg =
4963 $old_cust_pkg[0]->change( 'pkgpart' => $pkgparts->[0],
4964 'refnum' => $refnum,
4967 unless (ref($err_or_cust_pkg)) {
4968 $dbh->rollback if $oldAutoCommit;
4969 return $err_or_cust_pkg;
4972 push @$return_cust_pkg, $err_or_cust_pkg;
4973 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4978 # Create the new packages.
4979 foreach my $pkgpart (@$pkgparts) {
4981 warn "$me order: inserting pkgpart $pkgpart\n" if $DEBUG;
4983 my $cust_pkg = new FS::cust_pkg { custnum => $custnum,
4984 pkgpart => $pkgpart,
4988 $error = $cust_pkg->insert( 'change' => $change );
4989 push @$return_cust_pkg, $cust_pkg;
4991 foreach my $link ($cust_pkg->part_pkg->supp_part_pkg_link) {
4992 my $supp_pkg = FS::cust_pkg->new({
4993 custnum => $custnum,
4994 pkgpart => $link->dst_pkgpart,
4996 main_pkgnum => $cust_pkg->pkgnum,
4999 $error ||= $supp_pkg->insert( 'change' => $change );
5000 push @$return_cust_pkg, $supp_pkg;
5004 $dbh->rollback if $oldAutoCommit;
5009 # $return_cust_pkg now contains refs to all of the newly
5012 # Transfer services and cancel old packages.
5013 foreach my $old_pkg (@old_cust_pkg) {
5015 warn "$me order: transferring services from pkgnum ". $old_pkg->pkgnum. "\n"
5018 foreach my $new_pkg (@$return_cust_pkg) {
5019 $error = $old_pkg->transfer($new_pkg);
5020 if ($error and $error == 0) {
5021 # $old_pkg->transfer failed.
5022 $dbh->rollback if $oldAutoCommit;
5027 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
5028 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
5029 foreach my $new_pkg (@$return_cust_pkg) {
5030 $error = $old_pkg->transfer($new_pkg, 'change_svcpart'=>1 );
5031 if ($error and $error == 0) {
5032 # $old_pkg->transfer failed.
5033 $dbh->rollback if $oldAutoCommit;
5040 # Transfers were successful, but we went through all of the
5041 # new packages and still had services left on the old package.
5042 # We can't cancel the package under the circumstances, so abort.
5043 $dbh->rollback if $oldAutoCommit;
5044 return "Unable to transfer all services from package ".$old_pkg->pkgnum;
5046 $error = $old_pkg->cancel( quiet=>1 );
5052 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5056 =item bulk_change PKGPARTS_ARYREF, REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF ]
5058 A bulk change method to change packages for multiple customers.
5060 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
5061 L<FS::part_pkg>) to order for each customer. Duplicates are of course
5064 REMOVE_PKGNUMS is an list of pkgnums specifying the billing items to
5065 replace. The services (see L<FS::cust_svc>) are moved to the
5066 new billing items. An error is returned if this is not possible (see
5069 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
5070 newly-created cust_pkg objects.
5075 my ($pkgparts, $remove_pkgnum, $return_cust_pkg) = @_;
5077 # Transactionize this whole mess
5078 local $SIG{HUP} = 'IGNORE';
5079 local $SIG{INT} = 'IGNORE';
5080 local $SIG{QUIT} = 'IGNORE';
5081 local $SIG{TERM} = 'IGNORE';
5082 local $SIG{TSTP} = 'IGNORE';
5083 local $SIG{PIPE} = 'IGNORE';
5085 my $oldAutoCommit = $FS::UID::AutoCommit;
5086 local $FS::UID::AutoCommit = 0;
5090 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
5093 while(scalar(@old_cust_pkg)) {
5095 my $custnum = $old_cust_pkg[0]->custnum;
5096 my (@remove) = map { $_->pkgnum }
5097 grep { $_->custnum == $custnum } @old_cust_pkg;
5098 @old_cust_pkg = grep { $_->custnum != $custnum } @old_cust_pkg;
5100 my $error = order $custnum, $pkgparts, \@remove, \@return;
5102 push @errors, $error
5104 push @$return_cust_pkg, @return;
5107 if (scalar(@errors)) {
5108 $dbh->rollback if $oldAutoCommit;
5109 return join(' / ', @errors);
5112 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5116 # Used by FS::Upgrade to migrate to a new database.
5117 sub _upgrade_data { # class method
5118 my ($class, %opts) = @_;
5119 $class->_upgrade_otaker(%opts);
5121 # RT#10139, bug resulting in contract_end being set when it shouldn't
5122 'UPDATE cust_pkg SET contract_end = NULL WHERE contract_end = -1',
5123 # RT#10830, bad calculation of prorate date near end of year
5124 # the date range for bill is December 2009, and we move it forward
5125 # one year if it's before the previous bill date (which it should
5127 'UPDATE cust_pkg SET bill = bill + (365*24*60*60) WHERE bill < last_bill
5128 AND bill > 1259654400 AND bill < 1262332800 AND (SELECT plan FROM part_pkg
5129 WHERE part_pkg.pkgpart = cust_pkg.pkgpart) = \'prorate\'',
5130 # RT6628, add order_date to cust_pkg
5131 'update cust_pkg set order_date = (select history_date from h_cust_pkg
5132 where h_cust_pkg.pkgnum = cust_pkg.pkgnum and
5133 history_action = \'insert\') where order_date is null',
5135 foreach my $sql (@statements) {
5136 my $sth = dbh->prepare($sql);
5137 $sth->execute or die $sth->errstr;
5145 sub order is not OO. Perhaps it should be moved to FS::cust_main and made so?
5147 In sub order, the @pkgparts array (passed by reference) is clobbered.
5149 Also in sub order, no money is adjusted. Once FS::part_pkg defines a standard
5150 method to pass dates to the recur_prog expression, it should do so.
5152 FS::svc_acct, FS::svc_domain, FS::svc_www, FS::svc_ip and FS::svc_forward are
5153 loaded via 'use' at compile time, rather than via 'require' in sub { setup,
5154 suspend, unsuspend, cancel } because they use %FS::UID::callback to load
5155 configuration values. Probably need a subroutine which decides what to do
5156 based on whether or not we've fetched the user yet, rather than a hash. See
5157 FS::UID and the TODO.
5159 Now that things are transactional should the check in the insert method be
5164 L<FS::Record>, L<FS::cust_main>, L<FS::part_pkg>, L<FS::cust_svc>,
5165 L<FS::pkg_svc>, schema.html from the base documentation