2 use base qw( FS::otaker_Mixin FS::cust_main_Mixin FS::Sales_Mixin
3 FS::contact_Mixin FS::location_Mixin
4 FS::m2m_Common FS::option_Common );
7 use vars qw($disable_agentcheck $DEBUG $me);
9 use Scalar::Util qw( blessed );
10 use List::Util qw(min max);
12 use Time::Local qw( timelocal timelocal_nocheck );
14 use FS::UID qw( 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;
39 # need to 'use' these instead of 'require' in sub { cancel, suspend, unsuspend,
41 # because they load configuration by setting FS::UID::callback (see TODO)
47 # for sending cancel emails in sub cancel
51 $me = '[FS::cust_pkg]';
53 $disable_agentcheck = 0;
57 my ( $hashref, $cache ) = @_;
58 #if ( $hashref->{'pkgpart'} ) {
59 if ( $hashref->{'pkg'} ) {
60 # #@{ $self->{'_pkgnum'} } = ();
61 # my $subcache = $cache->subcache('pkgpart', 'part_pkg');
62 # $self->{'_pkgpart'} = $subcache;
63 # #push @{ $self->{'_pkgnum'} },
64 # FS::part_pkg->new_or_cached($hashref, $subcache);
65 $self->{'_pkgpart'} = FS::part_pkg->new($hashref);
67 if ( exists $hashref->{'svcnum'} ) {
68 #@{ $self->{'_pkgnum'} } = ();
69 my $subcache = $cache->subcache('svcnum', 'cust_svc', $hashref->{pkgnum});
70 $self->{'_svcnum'} = $subcache;
71 #push @{ $self->{'_pkgnum'} },
72 FS::cust_svc->new_or_cached($hashref, $subcache) if $hashref->{svcnum};
78 FS::cust_pkg - Object methods for cust_pkg objects
84 $record = new FS::cust_pkg \%hash;
85 $record = new FS::cust_pkg { 'column' => 'value' };
87 $error = $record->insert;
89 $error = $new_record->replace($old_record);
91 $error = $record->delete;
93 $error = $record->check;
95 $error = $record->cancel;
97 $error = $record->suspend;
99 $error = $record->unsuspend;
101 $part_pkg = $record->part_pkg;
103 @labels = $record->labels;
105 $seconds = $record->seconds_since($timestamp);
107 $error = FS::cust_pkg::order( $custnum, \@pkgparts );
108 $error = FS::cust_pkg::order( $custnum, \@pkgparts, \@remove_pkgnums ] );
112 An FS::cust_pkg object represents a customer billing item. FS::cust_pkg
113 inherits from FS::Record. The following fields are currently supported:
119 Primary key (assigned automatically for new billing items)
123 Customer (see L<FS::cust_main>)
127 Billing item definition (see L<FS::part_pkg>)
131 Optional link to package location (see L<FS::location>)
135 date package was ordered (also remains same on changes)
147 date (next bill date)
175 order taker (see L<FS::access_user>)
179 If this field is set to 1, disables the automatic
180 unsuspension of this package when using the B<unsuspendauto> config option.
184 If not set, defaults to 1
188 Date of change from previous package
198 =item change_locationnum
206 The pkgnum of the package that this package is supplemental to, if any.
210 The package link (L<FS::part_pkg_link>) that defines this supplemental
211 package, if it is one.
213 =item change_to_pkgnum
215 The pkgnum of the package this one will be "changed to" in the future
216 (on its expiration date).
220 Note: setup, last_bill, bill, adjourn, susp, expire, cancel and change_date
221 are specified as UNIX timestamps; see L<perlfunc/"time">. Also see
222 L<Time::Local> and L<Date::Parse> for conversion functions.
230 Create a new billing item. To add the item to the database, see L<"insert">.
234 sub table { 'cust_pkg'; }
235 sub cust_linked { $_[0]->cust_main_custnum || $_[0]->custnum }
236 sub cust_unlinked_msg {
238 "WARNING: can't find cust_main.custnum ". $self->custnum.
239 ' (cust_pkg.pkgnum '. $self->pkgnum. ')';
242 =item insert [ OPTION => VALUE ... ]
244 Adds this billing item to the database ("Orders" the item). If there is an
245 error, returns the error, otherwise returns false.
247 If the additional field I<promo_code> is defined instead of I<pkgpart>, it
248 will be used to look up the package definition and agent restrictions will be
251 If the additional field I<refnum> is defined, an FS::pkg_referral record will
252 be created and inserted. Multiple FS::pkg_referral records can be created by
253 setting I<refnum> to an array reference of refnums or a hash reference with
254 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
255 record will be created corresponding to cust_main.refnum.
257 The following options are available:
263 If set true, supresses actions that should only be taken for new package
264 orders. (Currently this includes: intro periods when delay_setup is on.)
268 cust_pkg_option records will be created
272 a ticket will be added to this customer with this subject
276 an optional queue name for ticket additions
280 Don't check the legality of the package definition. This should be used
281 when performing a package change that doesn't change the pkgpart (i.e.
289 my( $self, %options ) = @_;
292 $error = $self->check_pkgpart unless $options{'allow_pkgpart'};
293 return $error if $error;
295 my $part_pkg = $self->part_pkg;
297 # if the package def says to start only on the first of the month:
298 if ( $part_pkg->option('start_1st', 1) && !$self->start_date ) {
299 my ($sec,$min,$hour,$mday,$mon,$year) = (localtime(time) )[0,1,2,3,4,5];
300 $mon += 1 unless $mday == 1;
301 until ( $mon < 12 ) { $mon -= 12; $year++; }
302 $self->start_date( timelocal_nocheck(0,0,0,1,$mon,$year) );
305 # set up any automatic expire/adjourn/contract_end timers
306 # based on the start date
307 foreach my $action ( qw(expire adjourn contract_end) ) {
308 my $months = $part_pkg->option("${action}_months",1);
309 if($months and !$self->$action) {
310 my $start = $self->start_date || $self->setup || time;
311 $self->$action( $part_pkg->add_freq($start, $months) );
315 # if this package has "free days" and delayed setup fee, tehn
316 # set start date that many days in the future.
317 # (this should have been set in the UI, but enforce it here)
318 if ( ! $options{'change'}
319 && ( my $free_days = $part_pkg->option('free_days',1) )
320 && $part_pkg->option('delay_setup',1)
321 #&& ! $self->start_date
324 $self->start_date( $part_pkg->default_start_date );
327 $self->order_date(time);
329 local $SIG{HUP} = 'IGNORE';
330 local $SIG{INT} = 'IGNORE';
331 local $SIG{QUIT} = 'IGNORE';
332 local $SIG{TERM} = 'IGNORE';
333 local $SIG{TSTP} = 'IGNORE';
334 local $SIG{PIPE} = 'IGNORE';
336 my $oldAutoCommit = $FS::UID::AutoCommit;
337 local $FS::UID::AutoCommit = 0;
340 $error = $self->SUPER::insert($options{options} ? %{$options{options}} : ());
342 $dbh->rollback if $oldAutoCommit;
346 $self->refnum($self->cust_main->refnum) unless $self->refnum;
347 $self->refnum( [ $self->refnum ] ) unless ref($self->refnum);
348 $self->process_m2m( 'link_table' => 'pkg_referral',
349 'target_table' => 'part_referral',
350 'params' => $self->refnum,
353 if ( $self->discountnum ) {
354 my $error = $self->insert_discount();
356 $dbh->rollback if $oldAutoCommit;
361 my $conf = new FS::Conf;
363 if ( $conf->config('ticket_system') && $options{ticket_subject} ) {
365 #this init stuff is still inefficient, but at least its limited to
366 # the small number (any?) folks using ticket emailing on pkg order
369 # use lib ( "/opt/rt3/local/lib", "/opt/rt3/lib" );
376 use FS::TicketSystem;
377 FS::TicketSystem->init();
379 my $q = new RT::Queue($RT::SystemUser);
380 $q->Load($options{ticket_queue}) if $options{ticket_queue};
381 my $t = new RT::Ticket($RT::SystemUser);
382 my $mime = new MIME::Entity;
383 $mime->build( Type => 'text/plain', Data => $options{ticket_subject} );
384 $t->Create( $options{ticket_queue} ? (Queue => $q) : (),
385 Subject => $options{ticket_subject},
388 $t->AddLink( Type => 'MemberOf',
389 Target => 'freeside://freeside/cust_main/'. $self->custnum,
393 if ($conf->config('welcome_letter') && $self->cust_main->num_pkgs == 1) {
394 my $queue = new FS::queue {
395 'job' => 'FS::cust_main::queueable_print',
397 $error = $queue->insert(
398 'custnum' => $self->custnum,
399 'template' => 'welcome_letter',
403 warn "can't send welcome letter: $error";
408 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
415 This method now works but you probably shouldn't use it.
417 You don't want to delete packages, because there would then be no record
418 the customer ever purchased the package. Instead, see the cancel method and
419 hide cancelled packages.
426 local $SIG{HUP} = 'IGNORE';
427 local $SIG{INT} = 'IGNORE';
428 local $SIG{QUIT} = 'IGNORE';
429 local $SIG{TERM} = 'IGNORE';
430 local $SIG{TSTP} = 'IGNORE';
431 local $SIG{PIPE} = 'IGNORE';
433 my $oldAutoCommit = $FS::UID::AutoCommit;
434 local $FS::UID::AutoCommit = 0;
437 foreach my $cust_pkg_discount ($self->cust_pkg_discount) {
438 my $error = $cust_pkg_discount->delete;
440 $dbh->rollback if $oldAutoCommit;
444 #cust_bill_pkg_discount?
446 foreach my $cust_pkg_detail ($self->cust_pkg_detail) {
447 my $error = $cust_pkg_detail->delete;
449 $dbh->rollback if $oldAutoCommit;
454 foreach my $cust_pkg_reason (
456 'table' => 'cust_pkg_reason',
457 'hashref' => { 'pkgnum' => $self->pkgnum },
461 my $error = $cust_pkg_reason->delete;
463 $dbh->rollback if $oldAutoCommit;
470 my $error = $self->SUPER::delete(@_);
472 $dbh->rollback if $oldAutoCommit;
476 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
482 =item replace [ OLD_RECORD ] [ HASHREF | OPTION => VALUE ... ]
484 Replaces the OLD_RECORD with this one in the database. If there is an error,
485 returns the error, otherwise returns false.
487 Currently, custnum, setup, bill, adjourn, susp, expire, and cancel may be changed.
489 Changing pkgpart may have disasterous effects. See the order subroutine.
491 setup and bill are normally updated by calling the bill method of a customer
492 object (see L<FS::cust_main>).
494 suspend is normally updated by the suspend and unsuspend methods.
496 cancel is normally updated by the cancel method (and also the order subroutine
499 Available options are:
505 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.
509 the access_user (see L<FS::access_user>) providing the reason
513 hashref of keys and values - cust_pkg_option records will be created, updated or removed as appopriate
522 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
527 ( ref($_[0]) eq 'HASH' )
531 #return "Can't (yet?) change pkgpart!" if $old->pkgpart != $new->pkgpart;
532 #return "Can't change otaker!" if $old->otaker ne $new->otaker;
535 #return "Can't change setup once it exists!"
536 # if $old->getfield('setup') &&
537 # $old->getfield('setup') != $new->getfield('setup');
539 #some logic for bill, susp, cancel?
541 local($disable_agentcheck) = 1 if $old->pkgpart == $new->pkgpart;
543 local $SIG{HUP} = 'IGNORE';
544 local $SIG{INT} = 'IGNORE';
545 local $SIG{QUIT} = 'IGNORE';
546 local $SIG{TERM} = 'IGNORE';
547 local $SIG{TSTP} = 'IGNORE';
548 local $SIG{PIPE} = 'IGNORE';
550 my $oldAutoCommit = $FS::UID::AutoCommit;
551 local $FS::UID::AutoCommit = 0;
554 foreach my $method ( qw(adjourn expire) ) { # How many reasons?
555 if ($options->{'reason'} && $new->$method && $old->$method ne $new->$method) {
556 my $error = $new->insert_reason(
557 'reason' => $options->{'reason'},
558 'date' => $new->$method,
560 'reason_otaker' => $options->{'reason_otaker'},
563 dbh->rollback if $oldAutoCommit;
564 return "Error inserting cust_pkg_reason: $error";
569 #save off and freeze RADIUS attributes for any associated svc_acct records
571 if ( $old->part_pkg->is_prepaid || $new->part_pkg->is_prepaid ) {
573 #also check for specific exports?
574 # to avoid spurious modify export events
575 @svc_acct = map { $_->svc_x }
576 grep { $_->part_svc->svcdb eq 'svc_acct' }
579 $_->snapshot foreach @svc_acct;
583 my $error = $new->export_pkg_change($old)
584 || $new->SUPER::replace( $old,
586 ? $options->{options}
590 $dbh->rollback if $oldAutoCommit;
594 #for prepaid packages,
595 #trigger export of new RADIUS Expiration attribute when cust_pkg.bill changes
596 foreach my $old_svc_acct ( @svc_acct ) {
597 my $new_svc_acct = new FS::svc_acct { $old_svc_acct->hash };
599 $new_svc_acct->replace( $old_svc_acct,
600 'depend_jobnum' => $options->{depend_jobnum},
603 $dbh->rollback if $oldAutoCommit;
608 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
615 Checks all fields to make sure this is a valid billing item. If there is an
616 error, returns the error, otherwise returns false. Called by the insert and
624 if ( !$self->locationnum or $self->locationnum == -1 ) {
625 $self->set('locationnum', $self->cust_main->ship_locationnum);
629 $self->ut_numbern('pkgnum')
630 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum')
631 || $self->ut_numbern('pkgpart')
632 || $self->ut_foreign_keyn('contactnum', 'contact', 'contactnum' )
633 || $self->ut_foreign_keyn('locationnum', 'cust_location', 'locationnum')
634 || $self->ut_foreign_keyn('salesnum', 'sales', 'salesnum')
635 || $self->ut_numbern('quantity')
636 || $self->ut_numbern('start_date')
637 || $self->ut_numbern('setup')
638 || $self->ut_numbern('bill')
639 || $self->ut_numbern('susp')
640 || $self->ut_numbern('cancel')
641 || $self->ut_numbern('adjourn')
642 || $self->ut_numbern('resume')
643 || $self->ut_numbern('expire')
644 || $self->ut_numbern('dundate')
645 || $self->ut_enum('no_auto', [ '', 'Y' ])
646 || $self->ut_enum('waive_setup', [ '', 'Y' ])
647 || $self->ut_numbern('agent_pkgid')
648 || $self->ut_enum('recur_show_zero', [ '', 'Y', 'N', ])
649 || $self->ut_enum('setup_show_zero', [ '', 'Y', 'N', ])
650 || $self->ut_foreign_keyn('main_pkgnum', 'cust_pkg', 'pkgnum')
651 || $self->ut_foreign_keyn('pkglinknum', 'part_pkg_link', 'pkglinknum')
652 || $self->ut_foreign_keyn('change_to_pkgnum', 'cust_pkg', 'pkgnum')
654 return $error if $error;
656 return "A package with both start date (future start) and setup date (already started) will never bill"
657 if $self->start_date && $self->setup;
659 return "A future unsuspend date can only be set for a package with a suspend date"
660 if $self->resume and !$self->susp and !$self->adjourn;
662 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
664 if ( $self->dbdef_table->column('manual_flag') ) {
665 $self->manual_flag('') if $self->manual_flag eq ' ';
666 $self->manual_flag =~ /^([01]?)$/
667 or return "Illegal manual_flag ". $self->manual_flag;
668 $self->manual_flag($1);
676 Check the pkgpart to make sure it's allowed with the reg_code and/or
677 promo_code of the package (if present) and with the customer's agent.
678 Called from C<insert>, unless we are doing a package change that doesn't
686 # my $error = $self->ut_numbern('pkgpart'); # already done
689 if ( $self->reg_code ) {
691 unless ( grep { $self->pkgpart == $_->pkgpart }
692 map { $_->reg_code_pkg }
693 qsearchs( 'reg_code', { 'code' => $self->reg_code,
694 'agentnum' => $self->cust_main->agentnum })
696 return "Unknown registration code";
699 } elsif ( $self->promo_code ) {
702 qsearchs('part_pkg', {
703 'pkgpart' => $self->pkgpart,
704 'promo_code' => { op=>'ILIKE', value=>$self->promo_code },
706 return 'Unknown promotional code' unless $promo_part_pkg;
710 unless ( $disable_agentcheck ) {
712 qsearchs( 'agent', { 'agentnum' => $self->cust_main->agentnum } );
713 return "agent ". $agent->agentnum. ':'. $agent->agent.
714 " can't purchase pkgpart ". $self->pkgpart
715 unless $agent->pkgpart_hashref->{ $self->pkgpart }
716 || $agent->agentnum == $self->part_pkg->agentnum;
719 $error = $self->ut_foreign_key('pkgpart', 'part_pkg', 'pkgpart' );
720 return $error if $error;
728 =item cancel [ OPTION => VALUE ... ]
730 Cancels and removes all services (see L<FS::cust_svc> and L<FS::part_svc>)
731 in this package, then cancels the package itself (sets the cancel field to
734 Available options are:
738 =item quiet - can be set true to supress email cancellation notices.
740 =item time - can be set to cancel the package based on a specific future or
741 historical date. Using time ensures that the remaining amount is calculated
742 correctly. Note however that this is an immediate cancel and just changes
743 the date. You are PROBABLY looking to expire the account instead of using
746 =item reason - can be set to a cancellation reason (see L<FS:reason>),
747 either a reasonnum of an existing reason, or passing a hashref will create
748 a new reason. The hashref should have the following keys: typenum - Reason
749 type (see L<FS::reason_type>, reason - Text of the new reason.
751 =item date - can be set to a unix style timestamp to specify when to
754 =item nobill - can be set true to skip billing if it might otherwise be done.
756 =item unused_credit - can be set to 1 to credit the remaining time, or 0 to
757 not credit it. This must be set (by change()) when changing the package
758 to a different pkgpart or location, and probably shouldn't be in any other
759 case. If it's not set, the 'unused_credit_cancel' part_pkg option will
764 If there is an error, returns the error, otherwise returns false.
769 my( $self, %options ) = @_;
772 # pass all suspend/cancel actions to the main package
773 if ( $self->main_pkgnum and !$options{'from_main'} ) {
774 return $self->main_pkg->cancel(%options);
777 my $conf = new FS::Conf;
779 warn "cust_pkg::cancel called with options".
780 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
783 local $SIG{HUP} = 'IGNORE';
784 local $SIG{INT} = 'IGNORE';
785 local $SIG{QUIT} = 'IGNORE';
786 local $SIG{TERM} = 'IGNORE';
787 local $SIG{TSTP} = 'IGNORE';
788 local $SIG{PIPE} = 'IGNORE';
790 my $oldAutoCommit = $FS::UID::AutoCommit;
791 local $FS::UID::AutoCommit = 0;
794 my $old = $self->select_for_update;
796 if ( $old->get('cancel') || $self->get('cancel') ) {
797 dbh->rollback if $oldAutoCommit;
798 return ""; # no error
801 # XXX possibly set cancel_time to the expire date?
802 my $cancel_time = $options{'time'} || time;
803 my $date = $options{'date'} if $options{'date'}; # expire/cancel later
804 $date = '' if ($date && $date <= $cancel_time); # complain instead?
806 #race condition: usage could be ongoing until unprovisioned
807 #resolved by performing a change package instead (which unprovisions) and
809 if ( !$options{nobill} && !$date ) {
810 # && $conf->exists('bill_usage_on_cancel') ) { #calc_cancel checks this
811 my $copy = $self->new({$self->hash});
813 $copy->cust_main->bill( 'pkg_list' => [ $copy ],
815 'time' => $cancel_time );
816 warn "Error billing during cancel, custnum ".
817 #$self->cust_main->custnum. ": $error"
822 if ( $options{'reason'} ) {
823 $error = $self->insert_reason( 'reason' => $options{'reason'},
824 'action' => $date ? 'expire' : 'cancel',
825 'date' => $date ? $date : $cancel_time,
826 'reason_otaker' => $options{'reason_otaker'},
829 dbh->rollback if $oldAutoCommit;
830 return "Error inserting cust_pkg_reason: $error";
834 my %svc_cancel_opt = ();
835 $svc_cancel_opt{'date'} = $date if $date;
836 foreach my $cust_svc (
839 sort { $a->[1] <=> $b->[1] }
840 map { [ $_, $_->svc_x ? $_->svc_x->table_info->{'cancel_weight'} : -1 ]; }
841 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
843 my $part_svc = $cust_svc->part_svc;
844 next if ( defined($part_svc) and $part_svc->preserve );
845 my $error = $cust_svc->cancel( %svc_cancel_opt );
848 $dbh->rollback if $oldAutoCommit;
849 return 'Error '. ($svc_cancel_opt{'date'} ? 'expiring' : 'canceling' ).
855 # credit remaining time if appropriate
857 if ( exists($options{'unused_credit'}) ) {
858 $do_credit = $options{'unused_credit'};
861 $do_credit = $self->part_pkg->option('unused_credit_cancel', 1);
864 my $error = $self->credit_remaining('cancel', $cancel_time);
866 $dbh->rollback if $oldAutoCommit;
873 my %hash = $self->hash;
875 $hash{'expire'} = $date;
877 $hash{'cancel'} = $cancel_time;
879 $hash{'change_custnum'} = $options{'change_custnum'};
881 my $new = new FS::cust_pkg ( \%hash );
882 $error = $new->replace( $self, options => { $self->options } );
883 if ( $self->change_to_pkgnum ) {
884 my $change_to = FS::cust_pkg->by_key($self->change_to_pkgnum);
885 $error ||= $change_to->cancel || $change_to->delete;
888 $dbh->rollback if $oldAutoCommit;
892 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
893 $error = $supp_pkg->cancel(%options, 'from_main' => 1);
895 $dbh->rollback if $oldAutoCommit;
896 return "canceling supplemental pkg#".$supp_pkg->pkgnum.": $error";
900 foreach my $usage ( $self->cust_pkg_usage ) {
901 $error = $usage->delete;
903 $dbh->rollback if $oldAutoCommit;
904 return "deleting usage pools: $error";
908 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
909 return '' if $date; #no errors
911 my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ } $self->cust_main->invoicing_list;
912 if ( !$options{'quiet'} &&
913 $conf->exists('emailcancel', $self->cust_main->agentnum) &&
915 my $msgnum = $conf->config('cancel_msgnum', $self->cust_main->agentnum);
918 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum });
919 $error = $msg_template->send( 'cust_main' => $self->cust_main,
924 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
925 'to' => \@invoicing_list,
926 'subject' => ( $conf->config('cancelsubject') || 'Cancellation Notice' ),
927 'body' => [ map "$_\n", $conf->config('cancelmessage') ],
930 #should this do something on errors?
937 =item cancel_if_expired [ NOW_TIMESTAMP ]
939 Cancels this package if its expire date has been reached.
943 sub cancel_if_expired {
945 my $time = shift || time;
946 return '' unless $self->expire && $self->expire <= $time;
947 my $error = $self->cancel;
949 return "Error cancelling expired pkg ". $self->pkgnum. " for custnum ".
950 $self->custnum. ": $error";
957 "Un-cancels" this package: Orders a new package with the same custnum, pkgpart,
958 locationnum, (other fields?). Attempts to re-provision cancelled services
959 using history information (errors at this stage are not fatal).
961 cust_pkg: pass a scalar reference, will be filled in with the new cust_pkg object
963 svc_fatal: service provisioning errors are fatal
965 svc_errors: pass an array reference, will be filled in with any provisioning errors
967 main_pkgnum: link the package as a supplemental package of this one. For
973 my( $self, %options ) = @_;
975 #in case you try do do $uncancel-date = $cust_pkg->uncacel
976 return '' unless $self->get('cancel');
978 if ( $self->main_pkgnum and !$options{'main_pkgnum'} ) {
979 return $self->main_pkg->uncancel(%options);
986 local $SIG{HUP} = 'IGNORE';
987 local $SIG{INT} = 'IGNORE';
988 local $SIG{QUIT} = 'IGNORE';
989 local $SIG{TERM} = 'IGNORE';
990 local $SIG{TSTP} = 'IGNORE';
991 local $SIG{PIPE} = 'IGNORE';
993 my $oldAutoCommit = $FS::UID::AutoCommit;
994 local $FS::UID::AutoCommit = 0;
998 # insert the new package
1001 my $cust_pkg = new FS::cust_pkg {
1002 last_bill => ( $options{'last_bill'} || $self->get('last_bill') ),
1003 bill => ( $options{'bill'} || $self->get('bill') ),
1005 uncancel_pkgnum => $self->pkgnum,
1006 main_pkgnum => ($options{'main_pkgnum'} || ''),
1007 map { $_ => $self->get($_) } qw(
1008 custnum pkgpart locationnum
1010 susp adjourn resume expire start_date contract_end dundate
1011 change_date change_pkgpart change_locationnum
1012 manual_flag no_auto quantity agent_pkgid recur_show_zero setup_show_zero
1016 my $error = $cust_pkg->insert(
1017 'change' => 1, #supresses any referral credit to a referring customer
1018 'allow_pkgpart' => 1, # allow this even if the package def is disabled
1021 $dbh->rollback if $oldAutoCommit;
1029 #find historical services within this timeframe before the package cancel
1030 # (incompatible with "time" option to cust_pkg->cancel?)
1031 my $fuzz = 2 * 60; #2 minutes? too much? (might catch separate unprovision)
1032 # too little? (unprovisioing export delay?)
1033 my($end, $start) = ( $self->get('cancel'), $self->get('cancel') - $fuzz );
1034 my @h_cust_svc = $self->h_cust_svc( $end, $start );
1037 foreach my $h_cust_svc (@h_cust_svc) {
1038 my $h_svc_x = $h_cust_svc->h_svc_x( $end, $start );
1039 #next unless $h_svc_x; #should this happen?
1040 (my $table = $h_svc_x->table) =~ s/^h_//;
1041 require "FS/$table.pm";
1042 my $class = "FS::$table";
1043 my $svc_x = $class->new( {
1044 'pkgnum' => $cust_pkg->pkgnum,
1045 'svcpart' => $h_cust_svc->svcpart,
1046 map { $_ => $h_svc_x->get($_) } fields($table)
1050 if ( $h_svc_x->isa('FS::h_svc_Radius_Mixin') ) {
1051 $svc_x->usergroup( [ $h_svc_x->h_usergroup($end, $start) ] );
1054 my $svc_error = $svc_x->insert;
1056 if ( $options{svc_fatal} ) {
1057 $dbh->rollback if $oldAutoCommit;
1060 # if we've failed to insert the svc_x object, svc_Common->insert
1061 # will have removed the cust_svc already. if not, then both records
1062 # were inserted but we failed for some other reason (export, most
1063 # likely). in that case, report the error and delete the records.
1064 push @svc_errors, $svc_error;
1065 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svc_x->svcnum });
1067 # except if export_insert failed, export_delete probably won't be
1069 local $FS::svc_Common::noexport_hack = 1;
1070 my $cleanup_error = $svc_x->delete; # also deletes cust_svc
1071 if ( $cleanup_error ) { # and if THAT fails, then run away
1072 $dbh->rollback if $oldAutoCommit;
1073 return $cleanup_error;
1078 } #foreach $h_cust_svc
1080 #these are pretty rare, but should handle them
1081 # - dsl_device (mac addresses)
1082 # - phone_device (mac addresses)
1083 # - dsl_note (ikano notes)
1084 # - domain_record (i.e. restore DNS information w/domains)
1085 # - inventory_item(?) (inventory w/un-cancelling service?)
1086 # - nas (svc_broaband nas stuff)
1087 #this stuff is unused in the wild afaik
1088 # - mailinglistmember
1090 # - svc_domain.parent_svcnum?
1091 # - acct_snarf (ancient mail fetching config)
1092 # - cgp_rule (communigate)
1093 # - cust_svc_option (used by our Tron stuff)
1094 # - acct_rt_transaction (used by our time worked stuff)
1097 # also move over any services that didn't unprovision at cancellation
1100 foreach my $cust_svc ( qsearch('cust_svc', { pkgnum => $self->pkgnum } ) ) {
1101 $cust_svc->pkgnum( $cust_pkg->pkgnum );
1102 my $error = $cust_svc->replace;
1104 $dbh->rollback if $oldAutoCommit;
1110 # Uncancel any supplemental packages, and make them supplemental to the
1114 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1116 $error = $supp_pkg->uncancel(%options, 'main_pkgnum' => $cust_pkg->pkgnum);
1118 $dbh->rollback if $oldAutoCommit;
1119 return "canceling supplemental pkg#".$supp_pkg->pkgnum.": $error";
1127 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1129 ${ $options{cust_pkg} } = $cust_pkg if ref($options{cust_pkg});
1130 @{ $options{svc_errors} } = @svc_errors if ref($options{svc_errors});
1137 Cancels any pending expiration (sets the expire field to null).
1139 If there is an error, returns the error, otherwise returns false.
1144 my( $self, %options ) = @_;
1147 local $SIG{HUP} = 'IGNORE';
1148 local $SIG{INT} = 'IGNORE';
1149 local $SIG{QUIT} = 'IGNORE';
1150 local $SIG{TERM} = 'IGNORE';
1151 local $SIG{TSTP} = 'IGNORE';
1152 local $SIG{PIPE} = 'IGNORE';
1154 my $oldAutoCommit = $FS::UID::AutoCommit;
1155 local $FS::UID::AutoCommit = 0;
1158 my $old = $self->select_for_update;
1160 my $pkgnum = $old->pkgnum;
1161 if ( $old->get('cancel') || $self->get('cancel') ) {
1162 dbh->rollback if $oldAutoCommit;
1163 return "Can't unexpire cancelled package $pkgnum";
1164 # or at least it's pointless
1167 unless ( $old->get('expire') && $self->get('expire') ) {
1168 dbh->rollback if $oldAutoCommit;
1169 return ""; # no error
1172 my %hash = $self->hash;
1173 $hash{'expire'} = '';
1174 my $new = new FS::cust_pkg ( \%hash );
1175 $error = $new->replace( $self, options => { $self->options } );
1177 $dbh->rollback if $oldAutoCommit;
1181 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1187 =item suspend [ OPTION => VALUE ... ]
1189 Suspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
1190 package, then suspends the package itself (sets the susp field to now).
1192 Available options are:
1196 =item reason - can be set to a cancellation reason (see L<FS:reason>),
1197 either a reasonnum of an existing reason, or passing a hashref will create
1198 a new reason. The hashref should have the following keys:
1199 - typenum - Reason type (see L<FS::reason_type>
1200 - reason - Text of the new reason.
1202 =item date - can be set to a unix style timestamp to specify when to
1205 =item time - can be set to override the current time, for calculation
1206 of final invoices or unused-time credits
1208 =item resume_date - can be set to a time when the package should be
1209 unsuspended. This may be more convenient than calling C<unsuspend()>
1212 =item from_main - allows a supplemental package to be suspended, rather
1213 than redirecting the method call to its main package. For internal use.
1217 If there is an error, returns the error, otherwise returns false.
1222 my( $self, %options ) = @_;
1225 # pass all suspend/cancel actions to the main package
1226 if ( $self->main_pkgnum and !$options{'from_main'} ) {
1227 return $self->main_pkg->suspend(%options);
1230 local $SIG{HUP} = 'IGNORE';
1231 local $SIG{INT} = 'IGNORE';
1232 local $SIG{QUIT} = 'IGNORE';
1233 local $SIG{TERM} = 'IGNORE';
1234 local $SIG{TSTP} = 'IGNORE';
1235 local $SIG{PIPE} = 'IGNORE';
1237 my $oldAutoCommit = $FS::UID::AutoCommit;
1238 local $FS::UID::AutoCommit = 0;
1241 my $old = $self->select_for_update;
1243 my $pkgnum = $old->pkgnum;
1244 if ( $old->get('cancel') || $self->get('cancel') ) {
1245 dbh->rollback if $oldAutoCommit;
1246 return "Can't suspend cancelled package $pkgnum";
1249 if ( $old->get('susp') || $self->get('susp') ) {
1250 dbh->rollback if $oldAutoCommit;
1251 return ""; # no error # complain on adjourn?
1254 my $suspend_time = $options{'time'} || time;
1255 my $date = $options{date} if $options{date}; # adjourn/suspend later
1256 $date = '' if ($date && $date <= $suspend_time); # complain instead?
1258 if ( $date && $old->get('expire') && $old->get('expire') < $date ) {
1259 dbh->rollback if $oldAutoCommit;
1260 return "Package $pkgnum expires before it would be suspended.";
1263 # some false laziness with sub cancel
1264 if ( !$options{nobill} && !$date &&
1265 $self->part_pkg->option('bill_suspend_as_cancel',1) ) {
1266 # kind of a kludge--'bill_suspend_as_cancel' to avoid having to
1267 # make the entire cust_main->bill path recognize 'suspend' and
1268 # 'cancel' separately.
1269 warn "Billing $pkgnum on suspension (at $suspend_time)\n" if $DEBUG;
1270 my $copy = $self->new({$self->hash});
1272 $copy->cust_main->bill( 'pkg_list' => [ $copy ],
1274 'time' => $suspend_time );
1275 warn "Error billing during suspend, custnum ".
1276 #$self->cust_main->custnum. ": $error"
1281 if ( $options{'reason'} ) {
1282 $error = $self->insert_reason( 'reason' => $options{'reason'},
1283 'action' => $date ? 'adjourn' : 'suspend',
1284 'date' => $date ? $date : $suspend_time,
1285 'reason_otaker' => $options{'reason_otaker'},
1288 dbh->rollback if $oldAutoCommit;
1289 return "Error inserting cust_pkg_reason: $error";
1293 my %hash = $self->hash;
1295 $hash{'adjourn'} = $date;
1297 $hash{'susp'} = $suspend_time;
1300 my $resume_date = $options{'resume_date'} || 0;
1301 if ( $resume_date > ($date || $suspend_time) ) {
1302 $hash{'resume'} = $resume_date;
1305 $options{options} ||= {};
1307 my $new = new FS::cust_pkg ( \%hash );
1308 $error = $new->replace( $self, options => { $self->options,
1309 %{ $options{options} },
1313 $dbh->rollback if $oldAutoCommit;
1318 # credit remaining time if appropriate
1319 if ( $self->part_pkg->option('unused_credit_suspend', 1) ) {
1320 my $error = $self->credit_remaining('suspend', $suspend_time);
1322 $dbh->rollback if $oldAutoCommit;
1329 foreach my $cust_svc (
1330 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
1332 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
1334 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
1335 $dbh->rollback if $oldAutoCommit;
1336 return "Illegal svcdb value in part_svc!";
1339 require "FS/$svcdb.pm";
1341 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
1343 $error = $svc->suspend;
1345 $dbh->rollback if $oldAutoCommit;
1348 my( $label, $value ) = $cust_svc->label;
1349 push @labels, "$label: $value";
1353 my $conf = new FS::Conf;
1354 if ( $conf->config('suspend_email_admin') ) {
1356 my $error = send_email(
1357 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
1358 #invoice_from ??? well as good as any
1359 'to' => $conf->config('suspend_email_admin'),
1360 'subject' => 'FREESIDE NOTIFICATION: Customer package suspended',
1362 "This is an automatic message from your Freeside installation\n",
1363 "informing you that the following customer package has been suspended:\n",
1365 'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
1366 'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
1367 ( map { "Service : $_\n" } @labels ),
1372 warn "WARNING: can't send suspension admin email (suspending anyway): ".
1380 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1381 $error = $supp_pkg->suspend(%options, 'from_main' => 1);
1383 $dbh->rollback if $oldAutoCommit;
1384 return "suspending supplemental pkg#".$supp_pkg->pkgnum.": $error";
1388 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1393 =item credit_remaining MODE TIME
1395 Generate a credit for this package for the time remaining in the current
1396 billing period. MODE is either "suspend" or "cancel" (determines the
1397 credit type). TIME is the time of suspension/cancellation. Both arguments
1402 sub credit_remaining {
1403 # Add a credit for remaining service
1404 my ($self, $mode, $time) = @_;
1405 die 'credit_remaining requires suspend or cancel'
1406 unless $mode eq 'suspend' or $mode eq 'cancel';
1407 die 'no suspend/cancel time' unless $time > 0;
1409 my $conf = FS::Conf->new;
1410 my $reason_type = $conf->config($mode.'_credit_type');
1412 my $last_bill = $self->getfield('last_bill') || 0;
1413 my $next_bill = $self->getfield('bill') || 0;
1414 if ( $last_bill > 0 # the package has been billed
1415 and $next_bill > 0 # the package has a next bill date
1416 and $next_bill >= $time # which is in the future
1418 my $remaining_value = $self->calc_remain('time' => $time);
1419 if ( $remaining_value > 0 ) {
1420 warn "Crediting for $remaining_value on package ".$self->pkgnum."\n"
1422 my $error = $self->cust_main->credit(
1424 'Credit for unused time on '. $self->part_pkg->pkg,
1425 'reason_type' => $reason_type,
1427 return "Error crediting customer \$$remaining_value for unused time".
1428 " on ". $self->part_pkg->pkg. ": $error"
1430 } #if $remaining_value
1431 } #if $last_bill, etc.
1435 =item unsuspend [ OPTION => VALUE ... ]
1437 Unsuspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
1438 package, then unsuspends the package itself (clears the susp field and the
1439 adjourn field if it is in the past). If the suspend reason includes an
1440 unsuspension package, that package will be ordered.
1442 Available options are:
1448 Can be set to a date to unsuspend the package in the future (the 'resume'
1451 =item adjust_next_bill
1453 Can be set true to adjust the next bill date forward by
1454 the amount of time the account was inactive. This was set true by default
1455 in the past (from 1.4.2 and 1.5.0pre6 through 1.7.0), but now needs to be
1456 explicitly requested with this option or in the price plan.
1460 If there is an error, returns the error, otherwise returns false.
1465 my( $self, %opt ) = @_;
1468 # pass all suspend/cancel actions to the main package
1469 if ( $self->main_pkgnum and !$opt{'from_main'} ) {
1470 return $self->main_pkg->unsuspend(%opt);
1473 local $SIG{HUP} = 'IGNORE';
1474 local $SIG{INT} = 'IGNORE';
1475 local $SIG{QUIT} = 'IGNORE';
1476 local $SIG{TERM} = 'IGNORE';
1477 local $SIG{TSTP} = 'IGNORE';
1478 local $SIG{PIPE} = 'IGNORE';
1480 my $oldAutoCommit = $FS::UID::AutoCommit;
1481 local $FS::UID::AutoCommit = 0;
1484 my $old = $self->select_for_update;
1486 my $pkgnum = $old->pkgnum;
1487 if ( $old->get('cancel') || $self->get('cancel') ) {
1488 $dbh->rollback if $oldAutoCommit;
1489 return "Can't unsuspend cancelled package $pkgnum";
1492 unless ( $old->get('susp') && $self->get('susp') ) {
1493 $dbh->rollback if $oldAutoCommit;
1494 return ""; # no error # complain instead?
1497 my $date = $opt{'date'};
1498 if ( $date and $date > time ) { # return an error if $date <= time?
1500 if ( $old->get('expire') && $old->get('expire') < $date ) {
1501 $dbh->rollback if $oldAutoCommit;
1502 return "Package $pkgnum expires before it would be unsuspended.";
1505 my $new = new FS::cust_pkg { $self->hash };
1506 $new->set('resume', $date);
1507 $error = $new->replace($self, options => $self->options);
1510 $dbh->rollback if $oldAutoCommit;
1514 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1522 foreach my $cust_svc (
1523 qsearch('cust_svc',{'pkgnum'=> $self->pkgnum } )
1525 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
1527 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
1528 $dbh->rollback if $oldAutoCommit;
1529 return "Illegal svcdb value in part_svc!";
1532 require "FS/$svcdb.pm";
1534 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
1536 $error = $svc->unsuspend;
1538 $dbh->rollback if $oldAutoCommit;
1541 my( $label, $value ) = $cust_svc->label;
1542 push @labels, "$label: $value";
1547 my $cust_pkg_reason = $self->last_cust_pkg_reason('susp');
1548 my $reason = $cust_pkg_reason ? $cust_pkg_reason->reason : '';
1550 my %hash = $self->hash;
1551 my $inactive = time - $hash{'susp'};
1553 my $conf = new FS::Conf;
1555 if ( $inactive > 0 &&
1556 ( $hash{'bill'} || $hash{'setup'} ) &&
1557 ( $opt{'adjust_next_bill'} ||
1558 $conf->exists('unsuspend-always_adjust_next_bill_date') ||
1559 $self->part_pkg->option('unsuspend_adjust_bill', 1) )
1562 $hash{'bill'} = ( $hash{'bill'} || $hash{'setup'} ) + $inactive;
1567 $hash{'adjourn'} = '' if $hash{'adjourn'} and $hash{'adjourn'} < time;
1568 $hash{'resume'} = '' if !$hash{'adjourn'};
1569 my $new = new FS::cust_pkg ( \%hash );
1570 $error = $new->replace( $self, options => { $self->options } );
1572 $dbh->rollback if $oldAutoCommit;
1578 if ( $reason && $reason->unsuspend_pkgpart ) {
1579 my $part_pkg = FS::part_pkg->by_key($reason->unsuspend_pkgpart)
1580 or $error = "Unsuspend package definition ".$reason->unsuspend_pkgpart.
1582 my $start_date = $self->cust_main->next_bill_date
1583 if $reason->unsuspend_hold;
1586 $unsusp_pkg = FS::cust_pkg->new({
1587 'custnum' => $self->custnum,
1588 'pkgpart' => $reason->unsuspend_pkgpart,
1589 'start_date' => $start_date,
1590 'locationnum' => $self->locationnum,
1591 # discount? probably not...
1594 $error ||= $self->cust_main->order_pkg( 'cust_pkg' => $unsusp_pkg );
1598 $dbh->rollback if $oldAutoCommit;
1603 if ( $conf->config('unsuspend_email_admin') ) {
1605 my $error = send_email(
1606 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
1607 #invoice_from ??? well as good as any
1608 'to' => $conf->config('unsuspend_email_admin'),
1609 'subject' => 'FREESIDE NOTIFICATION: Customer package unsuspended', 'body' => [
1610 "This is an automatic message from your Freeside installation\n",
1611 "informing you that the following customer package has been unsuspended:\n",
1613 'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
1614 'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
1615 ( map { "Service : $_\n" } @labels ),
1617 "An unsuspension fee was charged: ".
1618 $unsusp_pkg->part_pkg->pkg_comment."\n"
1625 warn "WARNING: can't send unsuspension admin email (unsuspending anyway): ".
1631 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1632 $error = $supp_pkg->unsuspend(%opt, 'from_main' => 1);
1634 $dbh->rollback if $oldAutoCommit;
1635 return "unsuspending supplemental pkg#".$supp_pkg->pkgnum.": $error";
1639 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1646 Cancels any pending suspension (sets the adjourn field to null).
1648 If there is an error, returns the error, otherwise returns false.
1653 my( $self, %options ) = @_;
1656 local $SIG{HUP} = 'IGNORE';
1657 local $SIG{INT} = 'IGNORE';
1658 local $SIG{QUIT} = 'IGNORE';
1659 local $SIG{TERM} = 'IGNORE';
1660 local $SIG{TSTP} = 'IGNORE';
1661 local $SIG{PIPE} = 'IGNORE';
1663 my $oldAutoCommit = $FS::UID::AutoCommit;
1664 local $FS::UID::AutoCommit = 0;
1667 my $old = $self->select_for_update;
1669 my $pkgnum = $old->pkgnum;
1670 if ( $old->get('cancel') || $self->get('cancel') ) {
1671 dbh->rollback if $oldAutoCommit;
1672 return "Can't unadjourn cancelled package $pkgnum";
1673 # or at least it's pointless
1676 if ( $old->get('susp') || $self->get('susp') ) {
1677 dbh->rollback if $oldAutoCommit;
1678 return "Can't unadjourn suspended package $pkgnum";
1679 # perhaps this is arbitrary
1682 unless ( $old->get('adjourn') && $self->get('adjourn') ) {
1683 dbh->rollback if $oldAutoCommit;
1684 return ""; # no error
1687 my %hash = $self->hash;
1688 $hash{'adjourn'} = '';
1689 $hash{'resume'} = '';
1690 my $new = new FS::cust_pkg ( \%hash );
1691 $error = $new->replace( $self, options => { $self->options } );
1693 $dbh->rollback if $oldAutoCommit;
1697 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1704 =item change HASHREF | OPTION => VALUE ...
1706 Changes this package: cancels it and creates a new one, with a different
1707 pkgpart or locationnum or both. All services are transferred to the new
1708 package (no change will be made if this is not possible).
1710 Options may be passed as a list of key/value pairs or as a hash reference.
1717 New locationnum, to change the location for this package.
1721 New FS::cust_location object, to create a new location and assign it
1726 New FS::cust_main object, to create a new customer and assign the new package
1731 New pkgpart (see L<FS::part_pkg>).
1735 New refnum (see L<FS::part_referral>).
1739 New quantity; if unspecified, the new package will have the same quantity
1744 "New" (existing) FS::cust_pkg object. The package's services and other
1745 attributes will be transferred to this package.
1749 Set to true to transfer billing dates (start_date, setup, last_bill, bill,
1750 susp, adjourn, cancel, expire, and contract_end) to the new package.
1752 =item unprotect_svcs
1754 Normally, change() will rollback and return an error if some services
1755 can't be transferred (also see the I<cust_pkg-change_svcpart> config option).
1756 If unprotect_svcs is true, this method will transfer as many services as
1757 it can and then unconditionally cancel the old package.
1761 At least one of locationnum, cust_location, pkgpart, refnum, cust_main, or
1762 cust_pkg must be specified (otherwise, what's the point?)
1764 Returns either the new FS::cust_pkg object or a scalar error.
1768 my $err_or_new_cust_pkg = $old_cust_pkg->change
1772 #some false laziness w/order
1775 my $opt = ref($_[0]) ? shift : { @_ };
1777 my $conf = new FS::Conf;
1779 # Transactionize this whole mess
1780 local $SIG{HUP} = 'IGNORE';
1781 local $SIG{INT} = 'IGNORE';
1782 local $SIG{QUIT} = 'IGNORE';
1783 local $SIG{TERM} = 'IGNORE';
1784 local $SIG{TSTP} = 'IGNORE';
1785 local $SIG{PIPE} = 'IGNORE';
1787 my $oldAutoCommit = $FS::UID::AutoCommit;
1788 local $FS::UID::AutoCommit = 0;
1797 $hash{'setup'} = $time if $self->setup;
1799 $hash{'change_date'} = $time;
1800 $hash{"change_$_"} = $self->$_()
1801 foreach qw( pkgnum pkgpart locationnum );
1803 if ( $opt->{'cust_location'} ) {
1804 $error = $opt->{'cust_location'}->find_or_insert;
1806 $dbh->rollback if $oldAutoCommit;
1807 return "inserting cust_location (transaction rolled back): $error";
1809 $opt->{'locationnum'} = $opt->{'cust_location'}->locationnum;
1812 if ( $opt->{'cust_pkg'} ) {
1813 # treat changing to a package with a different pkgpart as a
1814 # pkgpart change (because it is)
1815 $opt->{'pkgpart'} = $opt->{'cust_pkg'}->pkgpart;
1818 # whether to override pkgpart checking on the new package
1819 my $same_pkgpart = 1;
1820 if ( $opt->{'pkgpart'} and ( $opt->{'pkgpart'} != $self->pkgpart ) ) {
1824 my $unused_credit = 0;
1825 my $keep_dates = $opt->{'keep_dates'};
1826 # Special case. If the pkgpart is changing, and the customer is
1827 # going to be credited for remaining time, don't keep setup, bill,
1828 # or last_bill dates, and DO pass the flag to cancel() to credit
1830 if ( $opt->{'pkgpart'}
1831 and $opt->{'pkgpart'} != $self->pkgpart
1832 and $self->part_pkg->option('unused_credit_change', 1) ) {
1835 $hash{$_} = '' foreach qw(setup bill last_bill);
1838 if ( $keep_dates ) {
1839 foreach my $date ( qw(setup bill last_bill susp adjourn cancel expire
1840 resume start_date contract_end ) ) {
1841 $hash{$date} = $self->getfield($date);
1845 # allow $opt->{'locationnum'} = '' to specifically set it to null
1846 # (i.e. customer default location)
1847 $opt->{'locationnum'} = $self->locationnum if !exists($opt->{'locationnum'});
1849 # usually this doesn't matter. the two cases where it does are:
1850 # 1. unused_credit_change + pkgpart change + setup fee on the new package
1852 # 2. (more importantly) changing a package before it's billed
1853 $hash{'waive_setup'} = $self->waive_setup;
1855 my $custnum = $self->custnum;
1856 if ( $opt->{cust_main} ) {
1857 my $cust_main = $opt->{cust_main};
1858 unless ( $cust_main->custnum ) {
1859 my $error = $cust_main->insert;
1861 $dbh->rollback if $oldAutoCommit;
1862 return "inserting cust_main (transaction rolled back): $error";
1865 $custnum = $cust_main->custnum;
1868 $hash{'contactnum'} = $opt->{'contactnum'} if $opt->{'contactnum'};
1871 if ( $opt->{'cust_pkg'} ) {
1872 # The target package already exists; update it to show that it was
1873 # changed from this package.
1874 $cust_pkg = $opt->{'cust_pkg'};
1876 foreach ( qw( pkgnum pkgpart locationnum ) ) {
1877 $cust_pkg->set("change_$_", $self->get($_));
1879 $cust_pkg->set('change_date', $time);
1880 $error = $cust_pkg->replace;
1883 # Create the new package.
1884 $cust_pkg = new FS::cust_pkg {
1885 custnum => $custnum,
1886 locationnum => $opt->{'locationnum'},
1887 ( map { $_ => ( $opt->{$_} || $self->$_() ) }
1888 qw( pkgpart quantity refnum salesnum )
1892 $error = $cust_pkg->insert( 'change' => 1,
1893 'allow_pkgpart' => $same_pkgpart );
1896 $dbh->rollback if $oldAutoCommit;
1900 # Transfer services and cancel old package.
1902 $error = $self->transfer($cust_pkg);
1903 if ($error and $error == 0) {
1904 # $old_pkg->transfer failed.
1905 $dbh->rollback if $oldAutoCommit;
1909 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
1910 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
1911 $error = $self->transfer($cust_pkg, 'change_svcpart'=>1 );
1912 if ($error and $error == 0) {
1913 # $old_pkg->transfer failed.
1914 $dbh->rollback if $oldAutoCommit;
1919 # We set unprotect_svcs when executing a "future package change". It's
1920 # not a user-interactive operation, so returning an error means the
1921 # package change will just fail. Rather than have that happen, we'll
1922 # let leftover services be deleted.
1923 if ($error > 0 and !$opt->{'unprotect_svcs'}) {
1924 # Transfers were successful, but we still had services left on the old
1925 # package. We can't change the package under this circumstances, so abort.
1926 $dbh->rollback if $oldAutoCommit;
1927 return "Unable to transfer all services from package ". $self->pkgnum;
1930 #reset usage if changing pkgpart
1931 # AND usage rollover is off (otherwise adds twice, now and at package bill)
1932 if ($self->pkgpart != $cust_pkg->pkgpart) {
1933 my $part_pkg = $cust_pkg->part_pkg;
1934 $error = $part_pkg->reset_usage($cust_pkg, $part_pkg->is_prepaid
1938 if $part_pkg->can('reset_usage') && ! $part_pkg->option('usage_rollover',1);
1941 $dbh->rollback if $oldAutoCommit;
1942 return "Error setting usage values: $error";
1945 # if NOT changing pkgpart, transfer any usage pools over
1946 foreach my $usage ($self->cust_pkg_usage) {
1947 $usage->set('pkgnum', $cust_pkg->pkgnum);
1948 $error = $usage->replace;
1950 $dbh->rollback if $oldAutoCommit;
1951 return "Error transferring usage pools: $error";
1956 # transfer discounts, if we're not changing pkgpart
1957 if ( $same_pkgpart ) {
1958 foreach my $old_discount ($self->cust_pkg_discount_active) {
1959 # don't remove the old discount, we may still need to bill that package.
1960 my $new_discount = new FS::cust_pkg_discount {
1961 'pkgnum' => $cust_pkg->pkgnum,
1962 'discountnum' => $old_discount->discountnum,
1963 'months_used' => $old_discount->months_used,
1965 $error = $new_discount->insert;
1967 $dbh->rollback if $oldAutoCommit;
1968 return "Error transferring discounts: $error";
1973 # transfer (copy) invoice details
1974 foreach my $detail ($self->cust_pkg_detail) {
1975 my $new_detail = FS::cust_pkg_detail->new({ $detail->hash });
1976 $new_detail->set('pkgdetailnum', '');
1977 $new_detail->set('pkgnum', $cust_pkg->pkgnum);
1978 $error = $new_detail->insert;
1980 $dbh->rollback if $oldAutoCommit;
1981 return "Error transferring package notes: $error";
1987 if ( !$opt->{'cust_pkg'} ) {
1988 # Order any supplemental packages.
1989 my $part_pkg = $cust_pkg->part_pkg;
1990 my @old_supp_pkgs = $self->supplemental_pkgs;
1991 foreach my $link ($part_pkg->supp_part_pkg_link) {
1993 foreach (@old_supp_pkgs) {
1994 if ($_->pkgpart == $link->dst_pkgpart) {
1996 $_->pkgpart(0); # so that it can't match more than once
2000 # false laziness with FS::cust_main::Packages::order_pkg
2001 my $new = FS::cust_pkg->new({
2002 pkgpart => $link->dst_pkgpart,
2003 pkglinknum => $link->pkglinknum,
2004 custnum => $custnum,
2005 main_pkgnum => $cust_pkg->pkgnum,
2006 locationnum => $cust_pkg->locationnum,
2007 start_date => $cust_pkg->start_date,
2008 order_date => $cust_pkg->order_date,
2009 expire => $cust_pkg->expire,
2010 adjourn => $cust_pkg->adjourn,
2011 contract_end => $cust_pkg->contract_end,
2012 refnum => $cust_pkg->refnum,
2013 discountnum => $cust_pkg->discountnum,
2014 waive_setup => $cust_pkg->waive_setup,
2016 if ( $old and $opt->{'keep_dates'} ) {
2017 foreach (qw(setup bill last_bill)) {
2018 $new->set($_, $old->get($_));
2021 $error = $new->insert( allow_pkgpart => $same_pkgpart );
2024 $error ||= $old->transfer($new);
2026 if ( $error and $error > 0 ) {
2027 # no reason why this should ever fail, but still...
2028 $error = "Unable to transfer all services from supplemental package ".
2032 $dbh->rollback if $oldAutoCommit;
2035 push @new_supp_pkgs, $new;
2037 } # if !$opt->{'cust_pkg'}
2038 # because if there is one, then supplemental packages would already
2039 # have been created for it.
2041 #Good to go, cancel old package. Notify 'cancel' of whether to credit
2043 #Don't allow billing the package (preceding period packages and/or
2044 #outstanding usage) if we are keeping dates (i.e. location changing),
2045 #because the new package will be billed for the same date range.
2046 #Supplemental packages are also canceled here.
2048 # during scheduled changes, avoid canceling the package we just
2050 $self->set('change_to_pkgnum' => '');
2052 $error = $self->cancel(
2054 unused_credit => $unused_credit,
2055 nobill => $keep_dates,
2056 change_custnum => ( $self->custnum != $custnum ? $custnum : '' ),
2059 $dbh->rollback if $oldAutoCommit;
2063 if ( $conf->exists('cust_pkg-change_pkgpart-bill_now') ) {
2065 my $error = $cust_pkg->cust_main->bill(
2066 'pkg_list' => [ $cust_pkg, @new_supp_pkgs ]
2069 $dbh->rollback if $oldAutoCommit;
2074 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2080 =item change_later OPTION => VALUE...
2082 Schedule a package change for a later date. This actually orders the new
2083 package immediately, but sets its start date for a future date, and sets
2084 the current package to expire on the same date.
2086 If the package is already scheduled for a change, this can be called with
2087 'start_date' to change the scheduled date, or with pkgpart and/or
2088 locationnum to modify the package change. To cancel the scheduled change
2089 entirely, see C<abort_change>.
2097 The date for the package change. Required, and must be in the future.
2105 The pkgpart. locationnum, and quantity of the new package, with the same
2106 meaning as in C<change>.
2114 my $opt = ref($_[0]) ? shift : { @_ };
2116 my $oldAutoCommit = $FS::UID::AutoCommit;
2117 local $FS::UID::AutoCommit = 0;
2120 my $cust_main = $self->cust_main;
2122 my $date = delete $opt->{'start_date'} or return 'start_date required';
2124 if ( $date <= time ) {
2125 $dbh->rollback if $oldAutoCommit;
2126 return "start_date $date is in the past";
2131 if ( $self->change_to_pkgnum ) {
2132 my $change_to = FS::cust_pkg->by_key($self->change_to_pkgnum);
2133 my $new_pkgpart = $opt->{'pkgpart'}
2134 if $opt->{'pkgpart'} and $opt->{'pkgpart'} != $change_to->pkgpart;
2135 my $new_locationnum = $opt->{'locationnum'}
2136 if $opt->{'locationnum'} and $opt->{'locationnum'} != $change_to->locationnum;
2137 my $new_quantity = $opt->{'quantity'}
2138 if $opt->{'quantity'} and $opt->{'quantity'} != $change_to->quantity;
2139 if ( $new_pkgpart or $new_locationnum or $new_quantity ) {
2140 # it hasn't been billed yet, so in principle we could just edit
2141 # it in place (w/o a package change), but that's bad form.
2142 # So change the package according to the new options...
2143 my $err_or_pkg = $change_to->change(%$opt);
2144 if ( ref $err_or_pkg ) {
2145 # Then set that package up for a future start.
2146 $self->set('change_to_pkgnum', $err_or_pkg->pkgnum);
2147 $self->set('expire', $date); # in case it's different
2148 $err_or_pkg->set('start_date', $date);
2149 $err_or_pkg->set('change_date', '');
2150 $err_or_pkg->set('change_pkgnum', '');
2152 $error = $self->replace ||
2153 $err_or_pkg->replace ||
2154 $change_to->cancel ||
2157 $error = $err_or_pkg;
2159 } else { # change the start date only.
2160 $self->set('expire', $date);
2161 $change_to->set('start_date', $date);
2162 $error = $self->replace || $change_to->replace;
2165 $dbh->rollback if $oldAutoCommit;
2168 $dbh->commit if $oldAutoCommit;
2171 } # if $self->change_to_pkgnum
2173 my $new_pkgpart = $opt->{'pkgpart'}
2174 if $opt->{'pkgpart'} and $opt->{'pkgpart'} != $self->pkgpart;
2175 my $new_locationnum = $opt->{'locationnum'}
2176 if $opt->{'locationnum'} and $opt->{'locationnum'} != $self->locationnum;
2177 my $new_quantity = $opt->{'quantity'}
2178 if $opt->{'quantity'} and $opt->{'quantity'} != $self->quantity;
2180 return '' unless $new_pkgpart or $new_locationnum or $new_quantity; # wouldn't do anything
2182 # allow $opt->{'locationnum'} = '' to specifically set it to null
2183 # (i.e. customer default location)
2184 $opt->{'locationnum'} = $self->locationnum if !exists($opt->{'locationnum'});
2186 my $new = FS::cust_pkg->new( {
2187 custnum => $self->custnum,
2188 locationnum => $opt->{'locationnum'},
2189 start_date => $date,
2190 map { $_ => ( $opt->{$_} || $self->$_() ) }
2191 qw( pkgpart quantity refnum salesnum )
2193 $error = $new->insert('change' => 1,
2194 'allow_pkgpart' => ($new_pkgpart ? 0 : 1));
2196 $self->set('change_to_pkgnum', $new->pkgnum);
2197 $self->set('expire', $date);
2198 $error = $self->replace;
2201 $dbh->rollback if $oldAutoCommit;
2203 $dbh->commit if $oldAutoCommit;
2211 Cancels a future package change scheduled by C<change_later>.
2217 my $pkgnum = $self->change_to_pkgnum;
2218 my $change_to = FS::cust_pkg->by_key($pkgnum) if $pkgnum;
2221 $error = $change_to->cancel || $change_to->delete;
2222 return $error if $error;
2224 $self->set('change_to_pkgnum', '');
2225 $self->set('expire', '');
2229 =item set_quantity QUANTITY
2231 Change the package's quantity field. This is one of the few package properties
2232 that can safely be changed without canceling and reordering the package
2233 (because it doesn't affect tax eligibility). Returns an error or an
2240 $self = $self->replace_old; # just to make sure
2241 $self->quantity(shift);
2245 =item set_salesnum SALESNUM
2247 Change the package's salesnum (sales person) field. This is one of the few
2248 package properties that can safely be changed without canceling and reordering
2249 the package (because it doesn't affect tax eligibility). Returns an error or
2256 $self = $self->replace_old; # just to make sure
2257 $self->salesnum(shift);
2261 use Storable 'thaw';
2264 sub process_bulk_cust_pkg {
2266 my $param = thaw(decode_base64(shift));
2267 warn Dumper($param) if $DEBUG;
2269 my $old_part_pkg = qsearchs('part_pkg',
2270 { pkgpart => $param->{'old_pkgpart'} });
2271 my $new_part_pkg = qsearchs('part_pkg',
2272 { pkgpart => $param->{'new_pkgpart'} });
2273 die "Must select a new package type\n" unless $new_part_pkg;
2274 #my $keep_dates = $param->{'keep_dates'} || 0;
2275 my $keep_dates = 1; # there is no good reason to turn this off
2277 local $SIG{HUP} = 'IGNORE';
2278 local $SIG{INT} = 'IGNORE';
2279 local $SIG{QUIT} = 'IGNORE';
2280 local $SIG{TERM} = 'IGNORE';
2281 local $SIG{TSTP} = 'IGNORE';
2282 local $SIG{PIPE} = 'IGNORE';
2284 my $oldAutoCommit = $FS::UID::AutoCommit;
2285 local $FS::UID::AutoCommit = 0;
2288 my @cust_pkgs = qsearch('cust_pkg', { 'pkgpart' => $param->{'old_pkgpart'} } );
2291 foreach my $old_cust_pkg ( @cust_pkgs ) {
2293 $job->update_statustext(int(100*$i/(scalar @cust_pkgs)));
2294 if ( $old_cust_pkg->getfield('cancel') ) {
2295 warn '[process_bulk_cust_pkg ] skipping canceled pkgnum '.
2296 $old_cust_pkg->pkgnum."\n"
2300 warn '[process_bulk_cust_pkg] changing pkgnum '.$old_cust_pkg->pkgnum."\n"
2302 my $error = $old_cust_pkg->change(
2303 'pkgpart' => $param->{'new_pkgpart'},
2304 'keep_dates' => $keep_dates
2306 if ( !ref($error) ) { # change returns the cust_pkg on success
2308 die "Error changing pkgnum ".$old_cust_pkg->pkgnum.": '$error'\n";
2311 $dbh->commit if $oldAutoCommit;
2317 Returns the last bill date, or if there is no last bill date, the setup date.
2318 Useful for billing metered services.
2324 return $self->setfield('last_bill', $_[0]) if @_;
2325 return $self->getfield('last_bill') if $self->getfield('last_bill');
2326 my $cust_bill_pkg = qsearchs('cust_bill_pkg', { 'pkgnum' => $self->pkgnum,
2327 'edate' => $self->bill, } );
2328 $cust_bill_pkg ? $cust_bill_pkg->sdate : $self->setup || 0;
2331 =item last_cust_pkg_reason ACTION
2333 Returns the most recent ACTION FS::cust_pkg_reason associated with the package.
2334 Returns false if there is no reason or the package is not currenly ACTION'd
2335 ACTION is one of adjourn, susp, cancel, or expire.
2339 sub last_cust_pkg_reason {
2340 my ( $self, $action ) = ( shift, shift );
2341 my $date = $self->get($action);
2343 'table' => 'cust_pkg_reason',
2344 'hashref' => { 'pkgnum' => $self->pkgnum,
2345 'action' => substr(uc($action), 0, 1),
2348 'order_by' => 'ORDER BY num DESC LIMIT 1',
2352 =item last_reason ACTION
2354 Returns the most recent ACTION FS::reason associated with the package.
2355 Returns false if there is no reason or the package is not currenly ACTION'd
2356 ACTION is one of adjourn, susp, cancel, or expire.
2361 my $cust_pkg_reason = shift->last_cust_pkg_reason(@_);
2362 $cust_pkg_reason->reason
2363 if $cust_pkg_reason;
2368 Returns the definition for this billing item, as an FS::part_pkg object (see
2375 return $self->{'_pkgpart'} if $self->{'_pkgpart'};
2376 cluck "cust_pkg->part_pkg called" if $DEBUG > 1;
2377 qsearchs( 'part_pkg', { 'pkgpart' => $self->pkgpart } );
2382 Returns the cancelled package this package was changed from, if any.
2388 return '' unless $self->change_pkgnum;
2389 qsearchs('cust_pkg', { 'pkgnum' => $self->change_pkgnum } );
2392 =item change_cust_main
2394 Returns the customter this package was detached to, if any.
2398 sub change_cust_main {
2400 return '' unless $self->change_custnum;
2401 qsearchs('cust_main', { 'custnum' => $self->change_custnum } );
2406 Calls the I<calc_setup> of the FS::part_pkg object associated with this billing
2413 $self->part_pkg->calc_setup($self, @_);
2418 Calls the I<calc_recur> of the FS::part_pkg object associated with this billing
2425 $self->part_pkg->calc_recur($self, @_);
2430 Calls the I<base_setup> of the FS::part_pkg object associated with this billing
2437 $self->part_pkg->base_setup($self, @_);
2442 Calls the I<base_recur> of the FS::part_pkg object associated with this billing
2449 $self->part_pkg->base_recur($self, @_);
2454 Calls the I<calc_remain> of the FS::part_pkg object associated with this
2461 $self->part_pkg->calc_remain($self, @_);
2466 Calls the I<calc_cancel> of the FS::part_pkg object associated with this
2473 $self->part_pkg->calc_cancel($self, @_);
2478 Returns any invoice line items for this package (see L<FS::cust_bill_pkg>).
2484 qsearch( 'cust_bill_pkg', { 'pkgnum' => $self->pkgnum } );
2487 =item cust_pkg_detail [ DETAILTYPE ]
2489 Returns any customer package details for this package (see
2490 L<FS::cust_pkg_detail>).
2492 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
2496 sub cust_pkg_detail {
2498 my %hash = ( 'pkgnum' => $self->pkgnum );
2499 $hash{detailtype} = shift if @_;
2501 'table' => 'cust_pkg_detail',
2502 'hashref' => \%hash,
2503 'order_by' => 'ORDER BY weight, pkgdetailnum',
2507 =item set_cust_pkg_detail DETAILTYPE [ DETAIL, DETAIL, ... ]
2509 Sets customer package details for this package (see L<FS::cust_pkg_detail>).
2511 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
2513 If there is an error, returns the error, otherwise returns false.
2517 sub set_cust_pkg_detail {
2518 my( $self, $detailtype, @details ) = @_;
2520 local $SIG{HUP} = 'IGNORE';
2521 local $SIG{INT} = 'IGNORE';
2522 local $SIG{QUIT} = 'IGNORE';
2523 local $SIG{TERM} = 'IGNORE';
2524 local $SIG{TSTP} = 'IGNORE';
2525 local $SIG{PIPE} = 'IGNORE';
2527 my $oldAutoCommit = $FS::UID::AutoCommit;
2528 local $FS::UID::AutoCommit = 0;
2531 foreach my $current ( $self->cust_pkg_detail($detailtype) ) {
2532 my $error = $current->delete;
2534 $dbh->rollback if $oldAutoCommit;
2535 return "error removing old detail: $error";
2539 foreach my $detail ( @details ) {
2540 my $cust_pkg_detail = new FS::cust_pkg_detail {
2541 'pkgnum' => $self->pkgnum,
2542 'detailtype' => $detailtype,
2543 'detail' => $detail,
2545 my $error = $cust_pkg_detail->insert;
2547 $dbh->rollback if $oldAutoCommit;
2548 return "error adding new detail: $error";
2553 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2560 Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.
2564 #false laziness w/cust_bill.pm
2568 'table' => 'cust_event',
2569 'addl_from' => 'JOIN part_event USING ( eventpart )',
2570 'hashref' => { 'tablenum' => $self->pkgnum },
2571 'extra_sql' => " AND eventtable = 'cust_pkg' ",
2575 =item num_cust_event
2577 Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.
2581 #false laziness w/cust_bill.pm
2582 sub num_cust_event {
2585 "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
2586 " WHERE tablenum = ? AND eventtable = 'cust_pkg'";
2587 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
2588 $sth->execute($self->pkgnum) or die $sth->errstr. " executing $sql";
2589 $sth->fetchrow_arrayref->[0];
2592 =item part_pkg_currency_option OPTIONNAME
2594 Returns a two item list consisting of the currency of this customer, if any,
2595 and a value for the provided option. If the customer has a currency, the value
2596 is the option value the given name and the currency (see
2597 L<FS::part_pkg_currency>). Otherwise, if the customer has no currency, is the
2598 regular option value for the given name (see L<FS::part_pkg_option>).
2602 sub part_pkg_currency_option {
2603 my( $self, $optionname ) = @_;
2604 my $part_pkg = $self->part_pkg;
2605 if ( my $currency = $self->cust_main->currency ) {
2606 ($currency, $part_pkg->part_pkg_currency_option($currency, $optionname) );
2608 ('', $part_pkg->option($optionname) );
2612 =item cust_svc [ SVCPART ] (old, deprecated usage)
2614 =item cust_svc [ OPTION => VALUE ... ] (current usage)
2616 =item cust_svc_unsorted [ OPTION => VALUE ... ]
2618 Returns the services for this package, as FS::cust_svc objects (see
2619 L<FS::cust_svc>). Available options are svcpart and svcdb. If either is
2620 spcififed, returns only the matching services.
2622 As an optimization, use the cust_svc_unsorted version if you are not displaying
2629 cluck "cust_pkg->cust_svc called" if $DEBUG > 2;
2630 $self->_sort_cust_svc( $self->cust_svc_unsorted_arrayref );
2633 sub cust_svc_unsorted {
2635 @{ $self->cust_svc_unsorted_arrayref };
2638 sub cust_svc_unsorted_arrayref {
2641 return () unless $self->num_cust_svc(@_);
2644 if ( @_ && $_[0] =~ /^\d+/ ) {
2645 $opt{svcpart} = shift;
2646 } elsif ( @_ && ref($_[0]) eq 'HASH' ) {
2653 'table' => 'cust_svc',
2654 'hashref' => { 'pkgnum' => $self->pkgnum },
2656 if ( $opt{svcpart} ) {
2657 $search{hashref}->{svcpart} = $opt{'svcpart'};
2659 if ( $opt{'svcdb'} ) {
2660 $search{addl_from} = ' LEFT JOIN part_svc USING ( svcpart ) ';
2661 $search{extra_sql} = ' AND svcdb = '. dbh->quote( $opt{'svcdb'} );
2664 [ qsearch(\%search) ];
2668 =item overlimit [ SVCPART ]
2670 Returns the services for this package which have exceeded their
2671 usage limit as FS::cust_svc objects (see L<FS::cust_svc>). If a svcpart
2672 is specified, return only the matching services.
2678 return () unless $self->num_cust_svc(@_);
2679 grep { $_->overlimit } $self->cust_svc(@_);
2682 =item h_cust_svc END_TIMESTAMP [ START_TIMESTAMP ] [ MODE ]
2684 Returns historical services for this package created before END TIMESTAMP and
2685 (optionally) not cancelled before START_TIMESTAMP, as FS::h_cust_svc objects
2686 (see L<FS::h_cust_svc>). If MODE is 'I' (for 'invoice'), services with the
2687 I<pkg_svc.hidden> flag will be omitted.
2693 warn "$me _h_cust_svc called on $self\n"
2696 my ($end, $start, $mode) = @_;
2697 my @cust_svc = $self->_sort_cust_svc(
2698 [ qsearch( 'h_cust_svc',
2699 { 'pkgnum' => $self->pkgnum, },
2700 FS::h_cust_svc->sql_h_search(@_),
2703 if ( defined($mode) && $mode eq 'I' ) {
2704 my %hidden_svcpart = map { $_->svcpart => $_->hidden } $self->part_svc;
2705 return grep { !$hidden_svcpart{$_->svcpart} } @cust_svc;
2711 sub _sort_cust_svc {
2712 my( $self, $arrayref ) = @_;
2715 sub ($$) { my ($a, $b) = @_; $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] };
2717 my %pkg_svc = map { $_->svcpart => $_ }
2718 qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
2723 my $pkg_svc = $pkg_svc{ $_->svcpart } || '';
2725 $pkg_svc ? $pkg_svc->primary_svc : '',
2726 $pkg_svc ? $pkg_svc->quantity : 0,
2733 =item num_cust_svc [ SVCPART ] (old, deprecated usage)
2735 =item num_cust_svc [ OPTION => VALUE ... ] (current usage)
2737 Returns the number of services for this package. Available options are svcpart
2738 and svcdb. If either is spcififed, returns only the matching services.
2745 return $self->{'_num_cust_svc'}
2747 && exists($self->{'_num_cust_svc'})
2748 && $self->{'_num_cust_svc'} =~ /\d/;
2750 cluck "cust_pkg->num_cust_svc called, _num_cust_svc:".$self->{'_num_cust_svc'}
2754 if ( @_ && $_[0] =~ /^\d+/ ) {
2755 $opt{svcpart} = shift;
2756 } elsif ( @_ && ref($_[0]) eq 'HASH' ) {
2762 my $select = 'SELECT COUNT(*) FROM cust_svc ';
2763 my $where = ' WHERE pkgnum = ? ';
2764 my @param = ($self->pkgnum);
2766 if ( $opt{'svcpart'} ) {
2767 $where .= ' AND svcpart = ? ';
2768 push @param, $opt{'svcpart'};
2770 if ( $opt{'svcdb'} ) {
2771 $select .= ' LEFT JOIN part_svc USING ( svcpart ) ';
2772 $where .= ' AND svcdb = ? ';
2773 push @param, $opt{'svcdb'};
2776 my $sth = dbh->prepare("$select $where") or die dbh->errstr;
2777 $sth->execute(@param) or die $sth->errstr;
2778 $sth->fetchrow_arrayref->[0];
2781 =item available_part_svc
2783 Returns a list of FS::part_svc objects representing services included in this
2784 package but not yet provisioned. Each FS::part_svc object also has an extra
2785 field, I<num_avail>, which specifies the number of available services.
2789 sub available_part_svc {
2792 my $pkg_quantity = $self->quantity || 1;
2794 grep { $_->num_avail > 0 }
2796 my $part_svc = $_->part_svc;
2797 $part_svc->{'Hash'}{'num_avail'} = #evil encapsulation-breaking
2798 $pkg_quantity * $_->quantity - $self->num_cust_svc($_->svcpart);
2800 # more evil encapsulation breakage
2801 if($part_svc->{'Hash'}{'num_avail'} > 0) {
2802 my @exports = $part_svc->part_export_did;
2803 $part_svc->{'Hash'}{'can_get_dids'} = scalar(@exports);
2808 $self->part_pkg->pkg_svc;
2811 =item part_svc [ OPTION => VALUE ... ]
2813 Returns a list of FS::part_svc objects representing provisioned and available
2814 services included in this package. Each FS::part_svc object also has the
2815 following extra fields:
2819 =item num_cust_svc (count)
2821 =item num_avail (quantity - count)
2823 =item cust_pkg_svc (services) - array reference containing the provisioned services, as cust_svc objects
2827 Accepts one option: summarize_size. If specified and non-zero, will omit the
2828 extra cust_pkg_svc option for objects where num_cust_svc is this size or
2834 #label -> ($cust_svc->label)[1]
2840 my $pkg_quantity = $self->quantity || 1;
2842 #XXX some sort of sort order besides numeric by svcpart...
2843 my @part_svc = sort { $a->svcpart <=> $b->svcpart } map {
2845 my $part_svc = $pkg_svc->part_svc;
2846 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
2847 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #more evil
2848 $part_svc->{'Hash'}{'num_avail'} =
2849 max( 0, $pkg_quantity * $pkg_svc->quantity - $num_cust_svc );
2850 $part_svc->{'Hash'}{'cust_pkg_svc'} =
2851 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : []
2852 unless exists($opt{summarize_size}) && $opt{summarize_size} > 0
2853 && $num_cust_svc >= $opt{summarize_size};
2854 $part_svc->{'Hash'}{'hidden'} = $pkg_svc->hidden;
2856 } $self->part_pkg->pkg_svc;
2859 push @part_svc, map {
2861 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
2862 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #speak no evail
2863 $part_svc->{'Hash'}{'num_avail'} = 0; #0-$num_cust_svc ?
2864 $part_svc->{'Hash'}{'cust_pkg_svc'} =
2865 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : [];
2867 } $self->extra_part_svc;
2873 =item extra_part_svc
2875 Returns a list of FS::part_svc objects corresponding to services in this
2876 package which are still provisioned but not (any longer) available in the
2881 sub extra_part_svc {
2884 my $pkgnum = $self->pkgnum;
2885 #my $pkgpart = $self->pkgpart;
2888 # 'table' => 'part_svc',
2891 # "WHERE 0 = ( SELECT COUNT(*) FROM pkg_svc
2892 # WHERE pkg_svc.svcpart = part_svc.svcpart
2893 # AND pkg_svc.pkgpart = ?
2896 # AND 0 < ( SELECT COUNT(*) FROM cust_svc
2897 # LEFT JOIN cust_pkg USING ( pkgnum )
2898 # WHERE cust_svc.svcpart = part_svc.svcpart
2901 # 'extra_param' => [ [$self->pkgpart=>'int'], [$self->pkgnum=>'int'] ],
2904 #seems to benchmark slightly faster... (or did?)
2906 my @pkgparts = map $_->pkgpart, $self->part_pkg->self_and_svc_linked;
2907 my $pkgparts = join(',', @pkgparts);
2910 #'select' => 'DISTINCT ON (svcpart) part_svc.*',
2911 #MySQL doesn't grok DISINCT ON
2912 'select' => 'DISTINCT part_svc.*',
2913 'table' => 'part_svc',
2915 "LEFT JOIN pkg_svc ON ( pkg_svc.svcpart = part_svc.svcpart
2916 AND pkg_svc.pkgpart IN ($pkgparts)
2919 LEFT JOIN cust_svc ON ( cust_svc.svcpart = part_svc.svcpart )
2920 LEFT JOIN cust_pkg USING ( pkgnum )
2923 'extra_sql' => "WHERE pkgsvcnum IS NULL AND cust_pkg.pkgnum = ? ",
2924 'extra_param' => [ [$self->pkgnum=>'int'] ],
2930 Returns a short status string for this package, currently:
2934 =item not yet billed
2936 =item one-time charge
2951 my $freq = length($self->freq) ? $self->freq : $self->part_pkg->freq;
2953 return 'cancelled' if $self->get('cancel');
2954 return 'suspended' if $self->susp;
2955 return 'not yet billed' unless $self->setup;
2956 return 'one-time charge' if $freq =~ /^(0|$)/;
2960 =item ucfirst_status
2962 Returns the status with the first character capitalized.
2966 sub ucfirst_status {
2967 ucfirst(shift->status);
2972 Class method that returns the list of possible status strings for packages
2973 (see L<the status method|/status>). For example:
2975 @statuses = FS::cust_pkg->statuses();
2979 tie my %statuscolor, 'Tie::IxHash',
2980 'not yet billed' => '009999', #teal? cyan?
2981 'one-time charge' => '000000',
2982 'active' => '00CC00',
2983 'suspended' => 'FF9900',
2984 'cancelled' => 'FF0000',
2988 my $self = shift; #could be class...
2989 #grep { $_ !~ /^(not yet billed)$/ } #this is a dumb status anyway
2990 # # mayble split btw one-time vs. recur
2996 Returns a hex triplet color string for this package's status.
3002 $statuscolor{$self->status};
3007 Returns a label for this package. (Currently "pkgnum: pkg - comment" or
3008 "pkg - comment" depending on user preference).
3014 my $label = $self->part_pkg->pkg_comment( 'nopkgpart' => 1 );
3015 $label = $self->pkgnum. ": $label"
3016 if $FS::CurrentUser::CurrentUser->option('show_pkgnum');
3020 =item pkg_label_long
3022 Returns a long label for this package, adding the primary service's label to
3027 sub pkg_label_long {
3029 my $label = $self->pkg_label;
3030 my $cust_svc = $self->primary_cust_svc;
3031 $label .= ' ('. ($cust_svc->label)[1]. ')' if $cust_svc;
3037 Returns a customer-localized label for this package.
3043 $self->part_pkg->pkg_locale( $self->cust_main->locale );
3046 =item primary_cust_svc
3048 Returns a primary service (as FS::cust_svc object) if one can be identified.
3052 #for labeling purposes - might not 100% match up with part_pkg->svcpart's idea
3054 sub primary_cust_svc {
3057 my @cust_svc = $self->cust_svc;
3059 return '' unless @cust_svc; #no serivces - irrelevant then
3061 return $cust_svc[0] if scalar(@cust_svc) == 1; #always return a single service
3063 # primary service as specified in the package definition
3064 # or exactly one service definition with quantity one
3065 my $svcpart = $self->part_pkg->svcpart;
3066 @cust_svc = grep { $_->svcpart == $svcpart } @cust_svc;
3067 return $cust_svc[0] if scalar(@cust_svc) == 1;
3069 #couldn't identify one thing..
3075 Returns a list of lists, calling the label method for all services
3076 (see L<FS::cust_svc>) of this billing item.
3082 map { [ $_->label ] } $self->cust_svc;
3085 =item h_labels END_TIMESTAMP [ START_TIMESTAMP ] [ MODE ]
3087 Like the labels method, but returns historical information on services that
3088 were active as of END_TIMESTAMP and (optionally) not cancelled before
3089 START_TIMESTAMP. If MODE is 'I' (for 'invoice'), services with the
3090 I<pkg_svc.hidden> flag will be omitted.
3092 Returns a list of lists, calling the label method for all (historical) services
3093 (see L<FS::h_cust_svc>) of this billing item.
3099 warn "$me _h_labels called on $self\n"
3101 map { [ $_->label(@_) ] } $self->h_cust_svc(@_);
3106 Like labels, except returns a simple flat list, and shortens long
3107 (currently >5 or the cust_bill-max_same_services configuration value) lists of
3108 identical services to one line that lists the service label and the number of
3109 individual services rather than individual items.
3114 shift->_labels_short( 'labels', @_ );
3117 =item h_labels_short END_TIMESTAMP [ START_TIMESTAMP ]
3119 Like h_labels, except returns a simple flat list, and shortens long
3120 (currently >5 or the cust_bill-max_same_services configuration value) lists of
3121 identical services to one line that lists the service label and the number of
3122 individual services rather than individual items.
3126 sub h_labels_short {
3127 shift->_labels_short( 'h_labels', @_ );
3131 my( $self, $method ) = ( shift, shift );
3133 warn "$me _labels_short called on $self with $method method\n"
3136 my $conf = new FS::Conf;
3137 my $max_same_services = $conf->config('cust_bill-max_same_services') || 5;
3139 warn "$me _labels_short populating \%labels\n"
3143 #tie %labels, 'Tie::IxHash';
3144 push @{ $labels{$_->[0]} }, $_->[1]
3145 foreach $self->$method(@_);
3147 warn "$me _labels_short populating \@labels\n"
3151 foreach my $label ( keys %labels ) {
3153 my @values = grep { ! $seen{$_}++ } @{ $labels{$label} };
3154 my $num = scalar(@values);
3155 warn "$me _labels_short $num items for $label\n"
3158 if ( $num > $max_same_services ) {
3159 warn "$me _labels_short more than $max_same_services, so summarizing\n"
3161 push @labels, "$label ($num)";
3163 if ( $conf->exists('cust_bill-consolidate_services') ) {
3164 warn "$me _labels_short consolidating services\n"
3166 # push @labels, "$label: ". join(', ', @values);
3168 my $detail = "$label: ";
3169 $detail .= shift(@values). ', '
3171 && ( length($detail.$values[0]) < 78 || $detail eq "$label: " );
3173 push @labels, $detail;
3175 warn "$me _labels_short done consolidating services\n"
3178 warn "$me _labels_short adding service data\n"
3180 push @labels, map { "$label: $_" } @values;
3191 Returns the parent customer object (see L<FS::cust_main>).
3197 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
3202 Returns the balance for this specific package, when using
3203 experimental package balance.
3209 $self->cust_main->balance_pkgnum( $self->pkgnum );
3212 #these subs are in location_Mixin.pm now... unfortunately the POD doesn't mixin
3216 Returns the location object, if any (see L<FS::cust_location>).
3218 =item cust_location_or_main
3220 If this package is associated with a location, returns the locaiton (see
3221 L<FS::cust_location>), otherwise returns the customer (see L<FS::cust_main>).
3223 =item location_label [ OPTION => VALUE ... ]
3225 Returns the label of the location object (see L<FS::cust_location>).
3229 #end of subs in location_Mixin.pm now... unfortunately the POD doesn't mixin
3231 =item tax_locationnum
3233 Returns the foreign key to a L<FS::cust_location> object for calculating
3234 tax on this package, as determined by the C<tax-pkg_address> and
3235 C<tax-ship_address> configuration flags.
3239 sub tax_locationnum {
3241 my $conf = FS::Conf->new;
3242 if ( $conf->exists('tax-pkg_address') ) {
3243 return $self->locationnum;
3245 elsif ( $conf->exists('tax-ship_address') ) {
3246 return $self->cust_main->ship_locationnum;
3249 return $self->cust_main->bill_locationnum;
3255 Returns the L<FS::cust_location> object for tax_locationnum.
3261 FS::cust_location->by_key( $self->tax_locationnum )
3264 =item seconds_since TIMESTAMP
3266 Returns the number of seconds all accounts (see L<FS::svc_acct>) in this
3267 package have been online since TIMESTAMP, according to the session monitor.
3269 TIMESTAMP is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
3270 L<Time::Local> and L<Date::Parse> for conversion functions.
3275 my($self, $since) = @_;
3278 foreach my $cust_svc (
3279 grep { $_->part_svc->svcdb eq 'svc_acct' } $self->cust_svc
3281 $seconds += $cust_svc->seconds_since($since);
3288 =item seconds_since_sqlradacct TIMESTAMP_START TIMESTAMP_END
3290 Returns the numbers of seconds all accounts (see L<FS::svc_acct>) in this
3291 package have been online between TIMESTAMP_START (inclusive) and TIMESTAMP_END
3294 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
3295 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
3301 sub seconds_since_sqlradacct {
3302 my($self, $start, $end) = @_;
3306 foreach my $cust_svc (
3308 my $part_svc = $_->part_svc;
3309 $part_svc->svcdb eq 'svc_acct'
3310 && scalar($part_svc->part_export_usage);
3313 $seconds += $cust_svc->seconds_since_sqlradacct($start, $end);
3320 =item attribute_since_sqlradacct TIMESTAMP_START TIMESTAMP_END ATTRIBUTE
3322 Returns the sum of the given attribute for all accounts (see L<FS::svc_acct>)
3323 in this package for sessions ending between TIMESTAMP_START (inclusive) and
3327 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
3328 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
3333 sub attribute_since_sqlradacct {
3334 my($self, $start, $end, $attrib) = @_;
3338 foreach my $cust_svc (
3340 my $part_svc = $_->part_svc;
3341 $part_svc->svcdb eq 'svc_acct'
3342 && scalar($part_svc->part_export_usage);
3345 $sum += $cust_svc->attribute_since_sqlradacct($start, $end, $attrib);
3357 my( $self, $value ) = @_;
3358 if ( defined($value) ) {
3359 $self->setfield('quantity', $value);
3361 $self->getfield('quantity') || 1;
3364 =item transfer DEST_PKGNUM | DEST_CUST_PKG, [ OPTION => VALUE ... ]
3366 Transfers as many services as possible from this package to another package.
3368 The destination package can be specified by pkgnum by passing an FS::cust_pkg
3369 object. The destination package must already exist.
3371 Services are moved only if the destination allows services with the correct
3372 I<svcpart> (not svcdb), unless the B<change_svcpart> option is set true. Use
3373 this option with caution! No provision is made for export differences
3374 between the old and new service definitions. Probably only should be used
3375 when your exports for all service definitions of a given svcdb are identical.
3376 (attempt a transfer without it first, to move all possible svcpart-matching
3379 Any services that can't be moved remain in the original package.
3381 Returns an error, if there is one; otherwise, returns the number of services
3382 that couldn't be moved.
3387 my ($self, $dest_pkgnum, %opt) = @_;
3393 if (ref ($dest_pkgnum) eq 'FS::cust_pkg') {
3394 $dest = $dest_pkgnum;
3395 $dest_pkgnum = $dest->pkgnum;
3397 $dest = qsearchs('cust_pkg', { pkgnum => $dest_pkgnum });
3400 return ('Package does not exist: '.$dest_pkgnum) unless $dest;
3402 foreach my $pkg_svc ( $dest->part_pkg->pkg_svc ) {
3403 $target{$pkg_svc->svcpart} = $pkg_svc->quantity;
3406 foreach my $cust_svc ($dest->cust_svc) {
3407 $target{$cust_svc->svcpart}--;
3410 my %svcpart2svcparts = ();
3411 if ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
3412 warn "change_svcpart option received, creating alternates list\n" if $DEBUG;
3413 foreach my $svcpart ( map { $_->svcpart } $self->cust_svc ) {
3414 next if exists $svcpart2svcparts{$svcpart};
3415 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
3416 $svcpart2svcparts{$svcpart} = [
3418 sort { $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] }
3420 my $pkg_svc = qsearchs( 'pkg_svc', { 'pkgpart' => $dest->pkgpart,
3421 'svcpart' => $_ } );
3423 $pkg_svc ? $pkg_svc->primary_svc : '',
3424 $pkg_svc ? $pkg_svc->quantity : 0,
3428 grep { $_ != $svcpart }
3430 qsearch('part_svc', { 'svcdb' => $part_svc->svcdb } )
3432 warn "alternates for svcpart $svcpart: ".
3433 join(', ', @{$svcpart2svcparts{$svcpart}}). "\n"
3438 foreach my $cust_svc ($self->cust_svc) {
3439 if($target{$cust_svc->svcpart} > 0
3440 or $FS::cust_svc::ignore_quantity) { # maybe should be a 'force' option
3441 $target{$cust_svc->svcpart}--;
3442 my $new = new FS::cust_svc { $cust_svc->hash };
3443 $new->pkgnum($dest_pkgnum);
3444 my $error = $new->replace($cust_svc);
3445 return $error if $error;
3446 } elsif ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
3448 warn "looking for alternates for svcpart ". $cust_svc->svcpart. "\n";
3449 warn "alternates to consider: ".
3450 join(', ', @{$svcpart2svcparts{$cust_svc->svcpart}}). "\n";
3452 my @alternate = grep {
3453 warn "considering alternate svcpart $_: ".
3454 "$target{$_} available in new package\n"
3457 } @{$svcpart2svcparts{$cust_svc->svcpart}};
3459 warn "alternate(s) found\n" if $DEBUG;
3460 my $change_svcpart = $alternate[0];
3461 $target{$change_svcpart}--;
3462 my $new = new FS::cust_svc { $cust_svc->hash };
3463 $new->svcpart($change_svcpart);
3464 $new->pkgnum($dest_pkgnum);
3465 my $error = $new->replace($cust_svc);
3466 return $error if $error;
3477 =item grab_svcnums SVCNUM, SVCNUM ...
3479 Change the pkgnum for the provided services to this packages. If there is an
3480 error, returns the error, otherwise returns false.
3488 local $SIG{HUP} = 'IGNORE';
3489 local $SIG{INT} = 'IGNORE';
3490 local $SIG{QUIT} = 'IGNORE';
3491 local $SIG{TERM} = 'IGNORE';
3492 local $SIG{TSTP} = 'IGNORE';
3493 local $SIG{PIPE} = 'IGNORE';
3495 my $oldAutoCommit = $FS::UID::AutoCommit;
3496 local $FS::UID::AutoCommit = 0;
3499 foreach my $svcnum (@svcnum) {
3500 my $cust_svc = qsearchs('cust_svc', { svcnum=>$svcnum } ) or do {
3501 $dbh->rollback if $oldAutoCommit;
3502 return "unknown svcnum $svcnum";
3504 $cust_svc->pkgnum( $self->pkgnum );
3505 my $error = $cust_svc->replace;
3507 $dbh->rollback if $oldAutoCommit;
3512 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3519 This method is deprecated. See the I<depend_jobnum> option to the insert and
3520 order_pkgs methods in FS::cust_main for a better way to defer provisioning.
3524 #looks like this is still used by the order_pkg and change_pkg methods in
3525 # ClientAPI/MyAccount, need to look into those before removing
3529 local $SIG{HUP} = 'IGNORE';
3530 local $SIG{INT} = 'IGNORE';
3531 local $SIG{QUIT} = 'IGNORE';
3532 local $SIG{TERM} = 'IGNORE';
3533 local $SIG{TSTP} = 'IGNORE';
3534 local $SIG{PIPE} = 'IGNORE';
3536 my $oldAutoCommit = $FS::UID::AutoCommit;
3537 local $FS::UID::AutoCommit = 0;
3540 foreach my $cust_svc ( $self->cust_svc ) {
3541 #false laziness w/svc_Common::insert
3542 my $svc_x = $cust_svc->svc_x;
3543 foreach my $part_export ( $cust_svc->part_svc->part_export ) {
3544 my $error = $part_export->export_insert($svc_x);
3546 $dbh->rollback if $oldAutoCommit;
3552 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3557 =item export_pkg_change OLD_CUST_PKG
3559 Calls the "pkg_change" export action for all services attached to this package.
3563 sub export_pkg_change {
3564 my( $self, $old ) = ( shift, shift );
3566 local $SIG{HUP} = 'IGNORE';
3567 local $SIG{INT} = 'IGNORE';
3568 local $SIG{QUIT} = 'IGNORE';
3569 local $SIG{TERM} = 'IGNORE';
3570 local $SIG{TSTP} = 'IGNORE';
3571 local $SIG{PIPE} = 'IGNORE';
3573 my $oldAutoCommit = $FS::UID::AutoCommit;
3574 local $FS::UID::AutoCommit = 0;
3577 foreach my $svc_x ( map $_->svc_x, $self->cust_svc ) {
3578 my $error = $svc_x->export('pkg_change', $self, $old);
3580 $dbh->rollback if $oldAutoCommit;
3585 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3592 Associates this package with a (suspension or cancellation) reason (see
3593 L<FS::cust_pkg_reason>, possibly inserting a new reason on the fly (see
3596 Available options are:
3602 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.
3606 the access_user (see L<FS::access_user>) providing the reason
3614 the action (cancel, susp, adjourn, expire) associated with the reason
3618 If there is an error, returns the error, otherwise returns false.
3623 my ($self, %options) = @_;
3625 my $otaker = $options{reason_otaker} ||
3626 $FS::CurrentUser::CurrentUser->username;
3629 if ( $options{'reason'} =~ /^(\d+)$/ ) {
3633 } elsif ( ref($options{'reason'}) ) {
3635 return 'Enter a new reason (or select an existing one)'
3636 unless $options{'reason'}->{'reason'} !~ /^\s*$/;
3638 my $reason = new FS::reason({
3639 'reason_type' => $options{'reason'}->{'typenum'},
3640 'reason' => $options{'reason'}->{'reason'},
3642 my $error = $reason->insert;
3643 return $error if $error;
3645 $reasonnum = $reason->reasonnum;
3648 return "Unparsable reason: ". $options{'reason'};
3651 my $cust_pkg_reason =
3652 new FS::cust_pkg_reason({ 'pkgnum' => $self->pkgnum,
3653 'reasonnum' => $reasonnum,
3654 'otaker' => $otaker,
3655 'action' => substr(uc($options{'action'}),0,1),
3656 'date' => $options{'date'}
3661 $cust_pkg_reason->insert;
3664 =item insert_discount
3666 Associates this package with a discount (see L<FS::cust_pkg_discount>, possibly
3667 inserting a new discount on the fly (see L<FS::discount>).
3669 Available options are:
3677 If there is an error, returns the error, otherwise returns false.
3681 sub insert_discount {
3682 #my ($self, %options) = @_;
3685 my $cust_pkg_discount = new FS::cust_pkg_discount {
3686 'pkgnum' => $self->pkgnum,
3687 'discountnum' => $self->discountnum,
3689 'end_date' => '', #XXX
3690 #for the create a new discount case
3691 '_type' => $self->discountnum__type,
3692 'amount' => $self->discountnum_amount,
3693 'percent' => $self->discountnum_percent,
3694 'months' => $self->discountnum_months,
3695 'setup' => $self->discountnum_setup,
3696 #'disabled' => $self->discountnum_disabled,
3699 $cust_pkg_discount->insert;
3702 =item set_usage USAGE_VALUE_HASHREF
3704 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
3705 to which they should be set (see L<FS::svc_acct>). Currently seconds,
3706 upbytes, downbytes, and totalbytes are appropriate keys.
3708 All svc_accts which are part of this package have their values reset.
3713 my ($self, $valueref, %opt) = @_;
3715 #only svc_acct can set_usage for now
3716 foreach my $cust_svc ( $self->cust_svc( 'svcdb'=>'svc_acct' ) ) {
3717 my $svc_x = $cust_svc->svc_x;
3718 $svc_x->set_usage($valueref, %opt)
3719 if $svc_x->can("set_usage");
3723 =item recharge USAGE_VALUE_HASHREF
3725 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
3726 to which they should be set (see L<FS::svc_acct>). Currently seconds,
3727 upbytes, downbytes, and totalbytes are appropriate keys.
3729 All svc_accts which are part of this package have their values incremented.
3734 my ($self, $valueref) = @_;
3736 #only svc_acct can set_usage for now
3737 foreach my $cust_svc ( $self->cust_svc( 'svcdb'=>'svc_acct' ) ) {
3738 my $svc_x = $cust_svc->svc_x;
3739 $svc_x->recharge($valueref)
3740 if $svc_x->can("recharge");
3744 =item cust_pkg_discount
3748 sub cust_pkg_discount {
3750 qsearch('cust_pkg_discount', { 'pkgnum' => $self->pkgnum } );
3753 =item cust_pkg_discount_active
3757 sub cust_pkg_discount_active {
3759 grep { $_->status eq 'active' } $self->cust_pkg_discount;
3762 =item cust_pkg_usage
3764 Returns a list of all voice usage counters attached to this package.
3768 sub cust_pkg_usage {
3770 qsearch('cust_pkg_usage', { pkgnum => $self->pkgnum });
3773 =item apply_usage OPTIONS
3775 Takes the following options:
3776 - cdr: a call detail record (L<FS::cdr>)
3777 - rate_detail: the rate determined for this call (L<FS::rate_detail>)
3778 - minutes: the maximum number of minutes to be charged
3780 Finds available usage minutes for a call of this class, and subtracts
3781 up to that many minutes from the usage pool. If the usage pool is empty,
3782 and the C<cdr-minutes_priority> global config option is set, minutes may
3783 be taken from other calls as well. Either way, an allocation record will
3784 be created (L<FS::cdr_cust_pkg_usage>) and this method will return the
3785 number of minutes of usage applied to the call.
3790 my ($self, %opt) = @_;
3791 my $cdr = $opt{cdr};
3792 my $rate_detail = $opt{rate_detail};
3793 my $minutes = $opt{minutes};
3794 my $classnum = $rate_detail->classnum;
3795 my $pkgnum = $self->pkgnum;
3796 my $custnum = $self->custnum;
3798 local $SIG{HUP} = 'IGNORE';
3799 local $SIG{INT} = 'IGNORE';
3800 local $SIG{QUIT} = 'IGNORE';
3801 local $SIG{TERM} = 'IGNORE';
3802 local $SIG{TSTP} = 'IGNORE';
3803 local $SIG{PIPE} = 'IGNORE';
3805 my $oldAutoCommit = $FS::UID::AutoCommit;
3806 local $FS::UID::AutoCommit = 0;
3808 my $order = FS::Conf->new->config('cdr-minutes_priority');
3812 $is_classnum = ' part_pkg_usage_class.classnum = '.$classnum;
3814 $is_classnum = ' part_pkg_usage_class.classnum IS NULL';
3816 my @usage_recs = qsearch({
3817 'table' => 'cust_pkg_usage',
3818 'addl_from' => ' JOIN part_pkg_usage USING (pkgusagepart)'.
3819 ' JOIN cust_pkg USING (pkgnum)'.
3820 ' JOIN part_pkg_usage_class USING (pkgusagepart)',
3821 'select' => 'cust_pkg_usage.*',
3822 'extra_sql' => " WHERE ( cust_pkg.pkgnum = $pkgnum OR ".
3823 " ( cust_pkg.custnum = $custnum AND ".
3824 " part_pkg_usage.shared IS NOT NULL ) ) AND ".
3825 $is_classnum . ' AND '.
3826 " cust_pkg_usage.minutes > 0",
3827 'order_by' => " ORDER BY priority ASC",
3830 my $orig_minutes = $minutes;
3832 while (!$error and $minutes > 0 and @usage_recs) {
3833 my $cust_pkg_usage = shift @usage_recs;
3834 $cust_pkg_usage->select_for_update;
3835 my $cdr_cust_pkg_usage = FS::cdr_cust_pkg_usage->new({
3836 pkgusagenum => $cust_pkg_usage->pkgusagenum,
3837 acctid => $cdr->acctid,
3838 minutes => min($cust_pkg_usage->minutes, $minutes),
3840 $cust_pkg_usage->set('minutes',
3841 sprintf('%.0f', $cust_pkg_usage->minutes - $cdr_cust_pkg_usage->minutes)
3843 $error = $cust_pkg_usage->replace || $cdr_cust_pkg_usage->insert;
3844 $minutes -= $cdr_cust_pkg_usage->minutes;
3846 if ( $order and $minutes > 0 and !$error ) {
3847 # then try to steal minutes from another call
3849 'table' => 'cdr_cust_pkg_usage',
3850 'addl_from' => ' JOIN cust_pkg_usage USING (pkgusagenum)'.
3851 ' JOIN part_pkg_usage USING (pkgusagepart)'.
3852 ' JOIN cust_pkg USING (pkgnum)'.
3853 ' JOIN part_pkg_usage_class USING (pkgusagepart)'.
3854 ' JOIN cdr USING (acctid)',
3855 'select' => 'cdr_cust_pkg_usage.*',
3856 'extra_sql' => " WHERE cdr.freesidestatus = 'rated' AND ".
3857 " ( cust_pkg.pkgnum = $pkgnum OR ".
3858 " ( cust_pkg.custnum = $custnum AND ".
3859 " part_pkg_usage.shared IS NOT NULL ) ) AND ".
3860 " part_pkg_usage_class.classnum = $classnum",
3861 'order_by' => ' ORDER BY part_pkg_usage.priority ASC',
3863 if ( $order eq 'time' ) {
3864 # find CDRs that are using minutes, but have a later startdate
3866 my $startdate = $cdr->startdate;
3867 if ($startdate !~ /^\d+$/) {
3868 die "bad cdr startdate '$startdate'";
3870 $search{'extra_sql'} .= " AND cdr.startdate > $startdate";
3871 # minimize needless reshuffling
3872 $search{'order_by'} .= ', cdr.startdate DESC';
3874 # XXX may not work correctly with rate_time schedules. Could
3875 # fix this by storing ratedetailnum in cdr_cust_pkg_usage, I
3877 $search{'addl_from'} .=
3878 ' JOIN rate_detail'.
3879 ' ON (cdr.rated_ratedetailnum = rate_detail.ratedetailnum)';
3880 if ( $order eq 'rate_high' ) {
3881 $search{'extra_sql'} .= ' AND rate_detail.min_charge < '.
3882 $rate_detail->min_charge;
3883 $search{'order_by'} .= ', rate_detail.min_charge ASC';
3884 } elsif ( $order eq 'rate_low' ) {
3885 $search{'extra_sql'} .= ' AND rate_detail.min_charge > '.
3886 $rate_detail->min_charge;
3887 $search{'order_by'} .= ', rate_detail.min_charge DESC';
3889 # this should really never happen
3890 die "invalid cdr-minutes_priority value '$order'\n";
3893 my @cdr_usage_recs = qsearch(\%search);
3895 while (!$error and @cdr_usage_recs and $minutes > 0) {
3896 my $cdr_cust_pkg_usage = shift @cdr_usage_recs;
3897 my $cust_pkg_usage = $cdr_cust_pkg_usage->cust_pkg_usage;
3898 my $old_cdr = $cdr_cust_pkg_usage->cdr;
3899 $reproc_cdrs{$old_cdr->acctid} = $old_cdr;
3900 $cdr_cust_pkg_usage->select_for_update;
3901 $old_cdr->select_for_update;
3902 $cust_pkg_usage->select_for_update;
3903 # in case someone else stole the usage from this CDR
3904 # while waiting for the lock...
3905 next if $old_cdr->acctid != $cdr_cust_pkg_usage->acctid;
3906 # steal the usage allocation and flag the old CDR for reprocessing
3907 $cdr_cust_pkg_usage->set('acctid', $cdr->acctid);
3908 # if the allocation is more minutes than we need, adjust it...
3909 my $delta = $cdr_cust_pkg_usage->minutes - $minutes;
3911 $cdr_cust_pkg_usage->set('minutes', $minutes);
3912 $cust_pkg_usage->set('minutes', $cust_pkg_usage->minutes + $delta);
3913 $error = $cust_pkg_usage->replace;
3915 #warn 'CDR '.$cdr->acctid . ' stealing allocation '.$cdr_cust_pkg_usage->cdrusagenum.' from CDR '.$old_cdr->acctid."\n";
3916 $error ||= $cdr_cust_pkg_usage->replace;
3917 # deduct the stolen minutes
3918 $minutes -= $cdr_cust_pkg_usage->minutes;
3920 # after all minute-stealing is done, reset the affected CDRs
3921 foreach (values %reproc_cdrs) {
3922 $error ||= $_->set_status('');
3923 # XXX or should we just call $cdr->rate right here?
3924 # it's not like we can create a loop this way, since the min_charge
3925 # or call time has to go monotonically in one direction.
3926 # we COULD get some very deep recursions going, though...
3928 } # if $order and $minutes
3931 die "error applying included minutes\npkgnum ".$self->pkgnum.", class $classnum, acctid ".$cdr->acctid."\n$error\n"
3933 $dbh->commit if $oldAutoCommit;
3934 return $orig_minutes - $minutes;
3938 =item supplemental_pkgs
3940 Returns a list of all packages supplemental to this one.
3944 sub supplemental_pkgs {
3946 qsearch('cust_pkg', { 'main_pkgnum' => $self->pkgnum });
3951 Returns the package that this one is supplemental to, if any.
3957 if ( $self->main_pkgnum ) {
3958 return FS::cust_pkg->by_key($self->main_pkgnum);
3965 =head1 CLASS METHODS
3971 Returns an SQL expression identifying recurring packages.
3975 sub recurring_sql { "
3976 '0' != ( select freq from part_pkg
3977 where cust_pkg.pkgpart = part_pkg.pkgpart )
3982 Returns an SQL expression identifying one-time packages.
3987 '0' = ( select freq from part_pkg
3988 where cust_pkg.pkgpart = part_pkg.pkgpart )
3993 Returns an SQL expression identifying ordered packages (recurring packages not
3999 $_[0]->recurring_sql. " AND ". $_[0]->not_yet_billed_sql;
4004 Returns an SQL expression identifying active packages.
4009 $_[0]->recurring_sql. "
4010 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
4011 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4012 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
4015 =item not_yet_billed_sql
4017 Returns an SQL expression identifying packages which have not yet been billed.
4021 sub not_yet_billed_sql { "
4022 ( cust_pkg.setup IS NULL OR cust_pkg.setup = 0 )
4023 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4024 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
4029 Returns an SQL expression identifying inactive packages (one-time packages
4030 that are otherwise unsuspended/uncancelled).
4034 sub inactive_sql { "
4035 ". $_[0]->onetime_sql(). "
4036 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
4037 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4038 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
4044 Returns an SQL expression identifying suspended packages.
4048 sub suspended_sql { susp_sql(@_); }
4050 #$_[0]->recurring_sql(). ' AND '.
4052 ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4053 AND cust_pkg.susp IS NOT NULL AND cust_pkg.susp != 0
4060 Returns an SQL exprression identifying cancelled packages.
4064 sub cancelled_sql { cancel_sql(@_); }
4066 #$_[0]->recurring_sql(). ' AND '.
4067 "cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0";
4072 Returns an SQL expression to give the package status as a string.
4078 WHEN cust_pkg.cancel IS NOT NULL THEN 'cancelled'
4079 WHEN cust_pkg.susp IS NOT NULL THEN 'suspended'
4080 WHEN cust_pkg.setup IS NULL THEN 'not yet billed'
4081 WHEN ".onetime_sql()." THEN 'one-time charge'
4086 =item search HASHREF
4090 Returns a qsearch hash expression to search for parameters specified in HASHREF.
4091 Valid parameters are
4099 active, inactive, suspended, cancel (or cancelled)
4103 active, inactive, suspended, one-time charge, inactive, cancel (or cancelled)
4107 boolean selects custom packages
4113 pkgpart or arrayref or hashref of pkgparts
4117 arrayref of beginning and ending epoch date
4121 arrayref of beginning and ending epoch date
4125 arrayref of beginning and ending epoch date
4129 arrayref of beginning and ending epoch date
4133 arrayref of beginning and ending epoch date
4137 arrayref of beginning and ending epoch date
4141 arrayref of beginning and ending epoch date
4145 pkgnum or APKG_pkgnum
4149 a value suited to passing to FS::UI::Web::cust_header
4153 specifies the user for agent virtualization
4157 boolean; if true, returns only packages with more than 0 FCC phone lines.
4159 =item state, country
4161 Limit to packages with a service location in the specified state and country.
4162 For FCC 477 reporting, mostly.
4169 my ($class, $params) = @_;
4176 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
4178 "cust_main.agentnum = $1";
4185 if ( $params->{'cust_status'} =~ /^([a-z]+)$/ ) {
4186 push @where, FS::cust_main->cust_status_sql . " = '$1' ";
4190 # parse customer sales person
4193 if ( $params->{'cust_main_salesnum'} =~ /^(\d+)$/ ) {
4194 push @where, ($1 > 0) ? "cust_main.salesnum = $1"
4195 : 'cust_main.salesnum IS NULL';
4200 # parse sales person
4203 if ( $params->{'salesnum'} =~ /^(\d+)$/ ) {
4204 push @where, ($1 > 0) ? "cust_pkg.salesnum = $1"
4205 : 'cust_pkg.salesnum IS NULL';
4212 if ( $params->{'custnum'} =~ /^(\d+)$/ and $1 ) {
4214 "cust_pkg.custnum = $1";
4221 if ( $params->{'pkgbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
4223 "cust_pkg.pkgbatch = '$1'";
4230 if ( $params->{'magic'} eq 'active'
4231 || $params->{'status'} eq 'active' ) {
4233 push @where, FS::cust_pkg->active_sql();
4235 } elsif ( $params->{'magic'} =~ /^not[ _]yet[ _]billed$/
4236 || $params->{'status'} =~ /^not[ _]yet[ _]billed$/ ) {
4238 push @where, FS::cust_pkg->not_yet_billed_sql();
4240 } elsif ( $params->{'magic'} =~ /^(one-time charge|inactive)/
4241 || $params->{'status'} =~ /^(one-time charge|inactive)/ ) {
4243 push @where, FS::cust_pkg->inactive_sql();
4245 } elsif ( $params->{'magic'} eq 'suspended'
4246 || $params->{'status'} eq 'suspended' ) {
4248 push @where, FS::cust_pkg->suspended_sql();
4250 } elsif ( $params->{'magic'} =~ /^cancell?ed$/
4251 || $params->{'status'} =~ /^cancell?ed$/ ) {
4253 push @where, FS::cust_pkg->cancelled_sql();
4258 # parse package class
4261 if ( exists($params->{'classnum'}) ) {
4264 if ( ref($params->{'classnum'}) ) {
4266 if ( ref($params->{'classnum'}) eq 'HASH' ) {
4267 @classnum = grep $params->{'classnum'}{$_}, keys %{ $params->{'classnum'} };
4268 } elsif ( ref($params->{'classnum'}) eq 'ARRAY' ) {
4269 @classnum = @{ $params->{'classnum'} };
4271 die 'unhandled classnum ref '. $params->{'classnum'};
4275 } elsif ( $params->{'classnum'} =~ /^(\d*)$/ && $1 ne '0' ) {
4282 my @nums = grep $_, @classnum;
4283 push @c_where, 'part_pkg.classnum IN ('. join(',',@nums). ')' if @nums;
4284 my $null = scalar( grep { $_ eq '' } @classnum );
4285 push @c_where, 'part_pkg.classnum IS NULL' if $null;
4287 if ( scalar(@c_where) == 1 ) {
4288 push @where, @c_where;
4289 } elsif ( @c_where ) {
4290 push @where, ' ( '. join(' OR ', @c_where). ' ) ';
4299 # parse package report options
4302 my @report_option = ();
4303 if ( exists($params->{'report_option'}) ) {
4304 if ( ref($params->{'report_option'}) eq 'ARRAY' ) {
4305 @report_option = @{ $params->{'report_option'} };
4306 } elsif ( $params->{'report_option'} =~ /^([,\d]*)$/ ) {
4307 @report_option = split(',', $1);
4312 if (@report_option) {
4313 # this will result in the empty set for the dangling comma case as it should
4315 map{ "0 < ( SELECT count(*) FROM part_pkg_option
4316 WHERE part_pkg_option.pkgpart = part_pkg.pkgpart
4317 AND optionname = 'report_option_$_'
4318 AND optionvalue = '1' )"
4322 foreach my $any ( grep /^report_option_any/, keys %$params ) {
4324 my @report_option_any = ();
4325 if ( ref($params->{$any}) eq 'ARRAY' ) {
4326 @report_option_any = @{ $params->{$any} };
4327 } elsif ( $params->{$any} =~ /^([,\d]*)$/ ) {
4328 @report_option_any = split(',', $1);
4331 if (@report_option_any) {
4332 # this will result in the empty set for the dangling comma case as it should
4333 push @where, ' ( '. join(' OR ',
4334 map{ "0 < ( SELECT count(*) FROM part_pkg_option
4335 WHERE part_pkg_option.pkgpart = part_pkg.pkgpart
4336 AND optionname = 'report_option_$_'
4337 AND optionvalue = '1' )"
4338 } @report_option_any
4348 push @where, "part_pkg.custom = 'Y'" if $params->{custom};
4354 push @where, "(part_pkg.fcc_ds0s > 0 OR pkg_class.fcc_ds0s > 0)"
4355 if $params->{fcc_line};
4361 if ( exists($params->{'censustract'}) ) {
4362 $params->{'censustract'} =~ /^([.\d]*)$/;
4363 my $censustract = "cust_location.censustract = '$1'";
4364 $censustract .= ' OR cust_location.censustract is NULL' unless $1;
4365 push @where, "( $censustract )";
4369 # parse censustract2
4371 if ( exists($params->{'censustract2'})
4372 && $params->{'censustract2'} =~ /^(\d*)$/
4376 push @where, "cust_location.censustract LIKE '$1%'";
4379 "( cust_location.censustract = '' OR cust_location.censustract IS NULL )";
4384 # parse country/state
4386 for (qw(state country)) { # parsing rules are the same for these
4387 if ( exists($params->{$_})
4388 && uc($params->{$_}) =~ /^([A-Z]{2})$/ )
4390 # XXX post-2.3 only--before that, state/country may be in cust_main
4391 push @where, "cust_location.$_ = '$1'";
4399 if ( ref($params->{'pkgpart'}) ) {
4402 if ( ref($params->{'pkgpart'}) eq 'HASH' ) {
4403 @pkgpart = grep $params->{'pkgpart'}{$_}, keys %{ $params->{'pkgpart'} };
4404 } elsif ( ref($params->{'pkgpart'}) eq 'ARRAY' ) {
4405 @pkgpart = @{ $params->{'pkgpart'} };
4407 die 'unhandled pkgpart ref '. $params->{'pkgpart'};
4410 @pkgpart = grep /^(\d+)$/, @pkgpart;
4412 push @where, 'pkgpart IN ('. join(',', @pkgpart). ')' if scalar(@pkgpart);
4414 } elsif ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
4415 push @where, "pkgpart = $1";
4424 #false laziness w/report_cust_pkg.html
4427 'one-time charge' => { 'last_bill'=>1, 'bill'=>1, 'adjourn'=>1, 'susp'=>1, 'expire'=>1, 'cancel'=>1, },
4428 'active' => { 'susp'=>1, 'cancel'=>1 },
4429 'suspended' => { 'cancel' => 1 },
4434 if( exists($params->{'active'} ) ) {
4435 # This overrides all the other date-related fields
4436 my($beginning, $ending) = @{$params->{'active'}};
4438 "cust_pkg.setup IS NOT NULL",
4439 "cust_pkg.setup <= $ending",
4440 "(cust_pkg.cancel IS NULL OR cust_pkg.cancel >= $beginning )",
4441 "NOT (".FS::cust_pkg->onetime_sql . ")";
4444 foreach my $field (qw( setup last_bill bill adjourn susp expire contract_end change_date cancel )) {
4446 next unless exists($params->{$field});
4448 my($beginning, $ending) = @{$params->{$field}};
4450 next if $beginning == 0 && $ending == 4294967295;
4453 "cust_pkg.$field IS NOT NULL",
4454 "cust_pkg.$field >= $beginning",
4455 "cust_pkg.$field <= $ending";
4457 $orderby ||= "ORDER BY cust_pkg.$field";
4462 $orderby ||= 'ORDER BY bill';
4465 # parse magic, legacy, etc.
4468 if ( $params->{'magic'} &&
4469 $params->{'magic'} =~ /^(active|inactive|suspended|cancell?ed)$/
4472 $orderby = 'ORDER BY pkgnum';
4474 if ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
4475 push @where, "pkgpart = $1";
4478 } elsif ( $params->{'query'} eq 'pkgnum' ) {
4480 $orderby = 'ORDER BY pkgnum';
4482 } elsif ( $params->{'query'} eq 'APKG_pkgnum' ) {
4484 $orderby = 'ORDER BY pkgnum';
4487 SELECT count(*) FROM pkg_svc
4488 WHERE pkg_svc.pkgpart = cust_pkg.pkgpart
4489 AND pkg_svc.quantity > ( SELECT count(*) FROM cust_svc
4490 WHERE cust_svc.pkgnum = cust_pkg.pkgnum
4491 AND cust_svc.svcpart = pkg_svc.svcpart
4498 # setup queries, links, subs, etc. for the search
4501 # here is the agent virtualization
4502 if ($params->{CurrentUser}) {
4504 qsearchs('access_user', { username => $params->{CurrentUser} });
4507 push @where, $access_user->agentnums_sql('table'=>'cust_main');
4512 push @where, $FS::CurrentUser::CurrentUser->agentnums_sql('table'=>'cust_main');
4515 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
4517 my $addl_from = 'LEFT JOIN part_pkg USING ( pkgpart ) '.
4518 'LEFT JOIN pkg_class ON ( part_pkg.classnum = pkg_class.classnum ) '.
4519 'LEFT JOIN cust_location USING ( locationnum ) '.
4520 FS::UI::Web::join_cust_main('cust_pkg', 'cust_pkg');
4524 if ( $params->{'select_zip5'} ) {
4525 my $zip = 'cust_location.zip';
4527 $select = "DISTINCT substr($zip,1,5) as zip";
4528 $orderby = "ORDER BY substr($zip,1,5)";
4529 $count_query = "SELECT COUNT( DISTINCT substr($zip,1,5) )";
4531 $select = join(', ',
4533 ( map "part_pkg.$_", qw( pkg freq ) ),
4534 'pkg_class.classname',
4535 'cust_main.custnum AS cust_main_custnum',
4536 FS::UI::Web::cust_sql_fields(
4537 $params->{'cust_fields'}
4540 $count_query = 'SELECT COUNT(*)';
4543 $count_query .= " FROM cust_pkg $addl_from $extra_sql";
4546 'table' => 'cust_pkg',
4548 'select' => $select,
4549 'extra_sql' => $extra_sql,
4550 'order_by' => $orderby,
4551 'addl_from' => $addl_from,
4552 'count_query' => $count_query,
4559 Returns a list of two package counts. The first is a count of packages
4560 based on the supplied criteria and the second is the count of residential
4561 packages with those same criteria. Criteria are specified as in the search
4567 my ($class, $params) = @_;
4569 my $sql_query = $class->search( $params );
4571 my $count_sql = delete($sql_query->{'count_query'});
4572 $count_sql =~ s/ FROM/,count(CASE WHEN cust_main.company IS NULL OR cust_main.company = '' THEN 1 END) FROM/
4573 or die "couldn't parse count_sql";
4575 my $count_sth = dbh->prepare($count_sql)
4576 or die "Error preparing $count_sql: ". dbh->errstr;
4578 or die "Error executing $count_sql: ". $count_sth->errstr;
4579 my $count_arrayref = $count_sth->fetchrow_arrayref;
4581 return ( @$count_arrayref );
4585 =item tax_locationnum_sql
4587 Returns an SQL expression for the tax location for a package, based
4588 on the settings of 'tax-pkg_address' and 'tax-ship_address'.
4592 sub tax_locationnum_sql {
4593 my $conf = FS::Conf->new;
4594 if ( $conf->exists('tax-pkg_address') ) {
4595 'cust_pkg.locationnum';
4597 elsif ( $conf->exists('tax-ship_address') ) {
4598 'cust_main.ship_locationnum';
4601 'cust_main.bill_locationnum';
4607 Returns a list: the first item is an SQL fragment identifying matching
4608 packages/customers via location (taking into account shipping and package
4609 address taxation, if enabled), and subsequent items are the parameters to
4610 substitute for the placeholders in that fragment.
4615 my($class, %opt) = @_;
4616 my $ornull = $opt{'ornull'};
4618 my $conf = new FS::Conf;
4620 # '?' placeholders in _location_sql_where
4621 my $x = $ornull ? 3 : 2;
4632 if ( $conf->exists('tax-ship_address') ) {
4635 ( ( ship_last IS NULL OR ship_last = '' )
4636 AND ". _location_sql_where('cust_main', '', $ornull ). "
4638 OR ( ship_last IS NOT NULL AND ship_last != ''
4639 AND ". _location_sql_where('cust_main', 'ship_', $ornull ). "
4642 # AND payby != 'COMP'
4644 @main_param = ( @bill_param, @bill_param );
4648 $main_where = _location_sql_where('cust_main'); # AND payby != 'COMP'
4649 @main_param = @bill_param;
4655 if ( $conf->exists('tax-pkg_address') ) {
4657 my $loc_where = _location_sql_where( 'cust_location', '', $ornull );
4660 ( cust_pkg.locationnum IS NULL AND $main_where )
4661 OR ( cust_pkg.locationnum IS NOT NULL AND $loc_where )
4664 @param = ( @main_param, @bill_param );
4668 $where = $main_where;
4669 @param = @main_param;
4677 #subroutine, helper for location_sql
4678 sub _location_sql_where {
4680 my $prefix = @_ ? shift : '';
4681 my $ornull = @_ ? shift : '';
4683 # $ornull = $ornull ? " OR ( ? IS NULL AND $table.${prefix}county IS NULL ) " : '';
4685 $ornull = $ornull ? ' OR ? IS NULL ' : '';
4687 my $or_empty_city = " OR ( ? = '' AND $table.${prefix}city IS NULL )";
4688 my $or_empty_county = " OR ( ? = '' AND $table.${prefix}county IS NULL )";
4689 my $or_empty_state = " OR ( ? = '' AND $table.${prefix}state IS NULL )";
4691 my $text = (driver_name =~ /^mysql/i) ? 'char' : 'text';
4693 # ( $table.${prefix}city = ? $or_empty_city $ornull )
4695 ( $table.district = ? OR ? = '' OR CAST(? AS $text) IS NULL )
4696 AND ( $table.${prefix}city = ? OR ? = '' OR CAST(? AS $text) IS NULL )
4697 AND ( $table.${prefix}county = ? $or_empty_county $ornull )
4698 AND ( $table.${prefix}state = ? $or_empty_state $ornull )
4699 AND $table.${prefix}country = ?
4704 my( $self, $what ) = @_;
4706 my $what_show_zero = $what. '_show_zero';
4707 length($self->$what_show_zero())
4708 ? ($self->$what_show_zero() eq 'Y')
4709 : $self->part_pkg->$what_show_zero();
4716 =item order CUSTNUM, PKGPARTS_ARYREF, [ REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF [ REFNUM ] ] ]
4718 CUSTNUM is a customer (see L<FS::cust_main>)
4720 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
4721 L<FS::part_pkg>) to order for this customer. Duplicates are of course
4724 REMOVE_PKGNUMS is an optional list of pkgnums specifying the billing items to
4725 remove for this customer. The services (see L<FS::cust_svc>) are moved to the
4726 new billing items. An error is returned if this is not possible (see
4727 L<FS::pkg_svc>). An empty arrayref is equivalent to not specifying this
4730 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
4731 newly-created cust_pkg objects.
4733 REFNUM, if specified, will specify the FS::pkg_referral record to be created
4734 and inserted. Multiple FS::pkg_referral records can be created by
4735 setting I<refnum> to an array reference of refnums or a hash reference with
4736 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
4737 record will be created corresponding to cust_main.refnum.
4742 my ($custnum, $pkgparts, $remove_pkgnum, $return_cust_pkg, $refnum) = @_;
4744 my $conf = new FS::Conf;
4746 # Transactionize this whole mess
4747 local $SIG{HUP} = 'IGNORE';
4748 local $SIG{INT} = 'IGNORE';
4749 local $SIG{QUIT} = 'IGNORE';
4750 local $SIG{TERM} = 'IGNORE';
4751 local $SIG{TSTP} = 'IGNORE';
4752 local $SIG{PIPE} = 'IGNORE';
4754 my $oldAutoCommit = $FS::UID::AutoCommit;
4755 local $FS::UID::AutoCommit = 0;
4759 # my $cust_main = qsearchs('cust_main', { custnum => $custnum });
4760 # return "Customer not found: $custnum" unless $cust_main;
4762 warn "$me order: pkgnums to remove: ". join(',', @$remove_pkgnum). "\n"
4765 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
4768 my $change = scalar(@old_cust_pkg) != 0;
4771 if ( scalar(@old_cust_pkg) == 1 && scalar(@$pkgparts) == 1 ) {
4773 warn "$me order: changing pkgnum ". $old_cust_pkg[0]->pkgnum.
4774 " to pkgpart ". $pkgparts->[0]. "\n"
4777 my $err_or_cust_pkg =
4778 $old_cust_pkg[0]->change( 'pkgpart' => $pkgparts->[0],
4779 'refnum' => $refnum,
4782 unless (ref($err_or_cust_pkg)) {
4783 $dbh->rollback if $oldAutoCommit;
4784 return $err_or_cust_pkg;
4787 push @$return_cust_pkg, $err_or_cust_pkg;
4788 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4793 # Create the new packages.
4794 foreach my $pkgpart (@$pkgparts) {
4796 warn "$me order: inserting pkgpart $pkgpart\n" if $DEBUG;
4798 my $cust_pkg = new FS::cust_pkg { custnum => $custnum,
4799 pkgpart => $pkgpart,
4803 $error = $cust_pkg->insert( 'change' => $change );
4804 push @$return_cust_pkg, $cust_pkg;
4806 foreach my $link ($cust_pkg->part_pkg->supp_part_pkg_link) {
4807 my $supp_pkg = FS::cust_pkg->new({
4808 custnum => $custnum,
4809 pkgpart => $link->dst_pkgpart,
4811 main_pkgnum => $cust_pkg->pkgnum,
4814 $error ||= $supp_pkg->insert( 'change' => $change );
4815 push @$return_cust_pkg, $supp_pkg;
4819 $dbh->rollback if $oldAutoCommit;
4824 # $return_cust_pkg now contains refs to all of the newly
4827 # Transfer services and cancel old packages.
4828 foreach my $old_pkg (@old_cust_pkg) {
4830 warn "$me order: transferring services from pkgnum ". $old_pkg->pkgnum. "\n"
4833 foreach my $new_pkg (@$return_cust_pkg) {
4834 $error = $old_pkg->transfer($new_pkg);
4835 if ($error and $error == 0) {
4836 # $old_pkg->transfer failed.
4837 $dbh->rollback if $oldAutoCommit;
4842 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
4843 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
4844 foreach my $new_pkg (@$return_cust_pkg) {
4845 $error = $old_pkg->transfer($new_pkg, 'change_svcpart'=>1 );
4846 if ($error and $error == 0) {
4847 # $old_pkg->transfer failed.
4848 $dbh->rollback if $oldAutoCommit;
4855 # Transfers were successful, but we went through all of the
4856 # new packages and still had services left on the old package.
4857 # We can't cancel the package under the circumstances, so abort.
4858 $dbh->rollback if $oldAutoCommit;
4859 return "Unable to transfer all services from package ".$old_pkg->pkgnum;
4861 $error = $old_pkg->cancel( quiet=>1 );
4867 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4871 =item bulk_change PKGPARTS_ARYREF, REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF ]
4873 A bulk change method to change packages for multiple customers.
4875 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
4876 L<FS::part_pkg>) to order for each customer. Duplicates are of course
4879 REMOVE_PKGNUMS is an list of pkgnums specifying the billing items to
4880 replace. The services (see L<FS::cust_svc>) are moved to the
4881 new billing items. An error is returned if this is not possible (see
4884 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
4885 newly-created cust_pkg objects.
4890 my ($pkgparts, $remove_pkgnum, $return_cust_pkg) = @_;
4892 # Transactionize this whole mess
4893 local $SIG{HUP} = 'IGNORE';
4894 local $SIG{INT} = 'IGNORE';
4895 local $SIG{QUIT} = 'IGNORE';
4896 local $SIG{TERM} = 'IGNORE';
4897 local $SIG{TSTP} = 'IGNORE';
4898 local $SIG{PIPE} = 'IGNORE';
4900 my $oldAutoCommit = $FS::UID::AutoCommit;
4901 local $FS::UID::AutoCommit = 0;
4905 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
4908 while(scalar(@old_cust_pkg)) {
4910 my $custnum = $old_cust_pkg[0]->custnum;
4911 my (@remove) = map { $_->pkgnum }
4912 grep { $_->custnum == $custnum } @old_cust_pkg;
4913 @old_cust_pkg = grep { $_->custnum != $custnum } @old_cust_pkg;
4915 my $error = order $custnum, $pkgparts, \@remove, \@return;
4917 push @errors, $error
4919 push @$return_cust_pkg, @return;
4922 if (scalar(@errors)) {
4923 $dbh->rollback if $oldAutoCommit;
4924 return join(' / ', @errors);
4927 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4931 # Used by FS::Upgrade to migrate to a new database.
4932 sub _upgrade_data { # class method
4933 my ($class, %opts) = @_;
4934 $class->_upgrade_otaker(%opts);
4936 # RT#10139, bug resulting in contract_end being set when it shouldn't
4937 'UPDATE cust_pkg SET contract_end = NULL WHERE contract_end = -1',
4938 # RT#10830, bad calculation of prorate date near end of year
4939 # the date range for bill is December 2009, and we move it forward
4940 # one year if it's before the previous bill date (which it should
4942 'UPDATE cust_pkg SET bill = bill + (365*24*60*60) WHERE bill < last_bill
4943 AND bill > 1259654400 AND bill < 1262332800 AND (SELECT plan FROM part_pkg
4944 WHERE part_pkg.pkgpart = cust_pkg.pkgpart) = \'prorate\'',
4945 # RT6628, add order_date to cust_pkg
4946 'update cust_pkg set order_date = (select history_date from h_cust_pkg
4947 where h_cust_pkg.pkgnum = cust_pkg.pkgnum and
4948 history_action = \'insert\') where order_date is null',
4950 foreach my $sql (@statements) {
4951 my $sth = dbh->prepare($sql);
4952 $sth->execute or die $sth->errstr;
4960 sub order is not OO. Perhaps it should be moved to FS::cust_main and made so?
4962 In sub order, the @pkgparts array (passed by reference) is clobbered.
4964 Also in sub order, no money is adjusted. Once FS::part_pkg defines a standard
4965 method to pass dates to the recur_prog expression, it should do so.
4967 FS::svc_acct, FS::svc_domain, FS::svc_www, FS::svc_ip and FS::svc_forward are
4968 loaded via 'use' at compile time, rather than via 'require' in sub { setup,
4969 suspend, unsuspend, cancel } because they use %FS::UID::callback to load
4970 configuration values. Probably need a subroutine which decides what to do
4971 based on whether or not we've fetched the user yet, rather than a hash. See
4972 FS::UID and the TODO.
4974 Now that things are transactional should the check in the insert method be
4979 L<FS::Record>, L<FS::cust_main>, L<FS::part_pkg>, L<FS::cust_svc>,
4980 L<FS::pkg_svc>, schema.html from the base documentation