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 ( $part_pkg->option('start_1st', 1) && !$self->start_date ) {
293 my ($sec,$min,$hour,$mday,$mon,$year) = (localtime(time) )[0,1,2,3,4,5];
294 $mon += 1 unless $mday == 1;
295 until ( $mon < 12 ) { $mon -= 12; $year++; }
296 $self->start_date( timelocal_nocheck(0,0,0,1,$mon,$year) );
299 foreach my $action ( qw(expire adjourn contract_end) ) {
300 my $months = $part_pkg->option("${action}_months",1);
301 if($months and !$self->$action) {
302 my $start = $self->start_date || $self->setup || time;
303 $self->$action( $part_pkg->add_freq($start, $months) );
307 if ( ! $options{'change'}
308 && ( my $free_days = $part_pkg->option('free_days',1) )
309 && $part_pkg->option('delay_setup',1)
310 #&& ! $self->start_date
313 my ($mday,$mon,$year) = (localtime(time) )[3,4,5];
314 #my $start_date = ($self->start_date || timelocal(0,0,0,$mday,$mon,$year)) + 86400 * $free_days;
315 my $start_date = timelocal(0,0,0,$mday,$mon,$year) + 86400 * $free_days;
316 $self->start_date($start_date);
319 $self->order_date(time);
321 local $SIG{HUP} = 'IGNORE';
322 local $SIG{INT} = 'IGNORE';
323 local $SIG{QUIT} = 'IGNORE';
324 local $SIG{TERM} = 'IGNORE';
325 local $SIG{TSTP} = 'IGNORE';
326 local $SIG{PIPE} = 'IGNORE';
328 my $oldAutoCommit = $FS::UID::AutoCommit;
329 local $FS::UID::AutoCommit = 0;
332 $error = $self->SUPER::insert($options{options} ? %{$options{options}} : ());
334 $dbh->rollback if $oldAutoCommit;
338 $self->refnum($self->cust_main->refnum) unless $self->refnum;
339 $self->refnum( [ $self->refnum ] ) unless ref($self->refnum);
340 $self->process_m2m( 'link_table' => 'pkg_referral',
341 'target_table' => 'part_referral',
342 'params' => $self->refnum,
345 if ( $self->discountnum ) {
346 my $error = $self->insert_discount();
348 $dbh->rollback if $oldAutoCommit;
353 #if ( $self->reg_code ) {
354 # my $reg_code = qsearchs('reg_code', { 'code' => $self->reg_code } );
355 # $error = $reg_code->delete;
357 # $dbh->rollback if $oldAutoCommit;
362 my $conf = new FS::Conf;
364 if ( $conf->config('ticket_system') && $options{ticket_subject} ) {
366 #this init stuff is still inefficient, but at least its limited to
367 # the small number (any?) folks using ticket emailing on pkg order
370 # use lib ( "/opt/rt3/local/lib", "/opt/rt3/lib" );
377 use FS::TicketSystem;
378 FS::TicketSystem->init();
380 my $q = new RT::Queue($RT::SystemUser);
381 $q->Load($options{ticket_queue}) if $options{ticket_queue};
382 my $t = new RT::Ticket($RT::SystemUser);
383 my $mime = new MIME::Entity;
384 $mime->build( Type => 'text/plain', Data => $options{ticket_subject} );
385 $t->Create( $options{ticket_queue} ? (Queue => $q) : (),
386 Subject => $options{ticket_subject},
389 $t->AddLink( Type => 'MemberOf',
390 Target => 'freeside://freeside/cust_main/'. $self->custnum,
394 if ($conf->config('welcome_letter') && $self->cust_main->num_pkgs == 1) {
395 my $queue = new FS::queue {
396 'job' => 'FS::cust_main::queueable_print',
398 $error = $queue->insert(
399 'custnum' => $self->custnum,
400 'template' => 'welcome_letter',
404 warn "can't send welcome letter: $error";
409 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
416 This method now works but you probably shouldn't use it.
418 You don't want to delete packages, because there would then be no record
419 the customer ever purchased the package. Instead, see the cancel method and
420 hide cancelled packages.
427 local $SIG{HUP} = 'IGNORE';
428 local $SIG{INT} = 'IGNORE';
429 local $SIG{QUIT} = 'IGNORE';
430 local $SIG{TERM} = 'IGNORE';
431 local $SIG{TSTP} = 'IGNORE';
432 local $SIG{PIPE} = 'IGNORE';
434 my $oldAutoCommit = $FS::UID::AutoCommit;
435 local $FS::UID::AutoCommit = 0;
438 foreach my $cust_pkg_discount ($self->cust_pkg_discount) {
439 my $error = $cust_pkg_discount->delete;
441 $dbh->rollback if $oldAutoCommit;
445 #cust_bill_pkg_discount?
447 foreach my $cust_pkg_detail ($self->cust_pkg_detail) {
448 my $error = $cust_pkg_detail->delete;
450 $dbh->rollback if $oldAutoCommit;
455 foreach my $cust_pkg_reason (
457 'table' => 'cust_pkg_reason',
458 'hashref' => { 'pkgnum' => $self->pkgnum },
462 my $error = $cust_pkg_reason->delete;
464 $dbh->rollback if $oldAutoCommit;
471 my $error = $self->SUPER::delete(@_);
473 $dbh->rollback if $oldAutoCommit;
477 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
483 =item replace [ OLD_RECORD ] [ HASHREF | OPTION => VALUE ... ]
485 Replaces the OLD_RECORD with this one in the database. If there is an error,
486 returns the error, otherwise returns false.
488 Currently, custnum, setup, bill, adjourn, susp, expire, and cancel may be changed.
490 Changing pkgpart may have disasterous effects. See the order subroutine.
492 setup and bill are normally updated by calling the bill method of a customer
493 object (see L<FS::cust_main>).
495 suspend is normally updated by the suspend and unsuspend methods.
497 cancel is normally updated by the cancel method (and also the order subroutine
500 Available options are:
506 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.
510 the access_user (see L<FS::access_user>) providing the reason
514 hashref of keys and values - cust_pkg_option records will be created, updated or removed as appopriate
523 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
528 ( ref($_[0]) eq 'HASH' )
532 #return "Can't (yet?) change pkgpart!" if $old->pkgpart != $new->pkgpart;
533 #return "Can't change otaker!" if $old->otaker ne $new->otaker;
536 #return "Can't change setup once it exists!"
537 # if $old->getfield('setup') &&
538 # $old->getfield('setup') != $new->getfield('setup');
540 #some logic for bill, susp, cancel?
542 local($disable_agentcheck) = 1 if $old->pkgpart == $new->pkgpart;
544 local $SIG{HUP} = 'IGNORE';
545 local $SIG{INT} = 'IGNORE';
546 local $SIG{QUIT} = 'IGNORE';
547 local $SIG{TERM} = 'IGNORE';
548 local $SIG{TSTP} = 'IGNORE';
549 local $SIG{PIPE} = 'IGNORE';
551 my $oldAutoCommit = $FS::UID::AutoCommit;
552 local $FS::UID::AutoCommit = 0;
555 foreach my $method ( qw(adjourn expire) ) { # How many reasons?
556 if ($options->{'reason'} && $new->$method && $old->$method ne $new->$method) {
557 my $error = $new->insert_reason(
558 'reason' => $options->{'reason'},
559 'date' => $new->$method,
561 'reason_otaker' => $options->{'reason_otaker'},
564 dbh->rollback if $oldAutoCommit;
565 return "Error inserting cust_pkg_reason: $error";
570 #save off and freeze RADIUS attributes for any associated svc_acct records
572 if ( $old->part_pkg->is_prepaid || $new->part_pkg->is_prepaid ) {
574 #also check for specific exports?
575 # to avoid spurious modify export events
576 @svc_acct = map { $_->svc_x }
577 grep { $_->part_svc->svcdb eq 'svc_acct' }
580 $_->snapshot foreach @svc_acct;
584 my $error = $new->SUPER::replace($old,
585 $options->{options} ? $options->{options} : ()
588 $dbh->rollback if $oldAutoCommit;
592 #for prepaid packages,
593 #trigger export of new RADIUS Expiration attribute when cust_pkg.bill changes
594 foreach my $old_svc_acct ( @svc_acct ) {
595 my $new_svc_acct = new FS::svc_acct { $old_svc_acct->hash };
597 $new_svc_acct->replace( $old_svc_acct,
598 'depend_jobnum' => $options->{depend_jobnum},
601 $dbh->rollback if $oldAutoCommit;
606 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
613 Checks all fields to make sure this is a valid billing item. If there is an
614 error, returns the error, otherwise returns false. Called by the insert and
622 if ( !$self->locationnum or $self->locationnum == -1 ) {
623 $self->set('locationnum', $self->cust_main->ship_locationnum);
627 $self->ut_numbern('pkgnum')
628 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum')
629 || $self->ut_numbern('pkgpart')
630 || $self->ut_foreign_keyn('contactnum', 'contact', 'contactnum' )
631 || $self->ut_foreign_keyn('locationnum', 'cust_location', 'locationnum')
632 || $self->ut_numbern('start_date')
633 || $self->ut_numbern('setup')
634 || $self->ut_numbern('bill')
635 || $self->ut_numbern('susp')
636 || $self->ut_numbern('cancel')
637 || $self->ut_numbern('adjourn')
638 || $self->ut_numbern('resume')
639 || $self->ut_numbern('expire')
640 || $self->ut_numbern('dundate')
641 || $self->ut_enum('no_auto', [ '', 'Y' ])
642 || $self->ut_enum('waive_setup', [ '', 'Y' ])
643 || $self->ut_numbern('agent_pkgid')
644 || $self->ut_enum('recur_show_zero', [ '', 'Y', 'N', ])
645 || $self->ut_enum('setup_show_zero', [ '', 'Y', 'N', ])
646 || $self->ut_foreign_keyn('main_pkgnum', 'cust_pkg', 'pkgnum')
647 || $self->ut_foreign_keyn('pkglinknum', 'part_pkg_link', 'pkglinknum')
649 return $error if $error;
651 return "A package with both start date (future start) and setup date (already started) will never bill"
652 if $self->start_date && $self->setup;
654 return "A future unsuspend date can only be set for a package with a suspend date"
655 if $self->resume and !$self->susp and !$self->adjourn;
657 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
659 if ( $self->dbdef_table->column('manual_flag') ) {
660 $self->manual_flag('') if $self->manual_flag eq ' ';
661 $self->manual_flag =~ /^([01]?)$/
662 or return "Illegal manual_flag ". $self->manual_flag;
663 $self->manual_flag($1);
671 Check the pkgpart to make sure it's allowed with the reg_code and/or
672 promo_code of the package (if present) and with the customer's agent.
673 Called from C<insert>, unless we are doing a package change that doesn't
681 # my $error = $self->ut_numbern('pkgpart'); # already done
684 if ( $self->reg_code ) {
686 unless ( grep { $self->pkgpart == $_->pkgpart }
687 map { $_->reg_code_pkg }
688 qsearchs( 'reg_code', { 'code' => $self->reg_code,
689 'agentnum' => $self->cust_main->agentnum })
691 return "Unknown registration code";
694 } elsif ( $self->promo_code ) {
697 qsearchs('part_pkg', {
698 'pkgpart' => $self->pkgpart,
699 'promo_code' => { op=>'ILIKE', value=>$self->promo_code },
701 return 'Unknown promotional code' unless $promo_part_pkg;
705 unless ( $disable_agentcheck ) {
707 qsearchs( 'agent', { 'agentnum' => $self->cust_main->agentnum } );
708 return "agent ". $agent->agentnum. ':'. $agent->agent.
709 " can't purchase pkgpart ". $self->pkgpart
710 unless $agent->pkgpart_hashref->{ $self->pkgpart }
711 || $agent->agentnum == $self->part_pkg->agentnum;
714 $error = $self->ut_foreign_key('pkgpart', 'part_pkg', 'pkgpart' );
715 return $error if $error;
723 =item cancel [ OPTION => VALUE ... ]
725 Cancels and removes all services (see L<FS::cust_svc> and L<FS::part_svc>)
726 in this package, then cancels the package itself (sets the cancel field to
729 Available options are:
733 =item quiet - can be set true to supress email cancellation notices.
735 =item time - can be set to cancel the package based on a specific future or
736 historical date. Using time ensures that the remaining amount is calculated
737 correctly. Note however that this is an immediate cancel and just changes
738 the date. You are PROBABLY looking to expire the account instead of using
741 =item reason - can be set to a cancellation reason (see L<FS:reason>),
742 either a reasonnum of an existing reason, or passing a hashref will create
743 a new reason. The hashref should have the following keys: typenum - Reason
744 type (see L<FS::reason_type>, reason - Text of the new reason.
746 =item date - can be set to a unix style timestamp to specify when to
749 =item nobill - can be set true to skip billing if it might otherwise be done.
751 =item unused_credit - can be set to 1 to credit the remaining time, or 0 to
752 not credit it. This must be set (by change()) when changing the package
753 to a different pkgpart or location, and probably shouldn't be in any other
754 case. If it's not set, the 'unused_credit_cancel' part_pkg option will
759 If there is an error, returns the error, otherwise returns false.
764 my( $self, %options ) = @_;
767 # pass all suspend/cancel actions to the main package
768 if ( $self->main_pkgnum and !$options{'from_main'} ) {
769 return $self->main_pkg->cancel(%options);
772 my $conf = new FS::Conf;
774 warn "cust_pkg::cancel called with options".
775 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
778 local $SIG{HUP} = 'IGNORE';
779 local $SIG{INT} = 'IGNORE';
780 local $SIG{QUIT} = 'IGNORE';
781 local $SIG{TERM} = 'IGNORE';
782 local $SIG{TSTP} = 'IGNORE';
783 local $SIG{PIPE} = 'IGNORE';
785 my $oldAutoCommit = $FS::UID::AutoCommit;
786 local $FS::UID::AutoCommit = 0;
789 my $old = $self->select_for_update;
791 if ( $old->get('cancel') || $self->get('cancel') ) {
792 dbh->rollback if $oldAutoCommit;
793 return ""; # no error
796 # XXX possibly set cancel_time to the expire date?
797 my $cancel_time = $options{'time'} || time;
798 my $date = $options{'date'} if $options{'date'}; # expire/cancel later
799 $date = '' if ($date && $date <= $cancel_time); # complain instead?
801 #race condition: usage could be ongoing until unprovisioned
802 #resolved by performing a change package instead (which unprovisions) and
804 if ( !$options{nobill} && !$date ) {
805 # && $conf->exists('bill_usage_on_cancel') ) { #calc_cancel checks this
806 my $copy = $self->new({$self->hash});
808 $copy->cust_main->bill( 'pkg_list' => [ $copy ],
810 'time' => $cancel_time );
811 warn "Error billing during cancel, custnum ".
812 #$self->cust_main->custnum. ": $error"
817 if ( $options{'reason'} ) {
818 $error = $self->insert_reason( 'reason' => $options{'reason'},
819 'action' => $date ? 'expire' : 'cancel',
820 'date' => $date ? $date : $cancel_time,
821 'reason_otaker' => $options{'reason_otaker'},
824 dbh->rollback if $oldAutoCommit;
825 return "Error inserting cust_pkg_reason: $error";
829 my %svc_cancel_opt = ();
830 $svc_cancel_opt{'date'} = $date if $date;
831 foreach my $cust_svc (
834 sort { $a->[1] <=> $b->[1] }
835 map { [ $_, $_->svc_x ? $_->svc_x->table_info->{'cancel_weight'} : -1 ]; }
836 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
838 my $part_svc = $cust_svc->part_svc;
839 next if ( defined($part_svc) and $part_svc->preserve );
840 my $error = $cust_svc->cancel( %svc_cancel_opt );
843 $dbh->rollback if $oldAutoCommit;
844 return 'Error '. ($svc_cancel_opt{'date'} ? 'expiring' : 'canceling' ).
850 # credit remaining time if appropriate
852 if ( exists($options{'unused_credit'}) ) {
853 $do_credit = $options{'unused_credit'};
856 $do_credit = $self->part_pkg->option('unused_credit_cancel', 1);
859 my $error = $self->credit_remaining('cancel', $cancel_time);
861 $dbh->rollback if $oldAutoCommit;
868 my %hash = $self->hash;
869 $date ? ($hash{'expire'} = $date) : ($hash{'cancel'} = $cancel_time);
870 $hash{'change_custnum'} = $options{'change_custnum'};
871 my $new = new FS::cust_pkg ( \%hash );
872 $error = $new->replace( $self, options => { $self->options } );
874 $dbh->rollback if $oldAutoCommit;
878 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
879 $error = $supp_pkg->cancel(%options, 'from_main' => 1);
881 $dbh->rollback if $oldAutoCommit;
882 return "canceling supplemental pkg#".$supp_pkg->pkgnum.": $error";
886 foreach my $usage ( $self->cust_pkg_usage ) {
887 $error = $usage->delete;
889 $dbh->rollback if $oldAutoCommit;
890 return "deleting usage pools: $error";
894 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
895 return '' if $date; #no errors
897 my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ } $self->cust_main->invoicing_list;
898 if ( !$options{'quiet'} &&
899 $conf->exists('emailcancel', $self->cust_main->agentnum) &&
901 my $msgnum = $conf->config('cancel_msgnum', $self->cust_main->agentnum);
904 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum });
905 $error = $msg_template->send( 'cust_main' => $self->cust_main,
910 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
911 'to' => \@invoicing_list,
912 'subject' => ( $conf->config('cancelsubject') || 'Cancellation Notice' ),
913 'body' => [ map "$_\n", $conf->config('cancelmessage') ],
916 #should this do something on errors?
923 =item cancel_if_expired [ NOW_TIMESTAMP ]
925 Cancels this package if its expire date has been reached.
929 sub cancel_if_expired {
931 my $time = shift || time;
932 return '' unless $self->expire && $self->expire <= $time;
933 my $error = $self->cancel;
935 return "Error cancelling expired pkg ". $self->pkgnum. " for custnum ".
936 $self->custnum. ": $error";
943 "Un-cancels" this package: Orders a new package with the same custnum, pkgpart,
944 locationnum, (other fields?). Attempts to re-provision cancelled services
945 using history information (errors at this stage are not fatal).
947 cust_pkg: pass a scalar reference, will be filled in with the new cust_pkg object
949 svc_fatal: service provisioning errors are fatal
951 svc_errors: pass an array reference, will be filled in with any provisioning errors
953 main_pkgnum: link the package as a supplemental package of this one. For
959 my( $self, %options ) = @_;
961 #in case you try do do $uncancel-date = $cust_pkg->uncacel
962 return '' unless $self->get('cancel');
964 if ( $self->main_pkgnum and !$options{'main_pkgnum'} ) {
965 return $self->main_pkg->uncancel(%options);
972 local $SIG{HUP} = 'IGNORE';
973 local $SIG{INT} = 'IGNORE';
974 local $SIG{QUIT} = 'IGNORE';
975 local $SIG{TERM} = 'IGNORE';
976 local $SIG{TSTP} = 'IGNORE';
977 local $SIG{PIPE} = 'IGNORE';
979 my $oldAutoCommit = $FS::UID::AutoCommit;
980 local $FS::UID::AutoCommit = 0;
984 # insert the new package
987 my $cust_pkg = new FS::cust_pkg {
988 last_bill => ( $options{'last_bill'} || $self->get('last_bill') ),
989 bill => ( $options{'bill'} || $self->get('bill') ),
991 uncancel_pkgnum => $self->pkgnum,
992 main_pkgnum => ($options{'main_pkgnum'} || ''),
993 map { $_ => $self->get($_) } qw(
994 custnum pkgpart locationnum
996 susp adjourn resume expire start_date contract_end dundate
997 change_date change_pkgpart change_locationnum
998 manual_flag no_auto quantity agent_pkgid recur_show_zero setup_show_zero
1002 my $error = $cust_pkg->insert(
1003 'change' => 1, #supresses any referral credit to a referring customer
1004 'allow_pkgpart' => 1, # allow this even if the package def is disabled
1007 $dbh->rollback if $oldAutoCommit;
1015 #find historical services within this timeframe before the package cancel
1016 # (incompatible with "time" option to cust_pkg->cancel?)
1017 my $fuzz = 2 * 60; #2 minutes? too much? (might catch separate unprovision)
1018 # too little? (unprovisioing export delay?)
1019 my($end, $start) = ( $self->get('cancel'), $self->get('cancel') - $fuzz );
1020 my @h_cust_svc = $self->h_cust_svc( $end, $start );
1023 foreach my $h_cust_svc (@h_cust_svc) {
1024 my $h_svc_x = $h_cust_svc->h_svc_x( $end, $start );
1025 #next unless $h_svc_x; #should this happen?
1026 (my $table = $h_svc_x->table) =~ s/^h_//;
1027 require "FS/$table.pm";
1028 my $class = "FS::$table";
1029 my $svc_x = $class->new( {
1030 'pkgnum' => $cust_pkg->pkgnum,
1031 'svcpart' => $h_cust_svc->svcpart,
1032 map { $_ => $h_svc_x->get($_) } fields($table)
1036 if ( $h_svc_x->isa('FS::h_svc_Radius_Mixin') ) {
1037 $svc_x->usergroup( [ $h_svc_x->h_usergroup($end, $start) ] );
1040 my $svc_error = $svc_x->insert;
1042 if ( $options{svc_fatal} ) {
1043 $dbh->rollback if $oldAutoCommit;
1046 # if we've failed to insert the svc_x object, svc_Common->insert
1047 # will have removed the cust_svc already. if not, then both records
1048 # were inserted but we failed for some other reason (export, most
1049 # likely). in that case, report the error and delete the records.
1050 push @svc_errors, $svc_error;
1051 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svc_x->svcnum });
1053 # except if export_insert failed, export_delete probably won't be
1055 local $FS::svc_Common::noexport_hack = 1;
1056 my $cleanup_error = $svc_x->delete; # also deletes cust_svc
1057 if ( $cleanup_error ) { # and if THAT fails, then run away
1058 $dbh->rollback if $oldAutoCommit;
1059 return $cleanup_error;
1064 } #foreach $h_cust_svc
1066 #these are pretty rare, but should handle them
1067 # - dsl_device (mac addresses)
1068 # - phone_device (mac addresses)
1069 # - dsl_note (ikano notes)
1070 # - domain_record (i.e. restore DNS information w/domains)
1071 # - inventory_item(?) (inventory w/un-cancelling service?)
1072 # - nas (svc_broaband nas stuff)
1073 #this stuff is unused in the wild afaik
1074 # - mailinglistmember
1076 # - svc_domain.parent_svcnum?
1077 # - acct_snarf (ancient mail fetching config)
1078 # - cgp_rule (communigate)
1079 # - cust_svc_option (used by our Tron stuff)
1080 # - acct_rt_transaction (used by our time worked stuff)
1083 # also move over any services that didn't unprovision at cancellation
1086 foreach my $cust_svc ( qsearch('cust_svc', { pkgnum => $self->pkgnum } ) ) {
1087 $cust_svc->pkgnum( $cust_pkg->pkgnum );
1088 my $error = $cust_svc->replace;
1090 $dbh->rollback if $oldAutoCommit;
1096 # Uncancel any supplemental packages, and make them supplemental to the
1100 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1102 $error = $supp_pkg->uncancel(%options, 'main_pkgnum' => $cust_pkg->pkgnum);
1104 $dbh->rollback if $oldAutoCommit;
1105 return "canceling supplemental pkg#".$supp_pkg->pkgnum.": $error";
1113 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1115 ${ $options{cust_pkg} } = $cust_pkg if ref($options{cust_pkg});
1116 @{ $options{svc_errors} } = @svc_errors if ref($options{svc_errors});
1123 Cancels any pending expiration (sets the expire field to null).
1125 If there is an error, returns the error, otherwise returns false.
1130 my( $self, %options ) = @_;
1133 local $SIG{HUP} = 'IGNORE';
1134 local $SIG{INT} = 'IGNORE';
1135 local $SIG{QUIT} = 'IGNORE';
1136 local $SIG{TERM} = 'IGNORE';
1137 local $SIG{TSTP} = 'IGNORE';
1138 local $SIG{PIPE} = 'IGNORE';
1140 my $oldAutoCommit = $FS::UID::AutoCommit;
1141 local $FS::UID::AutoCommit = 0;
1144 my $old = $self->select_for_update;
1146 my $pkgnum = $old->pkgnum;
1147 if ( $old->get('cancel') || $self->get('cancel') ) {
1148 dbh->rollback if $oldAutoCommit;
1149 return "Can't unexpire cancelled package $pkgnum";
1150 # or at least it's pointless
1153 unless ( $old->get('expire') && $self->get('expire') ) {
1154 dbh->rollback if $oldAutoCommit;
1155 return ""; # no error
1158 my %hash = $self->hash;
1159 $hash{'expire'} = '';
1160 my $new = new FS::cust_pkg ( \%hash );
1161 $error = $new->replace( $self, options => { $self->options } );
1163 $dbh->rollback if $oldAutoCommit;
1167 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1173 =item suspend [ OPTION => VALUE ... ]
1175 Suspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
1176 package, then suspends the package itself (sets the susp field to now).
1178 Available options are:
1182 =item reason - can be set to a cancellation reason (see L<FS:reason>),
1183 either a reasonnum of an existing reason, or passing a hashref will create
1184 a new reason. The hashref should have the following keys:
1185 - typenum - Reason type (see L<FS::reason_type>
1186 - reason - Text of the new reason.
1188 =item date - can be set to a unix style timestamp to specify when to
1191 =item time - can be set to override the current time, for calculation
1192 of final invoices or unused-time credits
1194 =item resume_date - can be set to a time when the package should be
1195 unsuspended. This may be more convenient than calling C<unsuspend()>
1198 =item from_main - allows a supplemental package to be suspended, rather
1199 than redirecting the method call to its main package. For internal use.
1203 If there is an error, returns the error, otherwise returns false.
1208 my( $self, %options ) = @_;
1211 # pass all suspend/cancel actions to the main package
1212 if ( $self->main_pkgnum and !$options{'from_main'} ) {
1213 return $self->main_pkg->suspend(%options);
1216 local $SIG{HUP} = 'IGNORE';
1217 local $SIG{INT} = 'IGNORE';
1218 local $SIG{QUIT} = 'IGNORE';
1219 local $SIG{TERM} = 'IGNORE';
1220 local $SIG{TSTP} = 'IGNORE';
1221 local $SIG{PIPE} = 'IGNORE';
1223 my $oldAutoCommit = $FS::UID::AutoCommit;
1224 local $FS::UID::AutoCommit = 0;
1227 my $old = $self->select_for_update;
1229 my $pkgnum = $old->pkgnum;
1230 if ( $old->get('cancel') || $self->get('cancel') ) {
1231 dbh->rollback if $oldAutoCommit;
1232 return "Can't suspend cancelled package $pkgnum";
1235 if ( $old->get('susp') || $self->get('susp') ) {
1236 dbh->rollback if $oldAutoCommit;
1237 return ""; # no error # complain on adjourn?
1240 my $suspend_time = $options{'time'} || time;
1241 my $date = $options{date} if $options{date}; # adjourn/suspend later
1242 $date = '' if ($date && $date <= $suspend_time); # complain instead?
1244 if ( $date && $old->get('expire') && $old->get('expire') < $date ) {
1245 dbh->rollback if $oldAutoCommit;
1246 return "Package $pkgnum expires before it would be suspended.";
1249 # some false laziness with sub cancel
1250 if ( !$options{nobill} && !$date &&
1251 $self->part_pkg->option('bill_suspend_as_cancel',1) ) {
1252 # kind of a kludge--'bill_suspend_as_cancel' to avoid having to
1253 # make the entire cust_main->bill path recognize 'suspend' and
1254 # 'cancel' separately.
1255 warn "Billing $pkgnum on suspension (at $suspend_time)\n" if $DEBUG;
1256 my $copy = $self->new({$self->hash});
1258 $copy->cust_main->bill( 'pkg_list' => [ $copy ],
1260 'time' => $suspend_time );
1261 warn "Error billing during suspend, custnum ".
1262 #$self->cust_main->custnum. ": $error"
1267 if ( $options{'reason'} ) {
1268 $error = $self->insert_reason( 'reason' => $options{'reason'},
1269 'action' => $date ? 'adjourn' : 'suspend',
1270 'date' => $date ? $date : $suspend_time,
1271 'reason_otaker' => $options{'reason_otaker'},
1274 dbh->rollback if $oldAutoCommit;
1275 return "Error inserting cust_pkg_reason: $error";
1279 my %hash = $self->hash;
1281 $hash{'adjourn'} = $date;
1283 $hash{'susp'} = $suspend_time;
1286 my $resume_date = $options{'resume_date'} || 0;
1287 if ( $resume_date > ($date || $suspend_time) ) {
1288 $hash{'resume'} = $resume_date;
1291 $options{options} ||= {};
1293 my $new = new FS::cust_pkg ( \%hash );
1294 $error = $new->replace( $self, options => { $self->options,
1295 %{ $options{options} },
1299 $dbh->rollback if $oldAutoCommit;
1304 # credit remaining time if appropriate
1305 if ( $self->part_pkg->option('unused_credit_suspend', 1) ) {
1306 my $error = $self->credit_remaining('suspend', $suspend_time);
1308 $dbh->rollback if $oldAutoCommit;
1315 foreach my $cust_svc (
1316 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
1318 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
1320 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
1321 $dbh->rollback if $oldAutoCommit;
1322 return "Illegal svcdb value in part_svc!";
1325 require "FS/$svcdb.pm";
1327 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
1329 $error = $svc->suspend;
1331 $dbh->rollback if $oldAutoCommit;
1334 my( $label, $value ) = $cust_svc->label;
1335 push @labels, "$label: $value";
1339 my $conf = new FS::Conf;
1340 if ( $conf->config('suspend_email_admin') ) {
1342 my $error = send_email(
1343 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
1344 #invoice_from ??? well as good as any
1345 'to' => $conf->config('suspend_email_admin'),
1346 'subject' => 'FREESIDE NOTIFICATION: Customer package suspended',
1348 "This is an automatic message from your Freeside installation\n",
1349 "informing you that the following customer package has been suspended:\n",
1351 'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
1352 'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
1353 ( map { "Service : $_\n" } @labels ),
1358 warn "WARNING: can't send suspension admin email (suspending anyway): ".
1366 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1367 $error = $supp_pkg->suspend(%options, 'from_main' => 1);
1369 $dbh->rollback if $oldAutoCommit;
1370 return "suspending supplemental pkg#".$supp_pkg->pkgnum.": $error";
1374 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1379 =item credit_remaining MODE TIME
1381 Generate a credit for this package for the time remaining in the current
1382 billing period. MODE is either "suspend" or "cancel" (determines the
1383 credit type). TIME is the time of suspension/cancellation. Both arguments
1388 sub credit_remaining {
1389 # Add a credit for remaining service
1390 my ($self, $mode, $time) = @_;
1391 die 'credit_remaining requires suspend or cancel'
1392 unless $mode eq 'suspend' or $mode eq 'cancel';
1393 die 'no suspend/cancel time' unless $time > 0;
1395 my $conf = FS::Conf->new;
1396 my $reason_type = $conf->config($mode.'_credit_type');
1398 my $last_bill = $self->getfield('last_bill') || 0;
1399 my $next_bill = $self->getfield('bill') || 0;
1400 if ( $last_bill > 0 # the package has been billed
1401 and $next_bill > 0 # the package has a next bill date
1402 and $next_bill >= $time # which is in the future
1404 my $remaining_value = $self->calc_remain('time' => $time);
1405 if ( $remaining_value > 0 ) {
1406 warn "Crediting for $remaining_value on package ".$self->pkgnum."\n"
1408 my $error = $self->cust_main->credit(
1410 'Credit for unused time on '. $self->part_pkg->pkg,
1411 'reason_type' => $reason_type,
1413 return "Error crediting customer \$$remaining_value for unused time".
1414 " on ". $self->part_pkg->pkg. ": $error"
1416 } #if $remaining_value
1417 } #if $last_bill, etc.
1421 =item unsuspend [ OPTION => VALUE ... ]
1423 Unsuspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
1424 package, then unsuspends the package itself (clears the susp field and the
1425 adjourn field if it is in the past). If the suspend reason includes an
1426 unsuspension package, that package will be ordered.
1428 Available options are:
1434 Can be set to a date to unsuspend the package in the future (the 'resume'
1437 =item adjust_next_bill
1439 Can be set true to adjust the next bill date forward by
1440 the amount of time the account was inactive. This was set true by default
1441 since 1.4.2 and 1.5.0pre6; however, starting with 1.7.0 this needs to be
1442 explicitly requested. Price plans for which this makes sense (anniversary-date
1443 based than prorate or subscription) could have an option to enable this
1448 If there is an error, returns the error, otherwise returns false.
1453 my( $self, %opt ) = @_;
1456 # pass all suspend/cancel actions to the main package
1457 if ( $self->main_pkgnum and !$opt{'from_main'} ) {
1458 return $self->main_pkg->unsuspend(%opt);
1461 local $SIG{HUP} = 'IGNORE';
1462 local $SIG{INT} = 'IGNORE';
1463 local $SIG{QUIT} = 'IGNORE';
1464 local $SIG{TERM} = 'IGNORE';
1465 local $SIG{TSTP} = 'IGNORE';
1466 local $SIG{PIPE} = 'IGNORE';
1468 my $oldAutoCommit = $FS::UID::AutoCommit;
1469 local $FS::UID::AutoCommit = 0;
1472 my $old = $self->select_for_update;
1474 my $pkgnum = $old->pkgnum;
1475 if ( $old->get('cancel') || $self->get('cancel') ) {
1476 $dbh->rollback if $oldAutoCommit;
1477 return "Can't unsuspend cancelled package $pkgnum";
1480 unless ( $old->get('susp') && $self->get('susp') ) {
1481 $dbh->rollback if $oldAutoCommit;
1482 return ""; # no error # complain instead?
1485 my $date = $opt{'date'};
1486 if ( $date and $date > time ) { # return an error if $date <= time?
1488 if ( $old->get('expire') && $old->get('expire') < $date ) {
1489 $dbh->rollback if $oldAutoCommit;
1490 return "Package $pkgnum expires before it would be unsuspended.";
1493 my $new = new FS::cust_pkg { $self->hash };
1494 $new->set('resume', $date);
1495 $error = $new->replace($self, options => $self->options);
1498 $dbh->rollback if $oldAutoCommit;
1502 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1510 foreach my $cust_svc (
1511 qsearch('cust_svc',{'pkgnum'=> $self->pkgnum } )
1513 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
1515 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
1516 $dbh->rollback if $oldAutoCommit;
1517 return "Illegal svcdb value in part_svc!";
1520 require "FS/$svcdb.pm";
1522 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
1524 $error = $svc->unsuspend;
1526 $dbh->rollback if $oldAutoCommit;
1529 my( $label, $value ) = $cust_svc->label;
1530 push @labels, "$label: $value";
1535 my $cust_pkg_reason = $self->last_cust_pkg_reason('susp');
1536 my $reason = $cust_pkg_reason ? $cust_pkg_reason->reason : '';
1538 my %hash = $self->hash;
1539 my $inactive = time - $hash{'susp'};
1541 my $conf = new FS::Conf;
1543 if ( $inactive > 0 &&
1544 ( $hash{'bill'} || $hash{'setup'} ) &&
1545 ( $opt{'adjust_next_bill'} ||
1546 $conf->exists('unsuspend-always_adjust_next_bill_date') ||
1547 $self->part_pkg->option('unsuspend_adjust_bill', 1) )
1550 $hash{'bill'} = ( $hash{'bill'} || $hash{'setup'} ) + $inactive;
1555 $hash{'adjourn'} = '' if $hash{'adjourn'} and $hash{'adjourn'} < time;
1556 $hash{'resume'} = '' if !$hash{'adjourn'};
1557 my $new = new FS::cust_pkg ( \%hash );
1558 $error = $new->replace( $self, options => { $self->options } );
1560 $dbh->rollback if $oldAutoCommit;
1566 if ( $reason && $reason->unsuspend_pkgpart ) {
1567 my $part_pkg = FS::part_pkg->by_key($reason->unsuspend_pkgpart)
1568 or $error = "Unsuspend package definition ".$reason->unsuspend_pkgpart.
1570 my $start_date = $self->cust_main->next_bill_date
1571 if $reason->unsuspend_hold;
1574 $unsusp_pkg = FS::cust_pkg->new({
1575 'custnum' => $self->custnum,
1576 'pkgpart' => $reason->unsuspend_pkgpart,
1577 'start_date' => $start_date,
1578 'locationnum' => $self->locationnum,
1579 # discount? probably not...
1582 $error ||= $self->cust_main->order_pkg( 'cust_pkg' => $unsusp_pkg );
1586 $dbh->rollback if $oldAutoCommit;
1591 if ( $conf->config('unsuspend_email_admin') ) {
1593 my $error = send_email(
1594 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
1595 #invoice_from ??? well as good as any
1596 'to' => $conf->config('unsuspend_email_admin'),
1597 'subject' => 'FREESIDE NOTIFICATION: Customer package unsuspended', 'body' => [
1598 "This is an automatic message from your Freeside installation\n",
1599 "informing you that the following customer package has been unsuspended:\n",
1601 'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
1602 'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
1603 ( map { "Service : $_\n" } @labels ),
1605 "An unsuspension fee was charged: ".
1606 $unsusp_pkg->part_pkg->pkg_comment."\n"
1613 warn "WARNING: can't send unsuspension admin email (unsuspending anyway): ".
1619 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1620 $error = $supp_pkg->unsuspend(%opt, 'from_main' => 1);
1622 $dbh->rollback if $oldAutoCommit;
1623 return "unsuspending supplemental pkg#".$supp_pkg->pkgnum.": $error";
1627 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1634 Cancels any pending suspension (sets the adjourn field to null).
1636 If there is an error, returns the error, otherwise returns false.
1641 my( $self, %options ) = @_;
1644 local $SIG{HUP} = 'IGNORE';
1645 local $SIG{INT} = 'IGNORE';
1646 local $SIG{QUIT} = 'IGNORE';
1647 local $SIG{TERM} = 'IGNORE';
1648 local $SIG{TSTP} = 'IGNORE';
1649 local $SIG{PIPE} = 'IGNORE';
1651 my $oldAutoCommit = $FS::UID::AutoCommit;
1652 local $FS::UID::AutoCommit = 0;
1655 my $old = $self->select_for_update;
1657 my $pkgnum = $old->pkgnum;
1658 if ( $old->get('cancel') || $self->get('cancel') ) {
1659 dbh->rollback if $oldAutoCommit;
1660 return "Can't unadjourn cancelled package $pkgnum";
1661 # or at least it's pointless
1664 if ( $old->get('susp') || $self->get('susp') ) {
1665 dbh->rollback if $oldAutoCommit;
1666 return "Can't unadjourn suspended package $pkgnum";
1667 # perhaps this is arbitrary
1670 unless ( $old->get('adjourn') && $self->get('adjourn') ) {
1671 dbh->rollback if $oldAutoCommit;
1672 return ""; # no error
1675 my %hash = $self->hash;
1676 $hash{'adjourn'} = '';
1677 $hash{'resume'} = '';
1678 my $new = new FS::cust_pkg ( \%hash );
1679 $error = $new->replace( $self, options => { $self->options } );
1681 $dbh->rollback if $oldAutoCommit;
1685 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1692 =item change HASHREF | OPTION => VALUE ...
1694 Changes this package: cancels it and creates a new one, with a different
1695 pkgpart or locationnum or both. All services are transferred to the new
1696 package (no change will be made if this is not possible).
1698 Options may be passed as a list of key/value pairs or as a hash reference.
1705 New locationnum, to change the location for this package.
1709 New FS::cust_location object, to create a new location and assign it
1714 New FS::cust_main object, to create a new customer and assign the new package
1719 New pkgpart (see L<FS::part_pkg>).
1723 New refnum (see L<FS::part_referral>).
1727 Set to true to transfer billing dates (start_date, setup, last_bill, bill,
1728 susp, adjourn, cancel, expire, and contract_end) to the new package.
1732 At least one of locationnum, cust_location, pkgpart, refnum must be specified
1733 (otherwise, what's the point?)
1735 Returns either the new FS::cust_pkg object or a scalar error.
1739 my $err_or_new_cust_pkg = $old_cust_pkg->change
1743 #some false laziness w/order
1746 my $opt = ref($_[0]) ? shift : { @_ };
1748 # my ($custnum, $pkgparts, $remove_pkgnum, $return_cust_pkg, $refnum) = @_;
1751 my $conf = new FS::Conf;
1753 # Transactionize this whole mess
1754 local $SIG{HUP} = 'IGNORE';
1755 local $SIG{INT} = 'IGNORE';
1756 local $SIG{QUIT} = 'IGNORE';
1757 local $SIG{TERM} = 'IGNORE';
1758 local $SIG{TSTP} = 'IGNORE';
1759 local $SIG{PIPE} = 'IGNORE';
1761 my $oldAutoCommit = $FS::UID::AutoCommit;
1762 local $FS::UID::AutoCommit = 0;
1771 #$hash{$_} = $self->$_() foreach qw( last_bill bill );
1773 #$hash{$_} = $self->$_() foreach qw( setup );
1775 $hash{'setup'} = $time if $self->setup;
1777 $hash{'change_date'} = $time;
1778 $hash{"change_$_"} = $self->$_()
1779 foreach qw( pkgnum pkgpart locationnum );
1781 if ( $opt->{'cust_location'} ) {
1782 $error = $opt->{'cust_location'}->find_or_insert;
1784 $dbh->rollback if $oldAutoCommit;
1785 return "inserting cust_location (transaction rolled back): $error";
1787 $opt->{'locationnum'} = $opt->{'cust_location'}->locationnum;
1790 # whether to override pkgpart checking on the new package
1791 my $same_pkgpart = 1;
1792 if ( $opt->{'pkgpart'} and ( $opt->{'pkgpart'} != $self->pkgpart ) ) {
1796 my $unused_credit = 0;
1797 my $keep_dates = $opt->{'keep_dates'};
1798 # Special case. If the pkgpart is changing, and the customer is
1799 # going to be credited for remaining time, don't keep setup, bill,
1800 # or last_bill dates, and DO pass the flag to cancel() to credit
1802 if ( $opt->{'pkgpart'}
1803 and $opt->{'pkgpart'} != $self->pkgpart
1804 and $self->part_pkg->option('unused_credit_change', 1) ) {
1807 $hash{$_} = '' foreach qw(setup bill last_bill);
1810 if ( $keep_dates ) {
1811 foreach my $date ( qw(setup bill last_bill susp adjourn cancel expire
1812 resume start_date contract_end ) ) {
1813 $hash{$date} = $self->getfield($date);
1816 # allow $opt->{'locationnum'} = '' to specifically set it to null
1817 # (i.e. customer default location)
1818 $opt->{'locationnum'} = $self->locationnum if !exists($opt->{'locationnum'});
1820 # usually this doesn't matter. the two cases where it does are:
1821 # 1. unused_credit_change + pkgpart change + setup fee on the new package
1823 # 2. (more importantly) changing a package before it's billed
1824 $hash{'waive_setup'} = $self->waive_setup;
1826 my $custnum = $self->custnum;
1827 if ( $opt->{cust_main} ) {
1828 my $cust_main = $opt->{cust_main};
1829 unless ( $cust_main->custnum ) {
1830 my $error = $cust_main->insert;
1832 $dbh->rollback if $oldAutoCommit;
1833 return "inserting cust_main (transaction rolled back): $error";
1836 $custnum = $cust_main->custnum;
1839 $hash{'contactnum'} = $opt->{'contactnum'} if $opt->{'contactnum'};
1841 # Create the new package.
1842 my $cust_pkg = new FS::cust_pkg {
1843 custnum => $custnum,
1844 pkgpart => ( $opt->{'pkgpart'} || $self->pkgpart ),
1845 refnum => ( $opt->{'refnum'} || $self->refnum ),
1846 locationnum => ( $opt->{'locationnum'} ),
1849 $error = $cust_pkg->insert( 'change' => 1,
1850 'allow_pkgpart' => $same_pkgpart );
1852 $dbh->rollback if $oldAutoCommit;
1856 # Transfer services and cancel old package.
1858 $error = $self->transfer($cust_pkg);
1859 if ($error and $error == 0) {
1860 # $old_pkg->transfer failed.
1861 $dbh->rollback if $oldAutoCommit;
1865 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
1866 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
1867 $error = $self->transfer($cust_pkg, 'change_svcpart'=>1 );
1868 if ($error and $error == 0) {
1869 # $old_pkg->transfer failed.
1870 $dbh->rollback if $oldAutoCommit;
1876 # Transfers were successful, but we still had services left on the old
1877 # package. We can't change the package under this circumstances, so abort.
1878 $dbh->rollback if $oldAutoCommit;
1879 return "Unable to transfer all services from package ". $self->pkgnum;
1882 #reset usage if changing pkgpart
1883 # AND usage rollover is off (otherwise adds twice, now and at package bill)
1884 if ($self->pkgpart != $cust_pkg->pkgpart) {
1885 my $part_pkg = $cust_pkg->part_pkg;
1886 $error = $part_pkg->reset_usage($cust_pkg, $part_pkg->is_prepaid
1890 if $part_pkg->can('reset_usage') && ! $part_pkg->option('usage_rollover',1);
1893 $dbh->rollback if $oldAutoCommit;
1894 return "Error setting usage values: $error";
1897 # if NOT changing pkgpart, transfer any usage pools over
1898 foreach my $usage ($self->cust_pkg_usage) {
1899 $usage->set('pkgnum', $cust_pkg->pkgnum);
1900 $error = $usage->replace;
1902 $dbh->rollback if $oldAutoCommit;
1903 return "Error transferring usage pools: $error";
1908 # transfer discounts, if we're not changing pkgpart
1909 if ( $same_pkgpart ) {
1910 foreach my $old_discount ($self->cust_pkg_discount_active) {
1911 # don't remove the old discount, we may still need to bill that package.
1912 my $new_discount = new FS::cust_pkg_discount {
1913 'pkgnum' => $cust_pkg->pkgnum,
1914 'discountnum' => $old_discount->discountnum,
1915 'months_used' => $old_discount->months_used,
1917 $error = $new_discount->insert;
1919 $dbh->rollback if $oldAutoCommit;
1920 return "Error transferring discounts: $error";
1925 # Order any supplemental packages.
1926 my $part_pkg = $cust_pkg->part_pkg;
1927 my @old_supp_pkgs = $self->supplemental_pkgs;
1929 foreach my $link ($part_pkg->supp_part_pkg_link) {
1931 foreach (@old_supp_pkgs) {
1932 if ($_->pkgpart == $link->dst_pkgpart) {
1934 $_->pkgpart(0); # so that it can't match more than once
1938 # false laziness with FS::cust_main::Packages::order_pkg
1939 my $new = FS::cust_pkg->new({
1940 pkgpart => $link->dst_pkgpart,
1941 pkglinknum => $link->pkglinknum,
1942 custnum => $custnum,
1943 main_pkgnum => $cust_pkg->pkgnum,
1944 locationnum => $cust_pkg->locationnum,
1945 start_date => $cust_pkg->start_date,
1946 order_date => $cust_pkg->order_date,
1947 expire => $cust_pkg->expire,
1948 adjourn => $cust_pkg->adjourn,
1949 contract_end => $cust_pkg->contract_end,
1950 refnum => $cust_pkg->refnum,
1951 discountnum => $cust_pkg->discountnum,
1952 waive_setup => $cust_pkg->waive_setup,
1954 if ( $old and $opt->{'keep_dates'} ) {
1955 foreach (qw(setup bill last_bill)) {
1956 $new->set($_, $old->get($_));
1959 $error = $new->insert( allow_pkgpart => $same_pkgpart );
1962 $error ||= $old->transfer($new);
1964 if ( $error and $error > 0 ) {
1965 # no reason why this should ever fail, but still...
1966 $error = "Unable to transfer all services from supplemental package ".
1970 $dbh->rollback if $oldAutoCommit;
1973 push @new_supp_pkgs, $new;
1976 #Good to go, cancel old package. Notify 'cancel' of whether to credit
1978 #Don't allow billing the package (preceding period packages and/or
1979 #outstanding usage) if we are keeping dates (i.e. location changing),
1980 #because the new package will be billed for the same date range.
1981 #Supplemental packages are also canceled here.
1982 $error = $self->cancel(
1984 unused_credit => $unused_credit,
1985 nobill => $keep_dates,
1986 change_custnum => ( $self->custnum != $custnum ? $custnum : '' ),
1989 $dbh->rollback if $oldAutoCommit;
1993 if ( $conf->exists('cust_pkg-change_pkgpart-bill_now') ) {
1995 my $error = $cust_pkg->cust_main->bill(
1996 'pkg_list' => [ $cust_pkg, @new_supp_pkgs ]
1999 $dbh->rollback if $oldAutoCommit;
2004 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2010 =item set_quantity QUANTITY
2012 Change the package's quantity field. This is the one package property
2013 that can safely be changed without canceling and reordering the package
2014 (because it doesn't affect tax eligibility). Returns an error or an
2021 $self = $self->replace_old; # just to make sure
2023 ($qty =~ /^\d+$/ and $qty > 0) or return "bad package quantity $qty";
2024 $self->set('quantity' => $qty);
2028 use Storable 'thaw';
2030 sub process_bulk_cust_pkg {
2032 my $param = thaw(decode_base64(shift));
2033 warn Dumper($param) if $DEBUG;
2035 my $old_part_pkg = qsearchs('part_pkg',
2036 { pkgpart => $param->{'old_pkgpart'} });
2037 my $new_part_pkg = qsearchs('part_pkg',
2038 { pkgpart => $param->{'new_pkgpart'} });
2039 die "Must select a new package type\n" unless $new_part_pkg;
2040 #my $keep_dates = $param->{'keep_dates'} || 0;
2041 my $keep_dates = 1; # there is no good reason to turn this off
2043 local $SIG{HUP} = 'IGNORE';
2044 local $SIG{INT} = 'IGNORE';
2045 local $SIG{QUIT} = 'IGNORE';
2046 local $SIG{TERM} = 'IGNORE';
2047 local $SIG{TSTP} = 'IGNORE';
2048 local $SIG{PIPE} = 'IGNORE';
2050 my $oldAutoCommit = $FS::UID::AutoCommit;
2051 local $FS::UID::AutoCommit = 0;
2054 my @cust_pkgs = qsearch('cust_pkg', { 'pkgpart' => $param->{'old_pkgpart'} } );
2057 foreach my $old_cust_pkg ( @cust_pkgs ) {
2059 $job->update_statustext(int(100*$i/(scalar @cust_pkgs)));
2060 if ( $old_cust_pkg->getfield('cancel') ) {
2061 warn '[process_bulk_cust_pkg ] skipping canceled pkgnum '.
2062 $old_cust_pkg->pkgnum."\n"
2066 warn '[process_bulk_cust_pkg] changing pkgnum '.$old_cust_pkg->pkgnum."\n"
2068 my $error = $old_cust_pkg->change(
2069 'pkgpart' => $param->{'new_pkgpart'},
2070 'keep_dates' => $keep_dates
2072 if ( !ref($error) ) { # change returns the cust_pkg on success
2074 die "Error changing pkgnum ".$old_cust_pkg->pkgnum.": '$error'\n";
2077 $dbh->commit if $oldAutoCommit;
2083 Returns the last bill date, or if there is no last bill date, the setup date.
2084 Useful for billing metered services.
2090 return $self->setfield('last_bill', $_[0]) if @_;
2091 return $self->getfield('last_bill') if $self->getfield('last_bill');
2092 my $cust_bill_pkg = qsearchs('cust_bill_pkg', { 'pkgnum' => $self->pkgnum,
2093 'edate' => $self->bill, } );
2094 $cust_bill_pkg ? $cust_bill_pkg->sdate : $self->setup || 0;
2097 =item last_cust_pkg_reason ACTION
2099 Returns the most recent ACTION FS::cust_pkg_reason associated with the package.
2100 Returns false if there is no reason or the package is not currenly ACTION'd
2101 ACTION is one of adjourn, susp, cancel, or expire.
2105 sub last_cust_pkg_reason {
2106 my ( $self, $action ) = ( shift, shift );
2107 my $date = $self->get($action);
2109 'table' => 'cust_pkg_reason',
2110 'hashref' => { 'pkgnum' => $self->pkgnum,
2111 'action' => substr(uc($action), 0, 1),
2114 'order_by' => 'ORDER BY num DESC LIMIT 1',
2118 =item last_reason ACTION
2120 Returns the most recent ACTION FS::reason associated with the package.
2121 Returns false if there is no reason or the package is not currenly ACTION'd
2122 ACTION is one of adjourn, susp, cancel, or expire.
2127 my $cust_pkg_reason = shift->last_cust_pkg_reason(@_);
2128 $cust_pkg_reason->reason
2129 if $cust_pkg_reason;
2134 Returns the definition for this billing item, as an FS::part_pkg object (see
2141 return $self->{'_pkgpart'} if $self->{'_pkgpart'};
2142 cluck "cust_pkg->part_pkg called" if $DEBUG > 1;
2143 qsearchs( 'part_pkg', { 'pkgpart' => $self->pkgpart } );
2148 Returns the cancelled package this package was changed from, if any.
2154 return '' unless $self->change_pkgnum;
2155 qsearchs('cust_pkg', { 'pkgnum' => $self->change_pkgnum } );
2158 =item change_cust_main
2160 Returns the customter this package was detached to, if any.
2164 sub change_cust_main {
2166 return '' unless $self->change_custnum;
2167 qsearchs('cust_main', { 'custnum' => $self->change_custnum } );
2172 Calls the I<calc_setup> of the FS::part_pkg object associated with this billing
2179 $self->part_pkg->calc_setup($self, @_);
2184 Calls the I<calc_recur> of the FS::part_pkg object associated with this billing
2191 $self->part_pkg->calc_recur($self, @_);
2196 Calls the I<base_recur> of the FS::part_pkg object associated with this billing
2203 $self->part_pkg->base_recur($self, @_);
2208 Calls the I<calc_remain> of the FS::part_pkg object associated with this
2215 $self->part_pkg->calc_remain($self, @_);
2220 Calls the I<calc_cancel> of the FS::part_pkg object associated with this
2227 $self->part_pkg->calc_cancel($self, @_);
2232 Returns any invoice line items for this package (see L<FS::cust_bill_pkg>).
2238 qsearch( 'cust_bill_pkg', { 'pkgnum' => $self->pkgnum } );
2241 =item cust_pkg_detail [ DETAILTYPE ]
2243 Returns any customer package details for this package (see
2244 L<FS::cust_pkg_detail>).
2246 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
2250 sub cust_pkg_detail {
2252 my %hash = ( 'pkgnum' => $self->pkgnum );
2253 $hash{detailtype} = shift if @_;
2255 'table' => 'cust_pkg_detail',
2256 'hashref' => \%hash,
2257 'order_by' => 'ORDER BY weight, pkgdetailnum',
2261 =item set_cust_pkg_detail DETAILTYPE [ DETAIL, DETAIL, ... ]
2263 Sets customer package details for this package (see L<FS::cust_pkg_detail>).
2265 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
2267 If there is an error, returns the error, otherwise returns false.
2271 sub set_cust_pkg_detail {
2272 my( $self, $detailtype, @details ) = @_;
2274 local $SIG{HUP} = 'IGNORE';
2275 local $SIG{INT} = 'IGNORE';
2276 local $SIG{QUIT} = 'IGNORE';
2277 local $SIG{TERM} = 'IGNORE';
2278 local $SIG{TSTP} = 'IGNORE';
2279 local $SIG{PIPE} = 'IGNORE';
2281 my $oldAutoCommit = $FS::UID::AutoCommit;
2282 local $FS::UID::AutoCommit = 0;
2285 foreach my $current ( $self->cust_pkg_detail($detailtype) ) {
2286 my $error = $current->delete;
2288 $dbh->rollback if $oldAutoCommit;
2289 return "error removing old detail: $error";
2293 foreach my $detail ( @details ) {
2294 my $cust_pkg_detail = new FS::cust_pkg_detail {
2295 'pkgnum' => $self->pkgnum,
2296 'detailtype' => $detailtype,
2297 'detail' => $detail,
2299 my $error = $cust_pkg_detail->insert;
2301 $dbh->rollback if $oldAutoCommit;
2302 return "error adding new detail: $error";
2307 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2314 Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.
2318 #false laziness w/cust_bill.pm
2322 'table' => 'cust_event',
2323 'addl_from' => 'JOIN part_event USING ( eventpart )',
2324 'hashref' => { 'tablenum' => $self->pkgnum },
2325 'extra_sql' => " AND eventtable = 'cust_pkg' ",
2329 =item num_cust_event
2331 Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.
2335 #false laziness w/cust_bill.pm
2336 sub num_cust_event {
2339 "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
2340 " WHERE tablenum = ? AND eventtable = 'cust_pkg'";
2341 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
2342 $sth->execute($self->pkgnum) or die $sth->errstr. " executing $sql";
2343 $sth->fetchrow_arrayref->[0];
2346 =item part_pkg_currency_option OPTIONNAME
2348 Returns the option value for the given name and the currency of this customer
2349 (see L<FS::part_pkg_currency>). If this customer has no currency, returns
2350 the regular option value for the given name (see L<FS::part_pkg_option>).
2354 sub part_pkg_currency_option {
2355 my( $self, $optionname ) = @_;
2356 my $part_pkg = $self->part_pkg;
2357 if ( my $currency = $self->cust_main->currency ) {
2358 $part_pkg->part_pkg_currency_option($currency, $optionname);
2360 $part_pkg->option($optionname);
2364 =item cust_svc [ SVCPART ] (old, deprecated usage)
2366 =item cust_svc [ OPTION => VALUE ... ] (current usage)
2368 Returns the services for this package, as FS::cust_svc objects (see
2369 L<FS::cust_svc>). Available options are svcpart and svcdb. If either is
2370 spcififed, returns only the matching services.
2377 return () unless $self->num_cust_svc(@_);
2380 if ( @_ && $_[0] =~ /^\d+/ ) {
2381 $opt{svcpart} = shift;
2382 } elsif ( @_ && ref($_[0]) eq 'HASH' ) {
2389 'table' => 'cust_svc',
2390 'hashref' => { 'pkgnum' => $self->pkgnum },
2392 if ( $opt{svcpart} ) {
2393 $search{hashref}->{svcpart} = $opt{'svcpart'};
2395 if ( $opt{'svcdb'} ) {
2396 $search{addl_from} = ' LEFT JOIN part_svc USING ( svcpart ) ';
2397 $search{extra_sql} = ' AND svcdb = '. dbh->quote( $opt{'svcdb'} );
2400 cluck "cust_pkg->cust_svc called" if $DEBUG > 2;
2402 #if ( $self->{'_svcnum'} ) {
2403 # values %{ $self->{'_svcnum'}->cache };
2405 $self->_sort_cust_svc( [ qsearch(\%search) ] );
2410 =item overlimit [ SVCPART ]
2412 Returns the services for this package which have exceeded their
2413 usage limit as FS::cust_svc objects (see L<FS::cust_svc>). If a svcpart
2414 is specified, return only the matching services.
2420 return () unless $self->num_cust_svc(@_);
2421 grep { $_->overlimit } $self->cust_svc(@_);
2424 =item h_cust_svc END_TIMESTAMP [ START_TIMESTAMP ] [ MODE ]
2426 Returns historical services for this package created before END TIMESTAMP and
2427 (optionally) not cancelled before START_TIMESTAMP, as FS::h_cust_svc objects
2428 (see L<FS::h_cust_svc>). If MODE is 'I' (for 'invoice'), services with the
2429 I<pkg_svc.hidden> flag will be omitted.
2435 warn "$me _h_cust_svc called on $self\n"
2438 my ($end, $start, $mode) = @_;
2439 my @cust_svc = $self->_sort_cust_svc(
2440 [ qsearch( 'h_cust_svc',
2441 { 'pkgnum' => $self->pkgnum, },
2442 FS::h_cust_svc->sql_h_search(@_),
2445 if ( defined($mode) && $mode eq 'I' ) {
2446 my %hidden_svcpart = map { $_->svcpart => $_->hidden } $self->part_svc;
2447 return grep { !$hidden_svcpart{$_->svcpart} } @cust_svc;
2453 sub _sort_cust_svc {
2454 my( $self, $arrayref ) = @_;
2457 sub ($$) { my ($a, $b) = @_; $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] };
2462 my $pkg_svc = qsearchs( 'pkg_svc', { 'pkgpart' => $self->pkgpart,
2463 'svcpart' => $_->svcpart } );
2465 $pkg_svc ? $pkg_svc->primary_svc : '',
2466 $pkg_svc ? $pkg_svc->quantity : 0,
2473 =item num_cust_svc [ SVCPART ] (old, deprecated usage)
2475 =item num_cust_svc [ OPTION => VALUE ... ] (current usage)
2477 Returns the number of services for this package. Available options are svcpart
2478 and svcdb. If either is spcififed, returns only the matching services.
2485 return $self->{'_num_cust_svc'}
2487 && exists($self->{'_num_cust_svc'})
2488 && $self->{'_num_cust_svc'} =~ /\d/;
2490 cluck "cust_pkg->num_cust_svc called, _num_cust_svc:".$self->{'_num_cust_svc'}
2494 if ( @_ && $_[0] =~ /^\d+/ ) {
2495 $opt{svcpart} = shift;
2496 } elsif ( @_ && ref($_[0]) eq 'HASH' ) {
2502 my $select = 'SELECT COUNT(*) FROM cust_svc ';
2503 my $where = ' WHERE pkgnum = ? ';
2504 my @param = ($self->pkgnum);
2506 if ( $opt{'svcpart'} ) {
2507 $where .= ' AND svcpart = ? ';
2508 push @param, $opt{'svcpart'};
2510 if ( $opt{'svcdb'} ) {
2511 $select .= ' LEFT JOIN part_svc USING ( svcpart ) ';
2512 $where .= ' AND svcdb = ? ';
2513 push @param, $opt{'svcdb'};
2516 my $sth = dbh->prepare("$select $where") or die dbh->errstr;
2517 $sth->execute(@param) or die $sth->errstr;
2518 $sth->fetchrow_arrayref->[0];
2521 =item available_part_svc
2523 Returns a list of FS::part_svc objects representing services included in this
2524 package but not yet provisioned. Each FS::part_svc object also has an extra
2525 field, I<num_avail>, which specifies the number of available services.
2529 sub available_part_svc {
2532 my $pkg_quantity = $self->quantity || 1;
2534 grep { $_->num_avail > 0 }
2536 my $part_svc = $_->part_svc;
2537 $part_svc->{'Hash'}{'num_avail'} = #evil encapsulation-breaking
2538 $pkg_quantity * $_->quantity - $self->num_cust_svc($_->svcpart);
2540 # more evil encapsulation breakage
2541 if($part_svc->{'Hash'}{'num_avail'} > 0) {
2542 my @exports = $part_svc->part_export_did;
2543 $part_svc->{'Hash'}{'can_get_dids'} = scalar(@exports);
2548 $self->part_pkg->pkg_svc;
2551 =item part_svc [ OPTION => VALUE ... ]
2553 Returns a list of FS::part_svc objects representing provisioned and available
2554 services included in this package. Each FS::part_svc object also has the
2555 following extra fields:
2559 =item num_cust_svc (count)
2561 =item num_avail (quantity - count)
2563 =item cust_pkg_svc (services) - array reference containing the provisioned services, as cust_svc objects
2567 Accepts one option: summarize_size. If specified and non-zero, will omit the
2568 extra cust_pkg_svc option for objects where num_cust_svc is this size or
2574 #label -> ($cust_svc->label)[1]
2580 my $pkg_quantity = $self->quantity || 1;
2582 #XXX some sort of sort order besides numeric by svcpart...
2583 my @part_svc = sort { $a->svcpart <=> $b->svcpart } map {
2585 my $part_svc = $pkg_svc->part_svc;
2586 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
2587 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #more evil
2588 $part_svc->{'Hash'}{'num_avail'} =
2589 max( 0, $pkg_quantity * $pkg_svc->quantity - $num_cust_svc );
2590 $part_svc->{'Hash'}{'cust_pkg_svc'} =
2591 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : []
2592 unless exists($opt{summarize_size}) && $opt{summarize_size} > 0
2593 && $num_cust_svc >= $opt{summarize_size};
2594 $part_svc->{'Hash'}{'hidden'} = $pkg_svc->hidden;
2596 } $self->part_pkg->pkg_svc;
2599 push @part_svc, map {
2601 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
2602 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #speak no evail
2603 $part_svc->{'Hash'}{'num_avail'} = 0; #0-$num_cust_svc ?
2604 $part_svc->{'Hash'}{'cust_pkg_svc'} =
2605 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : [];
2607 } $self->extra_part_svc;
2613 =item extra_part_svc
2615 Returns a list of FS::part_svc objects corresponding to services in this
2616 package which are still provisioned but not (any longer) available in the
2621 sub extra_part_svc {
2624 my $pkgnum = $self->pkgnum;
2625 #my $pkgpart = $self->pkgpart;
2628 # 'table' => 'part_svc',
2631 # "WHERE 0 = ( SELECT COUNT(*) FROM pkg_svc
2632 # WHERE pkg_svc.svcpart = part_svc.svcpart
2633 # AND pkg_svc.pkgpart = ?
2636 # AND 0 < ( SELECT COUNT(*) FROM cust_svc
2637 # LEFT JOIN cust_pkg USING ( pkgnum )
2638 # WHERE cust_svc.svcpart = part_svc.svcpart
2641 # 'extra_param' => [ [$self->pkgpart=>'int'], [$self->pkgnum=>'int'] ],
2644 #seems to benchmark slightly faster... (or did?)
2646 my @pkgparts = map $_->pkgpart, $self->part_pkg->self_and_svc_linked;
2647 my $pkgparts = join(',', @pkgparts);
2650 #'select' => 'DISTINCT ON (svcpart) part_svc.*',
2651 #MySQL doesn't grok DISINCT ON
2652 'select' => 'DISTINCT part_svc.*',
2653 'table' => 'part_svc',
2655 "LEFT JOIN pkg_svc ON ( pkg_svc.svcpart = part_svc.svcpart
2656 AND pkg_svc.pkgpart IN ($pkgparts)
2659 LEFT JOIN cust_svc ON ( cust_svc.svcpart = part_svc.svcpart )
2660 LEFT JOIN cust_pkg USING ( pkgnum )
2663 'extra_sql' => "WHERE pkgsvcnum IS NULL AND cust_pkg.pkgnum = ? ",
2664 'extra_param' => [ [$self->pkgnum=>'int'] ],
2670 Returns a short status string for this package, currently:
2674 =item not yet billed
2676 =item one-time charge
2691 my $freq = length($self->freq) ? $self->freq : $self->part_pkg->freq;
2693 return 'cancelled' if $self->get('cancel');
2694 return 'suspended' if $self->susp;
2695 return 'not yet billed' unless $self->setup;
2696 return 'one-time charge' if $freq =~ /^(0|$)/;
2700 =item ucfirst_status
2702 Returns the status with the first character capitalized.
2706 sub ucfirst_status {
2707 ucfirst(shift->status);
2712 Class method that returns the list of possible status strings for packages
2713 (see L<the status method|/status>). For example:
2715 @statuses = FS::cust_pkg->statuses();
2719 tie my %statuscolor, 'Tie::IxHash',
2720 'not yet billed' => '009999', #teal? cyan?
2721 'one-time charge' => '000000',
2722 'active' => '00CC00',
2723 'suspended' => 'FF9900',
2724 'cancelled' => 'FF0000',
2728 my $self = shift; #could be class...
2729 #grep { $_ !~ /^(not yet billed)$/ } #this is a dumb status anyway
2730 # # mayble split btw one-time vs. recur
2736 Returns a hex triplet color string for this package's status.
2742 $statuscolor{$self->status};
2747 Returns a label for this package. (Currently "pkgnum: pkg - comment" or
2748 "pkg - comment" depending on user preference).
2754 my $label = $self->part_pkg->pkg_comment( 'nopkgpart' => 1 );
2755 $label = $self->pkgnum. ": $label"
2756 if $FS::CurrentUser::CurrentUser->option('show_pkgnum');
2760 =item pkg_label_long
2762 Returns a long label for this package, adding the primary service's label to
2767 sub pkg_label_long {
2769 my $label = $self->pkg_label;
2770 my $cust_svc = $self->primary_cust_svc;
2771 $label .= ' ('. ($cust_svc->label)[1]. ')' if $cust_svc;
2777 Returns a customer-localized label for this package.
2783 $self->part_pkg->pkg_locale( $self->cust_main->locale );
2786 =item primary_cust_svc
2788 Returns a primary service (as FS::cust_svc object) if one can be identified.
2792 #for labeling purposes - might not 100% match up with part_pkg->svcpart's idea
2794 sub primary_cust_svc {
2797 my @cust_svc = $self->cust_svc;
2799 return '' unless @cust_svc; #no serivces - irrelevant then
2801 return $cust_svc[0] if scalar(@cust_svc) == 1; #always return a single service
2803 # primary service as specified in the package definition
2804 # or exactly one service definition with quantity one
2805 my $svcpart = $self->part_pkg->svcpart;
2806 @cust_svc = grep { $_->svcpart == $svcpart } @cust_svc;
2807 return $cust_svc[0] if scalar(@cust_svc) == 1;
2809 #couldn't identify one thing..
2815 Returns a list of lists, calling the label method for all services
2816 (see L<FS::cust_svc>) of this billing item.
2822 map { [ $_->label ] } $self->cust_svc;
2825 =item h_labels END_TIMESTAMP [ START_TIMESTAMP ] [ MODE ]
2827 Like the labels method, but returns historical information on services that
2828 were active as of END_TIMESTAMP and (optionally) not cancelled before
2829 START_TIMESTAMP. If MODE is 'I' (for 'invoice'), services with the
2830 I<pkg_svc.hidden> flag will be omitted.
2832 Returns a list of lists, calling the label method for all (historical) services
2833 (see L<FS::h_cust_svc>) of this billing item.
2839 warn "$me _h_labels called on $self\n"
2841 map { [ $_->label(@_) ] } $self->h_cust_svc(@_);
2846 Like labels, except returns a simple flat list, and shortens long
2847 (currently >5 or the cust_bill-max_same_services configuration value) lists of
2848 identical services to one line that lists the service label and the number of
2849 individual services rather than individual items.
2854 shift->_labels_short( 'labels', @_ );
2857 =item h_labels_short END_TIMESTAMP [ START_TIMESTAMP ]
2859 Like h_labels, except returns a simple flat list, and shortens long
2860 (currently >5 or the cust_bill-max_same_services configuration value) lists of
2861 identical services to one line that lists the service label and the number of
2862 individual services rather than individual items.
2866 sub h_labels_short {
2867 shift->_labels_short( 'h_labels', @_ );
2871 my( $self, $method ) = ( shift, shift );
2873 warn "$me _labels_short called on $self with $method method\n"
2876 my $conf = new FS::Conf;
2877 my $max_same_services = $conf->config('cust_bill-max_same_services') || 5;
2879 warn "$me _labels_short populating \%labels\n"
2883 #tie %labels, 'Tie::IxHash';
2884 push @{ $labels{$_->[0]} }, $_->[1]
2885 foreach $self->$method(@_);
2887 warn "$me _labels_short populating \@labels\n"
2891 foreach my $label ( keys %labels ) {
2893 my @values = grep { ! $seen{$_}++ } @{ $labels{$label} };
2894 my $num = scalar(@values);
2895 warn "$me _labels_short $num items for $label\n"
2898 if ( $num > $max_same_services ) {
2899 warn "$me _labels_short more than $max_same_services, so summarizing\n"
2901 push @labels, "$label ($num)";
2903 if ( $conf->exists('cust_bill-consolidate_services') ) {
2904 warn "$me _labels_short consolidating services\n"
2906 # push @labels, "$label: ". join(', ', @values);
2908 my $detail = "$label: ";
2909 $detail .= shift(@values). ', '
2911 && ( length($detail.$values[0]) < 78 || $detail eq "$label: " );
2913 push @labels, $detail;
2915 warn "$me _labels_short done consolidating services\n"
2918 warn "$me _labels_short adding service data\n"
2920 push @labels, map { "$label: $_" } @values;
2931 Returns the parent customer object (see L<FS::cust_main>).
2937 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
2942 Returns the balance for this specific package, when using
2943 experimental package balance.
2949 $self->cust_main->balance_pkgnum( $self->pkgnum );
2952 #these subs are in location_Mixin.pm now... unfortunately the POD doesn't mixin
2956 Returns the location object, if any (see L<FS::cust_location>).
2958 =item cust_location_or_main
2960 If this package is associated with a location, returns the locaiton (see
2961 L<FS::cust_location>), otherwise returns the customer (see L<FS::cust_main>).
2963 =item location_label [ OPTION => VALUE ... ]
2965 Returns the label of the location object (see L<FS::cust_location>).
2969 #end of subs in location_Mixin.pm now... unfortunately the POD doesn't mixin
2971 =item tax_locationnum
2973 Returns the foreign key to a L<FS::cust_location> object for calculating
2974 tax on this package, as determined by the C<tax-pkg_address> and
2975 C<tax-ship_address> configuration flags.
2979 sub tax_locationnum {
2981 my $conf = FS::Conf->new;
2982 if ( $conf->exists('tax-pkg_address') ) {
2983 return $self->locationnum;
2985 elsif ( $conf->exists('tax-ship_address') ) {
2986 return $self->cust_main->ship_locationnum;
2989 return $self->cust_main->bill_locationnum;
2995 Returns the L<FS::cust_location> object for tax_locationnum.
3001 FS::cust_location->by_key( $self->tax_locationnum )
3004 =item seconds_since TIMESTAMP
3006 Returns the number of seconds all accounts (see L<FS::svc_acct>) in this
3007 package have been online since TIMESTAMP, according to the session monitor.
3009 TIMESTAMP is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
3010 L<Time::Local> and L<Date::Parse> for conversion functions.
3015 my($self, $since) = @_;
3018 foreach my $cust_svc (
3019 grep { $_->part_svc->svcdb eq 'svc_acct' } $self->cust_svc
3021 $seconds += $cust_svc->seconds_since($since);
3028 =item seconds_since_sqlradacct TIMESTAMP_START TIMESTAMP_END
3030 Returns the numbers of seconds all accounts (see L<FS::svc_acct>) in this
3031 package have been online between TIMESTAMP_START (inclusive) and TIMESTAMP_END
3034 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
3035 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
3041 sub seconds_since_sqlradacct {
3042 my($self, $start, $end) = @_;
3046 foreach my $cust_svc (
3048 my $part_svc = $_->part_svc;
3049 $part_svc->svcdb eq 'svc_acct'
3050 && scalar($part_svc->part_export_usage);
3053 $seconds += $cust_svc->seconds_since_sqlradacct($start, $end);
3060 =item attribute_since_sqlradacct TIMESTAMP_START TIMESTAMP_END ATTRIBUTE
3062 Returns the sum of the given attribute for all accounts (see L<FS::svc_acct>)
3063 in this package for sessions ending between TIMESTAMP_START (inclusive) and
3067 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
3068 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
3073 sub attribute_since_sqlradacct {
3074 my($self, $start, $end, $attrib) = @_;
3078 foreach my $cust_svc (
3080 my $part_svc = $_->part_svc;
3081 $part_svc->svcdb eq 'svc_acct'
3082 && scalar($part_svc->part_export_usage);
3085 $sum += $cust_svc->attribute_since_sqlradacct($start, $end, $attrib);
3097 my( $self, $value ) = @_;
3098 if ( defined($value) ) {
3099 $self->setfield('quantity', $value);
3101 $self->getfield('quantity') || 1;
3104 =item transfer DEST_PKGNUM | DEST_CUST_PKG, [ OPTION => VALUE ... ]
3106 Transfers as many services as possible from this package to another package.
3108 The destination package can be specified by pkgnum by passing an FS::cust_pkg
3109 object. The destination package must already exist.
3111 Services are moved only if the destination allows services with the correct
3112 I<svcpart> (not svcdb), unless the B<change_svcpart> option is set true. Use
3113 this option with caution! No provision is made for export differences
3114 between the old and new service definitions. Probably only should be used
3115 when your exports for all service definitions of a given svcdb are identical.
3116 (attempt a transfer without it first, to move all possible svcpart-matching
3119 Any services that can't be moved remain in the original package.
3121 Returns an error, if there is one; otherwise, returns the number of services
3122 that couldn't be moved.
3127 my ($self, $dest_pkgnum, %opt) = @_;
3133 if (ref ($dest_pkgnum) eq 'FS::cust_pkg') {
3134 $dest = $dest_pkgnum;
3135 $dest_pkgnum = $dest->pkgnum;
3137 $dest = qsearchs('cust_pkg', { pkgnum => $dest_pkgnum });
3140 return ('Package does not exist: '.$dest_pkgnum) unless $dest;
3142 foreach my $pkg_svc ( $dest->part_pkg->pkg_svc ) {
3143 $target{$pkg_svc->svcpart} = $pkg_svc->quantity;
3146 foreach my $cust_svc ($dest->cust_svc) {
3147 $target{$cust_svc->svcpart}--;
3150 my %svcpart2svcparts = ();
3151 if ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
3152 warn "change_svcpart option received, creating alternates list\n" if $DEBUG;
3153 foreach my $svcpart ( map { $_->svcpart } $self->cust_svc ) {
3154 next if exists $svcpart2svcparts{$svcpart};
3155 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
3156 $svcpart2svcparts{$svcpart} = [
3158 sort { $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] }
3160 my $pkg_svc = qsearchs( 'pkg_svc', { 'pkgpart' => $dest->pkgpart,
3161 'svcpart' => $_ } );
3163 $pkg_svc ? $pkg_svc->primary_svc : '',
3164 $pkg_svc ? $pkg_svc->quantity : 0,
3168 grep { $_ != $svcpart }
3170 qsearch('part_svc', { 'svcdb' => $part_svc->svcdb } )
3172 warn "alternates for svcpart $svcpart: ".
3173 join(', ', @{$svcpart2svcparts{$svcpart}}). "\n"
3178 foreach my $cust_svc ($self->cust_svc) {
3179 if($target{$cust_svc->svcpart} > 0
3180 or $FS::cust_svc::ignore_quantity) { # maybe should be a 'force' option
3181 $target{$cust_svc->svcpart}--;
3182 my $new = new FS::cust_svc { $cust_svc->hash };
3183 $new->pkgnum($dest_pkgnum);
3184 my $error = $new->replace($cust_svc);
3185 return $error if $error;
3186 } elsif ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
3188 warn "looking for alternates for svcpart ". $cust_svc->svcpart. "\n";
3189 warn "alternates to consider: ".
3190 join(', ', @{$svcpart2svcparts{$cust_svc->svcpart}}). "\n";
3192 my @alternate = grep {
3193 warn "considering alternate svcpart $_: ".
3194 "$target{$_} available in new package\n"
3197 } @{$svcpart2svcparts{$cust_svc->svcpart}};
3199 warn "alternate(s) found\n" if $DEBUG;
3200 my $change_svcpart = $alternate[0];
3201 $target{$change_svcpart}--;
3202 my $new = new FS::cust_svc { $cust_svc->hash };
3203 $new->svcpart($change_svcpart);
3204 $new->pkgnum($dest_pkgnum);
3205 my $error = $new->replace($cust_svc);
3206 return $error if $error;
3217 =item grab_svcnums SVCNUM, SVCNUM ...
3219 Change the pkgnum for the provided services to this packages. If there is an
3220 error, returns the error, otherwise returns false.
3228 local $SIG{HUP} = 'IGNORE';
3229 local $SIG{INT} = 'IGNORE';
3230 local $SIG{QUIT} = 'IGNORE';
3231 local $SIG{TERM} = 'IGNORE';
3232 local $SIG{TSTP} = 'IGNORE';
3233 local $SIG{PIPE} = 'IGNORE';
3235 my $oldAutoCommit = $FS::UID::AutoCommit;
3236 local $FS::UID::AutoCommit = 0;
3239 foreach my $svcnum (@svcnum) {
3240 my $cust_svc = qsearchs('cust_svc', { svcnum=>$svcnum } ) or do {
3241 $dbh->rollback if $oldAutoCommit;
3242 return "unknown svcnum $svcnum";
3244 $cust_svc->pkgnum( $self->pkgnum );
3245 my $error = $cust_svc->replace;
3247 $dbh->rollback if $oldAutoCommit;
3252 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3259 This method is deprecated. See the I<depend_jobnum> option to the insert and
3260 order_pkgs methods in FS::cust_main for a better way to defer provisioning.
3267 local $SIG{HUP} = 'IGNORE';
3268 local $SIG{INT} = 'IGNORE';
3269 local $SIG{QUIT} = 'IGNORE';
3270 local $SIG{TERM} = 'IGNORE';
3271 local $SIG{TSTP} = 'IGNORE';
3272 local $SIG{PIPE} = 'IGNORE';
3274 my $oldAutoCommit = $FS::UID::AutoCommit;
3275 local $FS::UID::AutoCommit = 0;
3278 foreach my $cust_svc ( $self->cust_svc ) {
3279 #false laziness w/svc_Common::insert
3280 my $svc_x = $cust_svc->svc_x;
3281 foreach my $part_export ( $cust_svc->part_svc->part_export ) {
3282 my $error = $part_export->export_insert($svc_x);
3284 $dbh->rollback if $oldAutoCommit;
3290 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3297 Associates this package with a (suspension or cancellation) reason (see
3298 L<FS::cust_pkg_reason>, possibly inserting a new reason on the fly (see
3301 Available options are:
3307 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.
3311 the access_user (see L<FS::access_user>) providing the reason
3319 the action (cancel, susp, adjourn, expire) associated with the reason
3323 If there is an error, returns the error, otherwise returns false.
3328 my ($self, %options) = @_;
3330 my $otaker = $options{reason_otaker} ||
3331 $FS::CurrentUser::CurrentUser->username;
3334 if ( $options{'reason'} =~ /^(\d+)$/ ) {
3338 } elsif ( ref($options{'reason'}) ) {
3340 return 'Enter a new reason (or select an existing one)'
3341 unless $options{'reason'}->{'reason'} !~ /^\s*$/;
3343 my $reason = new FS::reason({
3344 'reason_type' => $options{'reason'}->{'typenum'},
3345 'reason' => $options{'reason'}->{'reason'},
3347 my $error = $reason->insert;
3348 return $error if $error;
3350 $reasonnum = $reason->reasonnum;
3353 return "Unparsable reason: ". $options{'reason'};
3356 my $cust_pkg_reason =
3357 new FS::cust_pkg_reason({ 'pkgnum' => $self->pkgnum,
3358 'reasonnum' => $reasonnum,
3359 'otaker' => $otaker,
3360 'action' => substr(uc($options{'action'}),0,1),
3361 'date' => $options{'date'}
3366 $cust_pkg_reason->insert;
3369 =item insert_discount
3371 Associates this package with a discount (see L<FS::cust_pkg_discount>, possibly
3372 inserting a new discount on the fly (see L<FS::discount>).
3374 Available options are:
3382 If there is an error, returns the error, otherwise returns false.
3386 sub insert_discount {
3387 #my ($self, %options) = @_;
3390 my $cust_pkg_discount = new FS::cust_pkg_discount {
3391 'pkgnum' => $self->pkgnum,
3392 'discountnum' => $self->discountnum,
3394 'end_date' => '', #XXX
3395 #for the create a new discount case
3396 '_type' => $self->discountnum__type,
3397 'amount' => $self->discountnum_amount,
3398 'percent' => $self->discountnum_percent,
3399 'months' => $self->discountnum_months,
3400 'setup' => $self->discountnum_setup,
3401 #'disabled' => $self->discountnum_disabled,
3404 $cust_pkg_discount->insert;
3407 =item set_usage USAGE_VALUE_HASHREF
3409 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
3410 to which they should be set (see L<FS::svc_acct>). Currently seconds,
3411 upbytes, downbytes, and totalbytes are appropriate keys.
3413 All svc_accts which are part of this package have their values reset.
3418 my ($self, $valueref, %opt) = @_;
3420 #only svc_acct can set_usage for now
3421 foreach my $cust_svc ( $self->cust_svc( 'svcdb'=>'svc_acct' ) ) {
3422 my $svc_x = $cust_svc->svc_x;
3423 $svc_x->set_usage($valueref, %opt)
3424 if $svc_x->can("set_usage");
3428 =item recharge USAGE_VALUE_HASHREF
3430 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
3431 to which they should be set (see L<FS::svc_acct>). Currently seconds,
3432 upbytes, downbytes, and totalbytes are appropriate keys.
3434 All svc_accts which are part of this package have their values incremented.
3439 my ($self, $valueref) = @_;
3441 #only svc_acct can set_usage for now
3442 foreach my $cust_svc ( $self->cust_svc( 'svcdb'=>'svc_acct' ) ) {
3443 my $svc_x = $cust_svc->svc_x;
3444 $svc_x->recharge($valueref)
3445 if $svc_x->can("recharge");
3449 =item cust_pkg_discount
3453 sub cust_pkg_discount {
3455 qsearch('cust_pkg_discount', { 'pkgnum' => $self->pkgnum } );
3458 =item cust_pkg_discount_active
3462 sub cust_pkg_discount_active {
3464 grep { $_->status eq 'active' } $self->cust_pkg_discount;
3467 =item cust_pkg_usage
3469 Returns a list of all voice usage counters attached to this package.
3473 sub cust_pkg_usage {
3475 qsearch('cust_pkg_usage', { pkgnum => $self->pkgnum });
3478 =item apply_usage OPTIONS
3480 Takes the following options:
3481 - cdr: a call detail record (L<FS::cdr>)
3482 - rate_detail: the rate determined for this call (L<FS::rate_detail>)
3483 - minutes: the maximum number of minutes to be charged
3485 Finds available usage minutes for a call of this class, and subtracts
3486 up to that many minutes from the usage pool. If the usage pool is empty,
3487 and the C<cdr-minutes_priority> global config option is set, minutes may
3488 be taken from other calls as well. Either way, an allocation record will
3489 be created (L<FS::cdr_cust_pkg_usage>) and this method will return the
3490 number of minutes of usage applied to the call.
3495 my ($self, %opt) = @_;
3496 my $cdr = $opt{cdr};
3497 my $rate_detail = $opt{rate_detail};
3498 my $minutes = $opt{minutes};
3499 my $classnum = $rate_detail->classnum;
3500 my $pkgnum = $self->pkgnum;
3501 my $custnum = $self->custnum;
3503 local $SIG{HUP} = 'IGNORE';
3504 local $SIG{INT} = 'IGNORE';
3505 local $SIG{QUIT} = 'IGNORE';
3506 local $SIG{TERM} = 'IGNORE';
3507 local $SIG{TSTP} = 'IGNORE';
3508 local $SIG{PIPE} = 'IGNORE';
3510 my $oldAutoCommit = $FS::UID::AutoCommit;
3511 local $FS::UID::AutoCommit = 0;
3513 my $order = FS::Conf->new->config('cdr-minutes_priority');
3517 $is_classnum = ' part_pkg_usage_class.classnum = '.$classnum;
3519 $is_classnum = ' part_pkg_usage_class.classnum IS NULL';
3521 my @usage_recs = qsearch({
3522 'table' => 'cust_pkg_usage',
3523 'addl_from' => ' JOIN part_pkg_usage USING (pkgusagepart)'.
3524 ' JOIN cust_pkg USING (pkgnum)'.
3525 ' JOIN part_pkg_usage_class USING (pkgusagepart)',
3526 'select' => 'cust_pkg_usage.*',
3527 'extra_sql' => " WHERE ( cust_pkg.pkgnum = $pkgnum OR ".
3528 " ( cust_pkg.custnum = $custnum AND ".
3529 " part_pkg_usage.shared IS NOT NULL ) ) AND ".
3530 $is_classnum . ' AND '.
3531 " cust_pkg_usage.minutes > 0",
3532 'order_by' => " ORDER BY priority ASC",
3535 my $orig_minutes = $minutes;
3537 while (!$error and $minutes > 0 and @usage_recs) {
3538 my $cust_pkg_usage = shift @usage_recs;
3539 $cust_pkg_usage->select_for_update;
3540 my $cdr_cust_pkg_usage = FS::cdr_cust_pkg_usage->new({
3541 pkgusagenum => $cust_pkg_usage->pkgusagenum,
3542 acctid => $cdr->acctid,
3543 minutes => min($cust_pkg_usage->minutes, $minutes),
3545 $cust_pkg_usage->set('minutes',
3546 sprintf('%.0f', $cust_pkg_usage->minutes - $cdr_cust_pkg_usage->minutes)
3548 $error = $cust_pkg_usage->replace || $cdr_cust_pkg_usage->insert;
3549 $minutes -= $cdr_cust_pkg_usage->minutes;
3551 if ( $order and $minutes > 0 and !$error ) {
3552 # then try to steal minutes from another call
3554 'table' => 'cdr_cust_pkg_usage',
3555 'addl_from' => ' JOIN cust_pkg_usage USING (pkgusagenum)'.
3556 ' JOIN part_pkg_usage USING (pkgusagepart)'.
3557 ' JOIN cust_pkg USING (pkgnum)'.
3558 ' JOIN part_pkg_usage_class USING (pkgusagepart)'.
3559 ' JOIN cdr USING (acctid)',
3560 'select' => 'cdr_cust_pkg_usage.*',
3561 'extra_sql' => " WHERE cdr.freesidestatus = 'rated' AND ".
3562 " ( cust_pkg.pkgnum = $pkgnum OR ".
3563 " ( cust_pkg.custnum = $custnum AND ".
3564 " part_pkg_usage.shared IS NOT NULL ) ) AND ".
3565 " part_pkg_usage_class.classnum = $classnum",
3566 'order_by' => ' ORDER BY part_pkg_usage.priority ASC',
3568 if ( $order eq 'time' ) {
3569 # find CDRs that are using minutes, but have a later startdate
3571 my $startdate = $cdr->startdate;
3572 if ($startdate !~ /^\d+$/) {
3573 die "bad cdr startdate '$startdate'";
3575 $search{'extra_sql'} .= " AND cdr.startdate > $startdate";
3576 # minimize needless reshuffling
3577 $search{'order_by'} .= ', cdr.startdate DESC';
3579 # XXX may not work correctly with rate_time schedules. Could
3580 # fix this by storing ratedetailnum in cdr_cust_pkg_usage, I
3582 $search{'addl_from'} .=
3583 ' JOIN rate_detail'.
3584 ' ON (cdr.rated_ratedetailnum = rate_detail.ratedetailnum)';
3585 if ( $order eq 'rate_high' ) {
3586 $search{'extra_sql'} .= ' AND rate_detail.min_charge < '.
3587 $rate_detail->min_charge;
3588 $search{'order_by'} .= ', rate_detail.min_charge ASC';
3589 } elsif ( $order eq 'rate_low' ) {
3590 $search{'extra_sql'} .= ' AND rate_detail.min_charge > '.
3591 $rate_detail->min_charge;
3592 $search{'order_by'} .= ', rate_detail.min_charge DESC';
3594 # this should really never happen
3595 die "invalid cdr-minutes_priority value '$order'\n";
3598 my @cdr_usage_recs = qsearch(\%search);
3600 while (!$error and @cdr_usage_recs and $minutes > 0) {
3601 my $cdr_cust_pkg_usage = shift @cdr_usage_recs;
3602 my $cust_pkg_usage = $cdr_cust_pkg_usage->cust_pkg_usage;
3603 my $old_cdr = $cdr_cust_pkg_usage->cdr;
3604 $reproc_cdrs{$old_cdr->acctid} = $old_cdr;
3605 $cdr_cust_pkg_usage->select_for_update;
3606 $old_cdr->select_for_update;
3607 $cust_pkg_usage->select_for_update;
3608 # in case someone else stole the usage from this CDR
3609 # while waiting for the lock...
3610 next if $old_cdr->acctid != $cdr_cust_pkg_usage->acctid;
3611 # steal the usage allocation and flag the old CDR for reprocessing
3612 $cdr_cust_pkg_usage->set('acctid', $cdr->acctid);
3613 # if the allocation is more minutes than we need, adjust it...
3614 my $delta = $cdr_cust_pkg_usage->minutes - $minutes;
3616 $cdr_cust_pkg_usage->set('minutes', $minutes);
3617 $cust_pkg_usage->set('minutes', $cust_pkg_usage->minutes + $delta);
3618 $error = $cust_pkg_usage->replace;
3620 #warn 'CDR '.$cdr->acctid . ' stealing allocation '.$cdr_cust_pkg_usage->cdrusagenum.' from CDR '.$old_cdr->acctid."\n";
3621 $error ||= $cdr_cust_pkg_usage->replace;
3622 # deduct the stolen minutes
3623 $minutes -= $cdr_cust_pkg_usage->minutes;
3625 # after all minute-stealing is done, reset the affected CDRs
3626 foreach (values %reproc_cdrs) {
3627 $error ||= $_->set_status('');
3628 # XXX or should we just call $cdr->rate right here?
3629 # it's not like we can create a loop this way, since the min_charge
3630 # or call time has to go monotonically in one direction.
3631 # we COULD get some very deep recursions going, though...
3633 } # if $order and $minutes
3636 die "error applying included minutes\npkgnum ".$self->pkgnum.", class $classnum, acctid ".$cdr->acctid."\n$error\n"
3638 $dbh->commit if $oldAutoCommit;
3639 return $orig_minutes - $minutes;
3643 =item supplemental_pkgs
3645 Returns a list of all packages supplemental to this one.
3649 sub supplemental_pkgs {
3651 qsearch('cust_pkg', { 'main_pkgnum' => $self->pkgnum });
3656 Returns the package that this one is supplemental to, if any.
3662 if ( $self->main_pkgnum ) {
3663 return FS::cust_pkg->by_key($self->main_pkgnum);
3670 =head1 CLASS METHODS
3676 Returns an SQL expression identifying recurring packages.
3680 sub recurring_sql { "
3681 '0' != ( select freq from part_pkg
3682 where cust_pkg.pkgpart = part_pkg.pkgpart )
3687 Returns an SQL expression identifying one-time packages.
3692 '0' = ( select freq from part_pkg
3693 where cust_pkg.pkgpart = part_pkg.pkgpart )
3698 Returns an SQL expression identifying ordered packages (recurring packages not
3704 $_[0]->recurring_sql. " AND ". $_[0]->not_yet_billed_sql;
3709 Returns an SQL expression identifying active packages.
3714 $_[0]->recurring_sql. "
3715 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
3716 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
3717 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
3720 =item not_yet_billed_sql
3722 Returns an SQL expression identifying packages which have not yet been billed.
3726 sub not_yet_billed_sql { "
3727 ( cust_pkg.setup IS NULL OR cust_pkg.setup = 0 )
3728 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
3729 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
3734 Returns an SQL expression identifying inactive packages (one-time packages
3735 that are otherwise unsuspended/uncancelled).
3739 sub inactive_sql { "
3740 ". $_[0]->onetime_sql(). "
3741 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
3742 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
3743 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
3749 Returns an SQL expression identifying suspended packages.
3753 sub suspended_sql { susp_sql(@_); }
3755 #$_[0]->recurring_sql(). ' AND '.
3757 ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
3758 AND cust_pkg.susp IS NOT NULL AND cust_pkg.susp != 0
3765 Returns an SQL exprression identifying cancelled packages.
3769 sub cancelled_sql { cancel_sql(@_); }
3771 #$_[0]->recurring_sql(). ' AND '.
3772 "cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0";
3777 Returns an SQL expression to give the package status as a string.
3783 WHEN cust_pkg.cancel IS NOT NULL THEN 'cancelled'
3784 WHEN cust_pkg.susp IS NOT NULL THEN 'suspended'
3785 WHEN cust_pkg.setup IS NULL THEN 'not yet billed'
3786 WHEN ".onetime_sql()." THEN 'one-time charge'
3791 =item search HASHREF
3795 Returns a qsearch hash expression to search for parameters specified in HASHREF.
3796 Valid parameters are
3804 active, inactive, suspended, cancel (or cancelled)
3808 active, inactive, suspended, one-time charge, inactive, cancel (or cancelled)
3812 boolean selects custom packages
3818 pkgpart or arrayref or hashref of pkgparts
3822 arrayref of beginning and ending epoch date
3826 arrayref of beginning and ending epoch date
3830 arrayref of beginning and ending epoch date
3834 arrayref of beginning and ending epoch date
3838 arrayref of beginning and ending epoch date
3842 arrayref of beginning and ending epoch date
3846 arrayref of beginning and ending epoch date
3850 pkgnum or APKG_pkgnum
3854 a value suited to passing to FS::UI::Web::cust_header
3858 specifies the user for agent virtualization
3862 boolean; if true, returns only packages with more than 0 FCC phone lines.
3864 =item state, country
3866 Limit to packages with a service location in the specified state and country.
3867 For FCC 477 reporting, mostly.
3874 my ($class, $params) = @_;
3881 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
3883 "cust_main.agentnum = $1";
3890 if ( $params->{'custnum'} =~ /^(\d+)$/ and $1 ) {
3892 "cust_pkg.custnum = $1";
3899 if ( $params->{'pkgbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
3901 "cust_pkg.pkgbatch = '$1'";
3908 if ( $params->{'magic'} eq 'active'
3909 || $params->{'status'} eq 'active' ) {
3911 push @where, FS::cust_pkg->active_sql();
3913 } elsif ( $params->{'magic'} =~ /^not[ _]yet[ _]billed$/
3914 || $params->{'status'} =~ /^not[ _]yet[ _]billed$/ ) {
3916 push @where, FS::cust_pkg->not_yet_billed_sql();
3918 } elsif ( $params->{'magic'} =~ /^(one-time charge|inactive)/
3919 || $params->{'status'} =~ /^(one-time charge|inactive)/ ) {
3921 push @where, FS::cust_pkg->inactive_sql();
3923 } elsif ( $params->{'magic'} eq 'suspended'
3924 || $params->{'status'} eq 'suspended' ) {
3926 push @where, FS::cust_pkg->suspended_sql();
3928 } elsif ( $params->{'magic'} =~ /^cancell?ed$/
3929 || $params->{'status'} =~ /^cancell?ed$/ ) {
3931 push @where, FS::cust_pkg->cancelled_sql();
3936 # parse package class
3939 if ( exists($params->{'classnum'}) ) {
3942 if ( ref($params->{'classnum'}) ) {
3944 if ( ref($params->{'classnum'}) eq 'HASH' ) {
3945 @classnum = grep $params->{'classnum'}{$_}, keys %{ $params->{'classnum'} };
3946 } elsif ( ref($params->{'classnum'}) eq 'ARRAY' ) {
3947 @classnum = @{ $params->{'classnum'} };
3949 die 'unhandled classnum ref '. $params->{'classnum'};
3953 } elsif ( $params->{'classnum'} =~ /^(\d*)$/ && $1 ne '0' ) {
3960 my @nums = grep $_, @classnum;
3961 push @c_where, 'part_pkg.classnum IN ('. join(',',@nums). ')' if @nums;
3962 my $null = scalar( grep { $_ eq '' } @classnum );
3963 push @c_where, 'part_pkg.classnum IS NULL' if $null;
3965 if ( scalar(@c_where) == 1 ) {
3966 push @where, @c_where;
3967 } elsif ( @c_where ) {
3968 push @where, ' ( '. join(' OR ', @c_where). ' ) ';
3977 # parse package report options
3980 my @report_option = ();
3981 if ( exists($params->{'report_option'}) ) {
3982 if ( ref($params->{'report_option'}) eq 'ARRAY' ) {
3983 @report_option = @{ $params->{'report_option'} };
3984 } elsif ( $params->{'report_option'} =~ /^([,\d]*)$/ ) {
3985 @report_option = split(',', $1);
3990 if (@report_option) {
3991 # this will result in the empty set for the dangling comma case as it should
3993 map{ "0 < ( SELECT count(*) FROM part_pkg_option
3994 WHERE part_pkg_option.pkgpart = part_pkg.pkgpart
3995 AND optionname = 'report_option_$_'
3996 AND optionvalue = '1' )"
4000 foreach my $any ( grep /^report_option_any/, keys %$params ) {
4002 my @report_option_any = ();
4003 if ( ref($params->{$any}) eq 'ARRAY' ) {
4004 @report_option_any = @{ $params->{$any} };
4005 } elsif ( $params->{$any} =~ /^([,\d]*)$/ ) {
4006 @report_option_any = split(',', $1);
4009 if (@report_option_any) {
4010 # this will result in the empty set for the dangling comma case as it should
4011 push @where, ' ( '. join(' OR ',
4012 map{ "0 < ( SELECT count(*) FROM part_pkg_option
4013 WHERE part_pkg_option.pkgpart = part_pkg.pkgpart
4014 AND optionname = 'report_option_$_'
4015 AND optionvalue = '1' )"
4016 } @report_option_any
4026 push @where, "part_pkg.custom = 'Y'" if $params->{custom};
4032 push @where, "(part_pkg.fcc_ds0s > 0 OR pkg_class.fcc_ds0s > 0)"
4033 if $params->{fcc_line};
4039 if ( exists($params->{'censustract'}) ) {
4040 $params->{'censustract'} =~ /^([.\d]*)$/;
4041 my $censustract = "cust_location.censustract = '$1'";
4042 $censustract .= ' OR cust_location.censustract is NULL' unless $1;
4043 push @where, "( $censustract )";
4047 # parse censustract2
4049 if ( exists($params->{'censustract2'})
4050 && $params->{'censustract2'} =~ /^(\d*)$/
4054 push @where, "cust_location.censustract LIKE '$1%'";
4057 "( cust_location.censustract = '' OR cust_location.censustract IS NULL )";
4062 # parse country/state
4064 for (qw(state country)) { # parsing rules are the same for these
4065 if ( exists($params->{$_})
4066 && uc($params->{$_}) =~ /^([A-Z]{2})$/ )
4068 # XXX post-2.3 only--before that, state/country may be in cust_main
4069 push @where, "cust_location.$_ = '$1'";
4077 if ( ref($params->{'pkgpart'}) ) {
4080 if ( ref($params->{'pkgpart'}) eq 'HASH' ) {
4081 @pkgpart = grep $params->{'pkgpart'}{$_}, keys %{ $params->{'pkgpart'} };
4082 } elsif ( ref($params->{'pkgpart'}) eq 'ARRAY' ) {
4083 @pkgpart = @{ $params->{'pkgpart'} };
4085 die 'unhandled pkgpart ref '. $params->{'pkgpart'};
4088 @pkgpart = grep /^(\d+)$/, @pkgpart;
4090 push @where, 'pkgpart IN ('. join(',', @pkgpart). ')' if scalar(@pkgpart);
4092 } elsif ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
4093 push @where, "pkgpart = $1";
4102 #false laziness w/report_cust_pkg.html
4105 'one-time charge' => { 'last_bill'=>1, 'bill'=>1, 'adjourn'=>1, 'susp'=>1, 'expire'=>1, 'cancel'=>1, },
4106 'active' => { 'susp'=>1, 'cancel'=>1 },
4107 'suspended' => { 'cancel' => 1 },
4112 if( exists($params->{'active'} ) ) {
4113 # This overrides all the other date-related fields
4114 my($beginning, $ending) = @{$params->{'active'}};
4116 "cust_pkg.setup IS NOT NULL",
4117 "cust_pkg.setup <= $ending",
4118 "(cust_pkg.cancel IS NULL OR cust_pkg.cancel >= $beginning )",
4119 "NOT (".FS::cust_pkg->onetime_sql . ")";
4122 foreach my $field (qw( setup last_bill bill adjourn susp expire contract_end change_date cancel )) {
4124 next unless exists($params->{$field});
4126 my($beginning, $ending) = @{$params->{$field}};
4128 next if $beginning == 0 && $ending == 4294967295;
4131 "cust_pkg.$field IS NOT NULL",
4132 "cust_pkg.$field >= $beginning",
4133 "cust_pkg.$field <= $ending";
4135 $orderby ||= "ORDER BY cust_pkg.$field";
4140 $orderby ||= 'ORDER BY bill';
4143 # parse magic, legacy, etc.
4146 if ( $params->{'magic'} &&
4147 $params->{'magic'} =~ /^(active|inactive|suspended|cancell?ed)$/
4150 $orderby = 'ORDER BY pkgnum';
4152 if ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
4153 push @where, "pkgpart = $1";
4156 } elsif ( $params->{'query'} eq 'pkgnum' ) {
4158 $orderby = 'ORDER BY pkgnum';
4160 } elsif ( $params->{'query'} eq 'APKG_pkgnum' ) {
4162 $orderby = 'ORDER BY pkgnum';
4165 SELECT count(*) FROM pkg_svc
4166 WHERE pkg_svc.pkgpart = cust_pkg.pkgpart
4167 AND pkg_svc.quantity > ( SELECT count(*) FROM cust_svc
4168 WHERE cust_svc.pkgnum = cust_pkg.pkgnum
4169 AND cust_svc.svcpart = pkg_svc.svcpart
4176 # setup queries, links, subs, etc. for the search
4179 # here is the agent virtualization
4180 if ($params->{CurrentUser}) {
4182 qsearchs('access_user', { username => $params->{CurrentUser} });
4185 push @where, $access_user->agentnums_sql('table'=>'cust_main');
4190 push @where, $FS::CurrentUser::CurrentUser->agentnums_sql('table'=>'cust_main');
4193 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
4195 my $addl_from = 'LEFT JOIN part_pkg USING ( pkgpart ) '.
4196 'LEFT JOIN pkg_class ON ( part_pkg.classnum = pkg_class.classnum ) '.
4197 'LEFT JOIN cust_location USING ( locationnum ) '.
4198 FS::UI::Web::join_cust_main('cust_pkg', 'cust_pkg');
4202 if ( $params->{'select_zip5'} ) {
4203 my $zip = 'cust_location.zip';
4205 $select = "DISTINCT substr($zip,1,5) as zip";
4206 $orderby = "ORDER BY substr($zip,1,5)";
4207 $count_query = "SELECT COUNT( DISTINCT substr($zip,1,5) )";
4209 $select = join(', ',
4211 ( map "part_pkg.$_", qw( pkg freq ) ),
4212 'pkg_class.classname',
4213 'cust_main.custnum AS cust_main_custnum',
4214 FS::UI::Web::cust_sql_fields(
4215 $params->{'cust_fields'}
4218 $count_query = 'SELECT COUNT(*)';
4221 $count_query .= " FROM cust_pkg $addl_from $extra_sql";
4224 'table' => 'cust_pkg',
4226 'select' => $select,
4227 'extra_sql' => $extra_sql,
4228 'order_by' => $orderby,
4229 'addl_from' => $addl_from,
4230 'count_query' => $count_query,
4237 Returns a list of two package counts. The first is a count of packages
4238 based on the supplied criteria and the second is the count of residential
4239 packages with those same criteria. Criteria are specified as in the search
4245 my ($class, $params) = @_;
4247 my $sql_query = $class->search( $params );
4249 my $count_sql = delete($sql_query->{'count_query'});
4250 $count_sql =~ s/ FROM/,count(CASE WHEN cust_main.company IS NULL OR cust_main.company = '' THEN 1 END) FROM/
4251 or die "couldn't parse count_sql";
4253 my $count_sth = dbh->prepare($count_sql)
4254 or die "Error preparing $count_sql: ". dbh->errstr;
4256 or die "Error executing $count_sql: ". $count_sth->errstr;
4257 my $count_arrayref = $count_sth->fetchrow_arrayref;
4259 return ( @$count_arrayref );
4263 =item tax_locationnum_sql
4265 Returns an SQL expression for the tax location for a package, based
4266 on the settings of 'tax-pkg_address' and 'tax-ship_address'.
4270 sub tax_locationnum_sql {
4271 my $conf = FS::Conf->new;
4272 if ( $conf->exists('tax-pkg_address') ) {
4273 'cust_pkg.locationnum';
4275 elsif ( $conf->exists('tax-ship_address') ) {
4276 'cust_main.ship_locationnum';
4279 'cust_main.bill_locationnum';
4285 Returns a list: the first item is an SQL fragment identifying matching
4286 packages/customers via location (taking into account shipping and package
4287 address taxation, if enabled), and subsequent items are the parameters to
4288 substitute for the placeholders in that fragment.
4293 my($class, %opt) = @_;
4294 my $ornull = $opt{'ornull'};
4296 my $conf = new FS::Conf;
4298 # '?' placeholders in _location_sql_where
4299 my $x = $ornull ? 3 : 2;
4310 if ( $conf->exists('tax-ship_address') ) {
4313 ( ( ship_last IS NULL OR ship_last = '' )
4314 AND ". _location_sql_where('cust_main', '', $ornull ). "
4316 OR ( ship_last IS NOT NULL AND ship_last != ''
4317 AND ". _location_sql_where('cust_main', 'ship_', $ornull ). "
4320 # AND payby != 'COMP'
4322 @main_param = ( @bill_param, @bill_param );
4326 $main_where = _location_sql_where('cust_main'); # AND payby != 'COMP'
4327 @main_param = @bill_param;
4333 if ( $conf->exists('tax-pkg_address') ) {
4335 my $loc_where = _location_sql_where( 'cust_location', '', $ornull );
4338 ( cust_pkg.locationnum IS NULL AND $main_where )
4339 OR ( cust_pkg.locationnum IS NOT NULL AND $loc_where )
4342 @param = ( @main_param, @bill_param );
4346 $where = $main_where;
4347 @param = @main_param;
4355 #subroutine, helper for location_sql
4356 sub _location_sql_where {
4358 my $prefix = @_ ? shift : '';
4359 my $ornull = @_ ? shift : '';
4361 # $ornull = $ornull ? " OR ( ? IS NULL AND $table.${prefix}county IS NULL ) " : '';
4363 $ornull = $ornull ? ' OR ? IS NULL ' : '';
4365 my $or_empty_city = " OR ( ? = '' AND $table.${prefix}city IS NULL )";
4366 my $or_empty_county = " OR ( ? = '' AND $table.${prefix}county IS NULL )";
4367 my $or_empty_state = " OR ( ? = '' AND $table.${prefix}state IS NULL )";
4369 my $text = (driver_name =~ /^mysql/i) ? 'char' : 'text';
4371 # ( $table.${prefix}city = ? $or_empty_city $ornull )
4373 ( $table.district = ? OR ? = '' OR CAST(? AS $text) IS NULL )
4374 AND ( $table.${prefix}city = ? OR ? = '' OR CAST(? AS $text) IS NULL )
4375 AND ( $table.${prefix}county = ? $or_empty_county $ornull )
4376 AND ( $table.${prefix}state = ? $or_empty_state $ornull )
4377 AND $table.${prefix}country = ?
4382 my( $self, $what ) = @_;
4384 my $what_show_zero = $what. '_show_zero';
4385 length($self->$what_show_zero())
4386 ? ($self->$what_show_zero() eq 'Y')
4387 : $self->part_pkg->$what_show_zero();
4394 =item order CUSTNUM, PKGPARTS_ARYREF, [ REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF [ REFNUM ] ] ]
4396 CUSTNUM is a customer (see L<FS::cust_main>)
4398 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
4399 L<FS::part_pkg>) to order for this customer. Duplicates are of course
4402 REMOVE_PKGNUMS is an optional list of pkgnums specifying the billing items to
4403 remove for this customer. The services (see L<FS::cust_svc>) are moved to the
4404 new billing items. An error is returned if this is not possible (see
4405 L<FS::pkg_svc>). An empty arrayref is equivalent to not specifying this
4408 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
4409 newly-created cust_pkg objects.
4411 REFNUM, if specified, will specify the FS::pkg_referral record to be created
4412 and inserted. Multiple FS::pkg_referral records can be created by
4413 setting I<refnum> to an array reference of refnums or a hash reference with
4414 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
4415 record will be created corresponding to cust_main.refnum.
4420 my ($custnum, $pkgparts, $remove_pkgnum, $return_cust_pkg, $refnum) = @_;
4422 my $conf = new FS::Conf;
4424 # Transactionize this whole mess
4425 local $SIG{HUP} = 'IGNORE';
4426 local $SIG{INT} = 'IGNORE';
4427 local $SIG{QUIT} = 'IGNORE';
4428 local $SIG{TERM} = 'IGNORE';
4429 local $SIG{TSTP} = 'IGNORE';
4430 local $SIG{PIPE} = 'IGNORE';
4432 my $oldAutoCommit = $FS::UID::AutoCommit;
4433 local $FS::UID::AutoCommit = 0;
4437 # my $cust_main = qsearchs('cust_main', { custnum => $custnum });
4438 # return "Customer not found: $custnum" unless $cust_main;
4440 warn "$me order: pkgnums to remove: ". join(',', @$remove_pkgnum). "\n"
4443 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
4446 my $change = scalar(@old_cust_pkg) != 0;
4449 if ( scalar(@old_cust_pkg) == 1 && scalar(@$pkgparts) == 1 ) {
4451 warn "$me order: changing pkgnum ". $old_cust_pkg[0]->pkgnum.
4452 " to pkgpart ". $pkgparts->[0]. "\n"
4455 my $err_or_cust_pkg =
4456 $old_cust_pkg[0]->change( 'pkgpart' => $pkgparts->[0],
4457 'refnum' => $refnum,
4460 unless (ref($err_or_cust_pkg)) {
4461 $dbh->rollback if $oldAutoCommit;
4462 return $err_or_cust_pkg;
4465 push @$return_cust_pkg, $err_or_cust_pkg;
4466 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4471 # Create the new packages.
4472 foreach my $pkgpart (@$pkgparts) {
4474 warn "$me order: inserting pkgpart $pkgpart\n" if $DEBUG;
4476 my $cust_pkg = new FS::cust_pkg { custnum => $custnum,
4477 pkgpart => $pkgpart,
4481 $error = $cust_pkg->insert( 'change' => $change );
4482 push @$return_cust_pkg, $cust_pkg;
4484 foreach my $link ($cust_pkg->part_pkg->supp_part_pkg_link) {
4485 my $supp_pkg = FS::cust_pkg->new({
4486 custnum => $custnum,
4487 pkgpart => $link->dst_pkgpart,
4489 main_pkgnum => $cust_pkg->pkgnum,
4492 $error ||= $supp_pkg->insert( 'change' => $change );
4493 push @$return_cust_pkg, $supp_pkg;
4497 $dbh->rollback if $oldAutoCommit;
4502 # $return_cust_pkg now contains refs to all of the newly
4505 # Transfer services and cancel old packages.
4506 foreach my $old_pkg (@old_cust_pkg) {
4508 warn "$me order: transferring services from pkgnum ". $old_pkg->pkgnum. "\n"
4511 foreach my $new_pkg (@$return_cust_pkg) {
4512 $error = $old_pkg->transfer($new_pkg);
4513 if ($error and $error == 0) {
4514 # $old_pkg->transfer failed.
4515 $dbh->rollback if $oldAutoCommit;
4520 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
4521 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
4522 foreach my $new_pkg (@$return_cust_pkg) {
4523 $error = $old_pkg->transfer($new_pkg, 'change_svcpart'=>1 );
4524 if ($error and $error == 0) {
4525 # $old_pkg->transfer failed.
4526 $dbh->rollback if $oldAutoCommit;
4533 # Transfers were successful, but we went through all of the
4534 # new packages and still had services left on the old package.
4535 # We can't cancel the package under the circumstances, so abort.
4536 $dbh->rollback if $oldAutoCommit;
4537 return "Unable to transfer all services from package ".$old_pkg->pkgnum;
4539 $error = $old_pkg->cancel( quiet=>1 );
4545 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4549 =item bulk_change PKGPARTS_ARYREF, REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF ]
4551 A bulk change method to change packages for multiple customers.
4553 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
4554 L<FS::part_pkg>) to order for each customer. Duplicates are of course
4557 REMOVE_PKGNUMS is an list of pkgnums specifying the billing items to
4558 replace. The services (see L<FS::cust_svc>) are moved to the
4559 new billing items. An error is returned if this is not possible (see
4562 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
4563 newly-created cust_pkg objects.
4568 my ($pkgparts, $remove_pkgnum, $return_cust_pkg) = @_;
4570 # Transactionize this whole mess
4571 local $SIG{HUP} = 'IGNORE';
4572 local $SIG{INT} = 'IGNORE';
4573 local $SIG{QUIT} = 'IGNORE';
4574 local $SIG{TERM} = 'IGNORE';
4575 local $SIG{TSTP} = 'IGNORE';
4576 local $SIG{PIPE} = 'IGNORE';
4578 my $oldAutoCommit = $FS::UID::AutoCommit;
4579 local $FS::UID::AutoCommit = 0;
4583 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
4586 while(scalar(@old_cust_pkg)) {
4588 my $custnum = $old_cust_pkg[0]->custnum;
4589 my (@remove) = map { $_->pkgnum }
4590 grep { $_->custnum == $custnum } @old_cust_pkg;
4591 @old_cust_pkg = grep { $_->custnum != $custnum } @old_cust_pkg;
4593 my $error = order $custnum, $pkgparts, \@remove, \@return;
4595 push @errors, $error
4597 push @$return_cust_pkg, @return;
4600 if (scalar(@errors)) {
4601 $dbh->rollback if $oldAutoCommit;
4602 return join(' / ', @errors);
4605 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4609 # Used by FS::Upgrade to migrate to a new database.
4610 sub _upgrade_data { # class method
4611 my ($class, %opts) = @_;
4612 $class->_upgrade_otaker(%opts);
4614 # RT#10139, bug resulting in contract_end being set when it shouldn't
4615 'UPDATE cust_pkg SET contract_end = NULL WHERE contract_end = -1',
4616 # RT#10830, bad calculation of prorate date near end of year
4617 # the date range for bill is December 2009, and we move it forward
4618 # one year if it's before the previous bill date (which it should
4620 'UPDATE cust_pkg SET bill = bill + (365*24*60*60) WHERE bill < last_bill
4621 AND bill > 1259654400 AND bill < 1262332800 AND (SELECT plan FROM part_pkg
4622 WHERE part_pkg.pkgpart = cust_pkg.pkgpart) = \'prorate\'',
4623 # RT6628, add order_date to cust_pkg
4624 'update cust_pkg set order_date = (select history_date from h_cust_pkg
4625 where h_cust_pkg.pkgnum = cust_pkg.pkgnum and
4626 history_action = \'insert\') where order_date is null',
4628 foreach my $sql (@statements) {
4629 my $sth = dbh->prepare($sql);
4630 $sth->execute or die $sth->errstr;
4638 sub order is not OO. Perhaps it should be moved to FS::cust_main and made so?
4640 In sub order, the @pkgparts array (passed by reference) is clobbered.
4642 Also in sub order, no money is adjusted. Once FS::part_pkg defines a standard
4643 method to pass dates to the recur_prog expression, it should do so.
4645 FS::svc_acct, FS::svc_domain, FS::svc_www, FS::svc_ip and FS::svc_forward are
4646 loaded via 'use' at compile time, rather than via 'require' in sub { setup,
4647 suspend, unsuspend, cancel } because they use %FS::UID::callback to load
4648 configuration values. Probably need a subroutine which decides what to do
4649 based on whether or not we've fetched the user yet, rather than a hash. See
4650 FS::UID and the TODO.
4652 Now that things are transactional should the check in the insert method be
4657 L<FS::Record>, L<FS::cust_main>, L<FS::part_pkg>, L<FS::cust_svc>,
4658 L<FS::pkg_svc>, schema.html from the base documentation