4 use base qw( FS::otaker_Mixin FS::cust_main_Mixin
5 FS::contact_Mixin FS::location_Mixin
6 FS::m2m_Common FS::option_Common );
7 use vars qw($disable_agentcheck $DEBUG $me);
9 use Scalar::Util qw( blessed );
10 use List::Util qw(min max);
12 use Time::Local qw( timelocal timelocal_nocheck );
14 use FS::UID qw( dbh driver_name );
15 use FS::Misc qw( send_email );
16 use FS::Record qw( qsearch qsearchs fields );
22 use FS::cust_location;
24 use FS::cust_bill_pkg;
25 use FS::cust_pkg_detail;
26 use FS::cust_pkg_usage;
27 use FS::cdr_cust_pkg_usage;
32 use FS::cust_pkg_reason;
34 use FS::cust_pkg_discount;
39 # need to 'use' these instead of 'require' in sub { cancel, suspend, unsuspend,
41 # because they load configuration by setting FS::UID::callback (see TODO)
47 # for sending cancel emails in sub cancel
51 $me = '[FS::cust_pkg]';
53 $disable_agentcheck = 0;
57 my ( $hashref, $cache ) = @_;
58 #if ( $hashref->{'pkgpart'} ) {
59 if ( $hashref->{'pkg'} ) {
60 # #@{ $self->{'_pkgnum'} } = ();
61 # my $subcache = $cache->subcache('pkgpart', 'part_pkg');
62 # $self->{'_pkgpart'} = $subcache;
63 # #push @{ $self->{'_pkgnum'} },
64 # FS::part_pkg->new_or_cached($hashref, $subcache);
65 $self->{'_pkgpart'} = FS::part_pkg->new($hashref);
67 if ( exists $hashref->{'svcnum'} ) {
68 #@{ $self->{'_pkgnum'} } = ();
69 my $subcache = $cache->subcache('svcnum', 'cust_svc', $hashref->{pkgnum});
70 $self->{'_svcnum'} = $subcache;
71 #push @{ $self->{'_pkgnum'} },
72 FS::cust_svc->new_or_cached($hashref, $subcache) if $hashref->{svcnum};
78 FS::cust_pkg - Object methods for cust_pkg objects
84 $record = new FS::cust_pkg \%hash;
85 $record = new FS::cust_pkg { 'column' => 'value' };
87 $error = $record->insert;
89 $error = $new_record->replace($old_record);
91 $error = $record->delete;
93 $error = $record->check;
95 $error = $record->cancel;
97 $error = $record->suspend;
99 $error = $record->unsuspend;
101 $part_pkg = $record->part_pkg;
103 @labels = $record->labels;
105 $seconds = $record->seconds_since($timestamp);
107 $error = FS::cust_pkg::order( $custnum, \@pkgparts );
108 $error = FS::cust_pkg::order( $custnum, \@pkgparts, \@remove_pkgnums ] );
112 An FS::cust_pkg object represents a customer billing item. FS::cust_pkg
113 inherits from FS::Record. The following fields are currently supported:
119 Primary key (assigned automatically for new billing items)
123 Customer (see L<FS::cust_main>)
127 Billing item definition (see L<FS::part_pkg>)
131 Optional link to package location (see L<FS::location>)
135 date package was ordered (also remains same on changes)
147 date (next bill date)
175 order taker (see L<FS::access_user>)
179 If this field is set to 1, disables the automatic
180 unsuspension of this package when using the B<unsuspendauto> config option.
184 If not set, defaults to 1
188 Date of change from previous package
198 =item change_locationnum
206 The pkgnum of the package that this package is supplemental to, if any.
210 The package link (L<FS::part_pkg_link>) that defines this supplemental
211 package, if it is one.
215 Note: setup, last_bill, bill, adjourn, susp, expire, cancel and change_date
216 are specified as UNIX timestamps; see L<perlfunc/"time">. Also see
217 L<Time::Local> and L<Date::Parse> for conversion functions.
225 Create a new billing item. To add the item to the database, see L<"insert">.
229 sub table { 'cust_pkg'; }
230 sub cust_linked { $_[0]->cust_main_custnum || $_[0]->custnum }
231 sub cust_unlinked_msg {
233 "WARNING: can't find cust_main.custnum ". $self->custnum.
234 ' (cust_pkg.pkgnum '. $self->pkgnum. ')';
237 =item insert [ OPTION => VALUE ... ]
239 Adds this billing item to the database ("Orders" the item). If there is an
240 error, returns the error, otherwise returns false.
242 If the additional field I<promo_code> is defined instead of I<pkgpart>, it
243 will be used to look up the package definition and agent restrictions will be
246 If the additional field I<refnum> is defined, an FS::pkg_referral record will
247 be created and inserted. Multiple FS::pkg_referral records can be created by
248 setting I<refnum> to an array reference of refnums or a hash reference with
249 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
250 record will be created corresponding to cust_main.refnum.
252 The following options are available:
258 If set true, supresses actions that should only be taken for new package
259 orders. (Currently this includes: intro periods when delay_setup is on.)
263 cust_pkg_option records will be created
267 a ticket will be added to this customer with this subject
271 an optional queue name for ticket additions
275 Don't check the legality of the package definition. This should be used
276 when performing a package change that doesn't change the pkgpart (i.e.
284 my( $self, %options ) = @_;
287 $error = $self->check_pkgpart unless $options{'allow_pkgpart'};
288 return $error if $error;
290 my $part_pkg = $self->part_pkg;
292 # if the package def says to start only on the first of the month:
293 if ( $part_pkg->option('start_1st', 1) && !$self->start_date ) {
294 my ($sec,$min,$hour,$mday,$mon,$year) = (localtime(time) )[0,1,2,3,4,5];
295 $mon += 1 unless $mday == 1;
296 until ( $mon < 12 ) { $mon -= 12; $year++; }
297 $self->start_date( timelocal_nocheck(0,0,0,1,$mon,$year) );
300 # set up any automatic expire/adjourn/contract_end timers
301 # based on the start date
302 foreach my $action ( qw(expire adjourn contract_end) ) {
303 my $months = $part_pkg->option("${action}_months",1);
304 if($months and !$self->$action) {
305 my $start = $self->start_date || $self->setup || time;
306 $self->$action( $part_pkg->add_freq($start, $months) );
310 # if this package has "free days" and delayed setup fee, tehn
311 # set start date that many days in the future.
312 # (this should have been set in the UI, but enforce it here)
313 if ( ! $options{'change'}
314 && ( my $free_days = $part_pkg->option('free_days',1) )
315 && $part_pkg->option('delay_setup',1)
316 #&& ! $self->start_date
319 $self->start_date( $part_pkg->default_start_date );
322 $self->order_date(time);
324 local $SIG{HUP} = 'IGNORE';
325 local $SIG{INT} = 'IGNORE';
326 local $SIG{QUIT} = 'IGNORE';
327 local $SIG{TERM} = 'IGNORE';
328 local $SIG{TSTP} = 'IGNORE';
329 local $SIG{PIPE} = 'IGNORE';
331 my $oldAutoCommit = $FS::UID::AutoCommit;
332 local $FS::UID::AutoCommit = 0;
335 $error = $self->SUPER::insert($options{options} ? %{$options{options}} : ());
337 $dbh->rollback if $oldAutoCommit;
341 $self->refnum($self->cust_main->refnum) unless $self->refnum;
342 $self->refnum( [ $self->refnum ] ) unless ref($self->refnum);
343 $self->process_m2m( 'link_table' => 'pkg_referral',
344 'target_table' => 'part_referral',
345 'params' => $self->refnum,
348 if ( $self->discountnum ) {
349 my $error = $self->insert_discount();
351 $dbh->rollback if $oldAutoCommit;
356 #if ( $self->reg_code ) {
357 # my $reg_code = qsearchs('reg_code', { 'code' => $self->reg_code } );
358 # $error = $reg_code->delete;
360 # $dbh->rollback if $oldAutoCommit;
365 my $conf = new FS::Conf;
367 if ( $conf->config('ticket_system') && $options{ticket_subject} ) {
369 #this init stuff is still inefficient, but at least its limited to
370 # the small number (any?) folks using ticket emailing on pkg order
373 # use lib ( "/opt/rt3/local/lib", "/opt/rt3/lib" );
380 use FS::TicketSystem;
381 FS::TicketSystem->init();
383 my $q = new RT::Queue($RT::SystemUser);
384 $q->Load($options{ticket_queue}) if $options{ticket_queue};
385 my $t = new RT::Ticket($RT::SystemUser);
386 my $mime = new MIME::Entity;
387 $mime->build( Type => 'text/plain', Data => $options{ticket_subject} );
388 $t->Create( $options{ticket_queue} ? (Queue => $q) : (),
389 Subject => $options{ticket_subject},
392 $t->AddLink( Type => 'MemberOf',
393 Target => 'freeside://freeside/cust_main/'. $self->custnum,
397 if ($conf->config('welcome_letter') && $self->cust_main->num_pkgs == 1) {
398 my $queue = new FS::queue {
399 'job' => 'FS::cust_main::queueable_print',
401 $error = $queue->insert(
402 'custnum' => $self->custnum,
403 'template' => 'welcome_letter',
407 warn "can't send welcome letter: $error";
412 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
419 This method now works but you probably shouldn't use it.
421 You don't want to delete packages, because there would then be no record
422 the customer ever purchased the package. Instead, see the cancel method and
423 hide cancelled packages.
430 local $SIG{HUP} = 'IGNORE';
431 local $SIG{INT} = 'IGNORE';
432 local $SIG{QUIT} = 'IGNORE';
433 local $SIG{TERM} = 'IGNORE';
434 local $SIG{TSTP} = 'IGNORE';
435 local $SIG{PIPE} = 'IGNORE';
437 my $oldAutoCommit = $FS::UID::AutoCommit;
438 local $FS::UID::AutoCommit = 0;
441 foreach my $cust_pkg_discount ($self->cust_pkg_discount) {
442 my $error = $cust_pkg_discount->delete;
444 $dbh->rollback if $oldAutoCommit;
448 #cust_bill_pkg_discount?
450 foreach my $cust_pkg_detail ($self->cust_pkg_detail) {
451 my $error = $cust_pkg_detail->delete;
453 $dbh->rollback if $oldAutoCommit;
458 foreach my $cust_pkg_reason (
460 'table' => 'cust_pkg_reason',
461 'hashref' => { 'pkgnum' => $self->pkgnum },
465 my $error = $cust_pkg_reason->delete;
467 $dbh->rollback if $oldAutoCommit;
474 my $error = $self->SUPER::delete(@_);
476 $dbh->rollback if $oldAutoCommit;
480 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
486 =item replace [ OLD_RECORD ] [ HASHREF | OPTION => VALUE ... ]
488 Replaces the OLD_RECORD with this one in the database. If there is an error,
489 returns the error, otherwise returns false.
491 Currently, custnum, setup, bill, adjourn, susp, expire, and cancel may be changed.
493 Changing pkgpart may have disasterous effects. See the order subroutine.
495 setup and bill are normally updated by calling the bill method of a customer
496 object (see L<FS::cust_main>).
498 suspend is normally updated by the suspend and unsuspend methods.
500 cancel is normally updated by the cancel method (and also the order subroutine
503 Available options are:
509 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.
513 the access_user (see L<FS::access_user>) providing the reason
517 hashref of keys and values - cust_pkg_option records will be created, updated or removed as appopriate
526 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
531 ( ref($_[0]) eq 'HASH' )
535 #return "Can't (yet?) change pkgpart!" if $old->pkgpart != $new->pkgpart;
536 #return "Can't change otaker!" if $old->otaker ne $new->otaker;
539 #return "Can't change setup once it exists!"
540 # if $old->getfield('setup') &&
541 # $old->getfield('setup') != $new->getfield('setup');
543 #some logic for bill, susp, cancel?
545 local($disable_agentcheck) = 1 if $old->pkgpart == $new->pkgpart;
547 local $SIG{HUP} = 'IGNORE';
548 local $SIG{INT} = 'IGNORE';
549 local $SIG{QUIT} = 'IGNORE';
550 local $SIG{TERM} = 'IGNORE';
551 local $SIG{TSTP} = 'IGNORE';
552 local $SIG{PIPE} = 'IGNORE';
554 my $oldAutoCommit = $FS::UID::AutoCommit;
555 local $FS::UID::AutoCommit = 0;
558 foreach my $method ( qw(adjourn expire) ) { # How many reasons?
559 if ($options->{'reason'} && $new->$method && $old->$method ne $new->$method) {
560 my $error = $new->insert_reason(
561 'reason' => $options->{'reason'},
562 'date' => $new->$method,
564 'reason_otaker' => $options->{'reason_otaker'},
567 dbh->rollback if $oldAutoCommit;
568 return "Error inserting cust_pkg_reason: $error";
573 #save off and freeze RADIUS attributes for any associated svc_acct records
575 if ( $old->part_pkg->is_prepaid || $new->part_pkg->is_prepaid ) {
577 #also check for specific exports?
578 # to avoid spurious modify export events
579 @svc_acct = map { $_->svc_x }
580 grep { $_->part_svc->svcdb eq 'svc_acct' }
583 $_->snapshot foreach @svc_acct;
587 my $error = $new->export_pkg_change($old)
588 || $new->SUPER::replace( $old,
590 ? $options->{options}
594 $dbh->rollback if $oldAutoCommit;
598 #for prepaid packages,
599 #trigger export of new RADIUS Expiration attribute when cust_pkg.bill changes
600 foreach my $old_svc_acct ( @svc_acct ) {
601 my $new_svc_acct = new FS::svc_acct { $old_svc_acct->hash };
603 $new_svc_acct->replace( $old_svc_acct,
604 'depend_jobnum' => $options->{depend_jobnum},
607 $dbh->rollback if $oldAutoCommit;
612 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
619 Checks all fields to make sure this is a valid billing item. If there is an
620 error, returns the error, otherwise returns false. Called by the insert and
628 if ( !$self->locationnum or $self->locationnum == -1 ) {
629 $self->set('locationnum', $self->cust_main->ship_locationnum);
633 $self->ut_numbern('pkgnum')
634 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum')
635 || $self->ut_numbern('pkgpart')
636 || $self->ut_foreign_keyn('contactnum', 'contact', 'contactnum' )
637 || $self->ut_foreign_keyn('locationnum', 'cust_location', 'locationnum')
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')
655 return $error if $error;
657 return "A package with both start date (future start) and setup date (already started) will never bill"
658 if $self->start_date && $self->setup;
660 return "A future unsuspend date can only be set for a package with a suspend date"
661 if $self->resume and !$self->susp and !$self->adjourn;
663 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
665 if ( $self->dbdef_table->column('manual_flag') ) {
666 $self->manual_flag('') if $self->manual_flag eq ' ';
667 $self->manual_flag =~ /^([01]?)$/
668 or return "Illegal manual_flag ". $self->manual_flag;
669 $self->manual_flag($1);
677 Check the pkgpart to make sure it's allowed with the reg_code and/or
678 promo_code of the package (if present) and with the customer's agent.
679 Called from C<insert>, unless we are doing a package change that doesn't
687 # my $error = $self->ut_numbern('pkgpart'); # already done
690 if ( $self->reg_code ) {
692 unless ( grep { $self->pkgpart == $_->pkgpart }
693 map { $_->reg_code_pkg }
694 qsearchs( 'reg_code', { 'code' => $self->reg_code,
695 'agentnum' => $self->cust_main->agentnum })
697 return "Unknown registration code";
700 } elsif ( $self->promo_code ) {
703 qsearchs('part_pkg', {
704 'pkgpart' => $self->pkgpart,
705 'promo_code' => { op=>'ILIKE', value=>$self->promo_code },
707 return 'Unknown promotional code' unless $promo_part_pkg;
711 unless ( $disable_agentcheck ) {
713 qsearchs( 'agent', { 'agentnum' => $self->cust_main->agentnum } );
714 return "agent ". $agent->agentnum. ':'. $agent->agent.
715 " can't purchase pkgpart ". $self->pkgpart
716 unless $agent->pkgpart_hashref->{ $self->pkgpart }
717 || $agent->agentnum == $self->part_pkg->agentnum;
720 $error = $self->ut_foreign_key('pkgpart', 'part_pkg', 'pkgpart' );
721 return $error if $error;
729 =item cancel [ OPTION => VALUE ... ]
731 Cancels and removes all services (see L<FS::cust_svc> and L<FS::part_svc>)
732 in this package, then cancels the package itself (sets the cancel field to
735 Available options are:
739 =item quiet - can be set true to supress email cancellation notices.
741 =item time - can be set to cancel the package based on a specific future or
742 historical date. Using time ensures that the remaining amount is calculated
743 correctly. Note however that this is an immediate cancel and just changes
744 the date. You are PROBABLY looking to expire the account instead of using
747 =item reason - can be set to a cancellation reason (see L<FS:reason>),
748 either a reasonnum of an existing reason, or passing a hashref will create
749 a new reason. The hashref should have the following keys: typenum - Reason
750 type (see L<FS::reason_type>, reason - Text of the new reason.
752 =item date - can be set to a unix style timestamp to specify when to
755 =item nobill - can be set true to skip billing if it might otherwise be done.
757 =item unused_credit - can be set to 1 to credit the remaining time, or 0 to
758 not credit it. This must be set (by change()) when changing the package
759 to a different pkgpart or location, and probably shouldn't be in any other
760 case. If it's not set, the 'unused_credit_cancel' part_pkg option will
765 If there is an error, returns the error, otherwise returns false.
770 my( $self, %options ) = @_;
773 # pass all suspend/cancel actions to the main package
774 if ( $self->main_pkgnum and !$options{'from_main'} ) {
775 return $self->main_pkg->cancel(%options);
778 my $conf = new FS::Conf;
780 warn "cust_pkg::cancel called with options".
781 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
784 local $SIG{HUP} = 'IGNORE';
785 local $SIG{INT} = 'IGNORE';
786 local $SIG{QUIT} = 'IGNORE';
787 local $SIG{TERM} = 'IGNORE';
788 local $SIG{TSTP} = 'IGNORE';
789 local $SIG{PIPE} = 'IGNORE';
791 my $oldAutoCommit = $FS::UID::AutoCommit;
792 local $FS::UID::AutoCommit = 0;
795 my $old = $self->select_for_update;
797 if ( $old->get('cancel') || $self->get('cancel') ) {
798 dbh->rollback if $oldAutoCommit;
799 return ""; # no error
802 # XXX possibly set cancel_time to the expire date?
803 my $cancel_time = $options{'time'} || time;
804 my $date = $options{'date'} if $options{'date'}; # expire/cancel later
805 $date = '' if ($date && $date <= $cancel_time); # complain instead?
807 #race condition: usage could be ongoing until unprovisioned
808 #resolved by performing a change package instead (which unprovisions) and
810 if ( !$options{nobill} && !$date ) {
811 # && $conf->exists('bill_usage_on_cancel') ) { #calc_cancel checks this
812 my $copy = $self->new({$self->hash});
814 $copy->cust_main->bill( 'pkg_list' => [ $copy ],
816 'time' => $cancel_time );
817 warn "Error billing during cancel, custnum ".
818 #$self->cust_main->custnum. ": $error"
823 if ( $options{'reason'} ) {
824 $error = $self->insert_reason( 'reason' => $options{'reason'},
825 'action' => $date ? 'expire' : 'cancel',
826 'date' => $date ? $date : $cancel_time,
827 'reason_otaker' => $options{'reason_otaker'},
830 dbh->rollback if $oldAutoCommit;
831 return "Error inserting cust_pkg_reason: $error";
835 my %svc_cancel_opt = ();
836 $svc_cancel_opt{'date'} = $date if $date;
837 foreach my $cust_svc (
840 sort { $a->[1] <=> $b->[1] }
841 map { [ $_, $_->svc_x ? $_->svc_x->table_info->{'cancel_weight'} : -1 ]; }
842 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
844 my $part_svc = $cust_svc->part_svc;
845 next if ( defined($part_svc) and $part_svc->preserve );
846 my $error = $cust_svc->cancel( %svc_cancel_opt );
849 $dbh->rollback if $oldAutoCommit;
850 return 'Error '. ($svc_cancel_opt{'date'} ? 'expiring' : 'canceling' ).
856 # credit remaining time if appropriate
858 if ( exists($options{'unused_credit'}) ) {
859 $do_credit = $options{'unused_credit'};
862 $do_credit = $self->part_pkg->option('unused_credit_cancel', 1);
865 my $error = $self->credit_remaining('cancel', $cancel_time);
867 $dbh->rollback if $oldAutoCommit;
874 my %hash = $self->hash;
875 $date ? ($hash{'expire'} = $date) : ($hash{'cancel'} = $cancel_time);
876 $hash{'change_custnum'} = $options{'change_custnum'};
877 my $new = new FS::cust_pkg ( \%hash );
878 $error = $new->replace( $self, options => { $self->options } );
880 $dbh->rollback if $oldAutoCommit;
884 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
885 $error = $supp_pkg->cancel(%options, 'from_main' => 1);
887 $dbh->rollback if $oldAutoCommit;
888 return "canceling supplemental pkg#".$supp_pkg->pkgnum.": $error";
892 foreach my $usage ( $self->cust_pkg_usage ) {
893 $error = $usage->delete;
895 $dbh->rollback if $oldAutoCommit;
896 return "deleting usage pools: $error";
900 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
901 return '' if $date; #no errors
903 my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ } $self->cust_main->invoicing_list;
904 if ( !$options{'quiet'} &&
905 $conf->exists('emailcancel', $self->cust_main->agentnum) &&
907 my $msgnum = $conf->config('cancel_msgnum', $self->cust_main->agentnum);
910 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum });
911 $error = $msg_template->send( 'cust_main' => $self->cust_main,
916 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
917 'to' => \@invoicing_list,
918 'subject' => ( $conf->config('cancelsubject') || 'Cancellation Notice' ),
919 'body' => [ map "$_\n", $conf->config('cancelmessage') ],
922 #should this do something on errors?
929 =item cancel_if_expired [ NOW_TIMESTAMP ]
931 Cancels this package if its expire date has been reached.
935 sub cancel_if_expired {
937 my $time = shift || time;
938 return '' unless $self->expire && $self->expire <= $time;
939 my $error = $self->cancel;
941 return "Error cancelling expired pkg ". $self->pkgnum. " for custnum ".
942 $self->custnum. ": $error";
949 "Un-cancels" this package: Orders a new package with the same custnum, pkgpart,
950 locationnum, (other fields?). Attempts to re-provision cancelled services
951 using history information (errors at this stage are not fatal).
953 cust_pkg: pass a scalar reference, will be filled in with the new cust_pkg object
955 svc_fatal: service provisioning errors are fatal
957 svc_errors: pass an array reference, will be filled in with any provisioning errors
959 main_pkgnum: link the package as a supplemental package of this one. For
965 my( $self, %options ) = @_;
967 #in case you try do do $uncancel-date = $cust_pkg->uncacel
968 return '' unless $self->get('cancel');
970 if ( $self->main_pkgnum and !$options{'main_pkgnum'} ) {
971 return $self->main_pkg->uncancel(%options);
978 local $SIG{HUP} = 'IGNORE';
979 local $SIG{INT} = 'IGNORE';
980 local $SIG{QUIT} = 'IGNORE';
981 local $SIG{TERM} = 'IGNORE';
982 local $SIG{TSTP} = 'IGNORE';
983 local $SIG{PIPE} = 'IGNORE';
985 my $oldAutoCommit = $FS::UID::AutoCommit;
986 local $FS::UID::AutoCommit = 0;
990 # insert the new package
993 my $cust_pkg = new FS::cust_pkg {
994 last_bill => ( $options{'last_bill'} || $self->get('last_bill') ),
995 bill => ( $options{'bill'} || $self->get('bill') ),
997 uncancel_pkgnum => $self->pkgnum,
998 main_pkgnum => ($options{'main_pkgnum'} || ''),
999 map { $_ => $self->get($_) } qw(
1000 custnum pkgpart locationnum
1002 susp adjourn resume expire start_date contract_end dundate
1003 change_date change_pkgpart change_locationnum
1004 manual_flag no_auto quantity agent_pkgid recur_show_zero setup_show_zero
1008 my $error = $cust_pkg->insert(
1009 'change' => 1, #supresses any referral credit to a referring customer
1010 'allow_pkgpart' => 1, # allow this even if the package def is disabled
1013 $dbh->rollback if $oldAutoCommit;
1021 #find historical services within this timeframe before the package cancel
1022 # (incompatible with "time" option to cust_pkg->cancel?)
1023 my $fuzz = 2 * 60; #2 minutes? too much? (might catch separate unprovision)
1024 # too little? (unprovisioing export delay?)
1025 my($end, $start) = ( $self->get('cancel'), $self->get('cancel') - $fuzz );
1026 my @h_cust_svc = $self->h_cust_svc( $end, $start );
1029 foreach my $h_cust_svc (@h_cust_svc) {
1030 my $h_svc_x = $h_cust_svc->h_svc_x( $end, $start );
1031 #next unless $h_svc_x; #should this happen?
1032 (my $table = $h_svc_x->table) =~ s/^h_//;
1033 require "FS/$table.pm";
1034 my $class = "FS::$table";
1035 my $svc_x = $class->new( {
1036 'pkgnum' => $cust_pkg->pkgnum,
1037 'svcpart' => $h_cust_svc->svcpart,
1038 map { $_ => $h_svc_x->get($_) } fields($table)
1042 if ( $h_svc_x->isa('FS::h_svc_Radius_Mixin') ) {
1043 $svc_x->usergroup( [ $h_svc_x->h_usergroup($end, $start) ] );
1046 my $svc_error = $svc_x->insert;
1048 if ( $options{svc_fatal} ) {
1049 $dbh->rollback if $oldAutoCommit;
1052 # if we've failed to insert the svc_x object, svc_Common->insert
1053 # will have removed the cust_svc already. if not, then both records
1054 # were inserted but we failed for some other reason (export, most
1055 # likely). in that case, report the error and delete the records.
1056 push @svc_errors, $svc_error;
1057 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svc_x->svcnum });
1059 # except if export_insert failed, export_delete probably won't be
1061 local $FS::svc_Common::noexport_hack = 1;
1062 my $cleanup_error = $svc_x->delete; # also deletes cust_svc
1063 if ( $cleanup_error ) { # and if THAT fails, then run away
1064 $dbh->rollback if $oldAutoCommit;
1065 return $cleanup_error;
1070 } #foreach $h_cust_svc
1072 #these are pretty rare, but should handle them
1073 # - dsl_device (mac addresses)
1074 # - phone_device (mac addresses)
1075 # - dsl_note (ikano notes)
1076 # - domain_record (i.e. restore DNS information w/domains)
1077 # - inventory_item(?) (inventory w/un-cancelling service?)
1078 # - nas (svc_broaband nas stuff)
1079 #this stuff is unused in the wild afaik
1080 # - mailinglistmember
1082 # - svc_domain.parent_svcnum?
1083 # - acct_snarf (ancient mail fetching config)
1084 # - cgp_rule (communigate)
1085 # - cust_svc_option (used by our Tron stuff)
1086 # - acct_rt_transaction (used by our time worked stuff)
1089 # also move over any services that didn't unprovision at cancellation
1092 foreach my $cust_svc ( qsearch('cust_svc', { pkgnum => $self->pkgnum } ) ) {
1093 $cust_svc->pkgnum( $cust_pkg->pkgnum );
1094 my $error = $cust_svc->replace;
1096 $dbh->rollback if $oldAutoCommit;
1102 # Uncancel any supplemental packages, and make them supplemental to the
1106 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1108 $error = $supp_pkg->uncancel(%options, 'main_pkgnum' => $cust_pkg->pkgnum);
1110 $dbh->rollback if $oldAutoCommit;
1111 return "canceling supplemental pkg#".$supp_pkg->pkgnum.": $error";
1119 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1121 ${ $options{cust_pkg} } = $cust_pkg if ref($options{cust_pkg});
1122 @{ $options{svc_errors} } = @svc_errors if ref($options{svc_errors});
1129 Cancels any pending expiration (sets the expire field to null).
1131 If there is an error, returns the error, otherwise returns false.
1136 my( $self, %options ) = @_;
1139 local $SIG{HUP} = 'IGNORE';
1140 local $SIG{INT} = 'IGNORE';
1141 local $SIG{QUIT} = 'IGNORE';
1142 local $SIG{TERM} = 'IGNORE';
1143 local $SIG{TSTP} = 'IGNORE';
1144 local $SIG{PIPE} = 'IGNORE';
1146 my $oldAutoCommit = $FS::UID::AutoCommit;
1147 local $FS::UID::AutoCommit = 0;
1150 my $old = $self->select_for_update;
1152 my $pkgnum = $old->pkgnum;
1153 if ( $old->get('cancel') || $self->get('cancel') ) {
1154 dbh->rollback if $oldAutoCommit;
1155 return "Can't unexpire cancelled package $pkgnum";
1156 # or at least it's pointless
1159 unless ( $old->get('expire') && $self->get('expire') ) {
1160 dbh->rollback if $oldAutoCommit;
1161 return ""; # no error
1164 my %hash = $self->hash;
1165 $hash{'expire'} = '';
1166 my $new = new FS::cust_pkg ( \%hash );
1167 $error = $new->replace( $self, options => { $self->options } );
1169 $dbh->rollback if $oldAutoCommit;
1173 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1179 =item suspend [ OPTION => VALUE ... ]
1181 Suspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
1182 package, then suspends the package itself (sets the susp field to now).
1184 Available options are:
1188 =item reason - can be set to a cancellation reason (see L<FS:reason>),
1189 either a reasonnum of an existing reason, or passing a hashref will create
1190 a new reason. The hashref should have the following keys:
1191 - typenum - Reason type (see L<FS::reason_type>
1192 - reason - Text of the new reason.
1194 =item date - can be set to a unix style timestamp to specify when to
1197 =item time - can be set to override the current time, for calculation
1198 of final invoices or unused-time credits
1200 =item resume_date - can be set to a time when the package should be
1201 unsuspended. This may be more convenient than calling C<unsuspend()>
1204 =item from_main - allows a supplemental package to be suspended, rather
1205 than redirecting the method call to its main package. For internal use.
1209 If there is an error, returns the error, otherwise returns false.
1214 my( $self, %options ) = @_;
1217 # pass all suspend/cancel actions to the main package
1218 if ( $self->main_pkgnum and !$options{'from_main'} ) {
1219 return $self->main_pkg->suspend(%options);
1222 local $SIG{HUP} = 'IGNORE';
1223 local $SIG{INT} = 'IGNORE';
1224 local $SIG{QUIT} = 'IGNORE';
1225 local $SIG{TERM} = 'IGNORE';
1226 local $SIG{TSTP} = 'IGNORE';
1227 local $SIG{PIPE} = 'IGNORE';
1229 my $oldAutoCommit = $FS::UID::AutoCommit;
1230 local $FS::UID::AutoCommit = 0;
1233 my $old = $self->select_for_update;
1235 my $pkgnum = $old->pkgnum;
1236 if ( $old->get('cancel') || $self->get('cancel') ) {
1237 dbh->rollback if $oldAutoCommit;
1238 return "Can't suspend cancelled package $pkgnum";
1241 if ( $old->get('susp') || $self->get('susp') ) {
1242 dbh->rollback if $oldAutoCommit;
1243 return ""; # no error # complain on adjourn?
1246 my $suspend_time = $options{'time'} || time;
1247 my $date = $options{date} if $options{date}; # adjourn/suspend later
1248 $date = '' if ($date && $date <= $suspend_time); # complain instead?
1250 if ( $date && $old->get('expire') && $old->get('expire') < $date ) {
1251 dbh->rollback if $oldAutoCommit;
1252 return "Package $pkgnum expires before it would be suspended.";
1255 # some false laziness with sub cancel
1256 if ( !$options{nobill} && !$date &&
1257 $self->part_pkg->option('bill_suspend_as_cancel',1) ) {
1258 # kind of a kludge--'bill_suspend_as_cancel' to avoid having to
1259 # make the entire cust_main->bill path recognize 'suspend' and
1260 # 'cancel' separately.
1261 warn "Billing $pkgnum on suspension (at $suspend_time)\n" if $DEBUG;
1262 my $copy = $self->new({$self->hash});
1264 $copy->cust_main->bill( 'pkg_list' => [ $copy ],
1266 'time' => $suspend_time );
1267 warn "Error billing during suspend, custnum ".
1268 #$self->cust_main->custnum. ": $error"
1273 if ( $options{'reason'} ) {
1274 $error = $self->insert_reason( 'reason' => $options{'reason'},
1275 'action' => $date ? 'adjourn' : 'suspend',
1276 'date' => $date ? $date : $suspend_time,
1277 'reason_otaker' => $options{'reason_otaker'},
1280 dbh->rollback if $oldAutoCommit;
1281 return "Error inserting cust_pkg_reason: $error";
1285 my %hash = $self->hash;
1287 $hash{'adjourn'} = $date;
1289 $hash{'susp'} = $suspend_time;
1292 my $resume_date = $options{'resume_date'} || 0;
1293 if ( $resume_date > ($date || $suspend_time) ) {
1294 $hash{'resume'} = $resume_date;
1297 $options{options} ||= {};
1299 my $new = new FS::cust_pkg ( \%hash );
1300 $error = $new->replace( $self, options => { $self->options,
1301 %{ $options{options} },
1305 $dbh->rollback if $oldAutoCommit;
1310 # credit remaining time if appropriate
1311 if ( $self->part_pkg->option('unused_credit_suspend', 1) ) {
1312 my $error = $self->credit_remaining('suspend', $suspend_time);
1314 $dbh->rollback if $oldAutoCommit;
1321 foreach my $cust_svc (
1322 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
1324 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
1326 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
1327 $dbh->rollback if $oldAutoCommit;
1328 return "Illegal svcdb value in part_svc!";
1331 require "FS/$svcdb.pm";
1333 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
1335 $error = $svc->suspend;
1337 $dbh->rollback if $oldAutoCommit;
1340 my( $label, $value ) = $cust_svc->label;
1341 push @labels, "$label: $value";
1345 my $conf = new FS::Conf;
1346 if ( $conf->config('suspend_email_admin') ) {
1348 my $error = send_email(
1349 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
1350 #invoice_from ??? well as good as any
1351 'to' => $conf->config('suspend_email_admin'),
1352 'subject' => 'FREESIDE NOTIFICATION: Customer package suspended',
1354 "This is an automatic message from your Freeside installation\n",
1355 "informing you that the following customer package has been suspended:\n",
1357 'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
1358 'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
1359 ( map { "Service : $_\n" } @labels ),
1364 warn "WARNING: can't send suspension admin email (suspending anyway): ".
1372 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1373 $error = $supp_pkg->suspend(%options, 'from_main' => 1);
1375 $dbh->rollback if $oldAutoCommit;
1376 return "suspending supplemental pkg#".$supp_pkg->pkgnum.": $error";
1380 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1385 =item credit_remaining MODE TIME
1387 Generate a credit for this package for the time remaining in the current
1388 billing period. MODE is either "suspend" or "cancel" (determines the
1389 credit type). TIME is the time of suspension/cancellation. Both arguments
1394 sub credit_remaining {
1395 # Add a credit for remaining service
1396 my ($self, $mode, $time) = @_;
1397 die 'credit_remaining requires suspend or cancel'
1398 unless $mode eq 'suspend' or $mode eq 'cancel';
1399 die 'no suspend/cancel time' unless $time > 0;
1401 my $conf = FS::Conf->new;
1402 my $reason_type = $conf->config($mode.'_credit_type');
1404 my $last_bill = $self->getfield('last_bill') || 0;
1405 my $next_bill = $self->getfield('bill') || 0;
1406 if ( $last_bill > 0 # the package has been billed
1407 and $next_bill > 0 # the package has a next bill date
1408 and $next_bill >= $time # which is in the future
1410 my $remaining_value = $self->calc_remain('time' => $time);
1411 if ( $remaining_value > 0 ) {
1412 warn "Crediting for $remaining_value on package ".$self->pkgnum."\n"
1414 my $error = $self->cust_main->credit(
1416 'Credit for unused time on '. $self->part_pkg->pkg,
1417 'reason_type' => $reason_type,
1419 return "Error crediting customer \$$remaining_value for unused time".
1420 " on ". $self->part_pkg->pkg. ": $error"
1422 } #if $remaining_value
1423 } #if $last_bill, etc.
1427 =item unsuspend [ OPTION => VALUE ... ]
1429 Unsuspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
1430 package, then unsuspends the package itself (clears the susp field and the
1431 adjourn field if it is in the past). If the suspend reason includes an
1432 unsuspension package, that package will be ordered.
1434 Available options are:
1440 Can be set to a date to unsuspend the package in the future (the 'resume'
1443 =item adjust_next_bill
1445 Can be set true to adjust the next bill date forward by
1446 the amount of time the account was inactive. This was set true by default
1447 since 1.4.2 and 1.5.0pre6; however, starting with 1.7.0 this needs to be
1448 explicitly requested. Price plans for which this makes sense (anniversary-date
1449 based than prorate or subscription) could have an option to enable this
1454 If there is an error, returns the error, otherwise returns false.
1459 my( $self, %opt ) = @_;
1462 # pass all suspend/cancel actions to the main package
1463 if ( $self->main_pkgnum and !$opt{'from_main'} ) {
1464 return $self->main_pkg->unsuspend(%opt);
1467 local $SIG{HUP} = 'IGNORE';
1468 local $SIG{INT} = 'IGNORE';
1469 local $SIG{QUIT} = 'IGNORE';
1470 local $SIG{TERM} = 'IGNORE';
1471 local $SIG{TSTP} = 'IGNORE';
1472 local $SIG{PIPE} = 'IGNORE';
1474 my $oldAutoCommit = $FS::UID::AutoCommit;
1475 local $FS::UID::AutoCommit = 0;
1478 my $old = $self->select_for_update;
1480 my $pkgnum = $old->pkgnum;
1481 if ( $old->get('cancel') || $self->get('cancel') ) {
1482 $dbh->rollback if $oldAutoCommit;
1483 return "Can't unsuspend cancelled package $pkgnum";
1486 unless ( $old->get('susp') && $self->get('susp') ) {
1487 $dbh->rollback if $oldAutoCommit;
1488 return ""; # no error # complain instead?
1491 my $date = $opt{'date'};
1492 if ( $date and $date > time ) { # return an error if $date <= time?
1494 if ( $old->get('expire') && $old->get('expire') < $date ) {
1495 $dbh->rollback if $oldAutoCommit;
1496 return "Package $pkgnum expires before it would be unsuspended.";
1499 my $new = new FS::cust_pkg { $self->hash };
1500 $new->set('resume', $date);
1501 $error = $new->replace($self, options => $self->options);
1504 $dbh->rollback if $oldAutoCommit;
1508 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1516 foreach my $cust_svc (
1517 qsearch('cust_svc',{'pkgnum'=> $self->pkgnum } )
1519 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
1521 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
1522 $dbh->rollback if $oldAutoCommit;
1523 return "Illegal svcdb value in part_svc!";
1526 require "FS/$svcdb.pm";
1528 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
1530 $error = $svc->unsuspend;
1532 $dbh->rollback if $oldAutoCommit;
1535 my( $label, $value ) = $cust_svc->label;
1536 push @labels, "$label: $value";
1541 my $cust_pkg_reason = $self->last_cust_pkg_reason('susp');
1542 my $reason = $cust_pkg_reason ? $cust_pkg_reason->reason : '';
1544 my %hash = $self->hash;
1545 my $inactive = time - $hash{'susp'};
1547 my $conf = new FS::Conf;
1549 if ( $inactive > 0 &&
1550 ( $hash{'bill'} || $hash{'setup'} ) &&
1551 ( $opt{'adjust_next_bill'} ||
1552 $conf->exists('unsuspend-always_adjust_next_bill_date') ||
1553 $self->part_pkg->option('unsuspend_adjust_bill', 1) )
1556 $hash{'bill'} = ( $hash{'bill'} || $hash{'setup'} ) + $inactive;
1561 $hash{'adjourn'} = '' if $hash{'adjourn'} and $hash{'adjourn'} < time;
1562 $hash{'resume'} = '' if !$hash{'adjourn'};
1563 my $new = new FS::cust_pkg ( \%hash );
1564 $error = $new->replace( $self, options => { $self->options } );
1566 $dbh->rollback if $oldAutoCommit;
1572 if ( $reason && $reason->unsuspend_pkgpart ) {
1573 my $part_pkg = FS::part_pkg->by_key($reason->unsuspend_pkgpart)
1574 or $error = "Unsuspend package definition ".$reason->unsuspend_pkgpart.
1576 my $start_date = $self->cust_main->next_bill_date
1577 if $reason->unsuspend_hold;
1580 $unsusp_pkg = FS::cust_pkg->new({
1581 'custnum' => $self->custnum,
1582 'pkgpart' => $reason->unsuspend_pkgpart,
1583 'start_date' => $start_date,
1584 'locationnum' => $self->locationnum,
1585 # discount? probably not...
1588 $error ||= $self->cust_main->order_pkg( 'cust_pkg' => $unsusp_pkg );
1592 $dbh->rollback if $oldAutoCommit;
1597 if ( $conf->config('unsuspend_email_admin') ) {
1599 my $error = send_email(
1600 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
1601 #invoice_from ??? well as good as any
1602 'to' => $conf->config('unsuspend_email_admin'),
1603 'subject' => 'FREESIDE NOTIFICATION: Customer package unsuspended', 'body' => [
1604 "This is an automatic message from your Freeside installation\n",
1605 "informing you that the following customer package has been unsuspended:\n",
1607 'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
1608 'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
1609 ( map { "Service : $_\n" } @labels ),
1611 "An unsuspension fee was charged: ".
1612 $unsusp_pkg->part_pkg->pkg_comment."\n"
1619 warn "WARNING: can't send unsuspension admin email (unsuspending anyway): ".
1625 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1626 $error = $supp_pkg->unsuspend(%opt, 'from_main' => 1);
1628 $dbh->rollback if $oldAutoCommit;
1629 return "unsuspending supplemental pkg#".$supp_pkg->pkgnum.": $error";
1633 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1640 Cancels any pending suspension (sets the adjourn field to null).
1642 If there is an error, returns the error, otherwise returns false.
1647 my( $self, %options ) = @_;
1650 local $SIG{HUP} = 'IGNORE';
1651 local $SIG{INT} = 'IGNORE';
1652 local $SIG{QUIT} = 'IGNORE';
1653 local $SIG{TERM} = 'IGNORE';
1654 local $SIG{TSTP} = 'IGNORE';
1655 local $SIG{PIPE} = 'IGNORE';
1657 my $oldAutoCommit = $FS::UID::AutoCommit;
1658 local $FS::UID::AutoCommit = 0;
1661 my $old = $self->select_for_update;
1663 my $pkgnum = $old->pkgnum;
1664 if ( $old->get('cancel') || $self->get('cancel') ) {
1665 dbh->rollback if $oldAutoCommit;
1666 return "Can't unadjourn cancelled package $pkgnum";
1667 # or at least it's pointless
1670 if ( $old->get('susp') || $self->get('susp') ) {
1671 dbh->rollback if $oldAutoCommit;
1672 return "Can't unadjourn suspended package $pkgnum";
1673 # perhaps this is arbitrary
1676 unless ( $old->get('adjourn') && $self->get('adjourn') ) {
1677 dbh->rollback if $oldAutoCommit;
1678 return ""; # no error
1681 my %hash = $self->hash;
1682 $hash{'adjourn'} = '';
1683 $hash{'resume'} = '';
1684 my $new = new FS::cust_pkg ( \%hash );
1685 $error = $new->replace( $self, options => { $self->options } );
1687 $dbh->rollback if $oldAutoCommit;
1691 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1698 =item change HASHREF | OPTION => VALUE ...
1700 Changes this package: cancels it and creates a new one, with a different
1701 pkgpart or locationnum or both. All services are transferred to the new
1702 package (no change will be made if this is not possible).
1704 Options may be passed as a list of key/value pairs or as a hash reference.
1711 New locationnum, to change the location for this package.
1715 New FS::cust_location object, to create a new location and assign it
1720 New FS::cust_main object, to create a new customer and assign the new package
1725 New pkgpart (see L<FS::part_pkg>).
1729 New refnum (see L<FS::part_referral>).
1733 Set to true to transfer billing dates (start_date, setup, last_bill, bill,
1734 susp, adjourn, cancel, expire, and contract_end) to the new package.
1738 At least one of locationnum, cust_location, pkgpart, refnum must be specified
1739 (otherwise, what's the point?)
1741 Returns either the new FS::cust_pkg object or a scalar error.
1745 my $err_or_new_cust_pkg = $old_cust_pkg->change
1749 #some false laziness w/order
1752 my $opt = ref($_[0]) ? shift : { @_ };
1754 # my ($custnum, $pkgparts, $remove_pkgnum, $return_cust_pkg, $refnum) = @_;
1757 my $conf = new FS::Conf;
1759 # Transactionize this whole mess
1760 local $SIG{HUP} = 'IGNORE';
1761 local $SIG{INT} = 'IGNORE';
1762 local $SIG{QUIT} = 'IGNORE';
1763 local $SIG{TERM} = 'IGNORE';
1764 local $SIG{TSTP} = 'IGNORE';
1765 local $SIG{PIPE} = 'IGNORE';
1767 my $oldAutoCommit = $FS::UID::AutoCommit;
1768 local $FS::UID::AutoCommit = 0;
1777 #$hash{$_} = $self->$_() foreach qw( last_bill bill );
1779 #$hash{$_} = $self->$_() foreach qw( setup );
1781 $hash{'setup'} = $time if $self->setup;
1783 $hash{'change_date'} = $time;
1784 $hash{"change_$_"} = $self->$_()
1785 foreach qw( pkgnum pkgpart locationnum );
1787 if ( $opt->{'cust_location'} ) {
1788 $error = $opt->{'cust_location'}->find_or_insert;
1790 $dbh->rollback if $oldAutoCommit;
1791 return "inserting cust_location (transaction rolled back): $error";
1793 $opt->{'locationnum'} = $opt->{'cust_location'}->locationnum;
1796 # whether to override pkgpart checking on the new package
1797 my $same_pkgpart = 1;
1798 if ( $opt->{'pkgpart'} and ( $opt->{'pkgpart'} != $self->pkgpart ) ) {
1802 my $unused_credit = 0;
1803 my $keep_dates = $opt->{'keep_dates'};
1804 # Special case. If the pkgpart is changing, and the customer is
1805 # going to be credited for remaining time, don't keep setup, bill,
1806 # or last_bill dates, and DO pass the flag to cancel() to credit
1808 if ( $opt->{'pkgpart'}
1809 and $opt->{'pkgpart'} != $self->pkgpart
1810 and $self->part_pkg->option('unused_credit_change', 1) ) {
1813 $hash{$_} = '' foreach qw(setup bill last_bill);
1816 if ( $keep_dates ) {
1817 foreach my $date ( qw(setup bill last_bill susp adjourn cancel expire
1818 resume start_date contract_end ) ) {
1819 $hash{$date} = $self->getfield($date);
1822 # allow $opt->{'locationnum'} = '' to specifically set it to null
1823 # (i.e. customer default location)
1824 $opt->{'locationnum'} = $self->locationnum if !exists($opt->{'locationnum'});
1826 # usually this doesn't matter. the two cases where it does are:
1827 # 1. unused_credit_change + pkgpart change + setup fee on the new package
1829 # 2. (more importantly) changing a package before it's billed
1830 $hash{'waive_setup'} = $self->waive_setup;
1832 my $custnum = $self->custnum;
1833 if ( $opt->{cust_main} ) {
1834 my $cust_main = $opt->{cust_main};
1835 unless ( $cust_main->custnum ) {
1836 my $error = $cust_main->insert;
1838 $dbh->rollback if $oldAutoCommit;
1839 return "inserting cust_main (transaction rolled back): $error";
1842 $custnum = $cust_main->custnum;
1845 $hash{'contactnum'} = $opt->{'contactnum'} if $opt->{'contactnum'};
1847 # Create the new package.
1848 my $cust_pkg = new FS::cust_pkg {
1849 custnum => $custnum,
1850 pkgpart => ( $opt->{'pkgpart'} || $self->pkgpart ),
1851 refnum => ( $opt->{'refnum'} || $self->refnum ),
1852 locationnum => ( $opt->{'locationnum'} ),
1855 $error = $cust_pkg->insert( 'change' => 1,
1856 'allow_pkgpart' => $same_pkgpart );
1858 $dbh->rollback if $oldAutoCommit;
1862 # Transfer services and cancel old package.
1864 $error = $self->transfer($cust_pkg);
1865 if ($error and $error == 0) {
1866 # $old_pkg->transfer failed.
1867 $dbh->rollback if $oldAutoCommit;
1871 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
1872 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
1873 $error = $self->transfer($cust_pkg, 'change_svcpart'=>1 );
1874 if ($error and $error == 0) {
1875 # $old_pkg->transfer failed.
1876 $dbh->rollback if $oldAutoCommit;
1882 # Transfers were successful, but we still had services left on the old
1883 # package. We can't change the package under this circumstances, so abort.
1884 $dbh->rollback if $oldAutoCommit;
1885 return "Unable to transfer all services from package ". $self->pkgnum;
1888 #reset usage if changing pkgpart
1889 # AND usage rollover is off (otherwise adds twice, now and at package bill)
1890 if ($self->pkgpart != $cust_pkg->pkgpart) {
1891 my $part_pkg = $cust_pkg->part_pkg;
1892 $error = $part_pkg->reset_usage($cust_pkg, $part_pkg->is_prepaid
1896 if $part_pkg->can('reset_usage') && ! $part_pkg->option('usage_rollover',1);
1899 $dbh->rollback if $oldAutoCommit;
1900 return "Error setting usage values: $error";
1903 # if NOT changing pkgpart, transfer any usage pools over
1904 foreach my $usage ($self->cust_pkg_usage) {
1905 $usage->set('pkgnum', $cust_pkg->pkgnum);
1906 $error = $usage->replace;
1908 $dbh->rollback if $oldAutoCommit;
1909 return "Error transferring usage pools: $error";
1914 # transfer discounts, if we're not changing pkgpart
1915 if ( $same_pkgpart ) {
1916 foreach my $old_discount ($self->cust_pkg_discount_active) {
1917 # don't remove the old discount, we may still need to bill that package.
1918 my $new_discount = new FS::cust_pkg_discount {
1919 'pkgnum' => $cust_pkg->pkgnum,
1920 'discountnum' => $old_discount->discountnum,
1921 'months_used' => $old_discount->months_used,
1923 $error = $new_discount->insert;
1925 $dbh->rollback if $oldAutoCommit;
1926 return "Error transferring discounts: $error";
1931 # transfer (copy) invoice details
1932 foreach my $detail ($self->cust_pkg_detail) {
1933 my $new_detail = FS::cust_pkg_detail->new({ $detail->hash });
1934 $new_detail->set('pkgdetailnum', '');
1935 $new_detail->set('pkgnum', $cust_pkg->pkgnum);
1936 $error = $new_detail->insert;
1938 $dbh->rollback if $oldAutoCommit;
1939 return "Error transferring package notes: $error";
1943 # Order any supplemental packages.
1944 my $part_pkg = $cust_pkg->part_pkg;
1945 my @old_supp_pkgs = $self->supplemental_pkgs;
1947 foreach my $link ($part_pkg->supp_part_pkg_link) {
1949 foreach (@old_supp_pkgs) {
1950 if ($_->pkgpart == $link->dst_pkgpart) {
1952 $_->pkgpart(0); # so that it can't match more than once
1956 # false laziness with FS::cust_main::Packages::order_pkg
1957 my $new = FS::cust_pkg->new({
1958 pkgpart => $link->dst_pkgpart,
1959 pkglinknum => $link->pkglinknum,
1960 custnum => $custnum,
1961 main_pkgnum => $cust_pkg->pkgnum,
1962 locationnum => $cust_pkg->locationnum,
1963 start_date => $cust_pkg->start_date,
1964 order_date => $cust_pkg->order_date,
1965 expire => $cust_pkg->expire,
1966 adjourn => $cust_pkg->adjourn,
1967 contract_end => $cust_pkg->contract_end,
1968 refnum => $cust_pkg->refnum,
1969 discountnum => $cust_pkg->discountnum,
1970 waive_setup => $cust_pkg->waive_setup,
1972 if ( $old and $opt->{'keep_dates'} ) {
1973 foreach (qw(setup bill last_bill)) {
1974 $new->set($_, $old->get($_));
1977 $error = $new->insert( allow_pkgpart => $same_pkgpart );
1980 $error ||= $old->transfer($new);
1982 if ( $error and $error > 0 ) {
1983 # no reason why this should ever fail, but still...
1984 $error = "Unable to transfer all services from supplemental package ".
1988 $dbh->rollback if $oldAutoCommit;
1991 push @new_supp_pkgs, $new;
1994 #Good to go, cancel old package. Notify 'cancel' of whether to credit
1996 #Don't allow billing the package (preceding period packages and/or
1997 #outstanding usage) if we are keeping dates (i.e. location changing),
1998 #because the new package will be billed for the same date range.
1999 #Supplemental packages are also canceled here.
2000 $error = $self->cancel(
2002 unused_credit => $unused_credit,
2003 nobill => $keep_dates,
2004 change_custnum => ( $self->custnum != $custnum ? $custnum : '' ),
2007 $dbh->rollback if $oldAutoCommit;
2011 if ( $conf->exists('cust_pkg-change_pkgpart-bill_now') ) {
2013 my $error = $cust_pkg->cust_main->bill(
2014 'pkg_list' => [ $cust_pkg, @new_supp_pkgs ]
2017 $dbh->rollback if $oldAutoCommit;
2022 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2028 =item set_quantity QUANTITY
2030 Change the package's quantity field. This is the one package property
2031 that can safely be changed without canceling and reordering the package
2032 (because it doesn't affect tax eligibility). Returns an error or an
2039 $self = $self->replace_old; # just to make sure
2041 ($qty =~ /^\d+$/ and $qty > 0) or return "bad package quantity $qty";
2042 $self->set('quantity' => $qty);
2046 use Storable 'thaw';
2048 sub process_bulk_cust_pkg {
2050 my $param = thaw(decode_base64(shift));
2051 warn Dumper($param) if $DEBUG;
2053 my $old_part_pkg = qsearchs('part_pkg',
2054 { pkgpart => $param->{'old_pkgpart'} });
2055 my $new_part_pkg = qsearchs('part_pkg',
2056 { pkgpart => $param->{'new_pkgpart'} });
2057 die "Must select a new package type\n" unless $new_part_pkg;
2058 #my $keep_dates = $param->{'keep_dates'} || 0;
2059 my $keep_dates = 1; # there is no good reason to turn this off
2061 local $SIG{HUP} = 'IGNORE';
2062 local $SIG{INT} = 'IGNORE';
2063 local $SIG{QUIT} = 'IGNORE';
2064 local $SIG{TERM} = 'IGNORE';
2065 local $SIG{TSTP} = 'IGNORE';
2066 local $SIG{PIPE} = 'IGNORE';
2068 my $oldAutoCommit = $FS::UID::AutoCommit;
2069 local $FS::UID::AutoCommit = 0;
2072 my @cust_pkgs = qsearch('cust_pkg', { 'pkgpart' => $param->{'old_pkgpart'} } );
2075 foreach my $old_cust_pkg ( @cust_pkgs ) {
2077 $job->update_statustext(int(100*$i/(scalar @cust_pkgs)));
2078 if ( $old_cust_pkg->getfield('cancel') ) {
2079 warn '[process_bulk_cust_pkg ] skipping canceled pkgnum '.
2080 $old_cust_pkg->pkgnum."\n"
2084 warn '[process_bulk_cust_pkg] changing pkgnum '.$old_cust_pkg->pkgnum."\n"
2086 my $error = $old_cust_pkg->change(
2087 'pkgpart' => $param->{'new_pkgpart'},
2088 'keep_dates' => $keep_dates
2090 if ( !ref($error) ) { # change returns the cust_pkg on success
2092 die "Error changing pkgnum ".$old_cust_pkg->pkgnum.": '$error'\n";
2095 $dbh->commit if $oldAutoCommit;
2101 Returns the last bill date, or if there is no last bill date, the setup date.
2102 Useful for billing metered services.
2108 return $self->setfield('last_bill', $_[0]) if @_;
2109 return $self->getfield('last_bill') if $self->getfield('last_bill');
2110 my $cust_bill_pkg = qsearchs('cust_bill_pkg', { 'pkgnum' => $self->pkgnum,
2111 'edate' => $self->bill, } );
2112 $cust_bill_pkg ? $cust_bill_pkg->sdate : $self->setup || 0;
2115 =item last_cust_pkg_reason ACTION
2117 Returns the most recent ACTION FS::cust_pkg_reason associated with the package.
2118 Returns false if there is no reason or the package is not currenly ACTION'd
2119 ACTION is one of adjourn, susp, cancel, or expire.
2123 sub last_cust_pkg_reason {
2124 my ( $self, $action ) = ( shift, shift );
2125 my $date = $self->get($action);
2127 'table' => 'cust_pkg_reason',
2128 'hashref' => { 'pkgnum' => $self->pkgnum,
2129 'action' => substr(uc($action), 0, 1),
2132 'order_by' => 'ORDER BY num DESC LIMIT 1',
2136 =item last_reason ACTION
2138 Returns the most recent ACTION FS::reason associated with the package.
2139 Returns false if there is no reason or the package is not currenly ACTION'd
2140 ACTION is one of adjourn, susp, cancel, or expire.
2145 my $cust_pkg_reason = shift->last_cust_pkg_reason(@_);
2146 $cust_pkg_reason->reason
2147 if $cust_pkg_reason;
2152 Returns the definition for this billing item, as an FS::part_pkg object (see
2159 return $self->{'_pkgpart'} if $self->{'_pkgpart'};
2160 cluck "cust_pkg->part_pkg called" if $DEBUG > 1;
2161 qsearchs( 'part_pkg', { 'pkgpart' => $self->pkgpart } );
2166 Returns the cancelled package this package was changed from, if any.
2172 return '' unless $self->change_pkgnum;
2173 qsearchs('cust_pkg', { 'pkgnum' => $self->change_pkgnum } );
2176 =item change_cust_main
2178 Returns the customter this package was detached to, if any.
2182 sub change_cust_main {
2184 return '' unless $self->change_custnum;
2185 qsearchs('cust_main', { 'custnum' => $self->change_custnum } );
2190 Calls the I<calc_setup> of the FS::part_pkg object associated with this billing
2197 $self->part_pkg->calc_setup($self, @_);
2202 Calls the I<calc_recur> of the FS::part_pkg object associated with this billing
2209 $self->part_pkg->calc_recur($self, @_);
2214 Calls the I<base_setup> of the FS::part_pkg object associated with this billing
2221 $self->part_pkg->base_setup($self, @_);
2226 Calls the I<base_recur> of the FS::part_pkg object associated with this billing
2233 $self->part_pkg->base_recur($self, @_);
2238 Calls the I<calc_remain> of the FS::part_pkg object associated with this
2245 $self->part_pkg->calc_remain($self, @_);
2250 Calls the I<calc_cancel> of the FS::part_pkg object associated with this
2257 $self->part_pkg->calc_cancel($self, @_);
2262 Returns any invoice line items for this package (see L<FS::cust_bill_pkg>).
2268 qsearch( 'cust_bill_pkg', { 'pkgnum' => $self->pkgnum } );
2271 =item cust_pkg_detail [ DETAILTYPE ]
2273 Returns any customer package details for this package (see
2274 L<FS::cust_pkg_detail>).
2276 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
2280 sub cust_pkg_detail {
2282 my %hash = ( 'pkgnum' => $self->pkgnum );
2283 $hash{detailtype} = shift if @_;
2285 'table' => 'cust_pkg_detail',
2286 'hashref' => \%hash,
2287 'order_by' => 'ORDER BY weight, pkgdetailnum',
2291 =item set_cust_pkg_detail DETAILTYPE [ DETAIL, DETAIL, ... ]
2293 Sets customer package details for this package (see L<FS::cust_pkg_detail>).
2295 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
2297 If there is an error, returns the error, otherwise returns false.
2301 sub set_cust_pkg_detail {
2302 my( $self, $detailtype, @details ) = @_;
2304 local $SIG{HUP} = 'IGNORE';
2305 local $SIG{INT} = 'IGNORE';
2306 local $SIG{QUIT} = 'IGNORE';
2307 local $SIG{TERM} = 'IGNORE';
2308 local $SIG{TSTP} = 'IGNORE';
2309 local $SIG{PIPE} = 'IGNORE';
2311 my $oldAutoCommit = $FS::UID::AutoCommit;
2312 local $FS::UID::AutoCommit = 0;
2315 foreach my $current ( $self->cust_pkg_detail($detailtype) ) {
2316 my $error = $current->delete;
2318 $dbh->rollback if $oldAutoCommit;
2319 return "error removing old detail: $error";
2323 foreach my $detail ( @details ) {
2324 my $cust_pkg_detail = new FS::cust_pkg_detail {
2325 'pkgnum' => $self->pkgnum,
2326 'detailtype' => $detailtype,
2327 'detail' => $detail,
2329 my $error = $cust_pkg_detail->insert;
2331 $dbh->rollback if $oldAutoCommit;
2332 return "error adding new detail: $error";
2337 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2344 Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.
2348 #false laziness w/cust_bill.pm
2352 'table' => 'cust_event',
2353 'addl_from' => 'JOIN part_event USING ( eventpart )',
2354 'hashref' => { 'tablenum' => $self->pkgnum },
2355 'extra_sql' => " AND eventtable = 'cust_pkg' ",
2359 =item num_cust_event
2361 Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.
2365 #false laziness w/cust_bill.pm
2366 sub num_cust_event {
2369 "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
2370 " WHERE tablenum = ? AND eventtable = 'cust_pkg'";
2371 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
2372 $sth->execute($self->pkgnum) or die $sth->errstr. " executing $sql";
2373 $sth->fetchrow_arrayref->[0];
2376 =item part_pkg_currency_option OPTIONNAME
2378 Returns a two item list consisting of the currency of this customer, if any,
2379 and a value for the provided option. If the customer has a currency, the value
2380 is the option value the given name and the currency (see
2381 L<FS::part_pkg_currency>). Otherwise, if the customer has no currency, is the
2382 regular option value for the given name (see L<FS::part_pkg_option>).
2386 sub part_pkg_currency_option {
2387 my( $self, $optionname ) = @_;
2388 my $part_pkg = $self->part_pkg;
2389 if ( my $currency = $self->cust_main->currency ) {
2390 ($currency, $part_pkg->part_pkg_currency_option($currency, $optionname) );
2392 ('', $part_pkg->option($optionname) );
2396 =item cust_svc [ SVCPART ] (old, deprecated usage)
2398 =item cust_svc [ OPTION => VALUE ... ] (current usage)
2400 Returns the services for this package, as FS::cust_svc objects (see
2401 L<FS::cust_svc>). Available options are svcpart and svcdb. If either is
2402 spcififed, returns only the matching services.
2409 return () unless $self->num_cust_svc(@_);
2412 if ( @_ && $_[0] =~ /^\d+/ ) {
2413 $opt{svcpart} = shift;
2414 } elsif ( @_ && ref($_[0]) eq 'HASH' ) {
2421 'table' => 'cust_svc',
2422 'hashref' => { 'pkgnum' => $self->pkgnum },
2424 if ( $opt{svcpart} ) {
2425 $search{hashref}->{svcpart} = $opt{'svcpart'};
2427 if ( $opt{'svcdb'} ) {
2428 $search{addl_from} = ' LEFT JOIN part_svc USING ( svcpart ) ';
2429 $search{extra_sql} = ' AND svcdb = '. dbh->quote( $opt{'svcdb'} );
2432 cluck "cust_pkg->cust_svc called" if $DEBUG > 2;
2434 #if ( $self->{'_svcnum'} ) {
2435 # values %{ $self->{'_svcnum'}->cache };
2437 $self->_sort_cust_svc( [ qsearch(\%search) ] );
2442 =item overlimit [ SVCPART ]
2444 Returns the services for this package which have exceeded their
2445 usage limit as FS::cust_svc objects (see L<FS::cust_svc>). If a svcpart
2446 is specified, return only the matching services.
2452 return () unless $self->num_cust_svc(@_);
2453 grep { $_->overlimit } $self->cust_svc(@_);
2456 =item h_cust_svc END_TIMESTAMP [ START_TIMESTAMP ] [ MODE ]
2458 Returns historical services for this package created before END TIMESTAMP and
2459 (optionally) not cancelled before START_TIMESTAMP, as FS::h_cust_svc objects
2460 (see L<FS::h_cust_svc>). If MODE is 'I' (for 'invoice'), services with the
2461 I<pkg_svc.hidden> flag will be omitted.
2467 warn "$me _h_cust_svc called on $self\n"
2470 my ($end, $start, $mode) = @_;
2471 my @cust_svc = $self->_sort_cust_svc(
2472 [ qsearch( 'h_cust_svc',
2473 { 'pkgnum' => $self->pkgnum, },
2474 FS::h_cust_svc->sql_h_search(@_),
2477 if ( defined($mode) && $mode eq 'I' ) {
2478 my %hidden_svcpart = map { $_->svcpart => $_->hidden } $self->part_svc;
2479 return grep { !$hidden_svcpart{$_->svcpart} } @cust_svc;
2485 sub _sort_cust_svc {
2486 my( $self, $arrayref ) = @_;
2489 sub ($$) { my ($a, $b) = @_; $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] };
2491 my %pkg_svc = map { $_->svcpart => $_ }
2492 qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
2497 my $pkg_svc = $pkg_svc{ $_->svcpart } || '';
2499 $pkg_svc ? $pkg_svc->primary_svc : '',
2500 $pkg_svc ? $pkg_svc->quantity : 0,
2507 =item num_cust_svc [ SVCPART ] (old, deprecated usage)
2509 =item num_cust_svc [ OPTION => VALUE ... ] (current usage)
2511 Returns the number of services for this package. Available options are svcpart
2512 and svcdb. If either is spcififed, returns only the matching services.
2519 return $self->{'_num_cust_svc'}
2521 && exists($self->{'_num_cust_svc'})
2522 && $self->{'_num_cust_svc'} =~ /\d/;
2524 cluck "cust_pkg->num_cust_svc called, _num_cust_svc:".$self->{'_num_cust_svc'}
2528 if ( @_ && $_[0] =~ /^\d+/ ) {
2529 $opt{svcpart} = shift;
2530 } elsif ( @_ && ref($_[0]) eq 'HASH' ) {
2536 my $select = 'SELECT COUNT(*) FROM cust_svc ';
2537 my $where = ' WHERE pkgnum = ? ';
2538 my @param = ($self->pkgnum);
2540 if ( $opt{'svcpart'} ) {
2541 $where .= ' AND svcpart = ? ';
2542 push @param, $opt{'svcpart'};
2544 if ( $opt{'svcdb'} ) {
2545 $select .= ' LEFT JOIN part_svc USING ( svcpart ) ';
2546 $where .= ' AND svcdb = ? ';
2547 push @param, $opt{'svcdb'};
2550 my $sth = dbh->prepare("$select $where") or die dbh->errstr;
2551 $sth->execute(@param) or die $sth->errstr;
2552 $sth->fetchrow_arrayref->[0];
2555 =item available_part_svc
2557 Returns a list of FS::part_svc objects representing services included in this
2558 package but not yet provisioned. Each FS::part_svc object also has an extra
2559 field, I<num_avail>, which specifies the number of available services.
2563 sub available_part_svc {
2566 my $pkg_quantity = $self->quantity || 1;
2568 grep { $_->num_avail > 0 }
2570 my $part_svc = $_->part_svc;
2571 $part_svc->{'Hash'}{'num_avail'} = #evil encapsulation-breaking
2572 $pkg_quantity * $_->quantity - $self->num_cust_svc($_->svcpart);
2574 # more evil encapsulation breakage
2575 if($part_svc->{'Hash'}{'num_avail'} > 0) {
2576 my @exports = $part_svc->part_export_did;
2577 $part_svc->{'Hash'}{'can_get_dids'} = scalar(@exports);
2582 $self->part_pkg->pkg_svc;
2585 =item part_svc [ OPTION => VALUE ... ]
2587 Returns a list of FS::part_svc objects representing provisioned and available
2588 services included in this package. Each FS::part_svc object also has the
2589 following extra fields:
2593 =item num_cust_svc (count)
2595 =item num_avail (quantity - count)
2597 =item cust_pkg_svc (services) - array reference containing the provisioned services, as cust_svc objects
2601 Accepts one option: summarize_size. If specified and non-zero, will omit the
2602 extra cust_pkg_svc option for objects where num_cust_svc is this size or
2608 #label -> ($cust_svc->label)[1]
2614 my $pkg_quantity = $self->quantity || 1;
2616 #XXX some sort of sort order besides numeric by svcpart...
2617 my @part_svc = sort { $a->svcpart <=> $b->svcpart } map {
2619 my $part_svc = $pkg_svc->part_svc;
2620 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
2621 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #more evil
2622 $part_svc->{'Hash'}{'num_avail'} =
2623 max( 0, $pkg_quantity * $pkg_svc->quantity - $num_cust_svc );
2624 $part_svc->{'Hash'}{'cust_pkg_svc'} =
2625 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : []
2626 unless exists($opt{summarize_size}) && $opt{summarize_size} > 0
2627 && $num_cust_svc >= $opt{summarize_size};
2628 $part_svc->{'Hash'}{'hidden'} = $pkg_svc->hidden;
2630 } $self->part_pkg->pkg_svc;
2633 push @part_svc, map {
2635 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
2636 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #speak no evail
2637 $part_svc->{'Hash'}{'num_avail'} = 0; #0-$num_cust_svc ?
2638 $part_svc->{'Hash'}{'cust_pkg_svc'} =
2639 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : [];
2641 } $self->extra_part_svc;
2647 =item extra_part_svc
2649 Returns a list of FS::part_svc objects corresponding to services in this
2650 package which are still provisioned but not (any longer) available in the
2655 sub extra_part_svc {
2658 my $pkgnum = $self->pkgnum;
2659 #my $pkgpart = $self->pkgpart;
2662 # 'table' => 'part_svc',
2665 # "WHERE 0 = ( SELECT COUNT(*) FROM pkg_svc
2666 # WHERE pkg_svc.svcpart = part_svc.svcpart
2667 # AND pkg_svc.pkgpart = ?
2670 # AND 0 < ( SELECT COUNT(*) FROM cust_svc
2671 # LEFT JOIN cust_pkg USING ( pkgnum )
2672 # WHERE cust_svc.svcpart = part_svc.svcpart
2675 # 'extra_param' => [ [$self->pkgpart=>'int'], [$self->pkgnum=>'int'] ],
2678 #seems to benchmark slightly faster... (or did?)
2680 my @pkgparts = map $_->pkgpart, $self->part_pkg->self_and_svc_linked;
2681 my $pkgparts = join(',', @pkgparts);
2684 #'select' => 'DISTINCT ON (svcpart) part_svc.*',
2685 #MySQL doesn't grok DISINCT ON
2686 'select' => 'DISTINCT part_svc.*',
2687 'table' => 'part_svc',
2689 "LEFT JOIN pkg_svc ON ( pkg_svc.svcpart = part_svc.svcpart
2690 AND pkg_svc.pkgpart IN ($pkgparts)
2693 LEFT JOIN cust_svc ON ( cust_svc.svcpart = part_svc.svcpart )
2694 LEFT JOIN cust_pkg USING ( pkgnum )
2697 'extra_sql' => "WHERE pkgsvcnum IS NULL AND cust_pkg.pkgnum = ? ",
2698 'extra_param' => [ [$self->pkgnum=>'int'] ],
2704 Returns a short status string for this package, currently:
2708 =item not yet billed
2710 =item one-time charge
2725 my $freq = length($self->freq) ? $self->freq : $self->part_pkg->freq;
2727 return 'cancelled' if $self->get('cancel');
2728 return 'suspended' if $self->susp;
2729 return 'not yet billed' unless $self->setup;
2730 return 'one-time charge' if $freq =~ /^(0|$)/;
2734 =item ucfirst_status
2736 Returns the status with the first character capitalized.
2740 sub ucfirst_status {
2741 ucfirst(shift->status);
2746 Class method that returns the list of possible status strings for packages
2747 (see L<the status method|/status>). For example:
2749 @statuses = FS::cust_pkg->statuses();
2753 tie my %statuscolor, 'Tie::IxHash',
2754 'not yet billed' => '009999', #teal? cyan?
2755 'one-time charge' => '000000',
2756 'active' => '00CC00',
2757 'suspended' => 'FF9900',
2758 'cancelled' => 'FF0000',
2762 my $self = shift; #could be class...
2763 #grep { $_ !~ /^(not yet billed)$/ } #this is a dumb status anyway
2764 # # mayble split btw one-time vs. recur
2770 Returns a hex triplet color string for this package's status.
2776 $statuscolor{$self->status};
2781 Returns a label for this package. (Currently "pkgnum: pkg - comment" or
2782 "pkg - comment" depending on user preference).
2788 my $label = $self->part_pkg->pkg_comment( 'nopkgpart' => 1 );
2789 $label = $self->pkgnum. ": $label"
2790 if $FS::CurrentUser::CurrentUser->option('show_pkgnum');
2794 =item pkg_label_long
2796 Returns a long label for this package, adding the primary service's label to
2801 sub pkg_label_long {
2803 my $label = $self->pkg_label;
2804 my $cust_svc = $self->primary_cust_svc;
2805 $label .= ' ('. ($cust_svc->label)[1]. ')' if $cust_svc;
2811 Returns a customer-localized label for this package.
2817 $self->part_pkg->pkg_locale( $self->cust_main->locale );
2820 =item primary_cust_svc
2822 Returns a primary service (as FS::cust_svc object) if one can be identified.
2826 #for labeling purposes - might not 100% match up with part_pkg->svcpart's idea
2828 sub primary_cust_svc {
2831 my @cust_svc = $self->cust_svc;
2833 return '' unless @cust_svc; #no serivces - irrelevant then
2835 return $cust_svc[0] if scalar(@cust_svc) == 1; #always return a single service
2837 # primary service as specified in the package definition
2838 # or exactly one service definition with quantity one
2839 my $svcpart = $self->part_pkg->svcpart;
2840 @cust_svc = grep { $_->svcpart == $svcpart } @cust_svc;
2841 return $cust_svc[0] if scalar(@cust_svc) == 1;
2843 #couldn't identify one thing..
2849 Returns a list of lists, calling the label method for all services
2850 (see L<FS::cust_svc>) of this billing item.
2856 map { [ $_->label ] } $self->cust_svc;
2859 =item h_labels END_TIMESTAMP [ START_TIMESTAMP ] [ MODE ]
2861 Like the labels method, but returns historical information on services that
2862 were active as of END_TIMESTAMP and (optionally) not cancelled before
2863 START_TIMESTAMP. If MODE is 'I' (for 'invoice'), services with the
2864 I<pkg_svc.hidden> flag will be omitted.
2866 Returns a list of lists, calling the label method for all (historical) services
2867 (see L<FS::h_cust_svc>) of this billing item.
2873 warn "$me _h_labels called on $self\n"
2875 map { [ $_->label(@_) ] } $self->h_cust_svc(@_);
2880 Like labels, except returns a simple flat list, and shortens long
2881 (currently >5 or the cust_bill-max_same_services configuration value) lists of
2882 identical services to one line that lists the service label and the number of
2883 individual services rather than individual items.
2888 shift->_labels_short( 'labels', @_ );
2891 =item h_labels_short END_TIMESTAMP [ START_TIMESTAMP ]
2893 Like h_labels, except returns a simple flat list, and shortens long
2894 (currently >5 or the cust_bill-max_same_services configuration value) lists of
2895 identical services to one line that lists the service label and the number of
2896 individual services rather than individual items.
2900 sub h_labels_short {
2901 shift->_labels_short( 'h_labels', @_ );
2905 my( $self, $method ) = ( shift, shift );
2907 warn "$me _labels_short called on $self with $method method\n"
2910 my $conf = new FS::Conf;
2911 my $max_same_services = $conf->config('cust_bill-max_same_services') || 5;
2913 warn "$me _labels_short populating \%labels\n"
2917 #tie %labels, 'Tie::IxHash';
2918 push @{ $labels{$_->[0]} }, $_->[1]
2919 foreach $self->$method(@_);
2921 warn "$me _labels_short populating \@labels\n"
2925 foreach my $label ( keys %labels ) {
2927 my @values = grep { ! $seen{$_}++ } @{ $labels{$label} };
2928 my $num = scalar(@values);
2929 warn "$me _labels_short $num items for $label\n"
2932 if ( $num > $max_same_services ) {
2933 warn "$me _labels_short more than $max_same_services, so summarizing\n"
2935 push @labels, "$label ($num)";
2937 if ( $conf->exists('cust_bill-consolidate_services') ) {
2938 warn "$me _labels_short consolidating services\n"
2940 # push @labels, "$label: ". join(', ', @values);
2942 my $detail = "$label: ";
2943 $detail .= shift(@values). ', '
2945 && ( length($detail.$values[0]) < 78 || $detail eq "$label: " );
2947 push @labels, $detail;
2949 warn "$me _labels_short done consolidating services\n"
2952 warn "$me _labels_short adding service data\n"
2954 push @labels, map { "$label: $_" } @values;
2965 Returns the parent customer object (see L<FS::cust_main>).
2971 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
2976 Returns the balance for this specific package, when using
2977 experimental package balance.
2983 $self->cust_main->balance_pkgnum( $self->pkgnum );
2986 #these subs are in location_Mixin.pm now... unfortunately the POD doesn't mixin
2990 Returns the location object, if any (see L<FS::cust_location>).
2992 =item cust_location_or_main
2994 If this package is associated with a location, returns the locaiton (see
2995 L<FS::cust_location>), otherwise returns the customer (see L<FS::cust_main>).
2997 =item location_label [ OPTION => VALUE ... ]
2999 Returns the label of the location object (see L<FS::cust_location>).
3003 #end of subs in location_Mixin.pm now... unfortunately the POD doesn't mixin
3005 =item tax_locationnum
3007 Returns the foreign key to a L<FS::cust_location> object for calculating
3008 tax on this package, as determined by the C<tax-pkg_address> and
3009 C<tax-ship_address> configuration flags.
3013 sub tax_locationnum {
3015 my $conf = FS::Conf->new;
3016 if ( $conf->exists('tax-pkg_address') ) {
3017 return $self->locationnum;
3019 elsif ( $conf->exists('tax-ship_address') ) {
3020 return $self->cust_main->ship_locationnum;
3023 return $self->cust_main->bill_locationnum;
3029 Returns the L<FS::cust_location> object for tax_locationnum.
3035 FS::cust_location->by_key( $self->tax_locationnum )
3038 =item seconds_since TIMESTAMP
3040 Returns the number of seconds all accounts (see L<FS::svc_acct>) in this
3041 package have been online since TIMESTAMP, according to the session monitor.
3043 TIMESTAMP is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
3044 L<Time::Local> and L<Date::Parse> for conversion functions.
3049 my($self, $since) = @_;
3052 foreach my $cust_svc (
3053 grep { $_->part_svc->svcdb eq 'svc_acct' } $self->cust_svc
3055 $seconds += $cust_svc->seconds_since($since);
3062 =item seconds_since_sqlradacct TIMESTAMP_START TIMESTAMP_END
3064 Returns the numbers of seconds all accounts (see L<FS::svc_acct>) in this
3065 package have been online between TIMESTAMP_START (inclusive) and TIMESTAMP_END
3068 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
3069 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
3075 sub seconds_since_sqlradacct {
3076 my($self, $start, $end) = @_;
3080 foreach my $cust_svc (
3082 my $part_svc = $_->part_svc;
3083 $part_svc->svcdb eq 'svc_acct'
3084 && scalar($part_svc->part_export_usage);
3087 $seconds += $cust_svc->seconds_since_sqlradacct($start, $end);
3094 =item attribute_since_sqlradacct TIMESTAMP_START TIMESTAMP_END ATTRIBUTE
3096 Returns the sum of the given attribute for all accounts (see L<FS::svc_acct>)
3097 in this package for sessions ending between TIMESTAMP_START (inclusive) and
3101 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
3102 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
3107 sub attribute_since_sqlradacct {
3108 my($self, $start, $end, $attrib) = @_;
3112 foreach my $cust_svc (
3114 my $part_svc = $_->part_svc;
3115 $part_svc->svcdb eq 'svc_acct'
3116 && scalar($part_svc->part_export_usage);
3119 $sum += $cust_svc->attribute_since_sqlradacct($start, $end, $attrib);
3131 my( $self, $value ) = @_;
3132 if ( defined($value) ) {
3133 $self->setfield('quantity', $value);
3135 $self->getfield('quantity') || 1;
3138 =item transfer DEST_PKGNUM | DEST_CUST_PKG, [ OPTION => VALUE ... ]
3140 Transfers as many services as possible from this package to another package.
3142 The destination package can be specified by pkgnum by passing an FS::cust_pkg
3143 object. The destination package must already exist.
3145 Services are moved only if the destination allows services with the correct
3146 I<svcpart> (not svcdb), unless the B<change_svcpart> option is set true. Use
3147 this option with caution! No provision is made for export differences
3148 between the old and new service definitions. Probably only should be used
3149 when your exports for all service definitions of a given svcdb are identical.
3150 (attempt a transfer without it first, to move all possible svcpart-matching
3153 Any services that can't be moved remain in the original package.
3155 Returns an error, if there is one; otherwise, returns the number of services
3156 that couldn't be moved.
3161 my ($self, $dest_pkgnum, %opt) = @_;
3167 if (ref ($dest_pkgnum) eq 'FS::cust_pkg') {
3168 $dest = $dest_pkgnum;
3169 $dest_pkgnum = $dest->pkgnum;
3171 $dest = qsearchs('cust_pkg', { pkgnum => $dest_pkgnum });
3174 return ('Package does not exist: '.$dest_pkgnum) unless $dest;
3176 foreach my $pkg_svc ( $dest->part_pkg->pkg_svc ) {
3177 $target{$pkg_svc->svcpart} = $pkg_svc->quantity;
3180 foreach my $cust_svc ($dest->cust_svc) {
3181 $target{$cust_svc->svcpart}--;
3184 my %svcpart2svcparts = ();
3185 if ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
3186 warn "change_svcpart option received, creating alternates list\n" if $DEBUG;
3187 foreach my $svcpart ( map { $_->svcpart } $self->cust_svc ) {
3188 next if exists $svcpart2svcparts{$svcpart};
3189 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
3190 $svcpart2svcparts{$svcpart} = [
3192 sort { $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] }
3194 my $pkg_svc = qsearchs( 'pkg_svc', { 'pkgpart' => $dest->pkgpart,
3195 'svcpart' => $_ } );
3197 $pkg_svc ? $pkg_svc->primary_svc : '',
3198 $pkg_svc ? $pkg_svc->quantity : 0,
3202 grep { $_ != $svcpart }
3204 qsearch('part_svc', { 'svcdb' => $part_svc->svcdb } )
3206 warn "alternates for svcpart $svcpart: ".
3207 join(', ', @{$svcpart2svcparts{$svcpart}}). "\n"
3212 foreach my $cust_svc ($self->cust_svc) {
3213 if($target{$cust_svc->svcpart} > 0
3214 or $FS::cust_svc::ignore_quantity) { # maybe should be a 'force' option
3215 $target{$cust_svc->svcpart}--;
3216 my $new = new FS::cust_svc { $cust_svc->hash };
3217 $new->pkgnum($dest_pkgnum);
3218 my $error = $new->replace($cust_svc);
3219 return $error if $error;
3220 } elsif ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
3222 warn "looking for alternates for svcpart ". $cust_svc->svcpart. "\n";
3223 warn "alternates to consider: ".
3224 join(', ', @{$svcpart2svcparts{$cust_svc->svcpart}}). "\n";
3226 my @alternate = grep {
3227 warn "considering alternate svcpart $_: ".
3228 "$target{$_} available in new package\n"
3231 } @{$svcpart2svcparts{$cust_svc->svcpart}};
3233 warn "alternate(s) found\n" if $DEBUG;
3234 my $change_svcpart = $alternate[0];
3235 $target{$change_svcpart}--;
3236 my $new = new FS::cust_svc { $cust_svc->hash };
3237 $new->svcpart($change_svcpart);
3238 $new->pkgnum($dest_pkgnum);
3239 my $error = $new->replace($cust_svc);
3240 return $error if $error;
3251 =item grab_svcnums SVCNUM, SVCNUM ...
3253 Change the pkgnum for the provided services to this packages. If there is an
3254 error, returns the error, otherwise returns false.
3262 local $SIG{HUP} = 'IGNORE';
3263 local $SIG{INT} = 'IGNORE';
3264 local $SIG{QUIT} = 'IGNORE';
3265 local $SIG{TERM} = 'IGNORE';
3266 local $SIG{TSTP} = 'IGNORE';
3267 local $SIG{PIPE} = 'IGNORE';
3269 my $oldAutoCommit = $FS::UID::AutoCommit;
3270 local $FS::UID::AutoCommit = 0;
3273 foreach my $svcnum (@svcnum) {
3274 my $cust_svc = qsearchs('cust_svc', { svcnum=>$svcnum } ) or do {
3275 $dbh->rollback if $oldAutoCommit;
3276 return "unknown svcnum $svcnum";
3278 $cust_svc->pkgnum( $self->pkgnum );
3279 my $error = $cust_svc->replace;
3281 $dbh->rollback if $oldAutoCommit;
3286 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3293 This method is deprecated. See the I<depend_jobnum> option to the insert and
3294 order_pkgs methods in FS::cust_main for a better way to defer provisioning.
3298 #looks like this is still used by the order_pkg and change_pkg methods in
3299 # ClientAPI/MyAccount, need to look into those before removing
3303 local $SIG{HUP} = 'IGNORE';
3304 local $SIG{INT} = 'IGNORE';
3305 local $SIG{QUIT} = 'IGNORE';
3306 local $SIG{TERM} = 'IGNORE';
3307 local $SIG{TSTP} = 'IGNORE';
3308 local $SIG{PIPE} = 'IGNORE';
3310 my $oldAutoCommit = $FS::UID::AutoCommit;
3311 local $FS::UID::AutoCommit = 0;
3314 foreach my $cust_svc ( $self->cust_svc ) {
3315 #false laziness w/svc_Common::insert
3316 my $svc_x = $cust_svc->svc_x;
3317 foreach my $part_export ( $cust_svc->part_svc->part_export ) {
3318 my $error = $part_export->export_insert($svc_x);
3320 $dbh->rollback if $oldAutoCommit;
3326 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3331 =item export_pkg_change OLD_CUST_PKG
3333 Calls the "pkg_change" export action for all services attached to this package.
3337 sub export_pkg_change {
3338 my( $self, $old ) = ( shift, shift );
3340 local $SIG{HUP} = 'IGNORE';
3341 local $SIG{INT} = 'IGNORE';
3342 local $SIG{QUIT} = 'IGNORE';
3343 local $SIG{TERM} = 'IGNORE';
3344 local $SIG{TSTP} = 'IGNORE';
3345 local $SIG{PIPE} = 'IGNORE';
3347 my $oldAutoCommit = $FS::UID::AutoCommit;
3348 local $FS::UID::AutoCommit = 0;
3351 foreach my $svc_x ( map $_->svc_x, $self->cust_svc ) {
3352 my $error = $svc_x->export('pkg_change', $self, $old);
3354 $dbh->rollback if $oldAutoCommit;
3359 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3366 Associates this package with a (suspension or cancellation) reason (see
3367 L<FS::cust_pkg_reason>, possibly inserting a new reason on the fly (see
3370 Available options are:
3376 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.
3380 the access_user (see L<FS::access_user>) providing the reason
3388 the action (cancel, susp, adjourn, expire) associated with the reason
3392 If there is an error, returns the error, otherwise returns false.
3397 my ($self, %options) = @_;
3399 my $otaker = $options{reason_otaker} ||
3400 $FS::CurrentUser::CurrentUser->username;
3403 if ( $options{'reason'} =~ /^(\d+)$/ ) {
3407 } elsif ( ref($options{'reason'}) ) {
3409 return 'Enter a new reason (or select an existing one)'
3410 unless $options{'reason'}->{'reason'} !~ /^\s*$/;
3412 my $reason = new FS::reason({
3413 'reason_type' => $options{'reason'}->{'typenum'},
3414 'reason' => $options{'reason'}->{'reason'},
3416 my $error = $reason->insert;
3417 return $error if $error;
3419 $reasonnum = $reason->reasonnum;
3422 return "Unparsable reason: ". $options{'reason'};
3425 my $cust_pkg_reason =
3426 new FS::cust_pkg_reason({ 'pkgnum' => $self->pkgnum,
3427 'reasonnum' => $reasonnum,
3428 'otaker' => $otaker,
3429 'action' => substr(uc($options{'action'}),0,1),
3430 'date' => $options{'date'}
3435 $cust_pkg_reason->insert;
3438 =item insert_discount
3440 Associates this package with a discount (see L<FS::cust_pkg_discount>, possibly
3441 inserting a new discount on the fly (see L<FS::discount>).
3443 Available options are:
3451 If there is an error, returns the error, otherwise returns false.
3455 sub insert_discount {
3456 #my ($self, %options) = @_;
3459 my $cust_pkg_discount = new FS::cust_pkg_discount {
3460 'pkgnum' => $self->pkgnum,
3461 'discountnum' => $self->discountnum,
3463 'end_date' => '', #XXX
3464 #for the create a new discount case
3465 '_type' => $self->discountnum__type,
3466 'amount' => $self->discountnum_amount,
3467 'percent' => $self->discountnum_percent,
3468 'months' => $self->discountnum_months,
3469 'setup' => $self->discountnum_setup,
3470 #'disabled' => $self->discountnum_disabled,
3473 $cust_pkg_discount->insert;
3476 =item set_usage USAGE_VALUE_HASHREF
3478 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
3479 to which they should be set (see L<FS::svc_acct>). Currently seconds,
3480 upbytes, downbytes, and totalbytes are appropriate keys.
3482 All svc_accts which are part of this package have their values reset.
3487 my ($self, $valueref, %opt) = @_;
3489 #only svc_acct can set_usage for now
3490 foreach my $cust_svc ( $self->cust_svc( 'svcdb'=>'svc_acct' ) ) {
3491 my $svc_x = $cust_svc->svc_x;
3492 $svc_x->set_usage($valueref, %opt)
3493 if $svc_x->can("set_usage");
3497 =item recharge USAGE_VALUE_HASHREF
3499 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
3500 to which they should be set (see L<FS::svc_acct>). Currently seconds,
3501 upbytes, downbytes, and totalbytes are appropriate keys.
3503 All svc_accts which are part of this package have their values incremented.
3508 my ($self, $valueref) = @_;
3510 #only svc_acct can set_usage for now
3511 foreach my $cust_svc ( $self->cust_svc( 'svcdb'=>'svc_acct' ) ) {
3512 my $svc_x = $cust_svc->svc_x;
3513 $svc_x->recharge($valueref)
3514 if $svc_x->can("recharge");
3518 =item cust_pkg_discount
3522 sub cust_pkg_discount {
3524 qsearch('cust_pkg_discount', { 'pkgnum' => $self->pkgnum } );
3527 =item cust_pkg_discount_active
3531 sub cust_pkg_discount_active {
3533 grep { $_->status eq 'active' } $self->cust_pkg_discount;
3536 =item cust_pkg_usage
3538 Returns a list of all voice usage counters attached to this package.
3542 sub cust_pkg_usage {
3544 qsearch('cust_pkg_usage', { pkgnum => $self->pkgnum });
3547 =item apply_usage OPTIONS
3549 Takes the following options:
3550 - cdr: a call detail record (L<FS::cdr>)
3551 - rate_detail: the rate determined for this call (L<FS::rate_detail>)
3552 - minutes: the maximum number of minutes to be charged
3554 Finds available usage minutes for a call of this class, and subtracts
3555 up to that many minutes from the usage pool. If the usage pool is empty,
3556 and the C<cdr-minutes_priority> global config option is set, minutes may
3557 be taken from other calls as well. Either way, an allocation record will
3558 be created (L<FS::cdr_cust_pkg_usage>) and this method will return the
3559 number of minutes of usage applied to the call.
3564 my ($self, %opt) = @_;
3565 my $cdr = $opt{cdr};
3566 my $rate_detail = $opt{rate_detail};
3567 my $minutes = $opt{minutes};
3568 my $classnum = $rate_detail->classnum;
3569 my $pkgnum = $self->pkgnum;
3570 my $custnum = $self->custnum;
3572 local $SIG{HUP} = 'IGNORE';
3573 local $SIG{INT} = 'IGNORE';
3574 local $SIG{QUIT} = 'IGNORE';
3575 local $SIG{TERM} = 'IGNORE';
3576 local $SIG{TSTP} = 'IGNORE';
3577 local $SIG{PIPE} = 'IGNORE';
3579 my $oldAutoCommit = $FS::UID::AutoCommit;
3580 local $FS::UID::AutoCommit = 0;
3582 my $order = FS::Conf->new->config('cdr-minutes_priority');
3586 $is_classnum = ' part_pkg_usage_class.classnum = '.$classnum;
3588 $is_classnum = ' part_pkg_usage_class.classnum IS NULL';
3590 my @usage_recs = qsearch({
3591 'table' => 'cust_pkg_usage',
3592 'addl_from' => ' JOIN part_pkg_usage USING (pkgusagepart)'.
3593 ' JOIN cust_pkg USING (pkgnum)'.
3594 ' JOIN part_pkg_usage_class USING (pkgusagepart)',
3595 'select' => 'cust_pkg_usage.*',
3596 'extra_sql' => " WHERE ( cust_pkg.pkgnum = $pkgnum OR ".
3597 " ( cust_pkg.custnum = $custnum AND ".
3598 " part_pkg_usage.shared IS NOT NULL ) ) AND ".
3599 $is_classnum . ' AND '.
3600 " cust_pkg_usage.minutes > 0",
3601 'order_by' => " ORDER BY priority ASC",
3604 my $orig_minutes = $minutes;
3606 while (!$error and $minutes > 0 and @usage_recs) {
3607 my $cust_pkg_usage = shift @usage_recs;
3608 $cust_pkg_usage->select_for_update;
3609 my $cdr_cust_pkg_usage = FS::cdr_cust_pkg_usage->new({
3610 pkgusagenum => $cust_pkg_usage->pkgusagenum,
3611 acctid => $cdr->acctid,
3612 minutes => min($cust_pkg_usage->minutes, $minutes),
3614 $cust_pkg_usage->set('minutes',
3615 sprintf('%.0f', $cust_pkg_usage->minutes - $cdr_cust_pkg_usage->minutes)
3617 $error = $cust_pkg_usage->replace || $cdr_cust_pkg_usage->insert;
3618 $minutes -= $cdr_cust_pkg_usage->minutes;
3620 if ( $order and $minutes > 0 and !$error ) {
3621 # then try to steal minutes from another call
3623 'table' => 'cdr_cust_pkg_usage',
3624 'addl_from' => ' JOIN cust_pkg_usage USING (pkgusagenum)'.
3625 ' JOIN part_pkg_usage USING (pkgusagepart)'.
3626 ' JOIN cust_pkg USING (pkgnum)'.
3627 ' JOIN part_pkg_usage_class USING (pkgusagepart)'.
3628 ' JOIN cdr USING (acctid)',
3629 'select' => 'cdr_cust_pkg_usage.*',
3630 'extra_sql' => " WHERE cdr.freesidestatus = 'rated' AND ".
3631 " ( cust_pkg.pkgnum = $pkgnum OR ".
3632 " ( cust_pkg.custnum = $custnum AND ".
3633 " part_pkg_usage.shared IS NOT NULL ) ) AND ".
3634 " part_pkg_usage_class.classnum = $classnum",
3635 'order_by' => ' ORDER BY part_pkg_usage.priority ASC',
3637 if ( $order eq 'time' ) {
3638 # find CDRs that are using minutes, but have a later startdate
3640 my $startdate = $cdr->startdate;
3641 if ($startdate !~ /^\d+$/) {
3642 die "bad cdr startdate '$startdate'";
3644 $search{'extra_sql'} .= " AND cdr.startdate > $startdate";
3645 # minimize needless reshuffling
3646 $search{'order_by'} .= ', cdr.startdate DESC';
3648 # XXX may not work correctly with rate_time schedules. Could
3649 # fix this by storing ratedetailnum in cdr_cust_pkg_usage, I
3651 $search{'addl_from'} .=
3652 ' JOIN rate_detail'.
3653 ' ON (cdr.rated_ratedetailnum = rate_detail.ratedetailnum)';
3654 if ( $order eq 'rate_high' ) {
3655 $search{'extra_sql'} .= ' AND rate_detail.min_charge < '.
3656 $rate_detail->min_charge;
3657 $search{'order_by'} .= ', rate_detail.min_charge ASC';
3658 } elsif ( $order eq 'rate_low' ) {
3659 $search{'extra_sql'} .= ' AND rate_detail.min_charge > '.
3660 $rate_detail->min_charge;
3661 $search{'order_by'} .= ', rate_detail.min_charge DESC';
3663 # this should really never happen
3664 die "invalid cdr-minutes_priority value '$order'\n";
3667 my @cdr_usage_recs = qsearch(\%search);
3669 while (!$error and @cdr_usage_recs and $minutes > 0) {
3670 my $cdr_cust_pkg_usage = shift @cdr_usage_recs;
3671 my $cust_pkg_usage = $cdr_cust_pkg_usage->cust_pkg_usage;
3672 my $old_cdr = $cdr_cust_pkg_usage->cdr;
3673 $reproc_cdrs{$old_cdr->acctid} = $old_cdr;
3674 $cdr_cust_pkg_usage->select_for_update;
3675 $old_cdr->select_for_update;
3676 $cust_pkg_usage->select_for_update;
3677 # in case someone else stole the usage from this CDR
3678 # while waiting for the lock...
3679 next if $old_cdr->acctid != $cdr_cust_pkg_usage->acctid;
3680 # steal the usage allocation and flag the old CDR for reprocessing
3681 $cdr_cust_pkg_usage->set('acctid', $cdr->acctid);
3682 # if the allocation is more minutes than we need, adjust it...
3683 my $delta = $cdr_cust_pkg_usage->minutes - $minutes;
3685 $cdr_cust_pkg_usage->set('minutes', $minutes);
3686 $cust_pkg_usage->set('minutes', $cust_pkg_usage->minutes + $delta);
3687 $error = $cust_pkg_usage->replace;
3689 #warn 'CDR '.$cdr->acctid . ' stealing allocation '.$cdr_cust_pkg_usage->cdrusagenum.' from CDR '.$old_cdr->acctid."\n";
3690 $error ||= $cdr_cust_pkg_usage->replace;
3691 # deduct the stolen minutes
3692 $minutes -= $cdr_cust_pkg_usage->minutes;
3694 # after all minute-stealing is done, reset the affected CDRs
3695 foreach (values %reproc_cdrs) {
3696 $error ||= $_->set_status('');
3697 # XXX or should we just call $cdr->rate right here?
3698 # it's not like we can create a loop this way, since the min_charge
3699 # or call time has to go monotonically in one direction.
3700 # we COULD get some very deep recursions going, though...
3702 } # if $order and $minutes
3705 die "error applying included minutes\npkgnum ".$self->pkgnum.", class $classnum, acctid ".$cdr->acctid."\n$error\n"
3707 $dbh->commit if $oldAutoCommit;
3708 return $orig_minutes - $minutes;
3712 =item supplemental_pkgs
3714 Returns a list of all packages supplemental to this one.
3718 sub supplemental_pkgs {
3720 qsearch('cust_pkg', { 'main_pkgnum' => $self->pkgnum });
3725 Returns the package that this one is supplemental to, if any.
3731 if ( $self->main_pkgnum ) {
3732 return FS::cust_pkg->by_key($self->main_pkgnum);
3739 =head1 CLASS METHODS
3745 Returns an SQL expression identifying recurring packages.
3749 sub recurring_sql { "
3750 '0' != ( select freq from part_pkg
3751 where cust_pkg.pkgpart = part_pkg.pkgpart )
3756 Returns an SQL expression identifying one-time packages.
3761 '0' = ( select freq from part_pkg
3762 where cust_pkg.pkgpart = part_pkg.pkgpart )
3767 Returns an SQL expression identifying ordered packages (recurring packages not
3773 $_[0]->recurring_sql. " AND ". $_[0]->not_yet_billed_sql;
3778 Returns an SQL expression identifying active packages.
3783 $_[0]->recurring_sql. "
3784 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
3785 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
3786 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
3789 =item not_yet_billed_sql
3791 Returns an SQL expression identifying packages which have not yet been billed.
3795 sub not_yet_billed_sql { "
3796 ( cust_pkg.setup IS NULL OR cust_pkg.setup = 0 )
3797 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
3798 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
3803 Returns an SQL expression identifying inactive packages (one-time packages
3804 that are otherwise unsuspended/uncancelled).
3808 sub inactive_sql { "
3809 ". $_[0]->onetime_sql(). "
3810 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
3811 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
3812 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
3818 Returns an SQL expression identifying suspended packages.
3822 sub suspended_sql { susp_sql(@_); }
3824 #$_[0]->recurring_sql(). ' AND '.
3826 ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
3827 AND cust_pkg.susp IS NOT NULL AND cust_pkg.susp != 0
3834 Returns an SQL exprression identifying cancelled packages.
3838 sub cancelled_sql { cancel_sql(@_); }
3840 #$_[0]->recurring_sql(). ' AND '.
3841 "cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0";
3846 Returns an SQL expression to give the package status as a string.
3852 WHEN cust_pkg.cancel IS NOT NULL THEN 'cancelled'
3853 WHEN cust_pkg.susp IS NOT NULL THEN 'suspended'
3854 WHEN cust_pkg.setup IS NULL THEN 'not yet billed'
3855 WHEN ".onetime_sql()." THEN 'one-time charge'
3860 =item search HASHREF
3864 Returns a qsearch hash expression to search for parameters specified in HASHREF.
3865 Valid parameters are
3873 active, inactive, suspended, cancel (or cancelled)
3877 active, inactive, suspended, one-time charge, inactive, cancel (or cancelled)
3881 boolean selects custom packages
3887 pkgpart or arrayref or hashref of pkgparts
3891 arrayref of beginning and ending epoch date
3895 arrayref of beginning and ending epoch date
3899 arrayref of beginning and ending epoch date
3903 arrayref of beginning and ending epoch date
3907 arrayref of beginning and ending epoch date
3911 arrayref of beginning and ending epoch date
3915 arrayref of beginning and ending epoch date
3919 pkgnum or APKG_pkgnum
3923 a value suited to passing to FS::UI::Web::cust_header
3927 specifies the user for agent virtualization
3931 boolean; if true, returns only packages with more than 0 FCC phone lines.
3933 =item state, country
3935 Limit to packages with a service location in the specified state and country.
3936 For FCC 477 reporting, mostly.
3943 my ($class, $params) = @_;
3950 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
3952 "cust_main.agentnum = $1";
3959 if ( $params->{'custnum'} =~ /^(\d+)$/ and $1 ) {
3961 "cust_pkg.custnum = $1";
3968 if ( $params->{'pkgbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
3970 "cust_pkg.pkgbatch = '$1'";
3977 if ( $params->{'magic'} eq 'active'
3978 || $params->{'status'} eq 'active' ) {
3980 push @where, FS::cust_pkg->active_sql();
3982 } elsif ( $params->{'magic'} =~ /^not[ _]yet[ _]billed$/
3983 || $params->{'status'} =~ /^not[ _]yet[ _]billed$/ ) {
3985 push @where, FS::cust_pkg->not_yet_billed_sql();
3987 } elsif ( $params->{'magic'} =~ /^(one-time charge|inactive)/
3988 || $params->{'status'} =~ /^(one-time charge|inactive)/ ) {
3990 push @where, FS::cust_pkg->inactive_sql();
3992 } elsif ( $params->{'magic'} eq 'suspended'
3993 || $params->{'status'} eq 'suspended' ) {
3995 push @where, FS::cust_pkg->suspended_sql();
3997 } elsif ( $params->{'magic'} =~ /^cancell?ed$/
3998 || $params->{'status'} =~ /^cancell?ed$/ ) {
4000 push @where, FS::cust_pkg->cancelled_sql();
4005 # parse package class
4008 if ( exists($params->{'classnum'}) ) {
4011 if ( ref($params->{'classnum'}) ) {
4013 if ( ref($params->{'classnum'}) eq 'HASH' ) {
4014 @classnum = grep $params->{'classnum'}{$_}, keys %{ $params->{'classnum'} };
4015 } elsif ( ref($params->{'classnum'}) eq 'ARRAY' ) {
4016 @classnum = @{ $params->{'classnum'} };
4018 die 'unhandled classnum ref '. $params->{'classnum'};
4022 } elsif ( $params->{'classnum'} =~ /^(\d*)$/ && $1 ne '0' ) {
4029 my @nums = grep $_, @classnum;
4030 push @c_where, 'part_pkg.classnum IN ('. join(',',@nums). ')' if @nums;
4031 my $null = scalar( grep { $_ eq '' } @classnum );
4032 push @c_where, 'part_pkg.classnum IS NULL' if $null;
4034 if ( scalar(@c_where) == 1 ) {
4035 push @where, @c_where;
4036 } elsif ( @c_where ) {
4037 push @where, ' ( '. join(' OR ', @c_where). ' ) ';
4046 # parse package report options
4049 my @report_option = ();
4050 if ( exists($params->{'report_option'}) ) {
4051 if ( ref($params->{'report_option'}) eq 'ARRAY' ) {
4052 @report_option = @{ $params->{'report_option'} };
4053 } elsif ( $params->{'report_option'} =~ /^([,\d]*)$/ ) {
4054 @report_option = split(',', $1);
4059 if (@report_option) {
4060 # this will result in the empty set for the dangling comma case as it should
4062 map{ "0 < ( SELECT count(*) FROM part_pkg_option
4063 WHERE part_pkg_option.pkgpart = part_pkg.pkgpart
4064 AND optionname = 'report_option_$_'
4065 AND optionvalue = '1' )"
4069 foreach my $any ( grep /^report_option_any/, keys %$params ) {
4071 my @report_option_any = ();
4072 if ( ref($params->{$any}) eq 'ARRAY' ) {
4073 @report_option_any = @{ $params->{$any} };
4074 } elsif ( $params->{$any} =~ /^([,\d]*)$/ ) {
4075 @report_option_any = split(',', $1);
4078 if (@report_option_any) {
4079 # this will result in the empty set for the dangling comma case as it should
4080 push @where, ' ( '. join(' OR ',
4081 map{ "0 < ( SELECT count(*) FROM part_pkg_option
4082 WHERE part_pkg_option.pkgpart = part_pkg.pkgpart
4083 AND optionname = 'report_option_$_'
4084 AND optionvalue = '1' )"
4085 } @report_option_any
4095 push @where, "part_pkg.custom = 'Y'" if $params->{custom};
4101 push @where, "(part_pkg.fcc_ds0s > 0 OR pkg_class.fcc_ds0s > 0)"
4102 if $params->{fcc_line};
4108 if ( exists($params->{'censustract'}) ) {
4109 $params->{'censustract'} =~ /^([.\d]*)$/;
4110 my $censustract = "cust_location.censustract = '$1'";
4111 $censustract .= ' OR cust_location.censustract is NULL' unless $1;
4112 push @where, "( $censustract )";
4116 # parse censustract2
4118 if ( exists($params->{'censustract2'})
4119 && $params->{'censustract2'} =~ /^(\d*)$/
4123 push @where, "cust_location.censustract LIKE '$1%'";
4126 "( cust_location.censustract = '' OR cust_location.censustract IS NULL )";
4131 # parse country/state
4133 for (qw(state country)) { # parsing rules are the same for these
4134 if ( exists($params->{$_})
4135 && uc($params->{$_}) =~ /^([A-Z]{2})$/ )
4137 # XXX post-2.3 only--before that, state/country may be in cust_main
4138 push @where, "cust_location.$_ = '$1'";
4146 if ( ref($params->{'pkgpart'}) ) {
4149 if ( ref($params->{'pkgpart'}) eq 'HASH' ) {
4150 @pkgpart = grep $params->{'pkgpart'}{$_}, keys %{ $params->{'pkgpart'} };
4151 } elsif ( ref($params->{'pkgpart'}) eq 'ARRAY' ) {
4152 @pkgpart = @{ $params->{'pkgpart'} };
4154 die 'unhandled pkgpart ref '. $params->{'pkgpart'};
4157 @pkgpart = grep /^(\d+)$/, @pkgpart;
4159 push @where, 'pkgpart IN ('. join(',', @pkgpart). ')' if scalar(@pkgpart);
4161 } elsif ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
4162 push @where, "pkgpart = $1";
4171 #false laziness w/report_cust_pkg.html
4174 'one-time charge' => { 'last_bill'=>1, 'bill'=>1, 'adjourn'=>1, 'susp'=>1, 'expire'=>1, 'cancel'=>1, },
4175 'active' => { 'susp'=>1, 'cancel'=>1 },
4176 'suspended' => { 'cancel' => 1 },
4181 if( exists($params->{'active'} ) ) {
4182 # This overrides all the other date-related fields
4183 my($beginning, $ending) = @{$params->{'active'}};
4185 "cust_pkg.setup IS NOT NULL",
4186 "cust_pkg.setup <= $ending",
4187 "(cust_pkg.cancel IS NULL OR cust_pkg.cancel >= $beginning )",
4188 "NOT (".FS::cust_pkg->onetime_sql . ")";
4191 foreach my $field (qw( setup last_bill bill adjourn susp expire contract_end change_date cancel )) {
4193 next unless exists($params->{$field});
4195 my($beginning, $ending) = @{$params->{$field}};
4197 next if $beginning == 0 && $ending == 4294967295;
4200 "cust_pkg.$field IS NOT NULL",
4201 "cust_pkg.$field >= $beginning",
4202 "cust_pkg.$field <= $ending";
4204 $orderby ||= "ORDER BY cust_pkg.$field";
4209 $orderby ||= 'ORDER BY bill';
4212 # parse magic, legacy, etc.
4215 if ( $params->{'magic'} &&
4216 $params->{'magic'} =~ /^(active|inactive|suspended|cancell?ed)$/
4219 $orderby = 'ORDER BY pkgnum';
4221 if ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
4222 push @where, "pkgpart = $1";
4225 } elsif ( $params->{'query'} eq 'pkgnum' ) {
4227 $orderby = 'ORDER BY pkgnum';
4229 } elsif ( $params->{'query'} eq 'APKG_pkgnum' ) {
4231 $orderby = 'ORDER BY pkgnum';
4234 SELECT count(*) FROM pkg_svc
4235 WHERE pkg_svc.pkgpart = cust_pkg.pkgpart
4236 AND pkg_svc.quantity > ( SELECT count(*) FROM cust_svc
4237 WHERE cust_svc.pkgnum = cust_pkg.pkgnum
4238 AND cust_svc.svcpart = pkg_svc.svcpart
4245 # setup queries, links, subs, etc. for the search
4248 # here is the agent virtualization
4249 if ($params->{CurrentUser}) {
4251 qsearchs('access_user', { username => $params->{CurrentUser} });
4254 push @where, $access_user->agentnums_sql('table'=>'cust_main');
4259 push @where, $FS::CurrentUser::CurrentUser->agentnums_sql('table'=>'cust_main');
4262 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
4264 my $addl_from = 'LEFT JOIN part_pkg USING ( pkgpart ) '.
4265 'LEFT JOIN pkg_class ON ( part_pkg.classnum = pkg_class.classnum ) '.
4266 'LEFT JOIN cust_location USING ( locationnum ) '.
4267 FS::UI::Web::join_cust_main('cust_pkg', 'cust_pkg');
4271 if ( $params->{'select_zip5'} ) {
4272 my $zip = 'cust_location.zip';
4274 $select = "DISTINCT substr($zip,1,5) as zip";
4275 $orderby = "ORDER BY substr($zip,1,5)";
4276 $count_query = "SELECT COUNT( DISTINCT substr($zip,1,5) )";
4278 $select = join(', ',
4280 ( map "part_pkg.$_", qw( pkg freq ) ),
4281 'pkg_class.classname',
4282 'cust_main.custnum AS cust_main_custnum',
4283 FS::UI::Web::cust_sql_fields(
4284 $params->{'cust_fields'}
4287 $count_query = 'SELECT COUNT(*)';
4290 $count_query .= " FROM cust_pkg $addl_from $extra_sql";
4293 'table' => 'cust_pkg',
4295 'select' => $select,
4296 'extra_sql' => $extra_sql,
4297 'order_by' => $orderby,
4298 'addl_from' => $addl_from,
4299 'count_query' => $count_query,
4306 Returns a list of two package counts. The first is a count of packages
4307 based on the supplied criteria and the second is the count of residential
4308 packages with those same criteria. Criteria are specified as in the search
4314 my ($class, $params) = @_;
4316 my $sql_query = $class->search( $params );
4318 my $count_sql = delete($sql_query->{'count_query'});
4319 $count_sql =~ s/ FROM/,count(CASE WHEN cust_main.company IS NULL OR cust_main.company = '' THEN 1 END) FROM/
4320 or die "couldn't parse count_sql";
4322 my $count_sth = dbh->prepare($count_sql)
4323 or die "Error preparing $count_sql: ". dbh->errstr;
4325 or die "Error executing $count_sql: ". $count_sth->errstr;
4326 my $count_arrayref = $count_sth->fetchrow_arrayref;
4328 return ( @$count_arrayref );
4332 =item tax_locationnum_sql
4334 Returns an SQL expression for the tax location for a package, based
4335 on the settings of 'tax-pkg_address' and 'tax-ship_address'.
4339 sub tax_locationnum_sql {
4340 my $conf = FS::Conf->new;
4341 if ( $conf->exists('tax-pkg_address') ) {
4342 'cust_pkg.locationnum';
4344 elsif ( $conf->exists('tax-ship_address') ) {
4345 'cust_main.ship_locationnum';
4348 'cust_main.bill_locationnum';
4354 Returns a list: the first item is an SQL fragment identifying matching
4355 packages/customers via location (taking into account shipping and package
4356 address taxation, if enabled), and subsequent items are the parameters to
4357 substitute for the placeholders in that fragment.
4362 my($class, %opt) = @_;
4363 my $ornull = $opt{'ornull'};
4365 my $conf = new FS::Conf;
4367 # '?' placeholders in _location_sql_where
4368 my $x = $ornull ? 3 : 2;
4379 if ( $conf->exists('tax-ship_address') ) {
4382 ( ( ship_last IS NULL OR ship_last = '' )
4383 AND ". _location_sql_where('cust_main', '', $ornull ). "
4385 OR ( ship_last IS NOT NULL AND ship_last != ''
4386 AND ". _location_sql_where('cust_main', 'ship_', $ornull ). "
4389 # AND payby != 'COMP'
4391 @main_param = ( @bill_param, @bill_param );
4395 $main_where = _location_sql_where('cust_main'); # AND payby != 'COMP'
4396 @main_param = @bill_param;
4402 if ( $conf->exists('tax-pkg_address') ) {
4404 my $loc_where = _location_sql_where( 'cust_location', '', $ornull );
4407 ( cust_pkg.locationnum IS NULL AND $main_where )
4408 OR ( cust_pkg.locationnum IS NOT NULL AND $loc_where )
4411 @param = ( @main_param, @bill_param );
4415 $where = $main_where;
4416 @param = @main_param;
4424 #subroutine, helper for location_sql
4425 sub _location_sql_where {
4427 my $prefix = @_ ? shift : '';
4428 my $ornull = @_ ? shift : '';
4430 # $ornull = $ornull ? " OR ( ? IS NULL AND $table.${prefix}county IS NULL ) " : '';
4432 $ornull = $ornull ? ' OR ? IS NULL ' : '';
4434 my $or_empty_city = " OR ( ? = '' AND $table.${prefix}city IS NULL )";
4435 my $or_empty_county = " OR ( ? = '' AND $table.${prefix}county IS NULL )";
4436 my $or_empty_state = " OR ( ? = '' AND $table.${prefix}state IS NULL )";
4438 my $text = (driver_name =~ /^mysql/i) ? 'char' : 'text';
4440 # ( $table.${prefix}city = ? $or_empty_city $ornull )
4442 ( $table.district = ? OR ? = '' OR CAST(? AS $text) IS NULL )
4443 AND ( $table.${prefix}city = ? OR ? = '' OR CAST(? AS $text) IS NULL )
4444 AND ( $table.${prefix}county = ? $or_empty_county $ornull )
4445 AND ( $table.${prefix}state = ? $or_empty_state $ornull )
4446 AND $table.${prefix}country = ?
4451 my( $self, $what ) = @_;
4453 my $what_show_zero = $what. '_show_zero';
4454 length($self->$what_show_zero())
4455 ? ($self->$what_show_zero() eq 'Y')
4456 : $self->part_pkg->$what_show_zero();
4463 =item order CUSTNUM, PKGPARTS_ARYREF, [ REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF [ REFNUM ] ] ]
4465 CUSTNUM is a customer (see L<FS::cust_main>)
4467 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
4468 L<FS::part_pkg>) to order for this customer. Duplicates are of course
4471 REMOVE_PKGNUMS is an optional list of pkgnums specifying the billing items to
4472 remove for this customer. The services (see L<FS::cust_svc>) are moved to the
4473 new billing items. An error is returned if this is not possible (see
4474 L<FS::pkg_svc>). An empty arrayref is equivalent to not specifying this
4477 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
4478 newly-created cust_pkg objects.
4480 REFNUM, if specified, will specify the FS::pkg_referral record to be created
4481 and inserted. Multiple FS::pkg_referral records can be created by
4482 setting I<refnum> to an array reference of refnums or a hash reference with
4483 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
4484 record will be created corresponding to cust_main.refnum.
4489 my ($custnum, $pkgparts, $remove_pkgnum, $return_cust_pkg, $refnum) = @_;
4491 my $conf = new FS::Conf;
4493 # Transactionize this whole mess
4494 local $SIG{HUP} = 'IGNORE';
4495 local $SIG{INT} = 'IGNORE';
4496 local $SIG{QUIT} = 'IGNORE';
4497 local $SIG{TERM} = 'IGNORE';
4498 local $SIG{TSTP} = 'IGNORE';
4499 local $SIG{PIPE} = 'IGNORE';
4501 my $oldAutoCommit = $FS::UID::AutoCommit;
4502 local $FS::UID::AutoCommit = 0;
4506 # my $cust_main = qsearchs('cust_main', { custnum => $custnum });
4507 # return "Customer not found: $custnum" unless $cust_main;
4509 warn "$me order: pkgnums to remove: ". join(',', @$remove_pkgnum). "\n"
4512 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
4515 my $change = scalar(@old_cust_pkg) != 0;
4518 if ( scalar(@old_cust_pkg) == 1 && scalar(@$pkgparts) == 1 ) {
4520 warn "$me order: changing pkgnum ". $old_cust_pkg[0]->pkgnum.
4521 " to pkgpart ". $pkgparts->[0]. "\n"
4524 my $err_or_cust_pkg =
4525 $old_cust_pkg[0]->change( 'pkgpart' => $pkgparts->[0],
4526 'refnum' => $refnum,
4529 unless (ref($err_or_cust_pkg)) {
4530 $dbh->rollback if $oldAutoCommit;
4531 return $err_or_cust_pkg;
4534 push @$return_cust_pkg, $err_or_cust_pkg;
4535 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4540 # Create the new packages.
4541 foreach my $pkgpart (@$pkgparts) {
4543 warn "$me order: inserting pkgpart $pkgpart\n" if $DEBUG;
4545 my $cust_pkg = new FS::cust_pkg { custnum => $custnum,
4546 pkgpart => $pkgpart,
4550 $error = $cust_pkg->insert( 'change' => $change );
4551 push @$return_cust_pkg, $cust_pkg;
4553 foreach my $link ($cust_pkg->part_pkg->supp_part_pkg_link) {
4554 my $supp_pkg = FS::cust_pkg->new({
4555 custnum => $custnum,
4556 pkgpart => $link->dst_pkgpart,
4558 main_pkgnum => $cust_pkg->pkgnum,
4561 $error ||= $supp_pkg->insert( 'change' => $change );
4562 push @$return_cust_pkg, $supp_pkg;
4566 $dbh->rollback if $oldAutoCommit;
4571 # $return_cust_pkg now contains refs to all of the newly
4574 # Transfer services and cancel old packages.
4575 foreach my $old_pkg (@old_cust_pkg) {
4577 warn "$me order: transferring services from pkgnum ". $old_pkg->pkgnum. "\n"
4580 foreach my $new_pkg (@$return_cust_pkg) {
4581 $error = $old_pkg->transfer($new_pkg);
4582 if ($error and $error == 0) {
4583 # $old_pkg->transfer failed.
4584 $dbh->rollback if $oldAutoCommit;
4589 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
4590 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
4591 foreach my $new_pkg (@$return_cust_pkg) {
4592 $error = $old_pkg->transfer($new_pkg, 'change_svcpart'=>1 );
4593 if ($error and $error == 0) {
4594 # $old_pkg->transfer failed.
4595 $dbh->rollback if $oldAutoCommit;
4602 # Transfers were successful, but we went through all of the
4603 # new packages and still had services left on the old package.
4604 # We can't cancel the package under the circumstances, so abort.
4605 $dbh->rollback if $oldAutoCommit;
4606 return "Unable to transfer all services from package ".$old_pkg->pkgnum;
4608 $error = $old_pkg->cancel( quiet=>1 );
4614 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4618 =item bulk_change PKGPARTS_ARYREF, REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF ]
4620 A bulk change method to change packages for multiple customers.
4622 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
4623 L<FS::part_pkg>) to order for each customer. Duplicates are of course
4626 REMOVE_PKGNUMS is an list of pkgnums specifying the billing items to
4627 replace. The services (see L<FS::cust_svc>) are moved to the
4628 new billing items. An error is returned if this is not possible (see
4631 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
4632 newly-created cust_pkg objects.
4637 my ($pkgparts, $remove_pkgnum, $return_cust_pkg) = @_;
4639 # Transactionize this whole mess
4640 local $SIG{HUP} = 'IGNORE';
4641 local $SIG{INT} = 'IGNORE';
4642 local $SIG{QUIT} = 'IGNORE';
4643 local $SIG{TERM} = 'IGNORE';
4644 local $SIG{TSTP} = 'IGNORE';
4645 local $SIG{PIPE} = 'IGNORE';
4647 my $oldAutoCommit = $FS::UID::AutoCommit;
4648 local $FS::UID::AutoCommit = 0;
4652 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
4655 while(scalar(@old_cust_pkg)) {
4657 my $custnum = $old_cust_pkg[0]->custnum;
4658 my (@remove) = map { $_->pkgnum }
4659 grep { $_->custnum == $custnum } @old_cust_pkg;
4660 @old_cust_pkg = grep { $_->custnum != $custnum } @old_cust_pkg;
4662 my $error = order $custnum, $pkgparts, \@remove, \@return;
4664 push @errors, $error
4666 push @$return_cust_pkg, @return;
4669 if (scalar(@errors)) {
4670 $dbh->rollback if $oldAutoCommit;
4671 return join(' / ', @errors);
4674 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4678 # Used by FS::Upgrade to migrate to a new database.
4679 sub _upgrade_data { # class method
4680 my ($class, %opts) = @_;
4681 $class->_upgrade_otaker(%opts);
4683 # RT#10139, bug resulting in contract_end being set when it shouldn't
4684 'UPDATE cust_pkg SET contract_end = NULL WHERE contract_end = -1',
4685 # RT#10830, bad calculation of prorate date near end of year
4686 # the date range for bill is December 2009, and we move it forward
4687 # one year if it's before the previous bill date (which it should
4689 'UPDATE cust_pkg SET bill = bill + (365*24*60*60) WHERE bill < last_bill
4690 AND bill > 1259654400 AND bill < 1262332800 AND (SELECT plan FROM part_pkg
4691 WHERE part_pkg.pkgpart = cust_pkg.pkgpart) = \'prorate\'',
4692 # RT6628, add order_date to cust_pkg
4693 'update cust_pkg set order_date = (select history_date from h_cust_pkg
4694 where h_cust_pkg.pkgnum = cust_pkg.pkgnum and
4695 history_action = \'insert\') where order_date is null',
4697 foreach my $sql (@statements) {
4698 my $sth = dbh->prepare($sql);
4699 $sth->execute or die $sth->errstr;
4707 sub order is not OO. Perhaps it should be moved to FS::cust_main and made so?
4709 In sub order, the @pkgparts array (passed by reference) is clobbered.
4711 Also in sub order, no money is adjusted. Once FS::part_pkg defines a standard
4712 method to pass dates to the recur_prog expression, it should do so.
4714 FS::svc_acct, FS::svc_domain, FS::svc_www, FS::svc_ip and FS::svc_forward are
4715 loaded via 'use' at compile time, rather than via 'require' in sub { setup,
4716 suspend, unsuspend, cancel } because they use %FS::UID::callback to load
4717 configuration values. Probably need a subroutine which decides what to do
4718 based on whether or not we've fetched the user yet, rather than a hash. See
4719 FS::UID and the TODO.
4721 Now that things are transactional should the check in the insert method be
4726 L<FS::Record>, L<FS::cust_main>, L<FS::part_pkg>, L<FS::cust_svc>,
4727 L<FS::pkg_svc>, schema.html from the base documentation