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;
41 # need to 'use' these instead of 'require' in sub { cancel, suspend, unsuspend,
43 # because they load configuration by setting FS::UID::callback (see TODO)
49 # for sending cancel emails in sub cancel
53 $me = '[FS::cust_pkg]';
55 $disable_agentcheck = 0;
59 my ( $hashref, $cache ) = @_;
60 #if ( $hashref->{'pkgpart'} ) {
61 if ( $hashref->{'pkg'} ) {
62 # #@{ $self->{'_pkgnum'} } = ();
63 # my $subcache = $cache->subcache('pkgpart', 'part_pkg');
64 # $self->{'_pkgpart'} = $subcache;
65 # #push @{ $self->{'_pkgnum'} },
66 # FS::part_pkg->new_or_cached($hashref, $subcache);
67 $self->{'_pkgpart'} = FS::part_pkg->new($hashref);
69 if ( exists $hashref->{'svcnum'} ) {
70 #@{ $self->{'_pkgnum'} } = ();
71 my $subcache = $cache->subcache('svcnum', 'cust_svc', $hashref->{pkgnum});
72 $self->{'_svcnum'} = $subcache;
73 #push @{ $self->{'_pkgnum'} },
74 FS::cust_svc->new_or_cached($hashref, $subcache) if $hashref->{svcnum};
80 FS::cust_pkg - Object methods for cust_pkg objects
86 $record = new FS::cust_pkg \%hash;
87 $record = new FS::cust_pkg { 'column' => 'value' };
89 $error = $record->insert;
91 $error = $new_record->replace($old_record);
93 $error = $record->delete;
95 $error = $record->check;
97 $error = $record->cancel;
99 $error = $record->suspend;
101 $error = $record->unsuspend;
103 $part_pkg = $record->part_pkg;
105 @labels = $record->labels;
107 $seconds = $record->seconds_since($timestamp);
109 $error = FS::cust_pkg::order( $custnum, \@pkgparts );
110 $error = FS::cust_pkg::order( $custnum, \@pkgparts, \@remove_pkgnums ] );
114 An FS::cust_pkg object represents a customer billing item. FS::cust_pkg
115 inherits from FS::Record. The following fields are currently supported:
121 Primary key (assigned automatically for new billing items)
125 Customer (see L<FS::cust_main>)
129 Billing item definition (see L<FS::part_pkg>)
133 Optional link to package location (see L<FS::location>)
137 date package was ordered (also remains same on changes)
149 date (next bill date)
177 order taker (see L<FS::access_user>)
181 If this field is set to 1, disables the automatic
182 unsuspension of this package when using the B<unsuspendauto> config option.
186 If not set, defaults to 1
190 Date of change from previous package
200 =item change_locationnum
208 The pkgnum of the package that this package is supplemental to, if any.
212 The package link (L<FS::part_pkg_link>) that defines this supplemental
213 package, if it is one.
215 =item change_to_pkgnum
217 The pkgnum of the package this one will be "changed to" in the future
218 (on its expiration date).
222 Note: setup, last_bill, bill, adjourn, susp, expire, cancel and change_date
223 are specified as UNIX timestamps; see L<perlfunc/"time">. Also see
224 L<Time::Local> and L<Date::Parse> for conversion functions.
232 Create a new billing item. To add the item to the database, see L<"insert">.
236 sub table { 'cust_pkg'; }
237 sub cust_linked { $_[0]->cust_main_custnum || $_[0]->custnum }
238 sub cust_unlinked_msg {
240 "WARNING: can't find cust_main.custnum ". $self->custnum.
241 ' (cust_pkg.pkgnum '. $self->pkgnum. ')';
244 =item insert [ OPTION => VALUE ... ]
246 Adds this billing item to the database ("Orders" the item). If there is an
247 error, returns the error, otherwise returns false.
249 If the additional field I<promo_code> is defined instead of I<pkgpart>, it
250 will be used to look up the package definition and agent restrictions will be
253 If the additional field I<refnum> is defined, an FS::pkg_referral record will
254 be created and inserted. Multiple FS::pkg_referral records can be created by
255 setting I<refnum> to an array reference of refnums or a hash reference with
256 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
257 record will be created corresponding to cust_main.refnum.
259 The following options are available:
265 If set true, supresses actions that should only be taken for new package
266 orders. (Currently this includes: intro periods when delay_setup is on.)
270 cust_pkg_option records will be created
274 a ticket will be added to this customer with this subject
278 an optional queue name for ticket additions
282 Don't check the legality of the package definition. This should be used
283 when performing a package change that doesn't change the pkgpart (i.e.
291 my( $self, %options ) = @_;
294 $error = $self->check_pkgpart unless $options{'allow_pkgpart'};
295 return $error if $error;
297 my $part_pkg = $self->part_pkg;
299 # if the package def says to start only on the first of the month:
300 if ( $part_pkg->option('start_1st', 1) && !$self->start_date ) {
301 my ($sec,$min,$hour,$mday,$mon,$year) = (localtime(time) )[0,1,2,3,4,5];
302 $mon += 1 unless $mday == 1;
303 until ( $mon < 12 ) { $mon -= 12; $year++; }
304 $self->start_date( timelocal_nocheck(0,0,0,1,$mon,$year) );
307 # set up any automatic expire/adjourn/contract_end timers
308 # based on the start date
309 foreach my $action ( qw(expire adjourn contract_end) ) {
310 my $months = $part_pkg->option("${action}_months",1);
311 if($months and !$self->$action) {
312 my $start = $self->start_date || $self->setup || time;
313 $self->$action( $part_pkg->add_freq($start, $months) );
317 # if this package has "free days" and delayed setup fee, tehn
318 # set start date that many days in the future.
319 # (this should have been set in the UI, but enforce it here)
320 if ( ! $options{'change'}
321 && ( my $free_days = $part_pkg->option('free_days',1) )
322 && $part_pkg->option('delay_setup',1)
323 #&& ! $self->start_date
326 $self->start_date( $part_pkg->default_start_date );
329 $self->order_date(time);
331 local $SIG{HUP} = 'IGNORE';
332 local $SIG{INT} = 'IGNORE';
333 local $SIG{QUIT} = 'IGNORE';
334 local $SIG{TERM} = 'IGNORE';
335 local $SIG{TSTP} = 'IGNORE';
336 local $SIG{PIPE} = 'IGNORE';
338 my $oldAutoCommit = $FS::UID::AutoCommit;
339 local $FS::UID::AutoCommit = 0;
342 $error = $self->SUPER::insert($options{options} ? %{$options{options}} : ());
344 $dbh->rollback if $oldAutoCommit;
348 $self->refnum($self->cust_main->refnum) unless $self->refnum;
349 $self->refnum( [ $self->refnum ] ) unless ref($self->refnum);
350 $self->process_m2m( 'link_table' => 'pkg_referral',
351 'target_table' => 'part_referral',
352 'params' => $self->refnum,
355 if ( $self->discountnum ) {
356 my $error = $self->insert_discount();
358 $dbh->rollback if $oldAutoCommit;
363 my $conf = new FS::Conf;
365 if ( $conf->config('ticket_system') && $options{ticket_subject} ) {
367 #this init stuff is still inefficient, but at least its limited to
368 # the small number (any?) folks using ticket emailing on pkg order
371 # use lib ( "/opt/rt3/local/lib", "/opt/rt3/lib" );
378 use FS::TicketSystem;
379 FS::TicketSystem->init();
381 my $q = new RT::Queue($RT::SystemUser);
382 $q->Load($options{ticket_queue}) if $options{ticket_queue};
383 my $t = new RT::Ticket($RT::SystemUser);
384 my $mime = new MIME::Entity;
385 $mime->build( Type => 'text/plain', Data => $options{ticket_subject} );
386 $t->Create( $options{ticket_queue} ? (Queue => $q) : (),
387 Subject => $options{ticket_subject},
390 $t->AddLink( Type => 'MemberOf',
391 Target => 'freeside://freeside/cust_main/'. $self->custnum,
395 if ($conf->config('welcome_letter') && $self->cust_main->num_pkgs == 1) {
396 my $queue = new FS::queue {
397 'job' => 'FS::cust_main::queueable_print',
399 $error = $queue->insert(
400 'custnum' => $self->custnum,
401 'template' => 'welcome_letter',
405 warn "can't send welcome letter: $error";
410 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
417 This method now works but you probably shouldn't use it.
419 You don't want to delete packages, because there would then be no record
420 the customer ever purchased the package. Instead, see the cancel method and
421 hide cancelled packages.
428 local $SIG{HUP} = 'IGNORE';
429 local $SIG{INT} = 'IGNORE';
430 local $SIG{QUIT} = 'IGNORE';
431 local $SIG{TERM} = 'IGNORE';
432 local $SIG{TSTP} = 'IGNORE';
433 local $SIG{PIPE} = 'IGNORE';
435 my $oldAutoCommit = $FS::UID::AutoCommit;
436 local $FS::UID::AutoCommit = 0;
439 foreach my $cust_pkg_discount ($self->cust_pkg_discount) {
440 my $error = $cust_pkg_discount->delete;
442 $dbh->rollback if $oldAutoCommit;
446 #cust_bill_pkg_discount?
448 foreach my $cust_pkg_detail ($self->cust_pkg_detail) {
449 my $error = $cust_pkg_detail->delete;
451 $dbh->rollback if $oldAutoCommit;
456 foreach my $cust_pkg_reason (
458 'table' => 'cust_pkg_reason',
459 'hashref' => { 'pkgnum' => $self->pkgnum },
463 my $error = $cust_pkg_reason->delete;
465 $dbh->rollback if $oldAutoCommit;
472 my $error = $self->SUPER::delete(@_);
474 $dbh->rollback if $oldAutoCommit;
478 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
484 =item replace [ OLD_RECORD ] [ HASHREF | OPTION => VALUE ... ]
486 Replaces the OLD_RECORD with this one in the database. If there is an error,
487 returns the error, otherwise returns false.
489 Currently, custnum, setup, bill, adjourn, susp, expire, and cancel may be changed.
491 Changing pkgpart may have disasterous effects. See the order subroutine.
493 setup and bill are normally updated by calling the bill method of a customer
494 object (see L<FS::cust_main>).
496 suspend is normally updated by the suspend and unsuspend methods.
498 cancel is normally updated by the cancel method (and also the order subroutine
501 Available options are:
507 can be set to a cancellation reason (see L<FS:reason>), either a reasonnum of an existing reason, or passing a hashref will create a new reason. The hashref should have the following keys: typenum - Reason type (see L<FS::reason_type>, reason - Text of the new reason.
511 the access_user (see L<FS::access_user>) providing the reason
515 hashref of keys and values - cust_pkg_option records will be created, updated or removed as appopriate
524 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
529 ( ref($_[0]) eq 'HASH' )
533 #return "Can't (yet?) change pkgpart!" if $old->pkgpart != $new->pkgpart;
534 #return "Can't change otaker!" if $old->otaker ne $new->otaker;
537 #return "Can't change setup once it exists!"
538 # if $old->getfield('setup') &&
539 # $old->getfield('setup') != $new->getfield('setup');
541 #some logic for bill, susp, cancel?
543 local($disable_agentcheck) = 1 if $old->pkgpart == $new->pkgpart;
545 local $SIG{HUP} = 'IGNORE';
546 local $SIG{INT} = 'IGNORE';
547 local $SIG{QUIT} = 'IGNORE';
548 local $SIG{TERM} = 'IGNORE';
549 local $SIG{TSTP} = 'IGNORE';
550 local $SIG{PIPE} = 'IGNORE';
552 my $oldAutoCommit = $FS::UID::AutoCommit;
553 local $FS::UID::AutoCommit = 0;
556 foreach my $method ( qw(adjourn expire) ) { # How many reasons?
557 if ($options->{'reason'} && $new->$method && $old->$method ne $new->$method) {
558 my $error = $new->insert_reason(
559 'reason' => $options->{'reason'},
560 'date' => $new->$method,
562 'reason_otaker' => $options->{'reason_otaker'},
565 dbh->rollback if $oldAutoCommit;
566 return "Error inserting cust_pkg_reason: $error";
571 #save off and freeze RADIUS attributes for any associated svc_acct records
573 if ( $old->part_pkg->is_prepaid || $new->part_pkg->is_prepaid ) {
575 #also check for specific exports?
576 # to avoid spurious modify export events
577 @svc_acct = map { $_->svc_x }
578 grep { $_->part_svc->svcdb eq 'svc_acct' }
581 $_->snapshot foreach @svc_acct;
585 my $error = $new->export_pkg_change($old)
586 || $new->SUPER::replace( $old,
588 ? $options->{options}
592 $dbh->rollback if $oldAutoCommit;
596 #for prepaid packages,
597 #trigger export of new RADIUS Expiration attribute when cust_pkg.bill changes
598 foreach my $old_svc_acct ( @svc_acct ) {
599 my $new_svc_acct = new FS::svc_acct { $old_svc_acct->hash };
601 $new_svc_acct->replace( $old_svc_acct,
602 'depend_jobnum' => $options->{depend_jobnum},
605 $dbh->rollback if $oldAutoCommit;
610 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
617 Checks all fields to make sure this is a valid billing item. If there is an
618 error, returns the error, otherwise returns false. Called by the insert and
626 if ( !$self->locationnum or $self->locationnum == -1 ) {
627 $self->set('locationnum', $self->cust_main->ship_locationnum);
631 $self->ut_numbern('pkgnum')
632 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum')
633 || $self->ut_numbern('pkgpart')
634 || $self->ut_foreign_keyn('contactnum', 'contact', 'contactnum' )
635 || $self->ut_foreign_keyn('locationnum', 'cust_location', 'locationnum')
636 || $self->ut_foreign_keyn('salesnum', 'sales', 'salesnum')
637 || $self->ut_numbern('quantity')
638 || $self->ut_numbern('start_date')
639 || $self->ut_numbern('setup')
640 || $self->ut_numbern('bill')
641 || $self->ut_numbern('susp')
642 || $self->ut_numbern('cancel')
643 || $self->ut_numbern('adjourn')
644 || $self->ut_numbern('resume')
645 || $self->ut_numbern('expire')
646 || $self->ut_numbern('dundate')
647 || $self->ut_enum('no_auto', [ '', 'Y' ])
648 || $self->ut_enum('waive_setup', [ '', 'Y' ])
649 || $self->ut_numbern('agent_pkgid')
650 || $self->ut_enum('recur_show_zero', [ '', 'Y', 'N', ])
651 || $self->ut_enum('setup_show_zero', [ '', 'Y', 'N', ])
652 || $self->ut_foreign_keyn('main_pkgnum', 'cust_pkg', 'pkgnum')
653 || $self->ut_foreign_keyn('pkglinknum', 'part_pkg_link', 'pkglinknum')
654 || $self->ut_foreign_keyn('change_to_pkgnum', 'cust_pkg', 'pkgnum')
656 return $error if $error;
658 return "A package with both start date (future start) and setup date (already started) will never bill"
659 if $self->start_date && $self->setup;
661 return "A future unsuspend date can only be set for a package with a suspend date"
662 if $self->resume and !$self->susp and !$self->adjourn;
664 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
666 if ( $self->dbdef_table->column('manual_flag') ) {
667 $self->manual_flag('') if $self->manual_flag eq ' ';
668 $self->manual_flag =~ /^([01]?)$/
669 or return "Illegal manual_flag ". $self->manual_flag;
670 $self->manual_flag($1);
678 Check the pkgpart to make sure it's allowed with the reg_code and/or
679 promo_code of the package (if present) and with the customer's agent.
680 Called from C<insert>, unless we are doing a package change that doesn't
688 # my $error = $self->ut_numbern('pkgpart'); # already done
691 if ( $self->reg_code ) {
693 unless ( grep { $self->pkgpart == $_->pkgpart }
694 map { $_->reg_code_pkg }
695 qsearchs( 'reg_code', { 'code' => $self->reg_code,
696 'agentnum' => $self->cust_main->agentnum })
698 return "Unknown registration code";
701 } elsif ( $self->promo_code ) {
704 qsearchs('part_pkg', {
705 'pkgpart' => $self->pkgpart,
706 'promo_code' => { op=>'ILIKE', value=>$self->promo_code },
708 return 'Unknown promotional code' unless $promo_part_pkg;
712 unless ( $disable_agentcheck ) {
714 qsearchs( 'agent', { 'agentnum' => $self->cust_main->agentnum } );
715 return "agent ". $agent->agentnum. ':'. $agent->agent.
716 " can't purchase pkgpart ". $self->pkgpart
717 unless $agent->pkgpart_hashref->{ $self->pkgpart }
718 || $agent->agentnum == $self->part_pkg->agentnum;
721 $error = $self->ut_foreign_key('pkgpart', 'part_pkg', 'pkgpart' );
722 return $error if $error;
730 =item cancel [ OPTION => VALUE ... ]
732 Cancels and removes all services (see L<FS::cust_svc> and L<FS::part_svc>)
733 in this package, then cancels the package itself (sets the cancel field to
736 Available options are:
740 =item quiet - can be set true to supress email cancellation notices.
742 =item time - can be set to cancel the package based on a specific future or
743 historical date. Using time ensures that the remaining amount is calculated
744 correctly. Note however that this is an immediate cancel and just changes
745 the date. You are PROBABLY looking to expire the account instead of using
748 =item reason - can be set to a cancellation reason (see L<FS:reason>),
749 either a reasonnum of an existing reason, or passing a hashref will create
750 a new reason. The hashref should have the following keys: typenum - Reason
751 type (see L<FS::reason_type>, reason - Text of the new reason.
753 =item date - can be set to a unix style timestamp to specify when to
756 =item nobill - can be set true to skip billing if it might otherwise be done.
758 =item unused_credit - can be set to 1 to credit the remaining time, or 0 to
759 not credit it. This must be set (by change()) when changing the package
760 to a different pkgpart or location, and probably shouldn't be in any other
761 case. If it's not set, the 'unused_credit_cancel' part_pkg option will
766 If there is an error, returns the error, otherwise returns false.
771 my( $self, %options ) = @_;
774 # pass all suspend/cancel actions to the main package
775 if ( $self->main_pkgnum and !$options{'from_main'} ) {
776 return $self->main_pkg->cancel(%options);
779 my $conf = new FS::Conf;
781 warn "cust_pkg::cancel called with options".
782 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
785 local $SIG{HUP} = 'IGNORE';
786 local $SIG{INT} = 'IGNORE';
787 local $SIG{QUIT} = 'IGNORE';
788 local $SIG{TERM} = 'IGNORE';
789 local $SIG{TSTP} = 'IGNORE';
790 local $SIG{PIPE} = 'IGNORE';
792 my $oldAutoCommit = $FS::UID::AutoCommit;
793 local $FS::UID::AutoCommit = 0;
796 my $old = $self->select_for_update;
798 if ( $old->get('cancel') || $self->get('cancel') ) {
799 dbh->rollback if $oldAutoCommit;
800 return ""; # no error
803 # XXX possibly set cancel_time to the expire date?
804 my $cancel_time = $options{'time'} || time;
805 my $date = $options{'date'} if $options{'date'}; # expire/cancel later
806 $date = '' if ($date && $date <= $cancel_time); # complain instead?
808 #race condition: usage could be ongoing until unprovisioned
809 #resolved by performing a change package instead (which unprovisions) and
811 if ( !$options{nobill} && !$date ) {
812 # && $conf->exists('bill_usage_on_cancel') ) { #calc_cancel checks this
813 my $copy = $self->new({$self->hash});
815 $copy->cust_main->bill( 'pkg_list' => [ $copy ],
817 'time' => $cancel_time );
818 warn "Error billing during cancel, custnum ".
819 #$self->cust_main->custnum. ": $error"
824 if ( $options{'reason'} ) {
825 $error = $self->insert_reason( 'reason' => $options{'reason'},
826 'action' => $date ? 'expire' : 'cancel',
827 'date' => $date ? $date : $cancel_time,
828 'reason_otaker' => $options{'reason_otaker'},
831 dbh->rollback if $oldAutoCommit;
832 return "Error inserting cust_pkg_reason: $error";
836 my %svc_cancel_opt = ();
837 $svc_cancel_opt{'date'} = $date if $date;
838 foreach my $cust_svc (
841 sort { $a->[1] <=> $b->[1] }
842 map { [ $_, $_->svc_x ? $_->svc_x->table_info->{'cancel_weight'} : -1 ]; }
843 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
845 my $part_svc = $cust_svc->part_svc;
846 next if ( defined($part_svc) and $part_svc->preserve );
847 my $error = $cust_svc->cancel( %svc_cancel_opt );
850 $dbh->rollback if $oldAutoCommit;
851 return 'Error '. ($svc_cancel_opt{'date'} ? 'expiring' : 'canceling' ).
857 # credit remaining time if appropriate
859 if ( exists($options{'unused_credit'}) ) {
860 $do_credit = $options{'unused_credit'};
863 $do_credit = $self->part_pkg->option('unused_credit_cancel', 1);
866 my $error = $self->credit_remaining('cancel', $cancel_time);
868 $dbh->rollback if $oldAutoCommit;
875 my %hash = $self->hash;
877 $hash{'expire'} = $date;
879 $hash{'cancel'} = $cancel_time;
881 $hash{'change_custnum'} = $options{'change_custnum'};
883 my $new = new FS::cust_pkg ( \%hash );
884 $error = $new->replace( $self, options => { $self->options } );
885 if ( $self->change_to_pkgnum ) {
886 my $change_to = FS::cust_pkg->by_key($self->change_to_pkgnum);
887 $error ||= $change_to->cancel || $change_to->delete;
890 $dbh->rollback if $oldAutoCommit;
894 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
895 $error = $supp_pkg->cancel(%options, 'from_main' => 1);
897 $dbh->rollback if $oldAutoCommit;
898 return "canceling supplemental pkg#".$supp_pkg->pkgnum.": $error";
902 foreach my $usage ( $self->cust_pkg_usage ) {
903 $error = $usage->delete;
905 $dbh->rollback if $oldAutoCommit;
906 return "deleting usage pools: $error";
910 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
911 return '' if $date; #no errors
913 my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ } $self->cust_main->invoicing_list;
914 if ( !$options{'quiet'} &&
915 $conf->exists('emailcancel', $self->cust_main->agentnum) &&
917 my $msgnum = $conf->config('cancel_msgnum', $self->cust_main->agentnum);
920 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum });
921 $error = $msg_template->send( 'cust_main' => $self->cust_main,
926 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
927 'to' => \@invoicing_list,
928 'subject' => ( $conf->config('cancelsubject') || 'Cancellation Notice' ),
929 'body' => [ map "$_\n", $conf->config('cancelmessage') ],
932 #should this do something on errors?
939 =item cancel_if_expired [ NOW_TIMESTAMP ]
941 Cancels this package if its expire date has been reached.
945 sub cancel_if_expired {
947 my $time = shift || time;
948 return '' unless $self->expire && $self->expire <= $time;
949 my $error = $self->cancel;
951 return "Error cancelling expired pkg ". $self->pkgnum. " for custnum ".
952 $self->custnum. ": $error";
959 "Un-cancels" this package: Orders a new package with the same custnum, pkgpart,
960 locationnum, (other fields?). Attempts to re-provision cancelled services
961 using history information (errors at this stage are not fatal).
963 cust_pkg: pass a scalar reference, will be filled in with the new cust_pkg object
965 svc_fatal: service provisioning errors are fatal
967 svc_errors: pass an array reference, will be filled in with any provisioning errors
969 main_pkgnum: link the package as a supplemental package of this one. For
975 my( $self, %options ) = @_;
977 #in case you try do do $uncancel-date = $cust_pkg->uncacel
978 return '' unless $self->get('cancel');
980 if ( $self->main_pkgnum and !$options{'main_pkgnum'} ) {
981 return $self->main_pkg->uncancel(%options);
988 local $SIG{HUP} = 'IGNORE';
989 local $SIG{INT} = 'IGNORE';
990 local $SIG{QUIT} = 'IGNORE';
991 local $SIG{TERM} = 'IGNORE';
992 local $SIG{TSTP} = 'IGNORE';
993 local $SIG{PIPE} = 'IGNORE';
995 my $oldAutoCommit = $FS::UID::AutoCommit;
996 local $FS::UID::AutoCommit = 0;
1000 # insert the new package
1003 my $cust_pkg = new FS::cust_pkg {
1004 last_bill => ( $options{'last_bill'} || $self->get('last_bill') ),
1005 bill => ( $options{'bill'} || $self->get('bill') ),
1007 uncancel_pkgnum => $self->pkgnum,
1008 main_pkgnum => ($options{'main_pkgnum'} || ''),
1009 map { $_ => $self->get($_) } qw(
1010 custnum pkgpart locationnum
1012 susp adjourn resume expire start_date contract_end dundate
1013 change_date change_pkgpart change_locationnum
1014 manual_flag no_auto quantity agent_pkgid recur_show_zero setup_show_zero
1018 my $error = $cust_pkg->insert(
1019 'change' => 1, #supresses any referral credit to a referring customer
1020 'allow_pkgpart' => 1, # allow this even if the package def is disabled
1023 $dbh->rollback if $oldAutoCommit;
1031 #find historical services within this timeframe before the package cancel
1032 # (incompatible with "time" option to cust_pkg->cancel?)
1033 my $fuzz = 2 * 60; #2 minutes? too much? (might catch separate unprovision)
1034 # too little? (unprovisioing export delay?)
1035 my($end, $start) = ( $self->get('cancel'), $self->get('cancel') - $fuzz );
1036 my @h_cust_svc = $self->h_cust_svc( $end, $start );
1039 foreach my $h_cust_svc (@h_cust_svc) {
1040 my $h_svc_x = $h_cust_svc->h_svc_x( $end, $start );
1041 #next unless $h_svc_x; #should this happen?
1042 (my $table = $h_svc_x->table) =~ s/^h_//;
1043 require "FS/$table.pm";
1044 my $class = "FS::$table";
1045 my $svc_x = $class->new( {
1046 'pkgnum' => $cust_pkg->pkgnum,
1047 'svcpart' => $h_cust_svc->svcpart,
1048 map { $_ => $h_svc_x->get($_) } fields($table)
1052 if ( $h_svc_x->isa('FS::h_svc_Radius_Mixin') ) {
1053 $svc_x->usergroup( [ $h_svc_x->h_usergroup($end, $start) ] );
1056 my $svc_error = $svc_x->insert;
1058 if ( $options{svc_fatal} ) {
1059 $dbh->rollback if $oldAutoCommit;
1062 # if we've failed to insert the svc_x object, svc_Common->insert
1063 # will have removed the cust_svc already. if not, then both records
1064 # were inserted but we failed for some other reason (export, most
1065 # likely). in that case, report the error and delete the records.
1066 push @svc_errors, $svc_error;
1067 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svc_x->svcnum });
1069 # except if export_insert failed, export_delete probably won't be
1071 local $FS::svc_Common::noexport_hack = 1;
1072 my $cleanup_error = $svc_x->delete; # also deletes cust_svc
1073 if ( $cleanup_error ) { # and if THAT fails, then run away
1074 $dbh->rollback if $oldAutoCommit;
1075 return $cleanup_error;
1080 } #foreach $h_cust_svc
1082 #these are pretty rare, but should handle them
1083 # - dsl_device (mac addresses)
1084 # - phone_device (mac addresses)
1085 # - dsl_note (ikano notes)
1086 # - domain_record (i.e. restore DNS information w/domains)
1087 # - inventory_item(?) (inventory w/un-cancelling service?)
1088 # - nas (svc_broaband nas stuff)
1089 #this stuff is unused in the wild afaik
1090 # - mailinglistmember
1092 # - svc_domain.parent_svcnum?
1093 # - acct_snarf (ancient mail fetching config)
1094 # - cgp_rule (communigate)
1095 # - cust_svc_option (used by our Tron stuff)
1096 # - acct_rt_transaction (used by our time worked stuff)
1099 # also move over any services that didn't unprovision at cancellation
1102 foreach my $cust_svc ( qsearch('cust_svc', { pkgnum => $self->pkgnum } ) ) {
1103 $cust_svc->pkgnum( $cust_pkg->pkgnum );
1104 my $error = $cust_svc->replace;
1106 $dbh->rollback if $oldAutoCommit;
1112 # Uncancel any supplemental packages, and make them supplemental to the
1116 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1118 $error = $supp_pkg->uncancel(%options, 'main_pkgnum' => $cust_pkg->pkgnum);
1120 $dbh->rollback if $oldAutoCommit;
1121 return "canceling supplemental pkg#".$supp_pkg->pkgnum.": $error";
1129 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1131 ${ $options{cust_pkg} } = $cust_pkg if ref($options{cust_pkg});
1132 @{ $options{svc_errors} } = @svc_errors if ref($options{svc_errors});
1139 Cancels any pending expiration (sets the expire field to null).
1141 If there is an error, returns the error, otherwise returns false.
1146 my( $self, %options ) = @_;
1149 local $SIG{HUP} = 'IGNORE';
1150 local $SIG{INT} = 'IGNORE';
1151 local $SIG{QUIT} = 'IGNORE';
1152 local $SIG{TERM} = 'IGNORE';
1153 local $SIG{TSTP} = 'IGNORE';
1154 local $SIG{PIPE} = 'IGNORE';
1156 my $oldAutoCommit = $FS::UID::AutoCommit;
1157 local $FS::UID::AutoCommit = 0;
1160 my $old = $self->select_for_update;
1162 my $pkgnum = $old->pkgnum;
1163 if ( $old->get('cancel') || $self->get('cancel') ) {
1164 dbh->rollback if $oldAutoCommit;
1165 return "Can't unexpire cancelled package $pkgnum";
1166 # or at least it's pointless
1169 unless ( $old->get('expire') && $self->get('expire') ) {
1170 dbh->rollback if $oldAutoCommit;
1171 return ""; # no error
1174 my %hash = $self->hash;
1175 $hash{'expire'} = '';
1176 my $new = new FS::cust_pkg ( \%hash );
1177 $error = $new->replace( $self, options => { $self->options } );
1179 $dbh->rollback if $oldAutoCommit;
1183 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1189 =item suspend [ OPTION => VALUE ... ]
1191 Suspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
1192 package, then suspends the package itself (sets the susp field to now).
1194 Available options are:
1198 =item reason - can be set to a cancellation reason (see L<FS:reason>),
1199 either a reasonnum of an existing reason, or passing a hashref will create
1200 a new reason. The hashref should have the following keys:
1201 - typenum - Reason type (see L<FS::reason_type>
1202 - reason - Text of the new reason.
1204 =item date - can be set to a unix style timestamp to specify when to
1207 =item time - can be set to override the current time, for calculation
1208 of final invoices or unused-time credits
1210 =item resume_date - can be set to a time when the package should be
1211 unsuspended. This may be more convenient than calling C<unsuspend()>
1214 =item from_main - allows a supplemental package to be suspended, rather
1215 than redirecting the method call to its main package. For internal use.
1219 If there is an error, returns the error, otherwise returns false.
1224 my( $self, %options ) = @_;
1227 # pass all suspend/cancel actions to the main package
1228 if ( $self->main_pkgnum and !$options{'from_main'} ) {
1229 return $self->main_pkg->suspend(%options);
1232 local $SIG{HUP} = 'IGNORE';
1233 local $SIG{INT} = 'IGNORE';
1234 local $SIG{QUIT} = 'IGNORE';
1235 local $SIG{TERM} = 'IGNORE';
1236 local $SIG{TSTP} = 'IGNORE';
1237 local $SIG{PIPE} = 'IGNORE';
1239 my $oldAutoCommit = $FS::UID::AutoCommit;
1240 local $FS::UID::AutoCommit = 0;
1243 my $old = $self->select_for_update;
1245 my $pkgnum = $old->pkgnum;
1246 if ( $old->get('cancel') || $self->get('cancel') ) {
1247 dbh->rollback if $oldAutoCommit;
1248 return "Can't suspend cancelled package $pkgnum";
1251 if ( $old->get('susp') || $self->get('susp') ) {
1252 dbh->rollback if $oldAutoCommit;
1253 return ""; # no error # complain on adjourn?
1256 my $suspend_time = $options{'time'} || time;
1257 my $date = $options{date} if $options{date}; # adjourn/suspend later
1258 $date = '' if ($date && $date <= $suspend_time); # complain instead?
1260 if ( $date && $old->get('expire') && $old->get('expire') < $date ) {
1261 dbh->rollback if $oldAutoCommit;
1262 return "Package $pkgnum expires before it would be suspended.";
1265 # some false laziness with sub cancel
1266 if ( !$options{nobill} && !$date &&
1267 $self->part_pkg->option('bill_suspend_as_cancel',1) ) {
1268 # kind of a kludge--'bill_suspend_as_cancel' to avoid having to
1269 # make the entire cust_main->bill path recognize 'suspend' and
1270 # 'cancel' separately.
1271 warn "Billing $pkgnum on suspension (at $suspend_time)\n" if $DEBUG;
1272 my $copy = $self->new({$self->hash});
1274 $copy->cust_main->bill( 'pkg_list' => [ $copy ],
1276 'time' => $suspend_time );
1277 warn "Error billing during suspend, custnum ".
1278 #$self->cust_main->custnum. ": $error"
1283 if ( $options{'reason'} ) {
1284 $error = $self->insert_reason( 'reason' => $options{'reason'},
1285 'action' => $date ? 'adjourn' : 'suspend',
1286 'date' => $date ? $date : $suspend_time,
1287 'reason_otaker' => $options{'reason_otaker'},
1290 dbh->rollback if $oldAutoCommit;
1291 return "Error inserting cust_pkg_reason: $error";
1295 my %hash = $self->hash;
1297 $hash{'adjourn'} = $date;
1299 $hash{'susp'} = $suspend_time;
1302 my $resume_date = $options{'resume_date'} || 0;
1303 if ( $resume_date > ($date || $suspend_time) ) {
1304 $hash{'resume'} = $resume_date;
1307 $options{options} ||= {};
1309 my $new = new FS::cust_pkg ( \%hash );
1310 $error = $new->replace( $self, options => { $self->options,
1311 %{ $options{options} },
1315 $dbh->rollback if $oldAutoCommit;
1320 # credit remaining time if appropriate
1321 if ( $self->part_pkg->option('unused_credit_suspend', 1) ) {
1322 my $error = $self->credit_remaining('suspend', $suspend_time);
1324 $dbh->rollback if $oldAutoCommit;
1331 foreach my $cust_svc (
1332 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
1334 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
1336 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
1337 $dbh->rollback if $oldAutoCommit;
1338 return "Illegal svcdb value in part_svc!";
1341 require "FS/$svcdb.pm";
1343 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
1345 $error = $svc->suspend;
1347 $dbh->rollback if $oldAutoCommit;
1350 my( $label, $value ) = $cust_svc->label;
1351 push @labels, "$label: $value";
1355 my $conf = new FS::Conf;
1356 if ( $conf->config('suspend_email_admin') ) {
1358 my $error = send_email(
1359 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
1360 #invoice_from ??? well as good as any
1361 'to' => $conf->config('suspend_email_admin'),
1362 'subject' => 'FREESIDE NOTIFICATION: Customer package suspended',
1364 "This is an automatic message from your Freeside installation\n",
1365 "informing you that the following customer package has been suspended:\n",
1367 'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
1368 'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
1369 ( map { "Service : $_\n" } @labels ),
1374 warn "WARNING: can't send suspension admin email (suspending anyway): ".
1382 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1383 $error = $supp_pkg->suspend(%options, 'from_main' => 1);
1385 $dbh->rollback if $oldAutoCommit;
1386 return "suspending supplemental pkg#".$supp_pkg->pkgnum.": $error";
1390 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1395 =item credit_remaining MODE TIME
1397 Generate a credit for this package for the time remaining in the current
1398 billing period. MODE is either "suspend" or "cancel" (determines the
1399 credit type). TIME is the time of suspension/cancellation. Both arguments
1404 sub credit_remaining {
1405 # Add a credit for remaining service
1406 my ($self, $mode, $time) = @_;
1407 die 'credit_remaining requires suspend or cancel'
1408 unless $mode eq 'suspend' or $mode eq 'cancel';
1409 die 'no suspend/cancel time' unless $time > 0;
1411 my $conf = FS::Conf->new;
1412 my $reason_type = $conf->config($mode.'_credit_type');
1414 my $last_bill = $self->getfield('last_bill') || 0;
1415 my $next_bill = $self->getfield('bill') || 0;
1416 if ( $last_bill > 0 # the package has been billed
1417 and $next_bill > 0 # the package has a next bill date
1418 and $next_bill >= $time # which is in the future
1420 my $remaining_value = $self->calc_remain('time' => $time);
1421 if ( $remaining_value > 0 ) {
1422 warn "Crediting for $remaining_value on package ".$self->pkgnum."\n"
1424 my $error = $self->cust_main->credit(
1426 'Credit for unused time on '. $self->part_pkg->pkg,
1427 'reason_type' => $reason_type,
1429 return "Error crediting customer \$$remaining_value for unused time".
1430 " on ". $self->part_pkg->pkg. ": $error"
1432 } #if $remaining_value
1433 } #if $last_bill, etc.
1437 =item unsuspend [ OPTION => VALUE ... ]
1439 Unsuspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
1440 package, then unsuspends the package itself (clears the susp field and the
1441 adjourn field if it is in the past). If the suspend reason includes an
1442 unsuspension package, that package will be ordered.
1444 Available options are:
1450 Can be set to a date to unsuspend the package in the future (the 'resume'
1453 =item adjust_next_bill
1455 Can be set true to adjust the next bill date forward by
1456 the amount of time the account was inactive. This was set true by default
1457 in the past (from 1.4.2 and 1.5.0pre6 through 1.7.0), but now needs to be
1458 explicitly requested with this option or in the price plan.
1462 If there is an error, returns the error, otherwise returns false.
1467 my( $self, %opt ) = @_;
1470 # pass all suspend/cancel actions to the main package
1471 if ( $self->main_pkgnum and !$opt{'from_main'} ) {
1472 return $self->main_pkg->unsuspend(%opt);
1475 local $SIG{HUP} = 'IGNORE';
1476 local $SIG{INT} = 'IGNORE';
1477 local $SIG{QUIT} = 'IGNORE';
1478 local $SIG{TERM} = 'IGNORE';
1479 local $SIG{TSTP} = 'IGNORE';
1480 local $SIG{PIPE} = 'IGNORE';
1482 my $oldAutoCommit = $FS::UID::AutoCommit;
1483 local $FS::UID::AutoCommit = 0;
1486 my $old = $self->select_for_update;
1488 my $pkgnum = $old->pkgnum;
1489 if ( $old->get('cancel') || $self->get('cancel') ) {
1490 $dbh->rollback if $oldAutoCommit;
1491 return "Can't unsuspend cancelled package $pkgnum";
1494 unless ( $old->get('susp') && $self->get('susp') ) {
1495 $dbh->rollback if $oldAutoCommit;
1496 return ""; # no error # complain instead?
1499 my $date = $opt{'date'};
1500 if ( $date and $date > time ) { # return an error if $date <= time?
1502 if ( $old->get('expire') && $old->get('expire') < $date ) {
1503 $dbh->rollback if $oldAutoCommit;
1504 return "Package $pkgnum expires before it would be unsuspended.";
1507 my $new = new FS::cust_pkg { $self->hash };
1508 $new->set('resume', $date);
1509 $error = $new->replace($self, options => $self->options);
1512 $dbh->rollback if $oldAutoCommit;
1516 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1524 foreach my $cust_svc (
1525 qsearch('cust_svc',{'pkgnum'=> $self->pkgnum } )
1527 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
1529 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
1530 $dbh->rollback if $oldAutoCommit;
1531 return "Illegal svcdb value in part_svc!";
1534 require "FS/$svcdb.pm";
1536 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
1538 $error = $svc->unsuspend;
1540 $dbh->rollback if $oldAutoCommit;
1543 my( $label, $value ) = $cust_svc->label;
1544 push @labels, "$label: $value";
1549 my $cust_pkg_reason = $self->last_cust_pkg_reason('susp');
1550 my $reason = $cust_pkg_reason ? $cust_pkg_reason->reason : '';
1552 my %hash = $self->hash;
1553 my $inactive = time - $hash{'susp'};
1555 my $conf = new FS::Conf;
1557 if ( $inactive > 0 &&
1558 ( $hash{'bill'} || $hash{'setup'} ) &&
1559 ( $opt{'adjust_next_bill'} ||
1560 $conf->exists('unsuspend-always_adjust_next_bill_date') ||
1561 $self->part_pkg->option('unsuspend_adjust_bill', 1) )
1564 $hash{'bill'} = ( $hash{'bill'} || $hash{'setup'} ) + $inactive;
1569 $hash{'adjourn'} = '' if $hash{'adjourn'} and $hash{'adjourn'} < time;
1570 $hash{'resume'} = '' if !$hash{'adjourn'};
1571 my $new = new FS::cust_pkg ( \%hash );
1572 $error = $new->replace( $self, options => { $self->options } );
1574 $dbh->rollback if $oldAutoCommit;
1580 if ( $reason && $reason->unsuspend_pkgpart ) {
1581 my $part_pkg = FS::part_pkg->by_key($reason->unsuspend_pkgpart)
1582 or $error = "Unsuspend package definition ".$reason->unsuspend_pkgpart.
1584 my $start_date = $self->cust_main->next_bill_date
1585 if $reason->unsuspend_hold;
1588 $unsusp_pkg = FS::cust_pkg->new({
1589 'custnum' => $self->custnum,
1590 'pkgpart' => $reason->unsuspend_pkgpart,
1591 'start_date' => $start_date,
1592 'locationnum' => $self->locationnum,
1593 # discount? probably not...
1596 $error ||= $self->cust_main->order_pkg( 'cust_pkg' => $unsusp_pkg );
1600 $dbh->rollback if $oldAutoCommit;
1605 if ( $conf->config('unsuspend_email_admin') ) {
1607 my $error = send_email(
1608 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
1609 #invoice_from ??? well as good as any
1610 'to' => $conf->config('unsuspend_email_admin'),
1611 'subject' => 'FREESIDE NOTIFICATION: Customer package unsuspended', 'body' => [
1612 "This is an automatic message from your Freeside installation\n",
1613 "informing you that the following customer package has been unsuspended:\n",
1615 'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
1616 'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
1617 ( map { "Service : $_\n" } @labels ),
1619 "An unsuspension fee was charged: ".
1620 $unsusp_pkg->part_pkg->pkg_comment."\n"
1627 warn "WARNING: can't send unsuspension admin email (unsuspending anyway): ".
1633 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1634 $error = $supp_pkg->unsuspend(%opt, 'from_main' => 1);
1636 $dbh->rollback if $oldAutoCommit;
1637 return "unsuspending supplemental pkg#".$supp_pkg->pkgnum.": $error";
1641 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1648 Cancels any pending suspension (sets the adjourn field to null).
1650 If there is an error, returns the error, otherwise returns false.
1655 my( $self, %options ) = @_;
1658 local $SIG{HUP} = 'IGNORE';
1659 local $SIG{INT} = 'IGNORE';
1660 local $SIG{QUIT} = 'IGNORE';
1661 local $SIG{TERM} = 'IGNORE';
1662 local $SIG{TSTP} = 'IGNORE';
1663 local $SIG{PIPE} = 'IGNORE';
1665 my $oldAutoCommit = $FS::UID::AutoCommit;
1666 local $FS::UID::AutoCommit = 0;
1669 my $old = $self->select_for_update;
1671 my $pkgnum = $old->pkgnum;
1672 if ( $old->get('cancel') || $self->get('cancel') ) {
1673 dbh->rollback if $oldAutoCommit;
1674 return "Can't unadjourn cancelled package $pkgnum";
1675 # or at least it's pointless
1678 if ( $old->get('susp') || $self->get('susp') ) {
1679 dbh->rollback if $oldAutoCommit;
1680 return "Can't unadjourn suspended package $pkgnum";
1681 # perhaps this is arbitrary
1684 unless ( $old->get('adjourn') && $self->get('adjourn') ) {
1685 dbh->rollback if $oldAutoCommit;
1686 return ""; # no error
1689 my %hash = $self->hash;
1690 $hash{'adjourn'} = '';
1691 $hash{'resume'} = '';
1692 my $new = new FS::cust_pkg ( \%hash );
1693 $error = $new->replace( $self, options => { $self->options } );
1695 $dbh->rollback if $oldAutoCommit;
1699 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1706 =item change HASHREF | OPTION => VALUE ...
1708 Changes this package: cancels it and creates a new one, with a different
1709 pkgpart or locationnum or both. All services are transferred to the new
1710 package (no change will be made if this is not possible).
1712 Options may be passed as a list of key/value pairs or as a hash reference.
1719 New locationnum, to change the location for this package.
1723 New FS::cust_location object, to create a new location and assign it
1728 New FS::cust_main object, to create a new customer and assign the new package
1733 New pkgpart (see L<FS::part_pkg>).
1737 New refnum (see L<FS::part_referral>).
1741 New quantity; if unspecified, the new package will have the same quantity
1746 "New" (existing) FS::cust_pkg object. The package's services and other
1747 attributes will be transferred to this package.
1751 Set to true to transfer billing dates (start_date, setup, last_bill, bill,
1752 susp, adjourn, cancel, expire, and contract_end) to the new package.
1754 =item unprotect_svcs
1756 Normally, change() will rollback and return an error if some services
1757 can't be transferred (also see the I<cust_pkg-change_svcpart> config option).
1758 If unprotect_svcs is true, this method will transfer as many services as
1759 it can and then unconditionally cancel the old package.
1763 At least one of locationnum, cust_location, pkgpart, refnum, cust_main, or
1764 cust_pkg must be specified (otherwise, what's the point?)
1766 Returns either the new FS::cust_pkg object or a scalar error.
1770 my $err_or_new_cust_pkg = $old_cust_pkg->change
1774 #some false laziness w/order
1777 my $opt = ref($_[0]) ? shift : { @_ };
1779 my $conf = new FS::Conf;
1781 # Transactionize this whole mess
1782 local $SIG{HUP} = 'IGNORE';
1783 local $SIG{INT} = 'IGNORE';
1784 local $SIG{QUIT} = 'IGNORE';
1785 local $SIG{TERM} = 'IGNORE';
1786 local $SIG{TSTP} = 'IGNORE';
1787 local $SIG{PIPE} = 'IGNORE';
1789 my $oldAutoCommit = $FS::UID::AutoCommit;
1790 local $FS::UID::AutoCommit = 0;
1799 $hash{'setup'} = $time if $self->setup;
1801 $hash{'change_date'} = $time;
1802 $hash{"change_$_"} = $self->$_()
1803 foreach qw( pkgnum pkgpart locationnum );
1805 if ( $opt->{'cust_location'} ) {
1806 $error = $opt->{'cust_location'}->find_or_insert;
1808 $dbh->rollback if $oldAutoCommit;
1809 return "inserting cust_location (transaction rolled back): $error";
1811 $opt->{'locationnum'} = $opt->{'cust_location'}->locationnum;
1814 if ( $opt->{'cust_pkg'} ) {
1815 # treat changing to a package with a different pkgpart as a
1816 # pkgpart change (because it is)
1817 $opt->{'pkgpart'} = $opt->{'cust_pkg'}->pkgpart;
1820 # whether to override pkgpart checking on the new package
1821 my $same_pkgpart = 1;
1822 if ( $opt->{'pkgpart'} and ( $opt->{'pkgpart'} != $self->pkgpart ) ) {
1826 my $unused_credit = 0;
1827 my $keep_dates = $opt->{'keep_dates'};
1828 # Special case. If the pkgpart is changing, and the customer is
1829 # going to be credited for remaining time, don't keep setup, bill,
1830 # or last_bill dates, and DO pass the flag to cancel() to credit
1832 if ( $opt->{'pkgpart'}
1833 and $opt->{'pkgpart'} != $self->pkgpart
1834 and $self->part_pkg->option('unused_credit_change', 1) ) {
1837 $hash{$_} = '' foreach qw(setup bill last_bill);
1840 if ( $keep_dates ) {
1841 foreach my $date ( qw(setup bill last_bill susp adjourn cancel expire
1842 resume start_date contract_end ) ) {
1843 $hash{$date} = $self->getfield($date);
1847 # allow $opt->{'locationnum'} = '' to specifically set it to null
1848 # (i.e. customer default location)
1849 $opt->{'locationnum'} = $self->locationnum if !exists($opt->{'locationnum'});
1851 # usually this doesn't matter. the two cases where it does are:
1852 # 1. unused_credit_change + pkgpart change + setup fee on the new package
1854 # 2. (more importantly) changing a package before it's billed
1855 $hash{'waive_setup'} = $self->waive_setup;
1857 my $custnum = $self->custnum;
1858 if ( $opt->{cust_main} ) {
1859 my $cust_main = $opt->{cust_main};
1860 unless ( $cust_main->custnum ) {
1861 my $error = $cust_main->insert;
1863 $dbh->rollback if $oldAutoCommit;
1864 return "inserting cust_main (transaction rolled back): $error";
1867 $custnum = $cust_main->custnum;
1870 $hash{'contactnum'} = $opt->{'contactnum'} if $opt->{'contactnum'};
1873 if ( $opt->{'cust_pkg'} ) {
1874 # The target package already exists; update it to show that it was
1875 # changed from this package.
1876 $cust_pkg = $opt->{'cust_pkg'};
1878 foreach ( qw( pkgnum pkgpart locationnum ) ) {
1879 $cust_pkg->set("change_$_", $self->get($_));
1881 $cust_pkg->set('change_date', $time);
1882 $error = $cust_pkg->replace;
1885 # Create the new package.
1886 $cust_pkg = new FS::cust_pkg {
1887 custnum => $custnum,
1888 locationnum => $opt->{'locationnum'},
1889 ( map { $_ => ( $opt->{$_} || $self->$_() ) }
1890 qw( pkgpart quantity refnum salesnum )
1894 $error = $cust_pkg->insert( 'change' => 1,
1895 'allow_pkgpart' => $same_pkgpart );
1898 $dbh->rollback if $oldAutoCommit;
1902 # Transfer services and cancel old package.
1904 $error = $self->transfer($cust_pkg);
1905 if ($error and $error == 0) {
1906 # $old_pkg->transfer failed.
1907 $dbh->rollback if $oldAutoCommit;
1911 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
1912 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
1913 $error = $self->transfer($cust_pkg, 'change_svcpart'=>1 );
1914 if ($error and $error == 0) {
1915 # $old_pkg->transfer failed.
1916 $dbh->rollback if $oldAutoCommit;
1921 # We set unprotect_svcs when executing a "future package change". It's
1922 # not a user-interactive operation, so returning an error means the
1923 # package change will just fail. Rather than have that happen, we'll
1924 # let leftover services be deleted.
1925 if ($error > 0 and !$opt->{'unprotect_svcs'}) {
1926 # Transfers were successful, but we still had services left on the old
1927 # package. We can't change the package under this circumstances, so abort.
1928 $dbh->rollback if $oldAutoCommit;
1929 return "Unable to transfer all services from package ". $self->pkgnum;
1932 #reset usage if changing pkgpart
1933 # AND usage rollover is off (otherwise adds twice, now and at package bill)
1934 if ($self->pkgpart != $cust_pkg->pkgpart) {
1935 my $part_pkg = $cust_pkg->part_pkg;
1936 $error = $part_pkg->reset_usage($cust_pkg, $part_pkg->is_prepaid
1940 if $part_pkg->can('reset_usage') && ! $part_pkg->option('usage_rollover',1);
1943 $dbh->rollback if $oldAutoCommit;
1944 return "Error setting usage values: $error";
1947 # if NOT changing pkgpart, transfer any usage pools over
1948 foreach my $usage ($self->cust_pkg_usage) {
1949 $usage->set('pkgnum', $cust_pkg->pkgnum);
1950 $error = $usage->replace;
1952 $dbh->rollback if $oldAutoCommit;
1953 return "Error transferring usage pools: $error";
1958 # transfer discounts, if we're not changing pkgpart
1959 if ( $same_pkgpart ) {
1960 foreach my $old_discount ($self->cust_pkg_discount_active) {
1961 # don't remove the old discount, we may still need to bill that package.
1962 my $new_discount = new FS::cust_pkg_discount {
1963 'pkgnum' => $cust_pkg->pkgnum,
1964 'discountnum' => $old_discount->discountnum,
1965 'months_used' => $old_discount->months_used,
1967 $error = $new_discount->insert;
1969 $dbh->rollback if $oldAutoCommit;
1970 return "Error transferring discounts: $error";
1975 # transfer (copy) invoice details
1976 foreach my $detail ($self->cust_pkg_detail) {
1977 my $new_detail = FS::cust_pkg_detail->new({ $detail->hash });
1978 $new_detail->set('pkgdetailnum', '');
1979 $new_detail->set('pkgnum', $cust_pkg->pkgnum);
1980 $error = $new_detail->insert;
1982 $dbh->rollback if $oldAutoCommit;
1983 return "Error transferring package notes: $error";
1989 if ( !$opt->{'cust_pkg'} ) {
1990 # Order any supplemental packages.
1991 my $part_pkg = $cust_pkg->part_pkg;
1992 my @old_supp_pkgs = $self->supplemental_pkgs;
1993 foreach my $link ($part_pkg->supp_part_pkg_link) {
1995 foreach (@old_supp_pkgs) {
1996 if ($_->pkgpart == $link->dst_pkgpart) {
1998 $_->pkgpart(0); # so that it can't match more than once
2002 # false laziness with FS::cust_main::Packages::order_pkg
2003 my $new = FS::cust_pkg->new({
2004 pkgpart => $link->dst_pkgpart,
2005 pkglinknum => $link->pkglinknum,
2006 custnum => $custnum,
2007 main_pkgnum => $cust_pkg->pkgnum,
2008 locationnum => $cust_pkg->locationnum,
2009 start_date => $cust_pkg->start_date,
2010 order_date => $cust_pkg->order_date,
2011 expire => $cust_pkg->expire,
2012 adjourn => $cust_pkg->adjourn,
2013 contract_end => $cust_pkg->contract_end,
2014 refnum => $cust_pkg->refnum,
2015 discountnum => $cust_pkg->discountnum,
2016 waive_setup => $cust_pkg->waive_setup,
2018 if ( $old and $opt->{'keep_dates'} ) {
2019 foreach (qw(setup bill last_bill)) {
2020 $new->set($_, $old->get($_));
2023 $error = $new->insert( allow_pkgpart => $same_pkgpart );
2026 $error ||= $old->transfer($new);
2028 if ( $error and $error > 0 ) {
2029 # no reason why this should ever fail, but still...
2030 $error = "Unable to transfer all services from supplemental package ".
2034 $dbh->rollback if $oldAutoCommit;
2037 push @new_supp_pkgs, $new;
2039 } # if !$opt->{'cust_pkg'}
2040 # because if there is one, then supplemental packages would already
2041 # have been created for it.
2043 #Good to go, cancel old package. Notify 'cancel' of whether to credit
2045 #Don't allow billing the package (preceding period packages and/or
2046 #outstanding usage) if we are keeping dates (i.e. location changing),
2047 #because the new package will be billed for the same date range.
2048 #Supplemental packages are also canceled here.
2050 # during scheduled changes, avoid canceling the package we just
2052 $self->set('change_to_pkgnum' => '');
2054 $error = $self->cancel(
2056 unused_credit => $unused_credit,
2057 nobill => $keep_dates,
2058 change_custnum => ( $self->custnum != $custnum ? $custnum : '' ),
2061 $dbh->rollback if $oldAutoCommit;
2065 if ( $conf->exists('cust_pkg-change_pkgpart-bill_now') ) {
2067 my $error = $cust_pkg->cust_main->bill(
2068 'pkg_list' => [ $cust_pkg, @new_supp_pkgs ]
2071 $dbh->rollback if $oldAutoCommit;
2076 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2082 =item change_later OPTION => VALUE...
2084 Schedule a package change for a later date. This actually orders the new
2085 package immediately, but sets its start date for a future date, and sets
2086 the current package to expire on the same date.
2088 If the package is already scheduled for a change, this can be called with
2089 'start_date' to change the scheduled date, or with pkgpart and/or
2090 locationnum to modify the package change. To cancel the scheduled change
2091 entirely, see C<abort_change>.
2099 The date for the package change. Required, and must be in the future.
2107 The pkgpart. locationnum, and quantity of the new package, with the same
2108 meaning as in C<change>.
2116 my $opt = ref($_[0]) ? shift : { @_ };
2118 my $oldAutoCommit = $FS::UID::AutoCommit;
2119 local $FS::UID::AutoCommit = 0;
2122 my $cust_main = $self->cust_main;
2124 my $date = delete $opt->{'start_date'} or return 'start_date required';
2126 if ( $date <= time ) {
2127 $dbh->rollback if $oldAutoCommit;
2128 return "start_date $date is in the past";
2133 if ( $self->change_to_pkgnum ) {
2134 my $change_to = FS::cust_pkg->by_key($self->change_to_pkgnum);
2135 my $new_pkgpart = $opt->{'pkgpart'}
2136 if $opt->{'pkgpart'} and $opt->{'pkgpart'} != $change_to->pkgpart;
2137 my $new_locationnum = $opt->{'locationnum'}
2138 if $opt->{'locationnum'} and $opt->{'locationnum'} != $change_to->locationnum;
2139 my $new_quantity = $opt->{'quantity'}
2140 if $opt->{'quantity'} and $opt->{'quantity'} != $change_to->quantity;
2141 if ( $new_pkgpart or $new_locationnum or $new_quantity ) {
2142 # it hasn't been billed yet, so in principle we could just edit
2143 # it in place (w/o a package change), but that's bad form.
2144 # So change the package according to the new options...
2145 my $err_or_pkg = $change_to->change(%$opt);
2146 if ( ref $err_or_pkg ) {
2147 # Then set that package up for a future start.
2148 $self->set('change_to_pkgnum', $err_or_pkg->pkgnum);
2149 $self->set('expire', $date); # in case it's different
2150 $err_or_pkg->set('start_date', $date);
2151 $err_or_pkg->set('change_date', '');
2152 $err_or_pkg->set('change_pkgnum', '');
2154 $error = $self->replace ||
2155 $err_or_pkg->replace ||
2156 $change_to->cancel ||
2159 $error = $err_or_pkg;
2161 } else { # change the start date only.
2162 $self->set('expire', $date);
2163 $change_to->set('start_date', $date);
2164 $error = $self->replace || $change_to->replace;
2167 $dbh->rollback if $oldAutoCommit;
2170 $dbh->commit if $oldAutoCommit;
2173 } # if $self->change_to_pkgnum
2175 my $new_pkgpart = $opt->{'pkgpart'}
2176 if $opt->{'pkgpart'} and $opt->{'pkgpart'} != $self->pkgpart;
2177 my $new_locationnum = $opt->{'locationnum'}
2178 if $opt->{'locationnum'} and $opt->{'locationnum'} != $self->locationnum;
2179 my $new_quantity = $opt->{'quantity'}
2180 if $opt->{'quantity'} and $opt->{'quantity'} != $self->quantity;
2182 return '' unless $new_pkgpart or $new_locationnum or $new_quantity; # wouldn't do anything
2184 # allow $opt->{'locationnum'} = '' to specifically set it to null
2185 # (i.e. customer default location)
2186 $opt->{'locationnum'} = $self->locationnum if !exists($opt->{'locationnum'});
2188 my $new = FS::cust_pkg->new( {
2189 custnum => $self->custnum,
2190 locationnum => $opt->{'locationnum'},
2191 start_date => $date,
2192 map { $_ => ( $opt->{$_} || $self->$_() ) }
2193 qw( pkgpart quantity refnum salesnum )
2195 $error = $new->insert('change' => 1,
2196 'allow_pkgpart' => ($new_pkgpart ? 0 : 1));
2198 $self->set('change_to_pkgnum', $new->pkgnum);
2199 $self->set('expire', $date);
2200 $error = $self->replace;
2203 $dbh->rollback if $oldAutoCommit;
2205 $dbh->commit if $oldAutoCommit;
2213 Cancels a future package change scheduled by C<change_later>.
2219 my $pkgnum = $self->change_to_pkgnum;
2220 my $change_to = FS::cust_pkg->by_key($pkgnum) if $pkgnum;
2223 $error = $change_to->cancel || $change_to->delete;
2224 return $error if $error;
2226 $self->set('change_to_pkgnum', '');
2227 $self->set('expire', '');
2231 =item set_quantity QUANTITY
2233 Change the package's quantity field. This is one of the few package properties
2234 that can safely be changed without canceling and reordering the package
2235 (because it doesn't affect tax eligibility). Returns an error or an
2242 $self = $self->replace_old; # just to make sure
2243 $self->quantity(shift);
2247 =item set_salesnum SALESNUM
2249 Change the package's salesnum (sales person) field. This is one of the few
2250 package properties that can safely be changed without canceling and reordering
2251 the package (because it doesn't affect tax eligibility). Returns an error or
2258 $self = $self->replace_old; # just to make sure
2259 $self->salesnum(shift);
2261 # XXX this should probably reassign any credit that's already been given
2264 =item modify_charge OPTIONS
2266 Change the properties of a one-time charge. Currently the only properties
2267 that can be changed this way are those that have no impact on billing
2269 - pkg: the package description
2270 - classnum: the package class
2271 - additional: arrayref of additional invoice details to add to this package
2273 If you pass 'adjust_commission' => 1, and the classnum changes, and there are
2274 commission credits linked to this charge, they will be recalculated.
2281 my $part_pkg = $self->part_pkg;
2282 my $pkgnum = $self->pkgnum;
2285 my $oldAutoCommit = $FS::UID::AutoCommit;
2286 local $FS::UID::AutoCommit = 0;
2288 return "Can't use modify_charge except on one-time charges"
2289 unless $part_pkg->freq eq '0';
2291 if ( length($opt{'pkg'}) and $part_pkg->pkg ne $opt{'pkg'} ) {
2292 $part_pkg->set('pkg', $opt{'pkg'});
2295 my %pkg_opt = $part_pkg->options;
2296 if ( ref($opt{'additional'}) ) {
2297 delete $pkg_opt{$_} foreach grep /^additional/, keys %pkg_opt;
2299 for ( $i = 0; exists($opt{'additional'}->[$i]); $i++ ) {
2300 $pkg_opt{ "additional_info$i" } = $opt{'additional'}->[$i];
2302 $pkg_opt{'additional_count'} = $i if $i > 0;
2306 if ( exists($opt{'classnum'}) and $part_pkg->classnum ne $opt{'classnum'} ) {
2308 $old_classnum = $part_pkg->classnum;
2309 $part_pkg->set('classnum', $opt{'classnum'});
2312 my $error = $part_pkg->replace( options => \%pkg_opt );
2313 return $error if $error;
2315 if (defined $old_classnum) {
2316 # fix invoice grouping records
2317 my $old_catname = $old_classnum
2318 ? FS::pkg_class->by_key($old_classnum)->categoryname
2320 my $new_catname = $opt{'classnum'}
2321 ? $part_pkg->pkg_class->categoryname
2323 if ( $old_catname ne $new_catname ) {
2324 foreach my $cust_bill_pkg ($self->cust_bill_pkg) {
2325 # (there should only be one...)
2326 my @display = qsearch( 'cust_bill_pkg_display', {
2327 'billpkgnum' => $cust_bill_pkg->billpkgnum,
2328 'section' => $old_catname,
2330 foreach (@display) {
2331 $_->set('section', $new_catname);
2332 $error = $_->replace;
2334 $dbh->rollback if $oldAutoCommit;
2338 } # foreach $cust_bill_pkg
2341 if ( $opt{'adjust_commission'} ) {
2342 # fix commission credits...tricky.
2343 foreach my $cust_event ($self->cust_event) {
2344 my $part_event = $cust_event->part_event;
2345 foreach my $table (qw(sales agent)) {
2347 "FS::part_event::Action::Mixin::credit_${table}_pkg_class";
2348 my $credit = qsearchs('cust_credit', {
2349 'eventnum' => $cust_event->eventnum,
2351 if ( $part_event->isa($class) ) {
2352 # Yes, this results in current commission rates being applied
2353 # retroactively to a one-time charge. For accounting purposes
2354 # there ought to be some kind of time limit on doing this.
2355 my $amount = $part_event->_calc_credit($self);
2356 if ( $credit and $credit->amount ne $amount ) {
2357 # Void the old credit.
2358 $error = $credit->void('Package class changed');
2360 $dbh->rollback if $oldAutoCommit;
2361 return "$error (adjusting commission credit)";
2364 # redo the event action to recreate the credit.
2366 eval { $part_event->do_action( $self, $cust_event ) };
2368 $dbh->rollback if $oldAutoCommit;
2371 } # if $part_event->isa($class)
2373 } # foreach $cust_event
2374 } # if $opt{'adjust_commission'}
2375 } # if defined $old_classnum
2377 $dbh->commit if $oldAutoCommit;
2383 use Storable 'thaw';
2386 sub process_bulk_cust_pkg {
2388 my $param = thaw(decode_base64(shift));
2389 warn Dumper($param) if $DEBUG;
2391 my $old_part_pkg = qsearchs('part_pkg',
2392 { pkgpart => $param->{'old_pkgpart'} });
2393 my $new_part_pkg = qsearchs('part_pkg',
2394 { pkgpart => $param->{'new_pkgpart'} });
2395 die "Must select a new package type\n" unless $new_part_pkg;
2396 #my $keep_dates = $param->{'keep_dates'} || 0;
2397 my $keep_dates = 1; # there is no good reason to turn this off
2399 local $SIG{HUP} = 'IGNORE';
2400 local $SIG{INT} = 'IGNORE';
2401 local $SIG{QUIT} = 'IGNORE';
2402 local $SIG{TERM} = 'IGNORE';
2403 local $SIG{TSTP} = 'IGNORE';
2404 local $SIG{PIPE} = 'IGNORE';
2406 my $oldAutoCommit = $FS::UID::AutoCommit;
2407 local $FS::UID::AutoCommit = 0;
2410 my @cust_pkgs = qsearch('cust_pkg', { 'pkgpart' => $param->{'old_pkgpart'} } );
2413 foreach my $old_cust_pkg ( @cust_pkgs ) {
2415 $job->update_statustext(int(100*$i/(scalar @cust_pkgs)));
2416 if ( $old_cust_pkg->getfield('cancel') ) {
2417 warn '[process_bulk_cust_pkg ] skipping canceled pkgnum '.
2418 $old_cust_pkg->pkgnum."\n"
2422 warn '[process_bulk_cust_pkg] changing pkgnum '.$old_cust_pkg->pkgnum."\n"
2424 my $error = $old_cust_pkg->change(
2425 'pkgpart' => $param->{'new_pkgpart'},
2426 'keep_dates' => $keep_dates
2428 if ( !ref($error) ) { # change returns the cust_pkg on success
2430 die "Error changing pkgnum ".$old_cust_pkg->pkgnum.": '$error'\n";
2433 $dbh->commit if $oldAutoCommit;
2439 Returns the last bill date, or if there is no last bill date, the setup date.
2440 Useful for billing metered services.
2446 return $self->setfield('last_bill', $_[0]) if @_;
2447 return $self->getfield('last_bill') if $self->getfield('last_bill');
2448 my $cust_bill_pkg = qsearchs('cust_bill_pkg', { 'pkgnum' => $self->pkgnum,
2449 'edate' => $self->bill, } );
2450 $cust_bill_pkg ? $cust_bill_pkg->sdate : $self->setup || 0;
2453 =item last_cust_pkg_reason ACTION
2455 Returns the most recent ACTION FS::cust_pkg_reason associated with the package.
2456 Returns false if there is no reason or the package is not currenly ACTION'd
2457 ACTION is one of adjourn, susp, cancel, or expire.
2461 sub last_cust_pkg_reason {
2462 my ( $self, $action ) = ( shift, shift );
2463 my $date = $self->get($action);
2465 'table' => 'cust_pkg_reason',
2466 'hashref' => { 'pkgnum' => $self->pkgnum,
2467 'action' => substr(uc($action), 0, 1),
2470 'order_by' => 'ORDER BY num DESC LIMIT 1',
2474 =item last_reason ACTION
2476 Returns the most recent ACTION FS::reason associated with the package.
2477 Returns false if there is no reason or the package is not currenly ACTION'd
2478 ACTION is one of adjourn, susp, cancel, or expire.
2483 my $cust_pkg_reason = shift->last_cust_pkg_reason(@_);
2484 $cust_pkg_reason->reason
2485 if $cust_pkg_reason;
2490 Returns the definition for this billing item, as an FS::part_pkg object (see
2497 return $self->{'_pkgpart'} if $self->{'_pkgpart'};
2498 cluck "cust_pkg->part_pkg called" if $DEBUG > 1;
2499 qsearchs( 'part_pkg', { 'pkgpart' => $self->pkgpart } );
2504 Returns the cancelled package this package was changed from, if any.
2510 return '' unless $self->change_pkgnum;
2511 qsearchs('cust_pkg', { 'pkgnum' => $self->change_pkgnum } );
2514 =item change_cust_main
2516 Returns the customter this package was detached to, if any.
2520 sub change_cust_main {
2522 return '' unless $self->change_custnum;
2523 qsearchs('cust_main', { 'custnum' => $self->change_custnum } );
2528 Calls the I<calc_setup> of the FS::part_pkg object associated with this billing
2535 $self->part_pkg->calc_setup($self, @_);
2540 Calls the I<calc_recur> of the FS::part_pkg object associated with this billing
2547 $self->part_pkg->calc_recur($self, @_);
2552 Calls the I<base_setup> of the FS::part_pkg object associated with this billing
2559 $self->part_pkg->base_setup($self, @_);
2564 Calls the I<base_recur> of the FS::part_pkg object associated with this billing
2571 $self->part_pkg->base_recur($self, @_);
2576 Calls the I<calc_remain> of the FS::part_pkg object associated with this
2583 $self->part_pkg->calc_remain($self, @_);
2588 Calls the I<calc_cancel> of the FS::part_pkg object associated with this
2595 $self->part_pkg->calc_cancel($self, @_);
2600 Returns any invoice line items for this package (see L<FS::cust_bill_pkg>).
2606 qsearch( 'cust_bill_pkg', { 'pkgnum' => $self->pkgnum } );
2609 =item cust_pkg_detail [ DETAILTYPE ]
2611 Returns any customer package details for this package (see
2612 L<FS::cust_pkg_detail>).
2614 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
2618 sub cust_pkg_detail {
2620 my %hash = ( 'pkgnum' => $self->pkgnum );
2621 $hash{detailtype} = shift if @_;
2623 'table' => 'cust_pkg_detail',
2624 'hashref' => \%hash,
2625 'order_by' => 'ORDER BY weight, pkgdetailnum',
2629 =item set_cust_pkg_detail DETAILTYPE [ DETAIL, DETAIL, ... ]
2631 Sets customer package details for this package (see L<FS::cust_pkg_detail>).
2633 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
2635 If there is an error, returns the error, otherwise returns false.
2639 sub set_cust_pkg_detail {
2640 my( $self, $detailtype, @details ) = @_;
2642 local $SIG{HUP} = 'IGNORE';
2643 local $SIG{INT} = 'IGNORE';
2644 local $SIG{QUIT} = 'IGNORE';
2645 local $SIG{TERM} = 'IGNORE';
2646 local $SIG{TSTP} = 'IGNORE';
2647 local $SIG{PIPE} = 'IGNORE';
2649 my $oldAutoCommit = $FS::UID::AutoCommit;
2650 local $FS::UID::AutoCommit = 0;
2653 foreach my $current ( $self->cust_pkg_detail($detailtype) ) {
2654 my $error = $current->delete;
2656 $dbh->rollback if $oldAutoCommit;
2657 return "error removing old detail: $error";
2661 foreach my $detail ( @details ) {
2662 my $cust_pkg_detail = new FS::cust_pkg_detail {
2663 'pkgnum' => $self->pkgnum,
2664 'detailtype' => $detailtype,
2665 'detail' => $detail,
2667 my $error = $cust_pkg_detail->insert;
2669 $dbh->rollback if $oldAutoCommit;
2670 return "error adding new detail: $error";
2675 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2682 Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.
2686 #false laziness w/cust_bill.pm
2690 'table' => 'cust_event',
2691 'addl_from' => 'JOIN part_event USING ( eventpart )',
2692 'hashref' => { 'tablenum' => $self->pkgnum },
2693 'extra_sql' => " AND eventtable = 'cust_pkg' ",
2697 =item num_cust_event
2699 Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.
2703 #false laziness w/cust_bill.pm
2704 sub num_cust_event {
2707 "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
2708 " WHERE tablenum = ? AND eventtable = 'cust_pkg'";
2709 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
2710 $sth->execute($self->pkgnum) or die $sth->errstr. " executing $sql";
2711 $sth->fetchrow_arrayref->[0];
2714 =item part_pkg_currency_option OPTIONNAME
2716 Returns a two item list consisting of the currency of this customer, if any,
2717 and a value for the provided option. If the customer has a currency, the value
2718 is the option value the given name and the currency (see
2719 L<FS::part_pkg_currency>). Otherwise, if the customer has no currency, is the
2720 regular option value for the given name (see L<FS::part_pkg_option>).
2724 sub part_pkg_currency_option {
2725 my( $self, $optionname ) = @_;
2726 my $part_pkg = $self->part_pkg;
2727 if ( my $currency = $self->cust_main->currency ) {
2728 ($currency, $part_pkg->part_pkg_currency_option($currency, $optionname) );
2730 ('', $part_pkg->option($optionname) );
2734 =item cust_svc [ SVCPART ] (old, deprecated usage)
2736 =item cust_svc [ OPTION => VALUE ... ] (current usage)
2738 =item cust_svc_unsorted [ OPTION => VALUE ... ]
2740 Returns the services for this package, as FS::cust_svc objects (see
2741 L<FS::cust_svc>). Available options are svcpart and svcdb. If either is
2742 spcififed, returns only the matching services.
2744 As an optimization, use the cust_svc_unsorted version if you are not displaying
2751 cluck "cust_pkg->cust_svc called" if $DEBUG > 2;
2752 $self->_sort_cust_svc( $self->cust_svc_unsorted_arrayref );
2755 sub cust_svc_unsorted {
2757 @{ $self->cust_svc_unsorted_arrayref };
2760 sub cust_svc_unsorted_arrayref {
2763 return () unless $self->num_cust_svc(@_);
2766 if ( @_ && $_[0] =~ /^\d+/ ) {
2767 $opt{svcpart} = shift;
2768 } elsif ( @_ && ref($_[0]) eq 'HASH' ) {
2775 'table' => 'cust_svc',
2776 'hashref' => { 'pkgnum' => $self->pkgnum },
2778 if ( $opt{svcpart} ) {
2779 $search{hashref}->{svcpart} = $opt{'svcpart'};
2781 if ( $opt{'svcdb'} ) {
2782 $search{addl_from} = ' LEFT JOIN part_svc USING ( svcpart ) ';
2783 $search{extra_sql} = ' AND svcdb = '. dbh->quote( $opt{'svcdb'} );
2786 [ qsearch(\%search) ];
2790 =item overlimit [ SVCPART ]
2792 Returns the services for this package which have exceeded their
2793 usage limit as FS::cust_svc objects (see L<FS::cust_svc>). If a svcpart
2794 is specified, return only the matching services.
2800 return () unless $self->num_cust_svc(@_);
2801 grep { $_->overlimit } $self->cust_svc(@_);
2804 =item h_cust_svc END_TIMESTAMP [ START_TIMESTAMP ] [ MODE ]
2806 Returns historical services for this package created before END TIMESTAMP and
2807 (optionally) not cancelled before START_TIMESTAMP, as FS::h_cust_svc objects
2808 (see L<FS::h_cust_svc>). If MODE is 'I' (for 'invoice'), services with the
2809 I<pkg_svc.hidden> flag will be omitted.
2815 warn "$me _h_cust_svc called on $self\n"
2818 my ($end, $start, $mode) = @_;
2819 my @cust_svc = $self->_sort_cust_svc(
2820 [ qsearch( 'h_cust_svc',
2821 { 'pkgnum' => $self->pkgnum, },
2822 FS::h_cust_svc->sql_h_search(@_),
2825 if ( defined($mode) && $mode eq 'I' ) {
2826 my %hidden_svcpart = map { $_->svcpart => $_->hidden } $self->part_svc;
2827 return grep { !$hidden_svcpart{$_->svcpart} } @cust_svc;
2833 sub _sort_cust_svc {
2834 my( $self, $arrayref ) = @_;
2837 sub ($$) { my ($a, $b) = @_; $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] };
2839 my %pkg_svc = map { $_->svcpart => $_ }
2840 qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
2845 my $pkg_svc = $pkg_svc{ $_->svcpart } || '';
2847 $pkg_svc ? $pkg_svc->primary_svc : '',
2848 $pkg_svc ? $pkg_svc->quantity : 0,
2855 =item num_cust_svc [ SVCPART ] (old, deprecated usage)
2857 =item num_cust_svc [ OPTION => VALUE ... ] (current usage)
2859 Returns the number of services for this package. Available options are svcpart
2860 and svcdb. If either is spcififed, returns only the matching services.
2867 return $self->{'_num_cust_svc'}
2869 && exists($self->{'_num_cust_svc'})
2870 && $self->{'_num_cust_svc'} =~ /\d/;
2872 cluck "cust_pkg->num_cust_svc called, _num_cust_svc:".$self->{'_num_cust_svc'}
2876 if ( @_ && $_[0] =~ /^\d+/ ) {
2877 $opt{svcpart} = shift;
2878 } elsif ( @_ && ref($_[0]) eq 'HASH' ) {
2884 my $select = 'SELECT COUNT(*) FROM cust_svc ';
2885 my $where = ' WHERE pkgnum = ? ';
2886 my @param = ($self->pkgnum);
2888 if ( $opt{'svcpart'} ) {
2889 $where .= ' AND svcpart = ? ';
2890 push @param, $opt{'svcpart'};
2892 if ( $opt{'svcdb'} ) {
2893 $select .= ' LEFT JOIN part_svc USING ( svcpart ) ';
2894 $where .= ' AND svcdb = ? ';
2895 push @param, $opt{'svcdb'};
2898 my $sth = dbh->prepare("$select $where") or die dbh->errstr;
2899 $sth->execute(@param) or die $sth->errstr;
2900 $sth->fetchrow_arrayref->[0];
2903 =item available_part_svc
2905 Returns a list of FS::part_svc objects representing services included in this
2906 package but not yet provisioned. Each FS::part_svc object also has an extra
2907 field, I<num_avail>, which specifies the number of available services.
2911 sub available_part_svc {
2914 my $pkg_quantity = $self->quantity || 1;
2916 grep { $_->num_avail > 0 }
2918 my $part_svc = $_->part_svc;
2919 $part_svc->{'Hash'}{'num_avail'} = #evil encapsulation-breaking
2920 $pkg_quantity * $_->quantity - $self->num_cust_svc($_->svcpart);
2922 # more evil encapsulation breakage
2923 if($part_svc->{'Hash'}{'num_avail'} > 0) {
2924 my @exports = $part_svc->part_export_did;
2925 $part_svc->{'Hash'}{'can_get_dids'} = scalar(@exports);
2930 $self->part_pkg->pkg_svc;
2933 =item part_svc [ OPTION => VALUE ... ]
2935 Returns a list of FS::part_svc objects representing provisioned and available
2936 services included in this package. Each FS::part_svc object also has the
2937 following extra fields:
2941 =item num_cust_svc (count)
2943 =item num_avail (quantity - count)
2945 =item cust_pkg_svc (services) - array reference containing the provisioned services, as cust_svc objects
2949 Accepts one option: summarize_size. If specified and non-zero, will omit the
2950 extra cust_pkg_svc option for objects where num_cust_svc is this size or
2956 #label -> ($cust_svc->label)[1]
2962 my $pkg_quantity = $self->quantity || 1;
2964 #XXX some sort of sort order besides numeric by svcpart...
2965 my @part_svc = sort { $a->svcpart <=> $b->svcpart } map {
2967 my $part_svc = $pkg_svc->part_svc;
2968 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
2969 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #more evil
2970 $part_svc->{'Hash'}{'num_avail'} =
2971 max( 0, $pkg_quantity * $pkg_svc->quantity - $num_cust_svc );
2972 $part_svc->{'Hash'}{'cust_pkg_svc'} =
2973 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : []
2974 unless exists($opt{summarize_size}) && $opt{summarize_size} > 0
2975 && $num_cust_svc >= $opt{summarize_size};
2976 $part_svc->{'Hash'}{'hidden'} = $pkg_svc->hidden;
2978 } $self->part_pkg->pkg_svc;
2981 push @part_svc, map {
2983 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
2984 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #speak no evail
2985 $part_svc->{'Hash'}{'num_avail'} = 0; #0-$num_cust_svc ?
2986 $part_svc->{'Hash'}{'cust_pkg_svc'} =
2987 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : [];
2989 } $self->extra_part_svc;
2995 =item extra_part_svc
2997 Returns a list of FS::part_svc objects corresponding to services in this
2998 package which are still provisioned but not (any longer) available in the
3003 sub extra_part_svc {
3006 my $pkgnum = $self->pkgnum;
3007 #my $pkgpart = $self->pkgpart;
3010 # 'table' => 'part_svc',
3013 # "WHERE 0 = ( SELECT COUNT(*) FROM pkg_svc
3014 # WHERE pkg_svc.svcpart = part_svc.svcpart
3015 # AND pkg_svc.pkgpart = ?
3018 # AND 0 < ( SELECT COUNT(*) FROM cust_svc
3019 # LEFT JOIN cust_pkg USING ( pkgnum )
3020 # WHERE cust_svc.svcpart = part_svc.svcpart
3023 # 'extra_param' => [ [$self->pkgpart=>'int'], [$self->pkgnum=>'int'] ],
3026 #seems to benchmark slightly faster... (or did?)
3028 my @pkgparts = map $_->pkgpart, $self->part_pkg->self_and_svc_linked;
3029 my $pkgparts = join(',', @pkgparts);
3032 #'select' => 'DISTINCT ON (svcpart) part_svc.*',
3033 #MySQL doesn't grok DISINCT ON
3034 'select' => 'DISTINCT part_svc.*',
3035 'table' => 'part_svc',
3037 "LEFT JOIN pkg_svc ON ( pkg_svc.svcpart = part_svc.svcpart
3038 AND pkg_svc.pkgpart IN ($pkgparts)
3041 LEFT JOIN cust_svc ON ( cust_svc.svcpart = part_svc.svcpart )
3042 LEFT JOIN cust_pkg USING ( pkgnum )
3045 'extra_sql' => "WHERE pkgsvcnum IS NULL AND cust_pkg.pkgnum = ? ",
3046 'extra_param' => [ [$self->pkgnum=>'int'] ],
3052 Returns a short status string for this package, currently:
3056 =item not yet billed
3058 =item one-time charge
3073 my $freq = length($self->freq) ? $self->freq : $self->part_pkg->freq;
3075 return 'cancelled' if $self->get('cancel');
3076 return 'suspended' if $self->susp;
3077 return 'not yet billed' unless $self->setup;
3078 return 'one-time charge' if $freq =~ /^(0|$)/;
3082 =item ucfirst_status
3084 Returns the status with the first character capitalized.
3088 sub ucfirst_status {
3089 ucfirst(shift->status);
3094 Class method that returns the list of possible status strings for packages
3095 (see L<the status method|/status>). For example:
3097 @statuses = FS::cust_pkg->statuses();
3101 tie my %statuscolor, 'Tie::IxHash',
3102 'not yet billed' => '009999', #teal? cyan?
3103 'one-time charge' => '000000',
3104 'active' => '00CC00',
3105 'suspended' => 'FF9900',
3106 'cancelled' => 'FF0000',
3110 my $self = shift; #could be class...
3111 #grep { $_ !~ /^(not yet billed)$/ } #this is a dumb status anyway
3112 # # mayble split btw one-time vs. recur
3118 Returns a hex triplet color string for this package's status.
3124 $statuscolor{$self->status};
3129 Returns a label for this package. (Currently "pkgnum: pkg - comment" or
3130 "pkg - comment" depending on user preference).
3136 my $label = $self->part_pkg->pkg_comment( 'nopkgpart' => 1 );
3137 $label = $self->pkgnum. ": $label"
3138 if $FS::CurrentUser::CurrentUser->option('show_pkgnum');
3142 =item pkg_label_long
3144 Returns a long label for this package, adding the primary service's label to
3149 sub pkg_label_long {
3151 my $label = $self->pkg_label;
3152 my $cust_svc = $self->primary_cust_svc;
3153 $label .= ' ('. ($cust_svc->label)[1]. ')' if $cust_svc;
3159 Returns a customer-localized label for this package.
3165 $self->part_pkg->pkg_locale( $self->cust_main->locale );
3168 =item primary_cust_svc
3170 Returns a primary service (as FS::cust_svc object) if one can be identified.
3174 #for labeling purposes - might not 100% match up with part_pkg->svcpart's idea
3176 sub primary_cust_svc {
3179 my @cust_svc = $self->cust_svc;
3181 return '' unless @cust_svc; #no serivces - irrelevant then
3183 return $cust_svc[0] if scalar(@cust_svc) == 1; #always return a single service
3185 # primary service as specified in the package definition
3186 # or exactly one service definition with quantity one
3187 my $svcpart = $self->part_pkg->svcpart;
3188 @cust_svc = grep { $_->svcpart == $svcpart } @cust_svc;
3189 return $cust_svc[0] if scalar(@cust_svc) == 1;
3191 #couldn't identify one thing..
3197 Returns a list of lists, calling the label method for all services
3198 (see L<FS::cust_svc>) of this billing item.
3204 map { [ $_->label ] } $self->cust_svc;
3207 =item h_labels END_TIMESTAMP [ START_TIMESTAMP ] [ MODE ]
3209 Like the labels method, but returns historical information on services that
3210 were active as of END_TIMESTAMP and (optionally) not cancelled before
3211 START_TIMESTAMP. If MODE is 'I' (for 'invoice'), services with the
3212 I<pkg_svc.hidden> flag will be omitted.
3214 Returns a list of lists, calling the label method for all (historical) services
3215 (see L<FS::h_cust_svc>) of this billing item.
3221 warn "$me _h_labels called on $self\n"
3223 map { [ $_->label(@_) ] } $self->h_cust_svc(@_);
3228 Like labels, except returns a simple flat list, and shortens long
3229 (currently >5 or the cust_bill-max_same_services configuration value) lists of
3230 identical services to one line that lists the service label and the number of
3231 individual services rather than individual items.
3236 shift->_labels_short( 'labels', @_ );
3239 =item h_labels_short END_TIMESTAMP [ START_TIMESTAMP ]
3241 Like h_labels, except returns a simple flat list, and shortens long
3242 (currently >5 or the cust_bill-max_same_services configuration value) lists of
3243 identical services to one line that lists the service label and the number of
3244 individual services rather than individual items.
3248 sub h_labels_short {
3249 shift->_labels_short( 'h_labels', @_ );
3253 my( $self, $method ) = ( shift, shift );
3255 warn "$me _labels_short called on $self with $method method\n"
3258 my $conf = new FS::Conf;
3259 my $max_same_services = $conf->config('cust_bill-max_same_services') || 5;
3261 warn "$me _labels_short populating \%labels\n"
3265 #tie %labels, 'Tie::IxHash';
3266 push @{ $labels{$_->[0]} }, $_->[1]
3267 foreach $self->$method(@_);
3269 warn "$me _labels_short populating \@labels\n"
3273 foreach my $label ( keys %labels ) {
3275 my @values = grep { ! $seen{$_}++ } @{ $labels{$label} };
3276 my $num = scalar(@values);
3277 warn "$me _labels_short $num items for $label\n"
3280 if ( $num > $max_same_services ) {
3281 warn "$me _labels_short more than $max_same_services, so summarizing\n"
3283 push @labels, "$label ($num)";
3285 if ( $conf->exists('cust_bill-consolidate_services') ) {
3286 warn "$me _labels_short consolidating services\n"
3288 # push @labels, "$label: ". join(', ', @values);
3290 my $detail = "$label: ";
3291 $detail .= shift(@values). ', '
3293 && ( length($detail.$values[0]) < 78 || $detail eq "$label: " );
3295 push @labels, $detail;
3297 warn "$me _labels_short done consolidating services\n"
3300 warn "$me _labels_short adding service data\n"
3302 push @labels, map { "$label: $_" } @values;
3313 Returns the parent customer object (see L<FS::cust_main>).
3319 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
3324 Returns the balance for this specific package, when using
3325 experimental package balance.
3331 $self->cust_main->balance_pkgnum( $self->pkgnum );
3334 #these subs are in location_Mixin.pm now... unfortunately the POD doesn't mixin
3338 Returns the location object, if any (see L<FS::cust_location>).
3340 =item cust_location_or_main
3342 If this package is associated with a location, returns the locaiton (see
3343 L<FS::cust_location>), otherwise returns the customer (see L<FS::cust_main>).
3345 =item location_label [ OPTION => VALUE ... ]
3347 Returns the label of the location object (see L<FS::cust_location>).
3351 #end of subs in location_Mixin.pm now... unfortunately the POD doesn't mixin
3353 =item tax_locationnum
3355 Returns the foreign key to a L<FS::cust_location> object for calculating
3356 tax on this package, as determined by the C<tax-pkg_address> and
3357 C<tax-ship_address> configuration flags.
3361 sub tax_locationnum {
3363 my $conf = FS::Conf->new;
3364 if ( $conf->exists('tax-pkg_address') ) {
3365 return $self->locationnum;
3367 elsif ( $conf->exists('tax-ship_address') ) {
3368 return $self->cust_main->ship_locationnum;
3371 return $self->cust_main->bill_locationnum;
3377 Returns the L<FS::cust_location> object for tax_locationnum.
3383 FS::cust_location->by_key( $self->tax_locationnum )
3386 =item seconds_since TIMESTAMP
3388 Returns the number of seconds all accounts (see L<FS::svc_acct>) in this
3389 package have been online since TIMESTAMP, according to the session monitor.
3391 TIMESTAMP is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
3392 L<Time::Local> and L<Date::Parse> for conversion functions.
3397 my($self, $since) = @_;
3400 foreach my $cust_svc (
3401 grep { $_->part_svc->svcdb eq 'svc_acct' } $self->cust_svc
3403 $seconds += $cust_svc->seconds_since($since);
3410 =item seconds_since_sqlradacct TIMESTAMP_START TIMESTAMP_END
3412 Returns the numbers of seconds all accounts (see L<FS::svc_acct>) in this
3413 package have been online between TIMESTAMP_START (inclusive) and TIMESTAMP_END
3416 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
3417 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
3423 sub seconds_since_sqlradacct {
3424 my($self, $start, $end) = @_;
3428 foreach my $cust_svc (
3430 my $part_svc = $_->part_svc;
3431 $part_svc->svcdb eq 'svc_acct'
3432 && scalar($part_svc->part_export_usage);
3435 $seconds += $cust_svc->seconds_since_sqlradacct($start, $end);
3442 =item attribute_since_sqlradacct TIMESTAMP_START TIMESTAMP_END ATTRIBUTE
3444 Returns the sum of the given attribute for all accounts (see L<FS::svc_acct>)
3445 in this package for sessions ending between TIMESTAMP_START (inclusive) and
3449 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
3450 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
3455 sub attribute_since_sqlradacct {
3456 my($self, $start, $end, $attrib) = @_;
3460 foreach my $cust_svc (
3462 my $part_svc = $_->part_svc;
3463 $part_svc->svcdb eq 'svc_acct'
3464 && scalar($part_svc->part_export_usage);
3467 $sum += $cust_svc->attribute_since_sqlradacct($start, $end, $attrib);
3479 my( $self, $value ) = @_;
3480 if ( defined($value) ) {
3481 $self->setfield('quantity', $value);
3483 $self->getfield('quantity') || 1;
3486 =item transfer DEST_PKGNUM | DEST_CUST_PKG, [ OPTION => VALUE ... ]
3488 Transfers as many services as possible from this package to another package.
3490 The destination package can be specified by pkgnum by passing an FS::cust_pkg
3491 object. The destination package must already exist.
3493 Services are moved only if the destination allows services with the correct
3494 I<svcpart> (not svcdb), unless the B<change_svcpart> option is set true. Use
3495 this option with caution! No provision is made for export differences
3496 between the old and new service definitions. Probably only should be used
3497 when your exports for all service definitions of a given svcdb are identical.
3498 (attempt a transfer without it first, to move all possible svcpart-matching
3501 Any services that can't be moved remain in the original package.
3503 Returns an error, if there is one; otherwise, returns the number of services
3504 that couldn't be moved.
3509 my ($self, $dest_pkgnum, %opt) = @_;
3515 if (ref ($dest_pkgnum) eq 'FS::cust_pkg') {
3516 $dest = $dest_pkgnum;
3517 $dest_pkgnum = $dest->pkgnum;
3519 $dest = qsearchs('cust_pkg', { pkgnum => $dest_pkgnum });
3522 return ('Package does not exist: '.$dest_pkgnum) unless $dest;
3524 foreach my $pkg_svc ( $dest->part_pkg->pkg_svc ) {
3525 $target{$pkg_svc->svcpart} = $pkg_svc->quantity;
3528 foreach my $cust_svc ($dest->cust_svc) {
3529 $target{$cust_svc->svcpart}--;
3532 my %svcpart2svcparts = ();
3533 if ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
3534 warn "change_svcpart option received, creating alternates list\n" if $DEBUG;
3535 foreach my $svcpart ( map { $_->svcpart } $self->cust_svc ) {
3536 next if exists $svcpart2svcparts{$svcpart};
3537 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
3538 $svcpart2svcparts{$svcpart} = [
3540 sort { $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] }
3542 my $pkg_svc = qsearchs( 'pkg_svc', { 'pkgpart' => $dest->pkgpart,
3543 'svcpart' => $_ } );
3545 $pkg_svc ? $pkg_svc->primary_svc : '',
3546 $pkg_svc ? $pkg_svc->quantity : 0,
3550 grep { $_ != $svcpart }
3552 qsearch('part_svc', { 'svcdb' => $part_svc->svcdb } )
3554 warn "alternates for svcpart $svcpart: ".
3555 join(', ', @{$svcpart2svcparts{$svcpart}}). "\n"
3560 foreach my $cust_svc ($self->cust_svc) {
3561 if($target{$cust_svc->svcpart} > 0
3562 or $FS::cust_svc::ignore_quantity) { # maybe should be a 'force' option
3563 $target{$cust_svc->svcpart}--;
3564 my $new = new FS::cust_svc { $cust_svc->hash };
3565 $new->pkgnum($dest_pkgnum);
3566 my $error = $new->replace($cust_svc);
3567 return $error if $error;
3568 } elsif ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
3570 warn "looking for alternates for svcpart ". $cust_svc->svcpart. "\n";
3571 warn "alternates to consider: ".
3572 join(', ', @{$svcpart2svcparts{$cust_svc->svcpart}}). "\n";
3574 my @alternate = grep {
3575 warn "considering alternate svcpart $_: ".
3576 "$target{$_} available in new package\n"
3579 } @{$svcpart2svcparts{$cust_svc->svcpart}};
3581 warn "alternate(s) found\n" if $DEBUG;
3582 my $change_svcpart = $alternate[0];
3583 $target{$change_svcpart}--;
3584 my $new = new FS::cust_svc { $cust_svc->hash };
3585 $new->svcpart($change_svcpart);
3586 $new->pkgnum($dest_pkgnum);
3587 my $error = $new->replace($cust_svc);
3588 return $error if $error;
3599 =item grab_svcnums SVCNUM, SVCNUM ...
3601 Change the pkgnum for the provided services to this packages. If there is an
3602 error, returns the error, otherwise returns false.
3610 local $SIG{HUP} = 'IGNORE';
3611 local $SIG{INT} = 'IGNORE';
3612 local $SIG{QUIT} = 'IGNORE';
3613 local $SIG{TERM} = 'IGNORE';
3614 local $SIG{TSTP} = 'IGNORE';
3615 local $SIG{PIPE} = 'IGNORE';
3617 my $oldAutoCommit = $FS::UID::AutoCommit;
3618 local $FS::UID::AutoCommit = 0;
3621 foreach my $svcnum (@svcnum) {
3622 my $cust_svc = qsearchs('cust_svc', { svcnum=>$svcnum } ) or do {
3623 $dbh->rollback if $oldAutoCommit;
3624 return "unknown svcnum $svcnum";
3626 $cust_svc->pkgnum( $self->pkgnum );
3627 my $error = $cust_svc->replace;
3629 $dbh->rollback if $oldAutoCommit;
3634 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3641 This method is deprecated. See the I<depend_jobnum> option to the insert and
3642 order_pkgs methods in FS::cust_main for a better way to defer provisioning.
3646 #looks like this is still used by the order_pkg and change_pkg methods in
3647 # ClientAPI/MyAccount, need to look into those before removing
3651 local $SIG{HUP} = 'IGNORE';
3652 local $SIG{INT} = 'IGNORE';
3653 local $SIG{QUIT} = 'IGNORE';
3654 local $SIG{TERM} = 'IGNORE';
3655 local $SIG{TSTP} = 'IGNORE';
3656 local $SIG{PIPE} = 'IGNORE';
3658 my $oldAutoCommit = $FS::UID::AutoCommit;
3659 local $FS::UID::AutoCommit = 0;
3662 foreach my $cust_svc ( $self->cust_svc ) {
3663 #false laziness w/svc_Common::insert
3664 my $svc_x = $cust_svc->svc_x;
3665 foreach my $part_export ( $cust_svc->part_svc->part_export ) {
3666 my $error = $part_export->export_insert($svc_x);
3668 $dbh->rollback if $oldAutoCommit;
3674 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3679 =item export_pkg_change OLD_CUST_PKG
3681 Calls the "pkg_change" export action for all services attached to this package.
3685 sub export_pkg_change {
3686 my( $self, $old ) = ( shift, shift );
3688 local $SIG{HUP} = 'IGNORE';
3689 local $SIG{INT} = 'IGNORE';
3690 local $SIG{QUIT} = 'IGNORE';
3691 local $SIG{TERM} = 'IGNORE';
3692 local $SIG{TSTP} = 'IGNORE';
3693 local $SIG{PIPE} = 'IGNORE';
3695 my $oldAutoCommit = $FS::UID::AutoCommit;
3696 local $FS::UID::AutoCommit = 0;
3699 foreach my $svc_x ( map $_->svc_x, $self->cust_svc ) {
3700 my $error = $svc_x->export('pkg_change', $self, $old);
3702 $dbh->rollback if $oldAutoCommit;
3707 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3714 Associates this package with a (suspension or cancellation) reason (see
3715 L<FS::cust_pkg_reason>, possibly inserting a new reason on the fly (see
3718 Available options are:
3724 can be set to a cancellation reason (see L<FS:reason>), either a reasonnum of an existing reason, or passing a hashref will create a new reason. The hashref should have the following keys: typenum - Reason type (see L<FS::reason_type>, reason - Text of the new reason.
3728 the access_user (see L<FS::access_user>) providing the reason
3736 the action (cancel, susp, adjourn, expire) associated with the reason
3740 If there is an error, returns the error, otherwise returns false.
3745 my ($self, %options) = @_;
3747 my $otaker = $options{reason_otaker} ||
3748 $FS::CurrentUser::CurrentUser->username;
3751 if ( $options{'reason'} =~ /^(\d+)$/ ) {
3755 } elsif ( ref($options{'reason'}) ) {
3757 return 'Enter a new reason (or select an existing one)'
3758 unless $options{'reason'}->{'reason'} !~ /^\s*$/;
3760 my $reason = new FS::reason({
3761 'reason_type' => $options{'reason'}->{'typenum'},
3762 'reason' => $options{'reason'}->{'reason'},
3764 my $error = $reason->insert;
3765 return $error if $error;
3767 $reasonnum = $reason->reasonnum;
3770 return "Unparsable reason: ". $options{'reason'};
3773 my $cust_pkg_reason =
3774 new FS::cust_pkg_reason({ 'pkgnum' => $self->pkgnum,
3775 'reasonnum' => $reasonnum,
3776 'otaker' => $otaker,
3777 'action' => substr(uc($options{'action'}),0,1),
3778 'date' => $options{'date'}
3783 $cust_pkg_reason->insert;
3786 =item insert_discount
3788 Associates this package with a discount (see L<FS::cust_pkg_discount>, possibly
3789 inserting a new discount on the fly (see L<FS::discount>).
3791 Available options are:
3799 If there is an error, returns the error, otherwise returns false.
3803 sub insert_discount {
3804 #my ($self, %options) = @_;
3807 my $cust_pkg_discount = new FS::cust_pkg_discount {
3808 'pkgnum' => $self->pkgnum,
3809 'discountnum' => $self->discountnum,
3811 'end_date' => '', #XXX
3812 #for the create a new discount case
3813 '_type' => $self->discountnum__type,
3814 'amount' => $self->discountnum_amount,
3815 'percent' => $self->discountnum_percent,
3816 'months' => $self->discountnum_months,
3817 'setup' => $self->discountnum_setup,
3818 #'disabled' => $self->discountnum_disabled,
3821 $cust_pkg_discount->insert;
3824 =item set_usage USAGE_VALUE_HASHREF
3826 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
3827 to which they should be set (see L<FS::svc_acct>). Currently seconds,
3828 upbytes, downbytes, and totalbytes are appropriate keys.
3830 All svc_accts which are part of this package have their values reset.
3835 my ($self, $valueref, %opt) = @_;
3837 #only svc_acct can set_usage for now
3838 foreach my $cust_svc ( $self->cust_svc( 'svcdb'=>'svc_acct' ) ) {
3839 my $svc_x = $cust_svc->svc_x;
3840 $svc_x->set_usage($valueref, %opt)
3841 if $svc_x->can("set_usage");
3845 =item recharge USAGE_VALUE_HASHREF
3847 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
3848 to which they should be set (see L<FS::svc_acct>). Currently seconds,
3849 upbytes, downbytes, and totalbytes are appropriate keys.
3851 All svc_accts which are part of this package have their values incremented.
3856 my ($self, $valueref) = @_;
3858 #only svc_acct can set_usage for now
3859 foreach my $cust_svc ( $self->cust_svc( 'svcdb'=>'svc_acct' ) ) {
3860 my $svc_x = $cust_svc->svc_x;
3861 $svc_x->recharge($valueref)
3862 if $svc_x->can("recharge");
3866 =item cust_pkg_discount
3870 sub cust_pkg_discount {
3872 qsearch('cust_pkg_discount', { 'pkgnum' => $self->pkgnum } );
3875 =item cust_pkg_discount_active
3879 sub cust_pkg_discount_active {
3881 grep { $_->status eq 'active' } $self->cust_pkg_discount;
3884 =item cust_pkg_usage
3886 Returns a list of all voice usage counters attached to this package.
3890 sub cust_pkg_usage {
3892 qsearch('cust_pkg_usage', { pkgnum => $self->pkgnum });
3895 =item apply_usage OPTIONS
3897 Takes the following options:
3898 - cdr: a call detail record (L<FS::cdr>)
3899 - rate_detail: the rate determined for this call (L<FS::rate_detail>)
3900 - minutes: the maximum number of minutes to be charged
3902 Finds available usage minutes for a call of this class, and subtracts
3903 up to that many minutes from the usage pool. If the usage pool is empty,
3904 and the C<cdr-minutes_priority> global config option is set, minutes may
3905 be taken from other calls as well. Either way, an allocation record will
3906 be created (L<FS::cdr_cust_pkg_usage>) and this method will return the
3907 number of minutes of usage applied to the call.
3912 my ($self, %opt) = @_;
3913 my $cdr = $opt{cdr};
3914 my $rate_detail = $opt{rate_detail};
3915 my $minutes = $opt{minutes};
3916 my $classnum = $rate_detail->classnum;
3917 my $pkgnum = $self->pkgnum;
3918 my $custnum = $self->custnum;
3920 local $SIG{HUP} = 'IGNORE';
3921 local $SIG{INT} = 'IGNORE';
3922 local $SIG{QUIT} = 'IGNORE';
3923 local $SIG{TERM} = 'IGNORE';
3924 local $SIG{TSTP} = 'IGNORE';
3925 local $SIG{PIPE} = 'IGNORE';
3927 my $oldAutoCommit = $FS::UID::AutoCommit;
3928 local $FS::UID::AutoCommit = 0;
3930 my $order = FS::Conf->new->config('cdr-minutes_priority');
3934 $is_classnum = ' part_pkg_usage_class.classnum = '.$classnum;
3936 $is_classnum = ' part_pkg_usage_class.classnum IS NULL';
3938 my @usage_recs = qsearch({
3939 'table' => 'cust_pkg_usage',
3940 'addl_from' => ' JOIN part_pkg_usage USING (pkgusagepart)'.
3941 ' JOIN cust_pkg USING (pkgnum)'.
3942 ' JOIN part_pkg_usage_class USING (pkgusagepart)',
3943 'select' => 'cust_pkg_usage.*',
3944 'extra_sql' => " WHERE ( cust_pkg.pkgnum = $pkgnum OR ".
3945 " ( cust_pkg.custnum = $custnum AND ".
3946 " part_pkg_usage.shared IS NOT NULL ) ) AND ".
3947 $is_classnum . ' AND '.
3948 " cust_pkg_usage.minutes > 0",
3949 'order_by' => " ORDER BY priority ASC",
3952 my $orig_minutes = $minutes;
3954 while (!$error and $minutes > 0 and @usage_recs) {
3955 my $cust_pkg_usage = shift @usage_recs;
3956 $cust_pkg_usage->select_for_update;
3957 my $cdr_cust_pkg_usage = FS::cdr_cust_pkg_usage->new({
3958 pkgusagenum => $cust_pkg_usage->pkgusagenum,
3959 acctid => $cdr->acctid,
3960 minutes => min($cust_pkg_usage->minutes, $minutes),
3962 $cust_pkg_usage->set('minutes',
3963 sprintf('%.0f', $cust_pkg_usage->minutes - $cdr_cust_pkg_usage->minutes)
3965 $error = $cust_pkg_usage->replace || $cdr_cust_pkg_usage->insert;
3966 $minutes -= $cdr_cust_pkg_usage->minutes;
3968 if ( $order and $minutes > 0 and !$error ) {
3969 # then try to steal minutes from another call
3971 'table' => 'cdr_cust_pkg_usage',
3972 'addl_from' => ' JOIN cust_pkg_usage USING (pkgusagenum)'.
3973 ' JOIN part_pkg_usage USING (pkgusagepart)'.
3974 ' JOIN cust_pkg USING (pkgnum)'.
3975 ' JOIN part_pkg_usage_class USING (pkgusagepart)'.
3976 ' JOIN cdr USING (acctid)',
3977 'select' => 'cdr_cust_pkg_usage.*',
3978 'extra_sql' => " WHERE cdr.freesidestatus = 'rated' AND ".
3979 " ( cust_pkg.pkgnum = $pkgnum OR ".
3980 " ( cust_pkg.custnum = $custnum AND ".
3981 " part_pkg_usage.shared IS NOT NULL ) ) AND ".
3982 " part_pkg_usage_class.classnum = $classnum",
3983 'order_by' => ' ORDER BY part_pkg_usage.priority ASC',
3985 if ( $order eq 'time' ) {
3986 # find CDRs that are using minutes, but have a later startdate
3988 my $startdate = $cdr->startdate;
3989 if ($startdate !~ /^\d+$/) {
3990 die "bad cdr startdate '$startdate'";
3992 $search{'extra_sql'} .= " AND cdr.startdate > $startdate";
3993 # minimize needless reshuffling
3994 $search{'order_by'} .= ', cdr.startdate DESC';
3996 # XXX may not work correctly with rate_time schedules. Could
3997 # fix this by storing ratedetailnum in cdr_cust_pkg_usage, I
3999 $search{'addl_from'} .=
4000 ' JOIN rate_detail'.
4001 ' ON (cdr.rated_ratedetailnum = rate_detail.ratedetailnum)';
4002 if ( $order eq 'rate_high' ) {
4003 $search{'extra_sql'} .= ' AND rate_detail.min_charge < '.
4004 $rate_detail->min_charge;
4005 $search{'order_by'} .= ', rate_detail.min_charge ASC';
4006 } elsif ( $order eq 'rate_low' ) {
4007 $search{'extra_sql'} .= ' AND rate_detail.min_charge > '.
4008 $rate_detail->min_charge;
4009 $search{'order_by'} .= ', rate_detail.min_charge DESC';
4011 # this should really never happen
4012 die "invalid cdr-minutes_priority value '$order'\n";
4015 my @cdr_usage_recs = qsearch(\%search);
4017 while (!$error and @cdr_usage_recs and $minutes > 0) {
4018 my $cdr_cust_pkg_usage = shift @cdr_usage_recs;
4019 my $cust_pkg_usage = $cdr_cust_pkg_usage->cust_pkg_usage;
4020 my $old_cdr = $cdr_cust_pkg_usage->cdr;
4021 $reproc_cdrs{$old_cdr->acctid} = $old_cdr;
4022 $cdr_cust_pkg_usage->select_for_update;
4023 $old_cdr->select_for_update;
4024 $cust_pkg_usage->select_for_update;
4025 # in case someone else stole the usage from this CDR
4026 # while waiting for the lock...
4027 next if $old_cdr->acctid != $cdr_cust_pkg_usage->acctid;
4028 # steal the usage allocation and flag the old CDR for reprocessing
4029 $cdr_cust_pkg_usage->set('acctid', $cdr->acctid);
4030 # if the allocation is more minutes than we need, adjust it...
4031 my $delta = $cdr_cust_pkg_usage->minutes - $minutes;
4033 $cdr_cust_pkg_usage->set('minutes', $minutes);
4034 $cust_pkg_usage->set('minutes', $cust_pkg_usage->minutes + $delta);
4035 $error = $cust_pkg_usage->replace;
4037 #warn 'CDR '.$cdr->acctid . ' stealing allocation '.$cdr_cust_pkg_usage->cdrusagenum.' from CDR '.$old_cdr->acctid."\n";
4038 $error ||= $cdr_cust_pkg_usage->replace;
4039 # deduct the stolen minutes
4040 $minutes -= $cdr_cust_pkg_usage->minutes;
4042 # after all minute-stealing is done, reset the affected CDRs
4043 foreach (values %reproc_cdrs) {
4044 $error ||= $_->set_status('');
4045 # XXX or should we just call $cdr->rate right here?
4046 # it's not like we can create a loop this way, since the min_charge
4047 # or call time has to go monotonically in one direction.
4048 # we COULD get some very deep recursions going, though...
4050 } # if $order and $minutes
4053 die "error applying included minutes\npkgnum ".$self->pkgnum.", class $classnum, acctid ".$cdr->acctid."\n$error\n"
4055 $dbh->commit if $oldAutoCommit;
4056 return $orig_minutes - $minutes;
4060 =item supplemental_pkgs
4062 Returns a list of all packages supplemental to this one.
4066 sub supplemental_pkgs {
4068 qsearch('cust_pkg', { 'main_pkgnum' => $self->pkgnum });
4073 Returns the package that this one is supplemental to, if any.
4079 if ( $self->main_pkgnum ) {
4080 return FS::cust_pkg->by_key($self->main_pkgnum);
4087 =head1 CLASS METHODS
4093 Returns an SQL expression identifying recurring packages.
4097 sub recurring_sql { "
4098 '0' != ( select freq from part_pkg
4099 where cust_pkg.pkgpart = part_pkg.pkgpart )
4104 Returns an SQL expression identifying one-time packages.
4109 '0' = ( select freq from part_pkg
4110 where cust_pkg.pkgpart = part_pkg.pkgpart )
4115 Returns an SQL expression identifying ordered packages (recurring packages not
4121 $_[0]->recurring_sql. " AND ". $_[0]->not_yet_billed_sql;
4126 Returns an SQL expression identifying active packages.
4131 $_[0]->recurring_sql. "
4132 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
4133 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4134 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
4137 =item not_yet_billed_sql
4139 Returns an SQL expression identifying packages which have not yet been billed.
4143 sub not_yet_billed_sql { "
4144 ( cust_pkg.setup IS NULL OR cust_pkg.setup = 0 )
4145 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4146 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
4151 Returns an SQL expression identifying inactive packages (one-time packages
4152 that are otherwise unsuspended/uncancelled).
4156 sub inactive_sql { "
4157 ". $_[0]->onetime_sql(). "
4158 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
4159 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4160 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
4166 Returns an SQL expression identifying suspended packages.
4170 sub suspended_sql { susp_sql(@_); }
4172 #$_[0]->recurring_sql(). ' AND '.
4174 ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4175 AND cust_pkg.susp IS NOT NULL AND cust_pkg.susp != 0
4182 Returns an SQL exprression identifying cancelled packages.
4186 sub cancelled_sql { cancel_sql(@_); }
4188 #$_[0]->recurring_sql(). ' AND '.
4189 "cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0";
4194 Returns an SQL expression to give the package status as a string.
4200 WHEN cust_pkg.cancel IS NOT NULL THEN 'cancelled'
4201 WHEN cust_pkg.susp IS NOT NULL THEN 'suspended'
4202 WHEN cust_pkg.setup IS NULL THEN 'not yet billed'
4203 WHEN ".onetime_sql()." THEN 'one-time charge'
4208 =item search HASHREF
4212 Returns a qsearch hash expression to search for parameters specified in HASHREF.
4213 Valid parameters are
4221 active, inactive, suspended, cancel (or cancelled)
4225 active, inactive, suspended, one-time charge, inactive, cancel (or cancelled)
4229 boolean selects custom packages
4235 pkgpart or arrayref or hashref of pkgparts
4239 arrayref of beginning and ending epoch date
4243 arrayref of beginning and ending epoch date
4247 arrayref of beginning and ending epoch date
4251 arrayref of beginning and ending epoch date
4255 arrayref of beginning and ending epoch date
4259 arrayref of beginning and ending epoch date
4263 arrayref of beginning and ending epoch date
4267 pkgnum or APKG_pkgnum
4271 a value suited to passing to FS::UI::Web::cust_header
4275 specifies the user for agent virtualization
4279 boolean; if true, returns only packages with more than 0 FCC phone lines.
4281 =item state, country
4283 Limit to packages with a service location in the specified state and country.
4284 For FCC 477 reporting, mostly.
4291 my ($class, $params) = @_;
4298 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
4300 "cust_main.agentnum = $1";
4307 if ( $params->{'cust_status'} =~ /^([a-z]+)$/ ) {
4308 push @where, FS::cust_main->cust_status_sql . " = '$1' ";
4312 # parse customer sales person
4315 if ( $params->{'cust_main_salesnum'} =~ /^(\d+)$/ ) {
4316 push @where, ($1 > 0) ? "cust_main.salesnum = $1"
4317 : 'cust_main.salesnum IS NULL';
4322 # parse sales person
4325 if ( $params->{'salesnum'} =~ /^(\d+)$/ ) {
4326 push @where, ($1 > 0) ? "cust_pkg.salesnum = $1"
4327 : 'cust_pkg.salesnum IS NULL';
4334 if ( $params->{'custnum'} =~ /^(\d+)$/ and $1 ) {
4336 "cust_pkg.custnum = $1";
4343 if ( $params->{'pkgbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
4345 "cust_pkg.pkgbatch = '$1'";
4352 if ( $params->{'magic'} eq 'active'
4353 || $params->{'status'} eq 'active' ) {
4355 push @where, FS::cust_pkg->active_sql();
4357 } elsif ( $params->{'magic'} =~ /^not[ _]yet[ _]billed$/
4358 || $params->{'status'} =~ /^not[ _]yet[ _]billed$/ ) {
4360 push @where, FS::cust_pkg->not_yet_billed_sql();
4362 } elsif ( $params->{'magic'} =~ /^(one-time charge|inactive)/
4363 || $params->{'status'} =~ /^(one-time charge|inactive)/ ) {
4365 push @where, FS::cust_pkg->inactive_sql();
4367 } elsif ( $params->{'magic'} eq 'suspended'
4368 || $params->{'status'} eq 'suspended' ) {
4370 push @where, FS::cust_pkg->suspended_sql();
4372 } elsif ( $params->{'magic'} =~ /^cancell?ed$/
4373 || $params->{'status'} =~ /^cancell?ed$/ ) {
4375 push @where, FS::cust_pkg->cancelled_sql();
4380 # parse package class
4383 if ( exists($params->{'classnum'}) ) {
4386 if ( ref($params->{'classnum'}) ) {
4388 if ( ref($params->{'classnum'}) eq 'HASH' ) {
4389 @classnum = grep $params->{'classnum'}{$_}, keys %{ $params->{'classnum'} };
4390 } elsif ( ref($params->{'classnum'}) eq 'ARRAY' ) {
4391 @classnum = @{ $params->{'classnum'} };
4393 die 'unhandled classnum ref '. $params->{'classnum'};
4397 } elsif ( $params->{'classnum'} =~ /^(\d*)$/ && $1 ne '0' ) {
4404 my @nums = grep $_, @classnum;
4405 push @c_where, 'part_pkg.classnum IN ('. join(',',@nums). ')' if @nums;
4406 my $null = scalar( grep { $_ eq '' } @classnum );
4407 push @c_where, 'part_pkg.classnum IS NULL' if $null;
4409 if ( scalar(@c_where) == 1 ) {
4410 push @where, @c_where;
4411 } elsif ( @c_where ) {
4412 push @where, ' ( '. join(' OR ', @c_where). ' ) ';
4421 # parse package report options
4424 my @report_option = ();
4425 if ( exists($params->{'report_option'}) ) {
4426 if ( ref($params->{'report_option'}) eq 'ARRAY' ) {
4427 @report_option = @{ $params->{'report_option'} };
4428 } elsif ( $params->{'report_option'} =~ /^([,\d]*)$/ ) {
4429 @report_option = split(',', $1);
4434 if (@report_option) {
4435 # this will result in the empty set for the dangling comma case as it should
4437 map{ "0 < ( SELECT count(*) FROM part_pkg_option
4438 WHERE part_pkg_option.pkgpart = part_pkg.pkgpart
4439 AND optionname = 'report_option_$_'
4440 AND optionvalue = '1' )"
4444 foreach my $any ( grep /^report_option_any/, keys %$params ) {
4446 my @report_option_any = ();
4447 if ( ref($params->{$any}) eq 'ARRAY' ) {
4448 @report_option_any = @{ $params->{$any} };
4449 } elsif ( $params->{$any} =~ /^([,\d]*)$/ ) {
4450 @report_option_any = split(',', $1);
4453 if (@report_option_any) {
4454 # this will result in the empty set for the dangling comma case as it should
4455 push @where, ' ( '. join(' OR ',
4456 map{ "0 < ( SELECT count(*) FROM part_pkg_option
4457 WHERE part_pkg_option.pkgpart = part_pkg.pkgpart
4458 AND optionname = 'report_option_$_'
4459 AND optionvalue = '1' )"
4460 } @report_option_any
4470 push @where, "part_pkg.custom = 'Y'" if $params->{custom};
4476 push @where, "(part_pkg.fcc_ds0s > 0 OR pkg_class.fcc_ds0s > 0)"
4477 if $params->{fcc_line};
4483 if ( exists($params->{'censustract'}) ) {
4484 $params->{'censustract'} =~ /^([.\d]*)$/;
4485 my $censustract = "cust_location.censustract = '$1'";
4486 $censustract .= ' OR cust_location.censustract is NULL' unless $1;
4487 push @where, "( $censustract )";
4491 # parse censustract2
4493 if ( exists($params->{'censustract2'})
4494 && $params->{'censustract2'} =~ /^(\d*)$/
4498 push @where, "cust_location.censustract LIKE '$1%'";
4501 "( cust_location.censustract = '' OR cust_location.censustract IS NULL )";
4506 # parse country/state
4508 for (qw(state country)) { # parsing rules are the same for these
4509 if ( exists($params->{$_})
4510 && uc($params->{$_}) =~ /^([A-Z]{2})$/ )
4512 # XXX post-2.3 only--before that, state/country may be in cust_main
4513 push @where, "cust_location.$_ = '$1'";
4521 if ( ref($params->{'pkgpart'}) ) {
4524 if ( ref($params->{'pkgpart'}) eq 'HASH' ) {
4525 @pkgpart = grep $params->{'pkgpart'}{$_}, keys %{ $params->{'pkgpart'} };
4526 } elsif ( ref($params->{'pkgpart'}) eq 'ARRAY' ) {
4527 @pkgpart = @{ $params->{'pkgpart'} };
4529 die 'unhandled pkgpart ref '. $params->{'pkgpart'};
4532 @pkgpart = grep /^(\d+)$/, @pkgpart;
4534 push @where, 'pkgpart IN ('. join(',', @pkgpart). ')' if scalar(@pkgpart);
4536 } elsif ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
4537 push @where, "pkgpart = $1";
4546 #false laziness w/report_cust_pkg.html
4549 'one-time charge' => { 'last_bill'=>1, 'bill'=>1, 'adjourn'=>1, 'susp'=>1, 'expire'=>1, 'cancel'=>1, },
4550 'active' => { 'susp'=>1, 'cancel'=>1 },
4551 'suspended' => { 'cancel' => 1 },
4556 if( exists($params->{'active'} ) ) {
4557 # This overrides all the other date-related fields
4558 my($beginning, $ending) = @{$params->{'active'}};
4560 "cust_pkg.setup IS NOT NULL",
4561 "cust_pkg.setup <= $ending",
4562 "(cust_pkg.cancel IS NULL OR cust_pkg.cancel >= $beginning )",
4563 "NOT (".FS::cust_pkg->onetime_sql . ")";
4566 foreach my $field (qw( setup last_bill bill adjourn susp expire contract_end change_date cancel )) {
4568 next unless exists($params->{$field});
4570 my($beginning, $ending) = @{$params->{$field}};
4572 next if $beginning == 0 && $ending == 4294967295;
4575 "cust_pkg.$field IS NOT NULL",
4576 "cust_pkg.$field >= $beginning",
4577 "cust_pkg.$field <= $ending";
4579 $orderby ||= "ORDER BY cust_pkg.$field";
4584 $orderby ||= 'ORDER BY bill';
4587 # parse magic, legacy, etc.
4590 if ( $params->{'magic'} &&
4591 $params->{'magic'} =~ /^(active|inactive|suspended|cancell?ed)$/
4594 $orderby = 'ORDER BY pkgnum';
4596 if ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
4597 push @where, "pkgpart = $1";
4600 } elsif ( $params->{'query'} eq 'pkgnum' ) {
4602 $orderby = 'ORDER BY pkgnum';
4604 } elsif ( $params->{'query'} eq 'APKG_pkgnum' ) {
4606 $orderby = 'ORDER BY pkgnum';
4609 SELECT count(*) FROM pkg_svc
4610 WHERE pkg_svc.pkgpart = cust_pkg.pkgpart
4611 AND pkg_svc.quantity > ( SELECT count(*) FROM cust_svc
4612 WHERE cust_svc.pkgnum = cust_pkg.pkgnum
4613 AND cust_svc.svcpart = pkg_svc.svcpart
4620 # setup queries, links, subs, etc. for the search
4623 # here is the agent virtualization
4624 if ($params->{CurrentUser}) {
4626 qsearchs('access_user', { username => $params->{CurrentUser} });
4629 push @where, $access_user->agentnums_sql('table'=>'cust_main');
4634 push @where, $FS::CurrentUser::CurrentUser->agentnums_sql('table'=>'cust_main');
4637 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
4639 my $addl_from = 'LEFT JOIN part_pkg USING ( pkgpart ) '.
4640 'LEFT JOIN pkg_class ON ( part_pkg.classnum = pkg_class.classnum ) '.
4641 'LEFT JOIN cust_location USING ( locationnum ) '.
4642 FS::UI::Web::join_cust_main('cust_pkg', 'cust_pkg');
4646 if ( $params->{'select_zip5'} ) {
4647 my $zip = 'cust_location.zip';
4649 $select = "DISTINCT substr($zip,1,5) as zip";
4650 $orderby = "ORDER BY substr($zip,1,5)";
4651 $count_query = "SELECT COUNT( DISTINCT substr($zip,1,5) )";
4653 $select = join(', ',
4655 ( map "part_pkg.$_", qw( pkg freq ) ),
4656 'pkg_class.classname',
4657 'cust_main.custnum AS cust_main_custnum',
4658 FS::UI::Web::cust_sql_fields(
4659 $params->{'cust_fields'}
4662 $count_query = 'SELECT COUNT(*)';
4665 $count_query .= " FROM cust_pkg $addl_from $extra_sql";
4668 'table' => 'cust_pkg',
4670 'select' => $select,
4671 'extra_sql' => $extra_sql,
4672 'order_by' => $orderby,
4673 'addl_from' => $addl_from,
4674 'count_query' => $count_query,
4681 Returns a list of two package counts. The first is a count of packages
4682 based on the supplied criteria and the second is the count of residential
4683 packages with those same criteria. Criteria are specified as in the search
4689 my ($class, $params) = @_;
4691 my $sql_query = $class->search( $params );
4693 my $count_sql = delete($sql_query->{'count_query'});
4694 $count_sql =~ s/ FROM/,count(CASE WHEN cust_main.company IS NULL OR cust_main.company = '' THEN 1 END) FROM/
4695 or die "couldn't parse count_sql";
4697 my $count_sth = dbh->prepare($count_sql)
4698 or die "Error preparing $count_sql: ". dbh->errstr;
4700 or die "Error executing $count_sql: ". $count_sth->errstr;
4701 my $count_arrayref = $count_sth->fetchrow_arrayref;
4703 return ( @$count_arrayref );
4707 =item tax_locationnum_sql
4709 Returns an SQL expression for the tax location for a package, based
4710 on the settings of 'tax-pkg_address' and 'tax-ship_address'.
4714 sub tax_locationnum_sql {
4715 my $conf = FS::Conf->new;
4716 if ( $conf->exists('tax-pkg_address') ) {
4717 'cust_pkg.locationnum';
4719 elsif ( $conf->exists('tax-ship_address') ) {
4720 'cust_main.ship_locationnum';
4723 'cust_main.bill_locationnum';
4729 Returns a list: the first item is an SQL fragment identifying matching
4730 packages/customers via location (taking into account shipping and package
4731 address taxation, if enabled), and subsequent items are the parameters to
4732 substitute for the placeholders in that fragment.
4737 my($class, %opt) = @_;
4738 my $ornull = $opt{'ornull'};
4740 my $conf = new FS::Conf;
4742 # '?' placeholders in _location_sql_where
4743 my $x = $ornull ? 3 : 2;
4754 if ( $conf->exists('tax-ship_address') ) {
4757 ( ( ship_last IS NULL OR ship_last = '' )
4758 AND ". _location_sql_where('cust_main', '', $ornull ). "
4760 OR ( ship_last IS NOT NULL AND ship_last != ''
4761 AND ". _location_sql_where('cust_main', 'ship_', $ornull ). "
4764 # AND payby != 'COMP'
4766 @main_param = ( @bill_param, @bill_param );
4770 $main_where = _location_sql_where('cust_main'); # AND payby != 'COMP'
4771 @main_param = @bill_param;
4777 if ( $conf->exists('tax-pkg_address') ) {
4779 my $loc_where = _location_sql_where( 'cust_location', '', $ornull );
4782 ( cust_pkg.locationnum IS NULL AND $main_where )
4783 OR ( cust_pkg.locationnum IS NOT NULL AND $loc_where )
4786 @param = ( @main_param, @bill_param );
4790 $where = $main_where;
4791 @param = @main_param;
4799 #subroutine, helper for location_sql
4800 sub _location_sql_where {
4802 my $prefix = @_ ? shift : '';
4803 my $ornull = @_ ? shift : '';
4805 # $ornull = $ornull ? " OR ( ? IS NULL AND $table.${prefix}county IS NULL ) " : '';
4807 $ornull = $ornull ? ' OR ? IS NULL ' : '';
4809 my $or_empty_city = " OR ( ? = '' AND $table.${prefix}city IS NULL )";
4810 my $or_empty_county = " OR ( ? = '' AND $table.${prefix}county IS NULL )";
4811 my $or_empty_state = " OR ( ? = '' AND $table.${prefix}state IS NULL )";
4813 my $text = (driver_name =~ /^mysql/i) ? 'char' : 'text';
4815 # ( $table.${prefix}city = ? $or_empty_city $ornull )
4817 ( $table.district = ? OR ? = '' OR CAST(? AS $text) IS NULL )
4818 AND ( $table.${prefix}city = ? OR ? = '' OR CAST(? AS $text) IS NULL )
4819 AND ( $table.${prefix}county = ? $or_empty_county $ornull )
4820 AND ( $table.${prefix}state = ? $or_empty_state $ornull )
4821 AND $table.${prefix}country = ?
4826 my( $self, $what ) = @_;
4828 my $what_show_zero = $what. '_show_zero';
4829 length($self->$what_show_zero())
4830 ? ($self->$what_show_zero() eq 'Y')
4831 : $self->part_pkg->$what_show_zero();
4838 =item order CUSTNUM, PKGPARTS_ARYREF, [ REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF [ REFNUM ] ] ]
4840 CUSTNUM is a customer (see L<FS::cust_main>)
4842 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
4843 L<FS::part_pkg>) to order for this customer. Duplicates are of course
4846 REMOVE_PKGNUMS is an optional list of pkgnums specifying the billing items to
4847 remove for this customer. The services (see L<FS::cust_svc>) are moved to the
4848 new billing items. An error is returned if this is not possible (see
4849 L<FS::pkg_svc>). An empty arrayref is equivalent to not specifying this
4852 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
4853 newly-created cust_pkg objects.
4855 REFNUM, if specified, will specify the FS::pkg_referral record to be created
4856 and inserted. Multiple FS::pkg_referral records can be created by
4857 setting I<refnum> to an array reference of refnums or a hash reference with
4858 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
4859 record will be created corresponding to cust_main.refnum.
4864 my ($custnum, $pkgparts, $remove_pkgnum, $return_cust_pkg, $refnum) = @_;
4866 my $conf = new FS::Conf;
4868 # Transactionize this whole mess
4869 local $SIG{HUP} = 'IGNORE';
4870 local $SIG{INT} = 'IGNORE';
4871 local $SIG{QUIT} = 'IGNORE';
4872 local $SIG{TERM} = 'IGNORE';
4873 local $SIG{TSTP} = 'IGNORE';
4874 local $SIG{PIPE} = 'IGNORE';
4876 my $oldAutoCommit = $FS::UID::AutoCommit;
4877 local $FS::UID::AutoCommit = 0;
4881 # my $cust_main = qsearchs('cust_main', { custnum => $custnum });
4882 # return "Customer not found: $custnum" unless $cust_main;
4884 warn "$me order: pkgnums to remove: ". join(',', @$remove_pkgnum). "\n"
4887 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
4890 my $change = scalar(@old_cust_pkg) != 0;
4893 if ( scalar(@old_cust_pkg) == 1 && scalar(@$pkgparts) == 1 ) {
4895 warn "$me order: changing pkgnum ". $old_cust_pkg[0]->pkgnum.
4896 " to pkgpart ". $pkgparts->[0]. "\n"
4899 my $err_or_cust_pkg =
4900 $old_cust_pkg[0]->change( 'pkgpart' => $pkgparts->[0],
4901 'refnum' => $refnum,
4904 unless (ref($err_or_cust_pkg)) {
4905 $dbh->rollback if $oldAutoCommit;
4906 return $err_or_cust_pkg;
4909 push @$return_cust_pkg, $err_or_cust_pkg;
4910 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4915 # Create the new packages.
4916 foreach my $pkgpart (@$pkgparts) {
4918 warn "$me order: inserting pkgpart $pkgpart\n" if $DEBUG;
4920 my $cust_pkg = new FS::cust_pkg { custnum => $custnum,
4921 pkgpart => $pkgpart,
4925 $error = $cust_pkg->insert( 'change' => $change );
4926 push @$return_cust_pkg, $cust_pkg;
4928 foreach my $link ($cust_pkg->part_pkg->supp_part_pkg_link) {
4929 my $supp_pkg = FS::cust_pkg->new({
4930 custnum => $custnum,
4931 pkgpart => $link->dst_pkgpart,
4933 main_pkgnum => $cust_pkg->pkgnum,
4936 $error ||= $supp_pkg->insert( 'change' => $change );
4937 push @$return_cust_pkg, $supp_pkg;
4941 $dbh->rollback if $oldAutoCommit;
4946 # $return_cust_pkg now contains refs to all of the newly
4949 # Transfer services and cancel old packages.
4950 foreach my $old_pkg (@old_cust_pkg) {
4952 warn "$me order: transferring services from pkgnum ". $old_pkg->pkgnum. "\n"
4955 foreach my $new_pkg (@$return_cust_pkg) {
4956 $error = $old_pkg->transfer($new_pkg);
4957 if ($error and $error == 0) {
4958 # $old_pkg->transfer failed.
4959 $dbh->rollback if $oldAutoCommit;
4964 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
4965 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
4966 foreach my $new_pkg (@$return_cust_pkg) {
4967 $error = $old_pkg->transfer($new_pkg, 'change_svcpart'=>1 );
4968 if ($error and $error == 0) {
4969 # $old_pkg->transfer failed.
4970 $dbh->rollback if $oldAutoCommit;
4977 # Transfers were successful, but we went through all of the
4978 # new packages and still had services left on the old package.
4979 # We can't cancel the package under the circumstances, so abort.
4980 $dbh->rollback if $oldAutoCommit;
4981 return "Unable to transfer all services from package ".$old_pkg->pkgnum;
4983 $error = $old_pkg->cancel( quiet=>1 );
4989 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4993 =item bulk_change PKGPARTS_ARYREF, REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF ]
4995 A bulk change method to change packages for multiple customers.
4997 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
4998 L<FS::part_pkg>) to order for each customer. Duplicates are of course
5001 REMOVE_PKGNUMS is an list of pkgnums specifying the billing items to
5002 replace. The services (see L<FS::cust_svc>) are moved to the
5003 new billing items. An error is returned if this is not possible (see
5006 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
5007 newly-created cust_pkg objects.
5012 my ($pkgparts, $remove_pkgnum, $return_cust_pkg) = @_;
5014 # Transactionize this whole mess
5015 local $SIG{HUP} = 'IGNORE';
5016 local $SIG{INT} = 'IGNORE';
5017 local $SIG{QUIT} = 'IGNORE';
5018 local $SIG{TERM} = 'IGNORE';
5019 local $SIG{TSTP} = 'IGNORE';
5020 local $SIG{PIPE} = 'IGNORE';
5022 my $oldAutoCommit = $FS::UID::AutoCommit;
5023 local $FS::UID::AutoCommit = 0;
5027 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
5030 while(scalar(@old_cust_pkg)) {
5032 my $custnum = $old_cust_pkg[0]->custnum;
5033 my (@remove) = map { $_->pkgnum }
5034 grep { $_->custnum == $custnum } @old_cust_pkg;
5035 @old_cust_pkg = grep { $_->custnum != $custnum } @old_cust_pkg;
5037 my $error = order $custnum, $pkgparts, \@remove, \@return;
5039 push @errors, $error
5041 push @$return_cust_pkg, @return;
5044 if (scalar(@errors)) {
5045 $dbh->rollback if $oldAutoCommit;
5046 return join(' / ', @errors);
5049 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5053 # Used by FS::Upgrade to migrate to a new database.
5054 sub _upgrade_data { # class method
5055 my ($class, %opts) = @_;
5056 $class->_upgrade_otaker(%opts);
5058 # RT#10139, bug resulting in contract_end being set when it shouldn't
5059 'UPDATE cust_pkg SET contract_end = NULL WHERE contract_end = -1',
5060 # RT#10830, bad calculation of prorate date near end of year
5061 # the date range for bill is December 2009, and we move it forward
5062 # one year if it's before the previous bill date (which it should
5064 'UPDATE cust_pkg SET bill = bill + (365*24*60*60) WHERE bill < last_bill
5065 AND bill > 1259654400 AND bill < 1262332800 AND (SELECT plan FROM part_pkg
5066 WHERE part_pkg.pkgpart = cust_pkg.pkgpart) = \'prorate\'',
5067 # RT6628, add order_date to cust_pkg
5068 'update cust_pkg set order_date = (select history_date from h_cust_pkg
5069 where h_cust_pkg.pkgnum = cust_pkg.pkgnum and
5070 history_action = \'insert\') where order_date is null',
5072 foreach my $sql (@statements) {
5073 my $sth = dbh->prepare($sql);
5074 $sth->execute or die $sth->errstr;
5082 sub order is not OO. Perhaps it should be moved to FS::cust_main and made so?
5084 In sub order, the @pkgparts array (passed by reference) is clobbered.
5086 Also in sub order, no money is adjusted. Once FS::part_pkg defines a standard
5087 method to pass dates to the recur_prog expression, it should do so.
5089 FS::svc_acct, FS::svc_domain, FS::svc_www, FS::svc_ip and FS::svc_forward are
5090 loaded via 'use' at compile time, rather than via 'require' in sub { setup,
5091 suspend, unsuspend, cancel } because they use %FS::UID::callback to load
5092 configuration values. Probably need a subroutine which decides what to do
5093 based on whether or not we've fetched the user yet, rather than a hash. See
5094 FS::UID and the TODO.
5096 Now that things are transactional should the check in the insert method be
5101 L<FS::Record>, L<FS::cust_main>, L<FS::part_pkg>, L<FS::cust_svc>,
5102 L<FS::pkg_svc>, schema.html from the base documentation