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->export_pkg_change($old)
585 || $new->SUPER::replace( $old,
587 ? $options->{options}
591 $dbh->rollback if $oldAutoCommit;
595 #for prepaid packages,
596 #trigger export of new RADIUS Expiration attribute when cust_pkg.bill changes
597 foreach my $old_svc_acct ( @svc_acct ) {
598 my $new_svc_acct = new FS::svc_acct { $old_svc_acct->hash };
600 $new_svc_acct->replace( $old_svc_acct,
601 'depend_jobnum' => $options->{depend_jobnum},
604 $dbh->rollback if $oldAutoCommit;
609 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
616 Checks all fields to make sure this is a valid billing item. If there is an
617 error, returns the error, otherwise returns false. Called by the insert and
625 if ( !$self->locationnum or $self->locationnum == -1 ) {
626 $self->set('locationnum', $self->cust_main->ship_locationnum);
630 $self->ut_numbern('pkgnum')
631 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum')
632 || $self->ut_numbern('pkgpart')
633 || $self->ut_foreign_keyn('contactnum', 'contact', 'contactnum' )
634 || $self->ut_foreign_keyn('locationnum', 'cust_location', 'locationnum')
635 || $self->ut_numbern('start_date')
636 || $self->ut_numbern('setup')
637 || $self->ut_numbern('bill')
638 || $self->ut_numbern('susp')
639 || $self->ut_numbern('cancel')
640 || $self->ut_numbern('adjourn')
641 || $self->ut_numbern('resume')
642 || $self->ut_numbern('expire')
643 || $self->ut_numbern('dundate')
644 || $self->ut_enum('no_auto', [ '', 'Y' ])
645 || $self->ut_enum('waive_setup', [ '', 'Y' ])
646 || $self->ut_numbern('agent_pkgid')
647 || $self->ut_enum('recur_show_zero', [ '', 'Y', 'N', ])
648 || $self->ut_enum('setup_show_zero', [ '', 'Y', 'N', ])
649 || $self->ut_foreign_keyn('main_pkgnum', 'cust_pkg', 'pkgnum')
650 || $self->ut_foreign_keyn('pkglinknum', 'part_pkg_link', 'pkglinknum')
652 return $error if $error;
654 return "A package with both start date (future start) and setup date (already started) will never bill"
655 if $self->start_date && $self->setup;
657 return "A future unsuspend date can only be set for a package with a suspend date"
658 if $self->resume and !$self->susp and !$self->adjourn;
660 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
662 if ( $self->dbdef_table->column('manual_flag') ) {
663 $self->manual_flag('') if $self->manual_flag eq ' ';
664 $self->manual_flag =~ /^([01]?)$/
665 or return "Illegal manual_flag ". $self->manual_flag;
666 $self->manual_flag($1);
674 Check the pkgpart to make sure it's allowed with the reg_code and/or
675 promo_code of the package (if present) and with the customer's agent.
676 Called from C<insert>, unless we are doing a package change that doesn't
684 # my $error = $self->ut_numbern('pkgpart'); # already done
687 if ( $self->reg_code ) {
689 unless ( grep { $self->pkgpart == $_->pkgpart }
690 map { $_->reg_code_pkg }
691 qsearchs( 'reg_code', { 'code' => $self->reg_code,
692 'agentnum' => $self->cust_main->agentnum })
694 return "Unknown registration code";
697 } elsif ( $self->promo_code ) {
700 qsearchs('part_pkg', {
701 'pkgpart' => $self->pkgpart,
702 'promo_code' => { op=>'ILIKE', value=>$self->promo_code },
704 return 'Unknown promotional code' unless $promo_part_pkg;
708 unless ( $disable_agentcheck ) {
710 qsearchs( 'agent', { 'agentnum' => $self->cust_main->agentnum } );
711 return "agent ". $agent->agentnum. ':'. $agent->agent.
712 " can't purchase pkgpart ". $self->pkgpart
713 unless $agent->pkgpart_hashref->{ $self->pkgpart }
714 || $agent->agentnum == $self->part_pkg->agentnum;
717 $error = $self->ut_foreign_key('pkgpart', 'part_pkg', 'pkgpart' );
718 return $error if $error;
726 =item cancel [ OPTION => VALUE ... ]
728 Cancels and removes all services (see L<FS::cust_svc> and L<FS::part_svc>)
729 in this package, then cancels the package itself (sets the cancel field to
732 Available options are:
736 =item quiet - can be set true to supress email cancellation notices.
738 =item time - can be set to cancel the package based on a specific future or
739 historical date. Using time ensures that the remaining amount is calculated
740 correctly. Note however that this is an immediate cancel and just changes
741 the date. You are PROBABLY looking to expire the account instead of using
744 =item reason - can be set to a cancellation reason (see L<FS:reason>),
745 either a reasonnum of an existing reason, or passing a hashref will create
746 a new reason. The hashref should have the following keys: typenum - Reason
747 type (see L<FS::reason_type>, reason - Text of the new reason.
749 =item date - can be set to a unix style timestamp to specify when to
752 =item nobill - can be set true to skip billing if it might otherwise be done.
754 =item unused_credit - can be set to 1 to credit the remaining time, or 0 to
755 not credit it. This must be set (by change()) when changing the package
756 to a different pkgpart or location, and probably shouldn't be in any other
757 case. If it's not set, the 'unused_credit_cancel' part_pkg option will
762 If there is an error, returns the error, otherwise returns false.
767 my( $self, %options ) = @_;
770 # pass all suspend/cancel actions to the main package
771 if ( $self->main_pkgnum and !$options{'from_main'} ) {
772 return $self->main_pkg->cancel(%options);
775 my $conf = new FS::Conf;
777 warn "cust_pkg::cancel called with options".
778 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
781 local $SIG{HUP} = 'IGNORE';
782 local $SIG{INT} = 'IGNORE';
783 local $SIG{QUIT} = 'IGNORE';
784 local $SIG{TERM} = 'IGNORE';
785 local $SIG{TSTP} = 'IGNORE';
786 local $SIG{PIPE} = 'IGNORE';
788 my $oldAutoCommit = $FS::UID::AutoCommit;
789 local $FS::UID::AutoCommit = 0;
792 my $old = $self->select_for_update;
794 if ( $old->get('cancel') || $self->get('cancel') ) {
795 dbh->rollback if $oldAutoCommit;
796 return ""; # no error
799 # XXX possibly set cancel_time to the expire date?
800 my $cancel_time = $options{'time'} || time;
801 my $date = $options{'date'} if $options{'date'}; # expire/cancel later
802 $date = '' if ($date && $date <= $cancel_time); # complain instead?
804 #race condition: usage could be ongoing until unprovisioned
805 #resolved by performing a change package instead (which unprovisions) and
807 if ( !$options{nobill} && !$date ) {
808 # && $conf->exists('bill_usage_on_cancel') ) { #calc_cancel checks this
809 my $copy = $self->new({$self->hash});
811 $copy->cust_main->bill( 'pkg_list' => [ $copy ],
813 'time' => $cancel_time );
814 warn "Error billing during cancel, custnum ".
815 #$self->cust_main->custnum. ": $error"
820 if ( $options{'reason'} ) {
821 $error = $self->insert_reason( 'reason' => $options{'reason'},
822 'action' => $date ? 'expire' : 'cancel',
823 'date' => $date ? $date : $cancel_time,
824 'reason_otaker' => $options{'reason_otaker'},
827 dbh->rollback if $oldAutoCommit;
828 return "Error inserting cust_pkg_reason: $error";
832 my %svc_cancel_opt = ();
833 $svc_cancel_opt{'date'} = $date if $date;
834 foreach my $cust_svc (
837 sort { $a->[1] <=> $b->[1] }
838 map { [ $_, $_->svc_x ? $_->svc_x->table_info->{'cancel_weight'} : -1 ]; }
839 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
841 my $part_svc = $cust_svc->part_svc;
842 next if ( defined($part_svc) and $part_svc->preserve );
843 my $error = $cust_svc->cancel( %svc_cancel_opt );
846 $dbh->rollback if $oldAutoCommit;
847 return 'Error '. ($svc_cancel_opt{'date'} ? 'expiring' : 'canceling' ).
853 # credit remaining time if appropriate
855 if ( exists($options{'unused_credit'}) ) {
856 $do_credit = $options{'unused_credit'};
859 $do_credit = $self->part_pkg->option('unused_credit_cancel', 1);
862 my $error = $self->credit_remaining('cancel', $cancel_time);
864 $dbh->rollback if $oldAutoCommit;
871 my %hash = $self->hash;
872 $date ? ($hash{'expire'} = $date) : ($hash{'cancel'} = $cancel_time);
873 $hash{'change_custnum'} = $options{'change_custnum'};
874 my $new = new FS::cust_pkg ( \%hash );
875 $error = $new->replace( $self, options => { $self->options } );
877 $dbh->rollback if $oldAutoCommit;
881 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
882 $error = $supp_pkg->cancel(%options, 'from_main' => 1);
884 $dbh->rollback if $oldAutoCommit;
885 return "canceling supplemental pkg#".$supp_pkg->pkgnum.": $error";
889 foreach my $usage ( $self->cust_pkg_usage ) {
890 $error = $usage->delete;
892 $dbh->rollback if $oldAutoCommit;
893 return "deleting usage pools: $error";
897 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
898 return '' if $date; #no errors
900 my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ } $self->cust_main->invoicing_list;
901 if ( !$options{'quiet'} &&
902 $conf->exists('emailcancel', $self->cust_main->agentnum) &&
904 my $msgnum = $conf->config('cancel_msgnum', $self->cust_main->agentnum);
907 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum });
908 $error = $msg_template->send( 'cust_main' => $self->cust_main,
913 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
914 'to' => \@invoicing_list,
915 'subject' => ( $conf->config('cancelsubject') || 'Cancellation Notice' ),
916 'body' => [ map "$_\n", $conf->config('cancelmessage') ],
919 #should this do something on errors?
926 =item cancel_if_expired [ NOW_TIMESTAMP ]
928 Cancels this package if its expire date has been reached.
932 sub cancel_if_expired {
934 my $time = shift || time;
935 return '' unless $self->expire && $self->expire <= $time;
936 my $error = $self->cancel;
938 return "Error cancelling expired pkg ". $self->pkgnum. " for custnum ".
939 $self->custnum. ": $error";
946 "Un-cancels" this package: Orders a new package with the same custnum, pkgpart,
947 locationnum, (other fields?). Attempts to re-provision cancelled services
948 using history information (errors at this stage are not fatal).
950 cust_pkg: pass a scalar reference, will be filled in with the new cust_pkg object
952 svc_fatal: service provisioning errors are fatal
954 svc_errors: pass an array reference, will be filled in with any provisioning errors
956 main_pkgnum: link the package as a supplemental package of this one. For
962 my( $self, %options ) = @_;
964 #in case you try do do $uncancel-date = $cust_pkg->uncacel
965 return '' unless $self->get('cancel');
967 if ( $self->main_pkgnum and !$options{'main_pkgnum'} ) {
968 return $self->main_pkg->uncancel(%options);
975 local $SIG{HUP} = 'IGNORE';
976 local $SIG{INT} = 'IGNORE';
977 local $SIG{QUIT} = 'IGNORE';
978 local $SIG{TERM} = 'IGNORE';
979 local $SIG{TSTP} = 'IGNORE';
980 local $SIG{PIPE} = 'IGNORE';
982 my $oldAutoCommit = $FS::UID::AutoCommit;
983 local $FS::UID::AutoCommit = 0;
987 # insert the new package
990 my $cust_pkg = new FS::cust_pkg {
991 last_bill => ( $options{'last_bill'} || $self->get('last_bill') ),
992 bill => ( $options{'bill'} || $self->get('bill') ),
994 uncancel_pkgnum => $self->pkgnum,
995 main_pkgnum => ($options{'main_pkgnum'} || ''),
996 map { $_ => $self->get($_) } qw(
997 custnum pkgpart locationnum
999 susp adjourn resume expire start_date contract_end dundate
1000 change_date change_pkgpart change_locationnum
1001 manual_flag no_auto quantity agent_pkgid recur_show_zero setup_show_zero
1005 my $error = $cust_pkg->insert(
1006 'change' => 1, #supresses any referral credit to a referring customer
1007 'allow_pkgpart' => 1, # allow this even if the package def is disabled
1010 $dbh->rollback if $oldAutoCommit;
1018 #find historical services within this timeframe before the package cancel
1019 # (incompatible with "time" option to cust_pkg->cancel?)
1020 my $fuzz = 2 * 60; #2 minutes? too much? (might catch separate unprovision)
1021 # too little? (unprovisioing export delay?)
1022 my($end, $start) = ( $self->get('cancel'), $self->get('cancel') - $fuzz );
1023 my @h_cust_svc = $self->h_cust_svc( $end, $start );
1026 foreach my $h_cust_svc (@h_cust_svc) {
1027 my $h_svc_x = $h_cust_svc->h_svc_x( $end, $start );
1028 #next unless $h_svc_x; #should this happen?
1029 (my $table = $h_svc_x->table) =~ s/^h_//;
1030 require "FS/$table.pm";
1031 my $class = "FS::$table";
1032 my $svc_x = $class->new( {
1033 'pkgnum' => $cust_pkg->pkgnum,
1034 'svcpart' => $h_cust_svc->svcpart,
1035 map { $_ => $h_svc_x->get($_) } fields($table)
1039 if ( $h_svc_x->isa('FS::h_svc_Radius_Mixin') ) {
1040 $svc_x->usergroup( [ $h_svc_x->h_usergroup($end, $start) ] );
1043 my $svc_error = $svc_x->insert;
1045 if ( $options{svc_fatal} ) {
1046 $dbh->rollback if $oldAutoCommit;
1049 # if we've failed to insert the svc_x object, svc_Common->insert
1050 # will have removed the cust_svc already. if not, then both records
1051 # were inserted but we failed for some other reason (export, most
1052 # likely). in that case, report the error and delete the records.
1053 push @svc_errors, $svc_error;
1054 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svc_x->svcnum });
1056 # except if export_insert failed, export_delete probably won't be
1058 local $FS::svc_Common::noexport_hack = 1;
1059 my $cleanup_error = $svc_x->delete; # also deletes cust_svc
1060 if ( $cleanup_error ) { # and if THAT fails, then run away
1061 $dbh->rollback if $oldAutoCommit;
1062 return $cleanup_error;
1067 } #foreach $h_cust_svc
1069 #these are pretty rare, but should handle them
1070 # - dsl_device (mac addresses)
1071 # - phone_device (mac addresses)
1072 # - dsl_note (ikano notes)
1073 # - domain_record (i.e. restore DNS information w/domains)
1074 # - inventory_item(?) (inventory w/un-cancelling service?)
1075 # - nas (svc_broaband nas stuff)
1076 #this stuff is unused in the wild afaik
1077 # - mailinglistmember
1079 # - svc_domain.parent_svcnum?
1080 # - acct_snarf (ancient mail fetching config)
1081 # - cgp_rule (communigate)
1082 # - cust_svc_option (used by our Tron stuff)
1083 # - acct_rt_transaction (used by our time worked stuff)
1086 # also move over any services that didn't unprovision at cancellation
1089 foreach my $cust_svc ( qsearch('cust_svc', { pkgnum => $self->pkgnum } ) ) {
1090 $cust_svc->pkgnum( $cust_pkg->pkgnum );
1091 my $error = $cust_svc->replace;
1093 $dbh->rollback if $oldAutoCommit;
1099 # Uncancel any supplemental packages, and make them supplemental to the
1103 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1105 $error = $supp_pkg->uncancel(%options, 'main_pkgnum' => $cust_pkg->pkgnum);
1107 $dbh->rollback if $oldAutoCommit;
1108 return "canceling supplemental pkg#".$supp_pkg->pkgnum.": $error";
1116 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1118 ${ $options{cust_pkg} } = $cust_pkg if ref($options{cust_pkg});
1119 @{ $options{svc_errors} } = @svc_errors if ref($options{svc_errors});
1126 Cancels any pending expiration (sets the expire field to null).
1128 If there is an error, returns the error, otherwise returns false.
1133 my( $self, %options ) = @_;
1136 local $SIG{HUP} = 'IGNORE';
1137 local $SIG{INT} = 'IGNORE';
1138 local $SIG{QUIT} = 'IGNORE';
1139 local $SIG{TERM} = 'IGNORE';
1140 local $SIG{TSTP} = 'IGNORE';
1141 local $SIG{PIPE} = 'IGNORE';
1143 my $oldAutoCommit = $FS::UID::AutoCommit;
1144 local $FS::UID::AutoCommit = 0;
1147 my $old = $self->select_for_update;
1149 my $pkgnum = $old->pkgnum;
1150 if ( $old->get('cancel') || $self->get('cancel') ) {
1151 dbh->rollback if $oldAutoCommit;
1152 return "Can't unexpire cancelled package $pkgnum";
1153 # or at least it's pointless
1156 unless ( $old->get('expire') && $self->get('expire') ) {
1157 dbh->rollback if $oldAutoCommit;
1158 return ""; # no error
1161 my %hash = $self->hash;
1162 $hash{'expire'} = '';
1163 my $new = new FS::cust_pkg ( \%hash );
1164 $error = $new->replace( $self, options => { $self->options } );
1166 $dbh->rollback if $oldAutoCommit;
1170 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1176 =item suspend [ OPTION => VALUE ... ]
1178 Suspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
1179 package, then suspends the package itself (sets the susp field to now).
1181 Available options are:
1185 =item reason - can be set to a cancellation reason (see L<FS:reason>),
1186 either a reasonnum of an existing reason, or passing a hashref will create
1187 a new reason. The hashref should have the following keys:
1188 - typenum - Reason type (see L<FS::reason_type>
1189 - reason - Text of the new reason.
1191 =item date - can be set to a unix style timestamp to specify when to
1194 =item time - can be set to override the current time, for calculation
1195 of final invoices or unused-time credits
1197 =item resume_date - can be set to a time when the package should be
1198 unsuspended. This may be more convenient than calling C<unsuspend()>
1201 =item from_main - allows a supplemental package to be suspended, rather
1202 than redirecting the method call to its main package. For internal use.
1206 If there is an error, returns the error, otherwise returns false.
1211 my( $self, %options ) = @_;
1214 # pass all suspend/cancel actions to the main package
1215 if ( $self->main_pkgnum and !$options{'from_main'} ) {
1216 return $self->main_pkg->suspend(%options);
1219 local $SIG{HUP} = 'IGNORE';
1220 local $SIG{INT} = 'IGNORE';
1221 local $SIG{QUIT} = 'IGNORE';
1222 local $SIG{TERM} = 'IGNORE';
1223 local $SIG{TSTP} = 'IGNORE';
1224 local $SIG{PIPE} = 'IGNORE';
1226 my $oldAutoCommit = $FS::UID::AutoCommit;
1227 local $FS::UID::AutoCommit = 0;
1230 my $old = $self->select_for_update;
1232 my $pkgnum = $old->pkgnum;
1233 if ( $old->get('cancel') || $self->get('cancel') ) {
1234 dbh->rollback if $oldAutoCommit;
1235 return "Can't suspend cancelled package $pkgnum";
1238 if ( $old->get('susp') || $self->get('susp') ) {
1239 dbh->rollback if $oldAutoCommit;
1240 return ""; # no error # complain on adjourn?
1243 my $suspend_time = $options{'time'} || time;
1244 my $date = $options{date} if $options{date}; # adjourn/suspend later
1245 $date = '' if ($date && $date <= $suspend_time); # complain instead?
1247 if ( $date && $old->get('expire') && $old->get('expire') < $date ) {
1248 dbh->rollback if $oldAutoCommit;
1249 return "Package $pkgnum expires before it would be suspended.";
1252 # some false laziness with sub cancel
1253 if ( !$options{nobill} && !$date &&
1254 $self->part_pkg->option('bill_suspend_as_cancel',1) ) {
1255 # kind of a kludge--'bill_suspend_as_cancel' to avoid having to
1256 # make the entire cust_main->bill path recognize 'suspend' and
1257 # 'cancel' separately.
1258 warn "Billing $pkgnum on suspension (at $suspend_time)\n" if $DEBUG;
1259 my $copy = $self->new({$self->hash});
1261 $copy->cust_main->bill( 'pkg_list' => [ $copy ],
1263 'time' => $suspend_time );
1264 warn "Error billing during suspend, custnum ".
1265 #$self->cust_main->custnum. ": $error"
1270 if ( $options{'reason'} ) {
1271 $error = $self->insert_reason( 'reason' => $options{'reason'},
1272 'action' => $date ? 'adjourn' : 'suspend',
1273 'date' => $date ? $date : $suspend_time,
1274 'reason_otaker' => $options{'reason_otaker'},
1277 dbh->rollback if $oldAutoCommit;
1278 return "Error inserting cust_pkg_reason: $error";
1282 my %hash = $self->hash;
1284 $hash{'adjourn'} = $date;
1286 $hash{'susp'} = $suspend_time;
1289 my $resume_date = $options{'resume_date'} || 0;
1290 if ( $resume_date > ($date || $suspend_time) ) {
1291 $hash{'resume'} = $resume_date;
1294 $options{options} ||= {};
1296 my $new = new FS::cust_pkg ( \%hash );
1297 $error = $new->replace( $self, options => { $self->options,
1298 %{ $options{options} },
1302 $dbh->rollback if $oldAutoCommit;
1307 # credit remaining time if appropriate
1308 if ( $self->part_pkg->option('unused_credit_suspend', 1) ) {
1309 my $error = $self->credit_remaining('suspend', $suspend_time);
1311 $dbh->rollback if $oldAutoCommit;
1318 foreach my $cust_svc (
1319 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
1321 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
1323 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
1324 $dbh->rollback if $oldAutoCommit;
1325 return "Illegal svcdb value in part_svc!";
1328 require "FS/$svcdb.pm";
1330 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
1332 $error = $svc->suspend;
1334 $dbh->rollback if $oldAutoCommit;
1337 my( $label, $value ) = $cust_svc->label;
1338 push @labels, "$label: $value";
1342 my $conf = new FS::Conf;
1343 if ( $conf->config('suspend_email_admin') ) {
1345 my $error = send_email(
1346 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
1347 #invoice_from ??? well as good as any
1348 'to' => $conf->config('suspend_email_admin'),
1349 'subject' => 'FREESIDE NOTIFICATION: Customer package suspended',
1351 "This is an automatic message from your Freeside installation\n",
1352 "informing you that the following customer package has been suspended:\n",
1354 'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
1355 'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
1356 ( map { "Service : $_\n" } @labels ),
1361 warn "WARNING: can't send suspension admin email (suspending anyway): ".
1369 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1370 $error = $supp_pkg->suspend(%options, 'from_main' => 1);
1372 $dbh->rollback if $oldAutoCommit;
1373 return "suspending supplemental pkg#".$supp_pkg->pkgnum.": $error";
1377 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1382 =item credit_remaining MODE TIME
1384 Generate a credit for this package for the time remaining in the current
1385 billing period. MODE is either "suspend" or "cancel" (determines the
1386 credit type). TIME is the time of suspension/cancellation. Both arguments
1391 sub credit_remaining {
1392 # Add a credit for remaining service
1393 my ($self, $mode, $time) = @_;
1394 die 'credit_remaining requires suspend or cancel'
1395 unless $mode eq 'suspend' or $mode eq 'cancel';
1396 die 'no suspend/cancel time' unless $time > 0;
1398 my $conf = FS::Conf->new;
1399 my $reason_type = $conf->config($mode.'_credit_type');
1401 my $last_bill = $self->getfield('last_bill') || 0;
1402 my $next_bill = $self->getfield('bill') || 0;
1403 if ( $last_bill > 0 # the package has been billed
1404 and $next_bill > 0 # the package has a next bill date
1405 and $next_bill >= $time # which is in the future
1407 my $remaining_value = $self->calc_remain('time' => $time);
1408 if ( $remaining_value > 0 ) {
1409 warn "Crediting for $remaining_value on package ".$self->pkgnum."\n"
1411 my $error = $self->cust_main->credit(
1413 'Credit for unused time on '. $self->part_pkg->pkg,
1414 'reason_type' => $reason_type,
1416 return "Error crediting customer \$$remaining_value for unused time".
1417 " on ". $self->part_pkg->pkg. ": $error"
1419 } #if $remaining_value
1420 } #if $last_bill, etc.
1424 =item unsuspend [ OPTION => VALUE ... ]
1426 Unsuspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
1427 package, then unsuspends the package itself (clears the susp field and the
1428 adjourn field if it is in the past). If the suspend reason includes an
1429 unsuspension package, that package will be ordered.
1431 Available options are:
1437 Can be set to a date to unsuspend the package in the future (the 'resume'
1440 =item adjust_next_bill
1442 Can be set true to adjust the next bill date forward by
1443 the amount of time the account was inactive. This was set true by default
1444 since 1.4.2 and 1.5.0pre6; however, starting with 1.7.0 this needs to be
1445 explicitly requested. Price plans for which this makes sense (anniversary-date
1446 based than prorate or subscription) could have an option to enable this
1451 If there is an error, returns the error, otherwise returns false.
1456 my( $self, %opt ) = @_;
1459 # pass all suspend/cancel actions to the main package
1460 if ( $self->main_pkgnum and !$opt{'from_main'} ) {
1461 return $self->main_pkg->unsuspend(%opt);
1464 local $SIG{HUP} = 'IGNORE';
1465 local $SIG{INT} = 'IGNORE';
1466 local $SIG{QUIT} = 'IGNORE';
1467 local $SIG{TERM} = 'IGNORE';
1468 local $SIG{TSTP} = 'IGNORE';
1469 local $SIG{PIPE} = 'IGNORE';
1471 my $oldAutoCommit = $FS::UID::AutoCommit;
1472 local $FS::UID::AutoCommit = 0;
1475 my $old = $self->select_for_update;
1477 my $pkgnum = $old->pkgnum;
1478 if ( $old->get('cancel') || $self->get('cancel') ) {
1479 $dbh->rollback if $oldAutoCommit;
1480 return "Can't unsuspend cancelled package $pkgnum";
1483 unless ( $old->get('susp') && $self->get('susp') ) {
1484 $dbh->rollback if $oldAutoCommit;
1485 return ""; # no error # complain instead?
1488 my $date = $opt{'date'};
1489 if ( $date and $date > time ) { # return an error if $date <= time?
1491 if ( $old->get('expire') && $old->get('expire') < $date ) {
1492 $dbh->rollback if $oldAutoCommit;
1493 return "Package $pkgnum expires before it would be unsuspended.";
1496 my $new = new FS::cust_pkg { $self->hash };
1497 $new->set('resume', $date);
1498 $error = $new->replace($self, options => $self->options);
1501 $dbh->rollback if $oldAutoCommit;
1505 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1513 foreach my $cust_svc (
1514 qsearch('cust_svc',{'pkgnum'=> $self->pkgnum } )
1516 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
1518 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
1519 $dbh->rollback if $oldAutoCommit;
1520 return "Illegal svcdb value in part_svc!";
1523 require "FS/$svcdb.pm";
1525 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
1527 $error = $svc->unsuspend;
1529 $dbh->rollback if $oldAutoCommit;
1532 my( $label, $value ) = $cust_svc->label;
1533 push @labels, "$label: $value";
1538 my $cust_pkg_reason = $self->last_cust_pkg_reason('susp');
1539 my $reason = $cust_pkg_reason ? $cust_pkg_reason->reason : '';
1541 my %hash = $self->hash;
1542 my $inactive = time - $hash{'susp'};
1544 my $conf = new FS::Conf;
1546 if ( $inactive > 0 &&
1547 ( $hash{'bill'} || $hash{'setup'} ) &&
1548 ( $opt{'adjust_next_bill'} ||
1549 $conf->exists('unsuspend-always_adjust_next_bill_date') ||
1550 $self->part_pkg->option('unsuspend_adjust_bill', 1) )
1553 $hash{'bill'} = ( $hash{'bill'} || $hash{'setup'} ) + $inactive;
1558 $hash{'adjourn'} = '' if $hash{'adjourn'} and $hash{'adjourn'} < time;
1559 $hash{'resume'} = '' if !$hash{'adjourn'};
1560 my $new = new FS::cust_pkg ( \%hash );
1561 $error = $new->replace( $self, options => { $self->options } );
1563 $dbh->rollback if $oldAutoCommit;
1569 if ( $reason && $reason->unsuspend_pkgpart ) {
1570 my $part_pkg = FS::part_pkg->by_key($reason->unsuspend_pkgpart)
1571 or $error = "Unsuspend package definition ".$reason->unsuspend_pkgpart.
1573 my $start_date = $self->cust_main->next_bill_date
1574 if $reason->unsuspend_hold;
1577 $unsusp_pkg = FS::cust_pkg->new({
1578 'custnum' => $self->custnum,
1579 'pkgpart' => $reason->unsuspend_pkgpart,
1580 'start_date' => $start_date,
1581 'locationnum' => $self->locationnum,
1582 # discount? probably not...
1585 $error ||= $self->cust_main->order_pkg( 'cust_pkg' => $unsusp_pkg );
1589 $dbh->rollback if $oldAutoCommit;
1594 if ( $conf->config('unsuspend_email_admin') ) {
1596 my $error = send_email(
1597 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
1598 #invoice_from ??? well as good as any
1599 'to' => $conf->config('unsuspend_email_admin'),
1600 'subject' => 'FREESIDE NOTIFICATION: Customer package unsuspended', 'body' => [
1601 "This is an automatic message from your Freeside installation\n",
1602 "informing you that the following customer package has been unsuspended:\n",
1604 'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
1605 'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
1606 ( map { "Service : $_\n" } @labels ),
1608 "An unsuspension fee was charged: ".
1609 $unsusp_pkg->part_pkg->pkg_comment."\n"
1616 warn "WARNING: can't send unsuspension admin email (unsuspending anyway): ".
1622 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1623 $error = $supp_pkg->unsuspend(%opt, 'from_main' => 1);
1625 $dbh->rollback if $oldAutoCommit;
1626 return "unsuspending supplemental pkg#".$supp_pkg->pkgnum.": $error";
1630 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1637 Cancels any pending suspension (sets the adjourn field to null).
1639 If there is an error, returns the error, otherwise returns false.
1644 my( $self, %options ) = @_;
1647 local $SIG{HUP} = 'IGNORE';
1648 local $SIG{INT} = 'IGNORE';
1649 local $SIG{QUIT} = 'IGNORE';
1650 local $SIG{TERM} = 'IGNORE';
1651 local $SIG{TSTP} = 'IGNORE';
1652 local $SIG{PIPE} = 'IGNORE';
1654 my $oldAutoCommit = $FS::UID::AutoCommit;
1655 local $FS::UID::AutoCommit = 0;
1658 my $old = $self->select_for_update;
1660 my $pkgnum = $old->pkgnum;
1661 if ( $old->get('cancel') || $self->get('cancel') ) {
1662 dbh->rollback if $oldAutoCommit;
1663 return "Can't unadjourn cancelled package $pkgnum";
1664 # or at least it's pointless
1667 if ( $old->get('susp') || $self->get('susp') ) {
1668 dbh->rollback if $oldAutoCommit;
1669 return "Can't unadjourn suspended package $pkgnum";
1670 # perhaps this is arbitrary
1673 unless ( $old->get('adjourn') && $self->get('adjourn') ) {
1674 dbh->rollback if $oldAutoCommit;
1675 return ""; # no error
1678 my %hash = $self->hash;
1679 $hash{'adjourn'} = '';
1680 $hash{'resume'} = '';
1681 my $new = new FS::cust_pkg ( \%hash );
1682 $error = $new->replace( $self, options => { $self->options } );
1684 $dbh->rollback if $oldAutoCommit;
1688 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1695 =item change HASHREF | OPTION => VALUE ...
1697 Changes this package: cancels it and creates a new one, with a different
1698 pkgpart or locationnum or both. All services are transferred to the new
1699 package (no change will be made if this is not possible).
1701 Options may be passed as a list of key/value pairs or as a hash reference.
1708 New locationnum, to change the location for this package.
1712 New FS::cust_location object, to create a new location and assign it
1717 New FS::cust_main object, to create a new customer and assign the new package
1722 New pkgpart (see L<FS::part_pkg>).
1726 New refnum (see L<FS::part_referral>).
1730 Set to true to transfer billing dates (start_date, setup, last_bill, bill,
1731 susp, adjourn, cancel, expire, and contract_end) to the new package.
1735 At least one of locationnum, cust_location, pkgpart, refnum must be specified
1736 (otherwise, what's the point?)
1738 Returns either the new FS::cust_pkg object or a scalar error.
1742 my $err_or_new_cust_pkg = $old_cust_pkg->change
1746 #some false laziness w/order
1749 my $opt = ref($_[0]) ? shift : { @_ };
1751 # my ($custnum, $pkgparts, $remove_pkgnum, $return_cust_pkg, $refnum) = @_;
1754 my $conf = new FS::Conf;
1756 # Transactionize this whole mess
1757 local $SIG{HUP} = 'IGNORE';
1758 local $SIG{INT} = 'IGNORE';
1759 local $SIG{QUIT} = 'IGNORE';
1760 local $SIG{TERM} = 'IGNORE';
1761 local $SIG{TSTP} = 'IGNORE';
1762 local $SIG{PIPE} = 'IGNORE';
1764 my $oldAutoCommit = $FS::UID::AutoCommit;
1765 local $FS::UID::AutoCommit = 0;
1774 #$hash{$_} = $self->$_() foreach qw( last_bill bill );
1776 #$hash{$_} = $self->$_() foreach qw( setup );
1778 $hash{'setup'} = $time if $self->setup;
1780 $hash{'change_date'} = $time;
1781 $hash{"change_$_"} = $self->$_()
1782 foreach qw( pkgnum pkgpart locationnum );
1784 if ( $opt->{'cust_location'} ) {
1785 $error = $opt->{'cust_location'}->find_or_insert;
1787 $dbh->rollback if $oldAutoCommit;
1788 return "inserting cust_location (transaction rolled back): $error";
1790 $opt->{'locationnum'} = $opt->{'cust_location'}->locationnum;
1793 # whether to override pkgpart checking on the new package
1794 my $same_pkgpart = 1;
1795 if ( $opt->{'pkgpart'} and ( $opt->{'pkgpart'} != $self->pkgpart ) ) {
1799 my $unused_credit = 0;
1800 my $keep_dates = $opt->{'keep_dates'};
1801 # Special case. If the pkgpart is changing, and the customer is
1802 # going to be credited for remaining time, don't keep setup, bill,
1803 # or last_bill dates, and DO pass the flag to cancel() to credit
1805 if ( $opt->{'pkgpart'}
1806 and $opt->{'pkgpart'} != $self->pkgpart
1807 and $self->part_pkg->option('unused_credit_change', 1) ) {
1810 $hash{$_} = '' foreach qw(setup bill last_bill);
1813 if ( $keep_dates ) {
1814 foreach my $date ( qw(setup bill last_bill susp adjourn cancel expire
1815 resume start_date contract_end ) ) {
1816 $hash{$date} = $self->getfield($date);
1819 # allow $opt->{'locationnum'} = '' to specifically set it to null
1820 # (i.e. customer default location)
1821 $opt->{'locationnum'} = $self->locationnum if !exists($opt->{'locationnum'});
1823 # usually this doesn't matter. the two cases where it does are:
1824 # 1. unused_credit_change + pkgpart change + setup fee on the new package
1826 # 2. (more importantly) changing a package before it's billed
1827 $hash{'waive_setup'} = $self->waive_setup;
1829 my $custnum = $self->custnum;
1830 if ( $opt->{cust_main} ) {
1831 my $cust_main = $opt->{cust_main};
1832 unless ( $cust_main->custnum ) {
1833 my $error = $cust_main->insert;
1835 $dbh->rollback if $oldAutoCommit;
1836 return "inserting cust_main (transaction rolled back): $error";
1839 $custnum = $cust_main->custnum;
1842 $hash{'contactnum'} = $opt->{'contactnum'} if $opt->{'contactnum'};
1844 # Create the new package.
1845 my $cust_pkg = new FS::cust_pkg {
1846 custnum => $custnum,
1847 pkgpart => ( $opt->{'pkgpart'} || $self->pkgpart ),
1848 refnum => ( $opt->{'refnum'} || $self->refnum ),
1849 locationnum => ( $opt->{'locationnum'} ),
1852 $error = $cust_pkg->insert( 'change' => 1,
1853 'allow_pkgpart' => $same_pkgpart );
1855 $dbh->rollback if $oldAutoCommit;
1859 # Transfer services and cancel old package.
1861 $error = $self->transfer($cust_pkg);
1862 if ($error and $error == 0) {
1863 # $old_pkg->transfer failed.
1864 $dbh->rollback if $oldAutoCommit;
1868 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
1869 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
1870 $error = $self->transfer($cust_pkg, 'change_svcpart'=>1 );
1871 if ($error and $error == 0) {
1872 # $old_pkg->transfer failed.
1873 $dbh->rollback if $oldAutoCommit;
1879 # Transfers were successful, but we still had services left on the old
1880 # package. We can't change the package under this circumstances, so abort.
1881 $dbh->rollback if $oldAutoCommit;
1882 return "Unable to transfer all services from package ". $self->pkgnum;
1885 #reset usage if changing pkgpart
1886 # AND usage rollover is off (otherwise adds twice, now and at package bill)
1887 if ($self->pkgpart != $cust_pkg->pkgpart) {
1888 my $part_pkg = $cust_pkg->part_pkg;
1889 $error = $part_pkg->reset_usage($cust_pkg, $part_pkg->is_prepaid
1893 if $part_pkg->can('reset_usage') && ! $part_pkg->option('usage_rollover',1);
1896 $dbh->rollback if $oldAutoCommit;
1897 return "Error setting usage values: $error";
1900 # if NOT changing pkgpart, transfer any usage pools over
1901 foreach my $usage ($self->cust_pkg_usage) {
1902 $usage->set('pkgnum', $cust_pkg->pkgnum);
1903 $error = $usage->replace;
1905 $dbh->rollback if $oldAutoCommit;
1906 return "Error transferring usage pools: $error";
1911 # transfer discounts, if we're not changing pkgpart
1912 if ( $same_pkgpart ) {
1913 foreach my $old_discount ($self->cust_pkg_discount_active) {
1914 # don't remove the old discount, we may still need to bill that package.
1915 my $new_discount = new FS::cust_pkg_discount {
1916 'pkgnum' => $cust_pkg->pkgnum,
1917 'discountnum' => $old_discount->discountnum,
1918 'months_used' => $old_discount->months_used,
1920 $error = $new_discount->insert;
1922 $dbh->rollback if $oldAutoCommit;
1923 return "Error transferring discounts: $error";
1928 # transfer (copy) invoice details
1929 foreach my $detail ($self->cust_pkg_detail) {
1930 my $new_detail = FS::cust_pkg_detail->new({ $detail->hash });
1931 $new_detail->set('pkgdetailnum', '');
1932 $new_detail->set('pkgnum', $cust_pkg->pkgnum);
1933 $error = $new_detail->insert;
1935 $dbh->rollback if $oldAutoCommit;
1936 return "Error transferring package notes: $error";
1940 # Order any supplemental packages.
1941 my $part_pkg = $cust_pkg->part_pkg;
1942 my @old_supp_pkgs = $self->supplemental_pkgs;
1944 foreach my $link ($part_pkg->supp_part_pkg_link) {
1946 foreach (@old_supp_pkgs) {
1947 if ($_->pkgpart == $link->dst_pkgpart) {
1949 $_->pkgpart(0); # so that it can't match more than once
1953 # false laziness with FS::cust_main::Packages::order_pkg
1954 my $new = FS::cust_pkg->new({
1955 pkgpart => $link->dst_pkgpart,
1956 pkglinknum => $link->pkglinknum,
1957 custnum => $custnum,
1958 main_pkgnum => $cust_pkg->pkgnum,
1959 locationnum => $cust_pkg->locationnum,
1960 start_date => $cust_pkg->start_date,
1961 order_date => $cust_pkg->order_date,
1962 expire => $cust_pkg->expire,
1963 adjourn => $cust_pkg->adjourn,
1964 contract_end => $cust_pkg->contract_end,
1965 refnum => $cust_pkg->refnum,
1966 discountnum => $cust_pkg->discountnum,
1967 waive_setup => $cust_pkg->waive_setup,
1969 if ( $old and $opt->{'keep_dates'} ) {
1970 foreach (qw(setup bill last_bill)) {
1971 $new->set($_, $old->get($_));
1974 $error = $new->insert( allow_pkgpart => $same_pkgpart );
1977 $error ||= $old->transfer($new);
1979 if ( $error and $error > 0 ) {
1980 # no reason why this should ever fail, but still...
1981 $error = "Unable to transfer all services from supplemental package ".
1985 $dbh->rollback if $oldAutoCommit;
1988 push @new_supp_pkgs, $new;
1991 #Good to go, cancel old package. Notify 'cancel' of whether to credit
1993 #Don't allow billing the package (preceding period packages and/or
1994 #outstanding usage) if we are keeping dates (i.e. location changing),
1995 #because the new package will be billed for the same date range.
1996 #Supplemental packages are also canceled here.
1997 $error = $self->cancel(
1999 unused_credit => $unused_credit,
2000 nobill => $keep_dates,
2001 change_custnum => ( $self->custnum != $custnum ? $custnum : '' ),
2004 $dbh->rollback if $oldAutoCommit;
2008 if ( $conf->exists('cust_pkg-change_pkgpart-bill_now') ) {
2010 my $error = $cust_pkg->cust_main->bill(
2011 'pkg_list' => [ $cust_pkg, @new_supp_pkgs ]
2014 $dbh->rollback if $oldAutoCommit;
2019 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2025 =item set_quantity QUANTITY
2027 Change the package's quantity field. This is the one package property
2028 that can safely be changed without canceling and reordering the package
2029 (because it doesn't affect tax eligibility). Returns an error or an
2036 $self = $self->replace_old; # just to make sure
2038 ($qty =~ /^\d+$/ and $qty > 0) or return "bad package quantity $qty";
2039 $self->set('quantity' => $qty);
2043 use Storable 'thaw';
2045 sub process_bulk_cust_pkg {
2047 my $param = thaw(decode_base64(shift));
2048 warn Dumper($param) if $DEBUG;
2050 my $old_part_pkg = qsearchs('part_pkg',
2051 { pkgpart => $param->{'old_pkgpart'} });
2052 my $new_part_pkg = qsearchs('part_pkg',
2053 { pkgpart => $param->{'new_pkgpart'} });
2054 die "Must select a new package type\n" unless $new_part_pkg;
2055 #my $keep_dates = $param->{'keep_dates'} || 0;
2056 my $keep_dates = 1; # there is no good reason to turn this off
2058 local $SIG{HUP} = 'IGNORE';
2059 local $SIG{INT} = 'IGNORE';
2060 local $SIG{QUIT} = 'IGNORE';
2061 local $SIG{TERM} = 'IGNORE';
2062 local $SIG{TSTP} = 'IGNORE';
2063 local $SIG{PIPE} = 'IGNORE';
2065 my $oldAutoCommit = $FS::UID::AutoCommit;
2066 local $FS::UID::AutoCommit = 0;
2069 my @cust_pkgs = qsearch('cust_pkg', { 'pkgpart' => $param->{'old_pkgpart'} } );
2072 foreach my $old_cust_pkg ( @cust_pkgs ) {
2074 $job->update_statustext(int(100*$i/(scalar @cust_pkgs)));
2075 if ( $old_cust_pkg->getfield('cancel') ) {
2076 warn '[process_bulk_cust_pkg ] skipping canceled pkgnum '.
2077 $old_cust_pkg->pkgnum."\n"
2081 warn '[process_bulk_cust_pkg] changing pkgnum '.$old_cust_pkg->pkgnum."\n"
2083 my $error = $old_cust_pkg->change(
2084 'pkgpart' => $param->{'new_pkgpart'},
2085 'keep_dates' => $keep_dates
2087 if ( !ref($error) ) { # change returns the cust_pkg on success
2089 die "Error changing pkgnum ".$old_cust_pkg->pkgnum.": '$error'\n";
2092 $dbh->commit if $oldAutoCommit;
2098 Returns the last bill date, or if there is no last bill date, the setup date.
2099 Useful for billing metered services.
2105 return $self->setfield('last_bill', $_[0]) if @_;
2106 return $self->getfield('last_bill') if $self->getfield('last_bill');
2107 my $cust_bill_pkg = qsearchs('cust_bill_pkg', { 'pkgnum' => $self->pkgnum,
2108 'edate' => $self->bill, } );
2109 $cust_bill_pkg ? $cust_bill_pkg->sdate : $self->setup || 0;
2112 =item last_cust_pkg_reason ACTION
2114 Returns the most recent ACTION FS::cust_pkg_reason associated with the package.
2115 Returns false if there is no reason or the package is not currenly ACTION'd
2116 ACTION is one of adjourn, susp, cancel, or expire.
2120 sub last_cust_pkg_reason {
2121 my ( $self, $action ) = ( shift, shift );
2122 my $date = $self->get($action);
2124 'table' => 'cust_pkg_reason',
2125 'hashref' => { 'pkgnum' => $self->pkgnum,
2126 'action' => substr(uc($action), 0, 1),
2129 'order_by' => 'ORDER BY num DESC LIMIT 1',
2133 =item last_reason ACTION
2135 Returns the most recent ACTION FS::reason associated with the package.
2136 Returns false if there is no reason or the package is not currenly ACTION'd
2137 ACTION is one of adjourn, susp, cancel, or expire.
2142 my $cust_pkg_reason = shift->last_cust_pkg_reason(@_);
2143 $cust_pkg_reason->reason
2144 if $cust_pkg_reason;
2149 Returns the definition for this billing item, as an FS::part_pkg object (see
2156 return $self->{'_pkgpart'} if $self->{'_pkgpart'};
2157 cluck "cust_pkg->part_pkg called" if $DEBUG > 1;
2158 qsearchs( 'part_pkg', { 'pkgpart' => $self->pkgpart } );
2163 Returns the cancelled package this package was changed from, if any.
2169 return '' unless $self->change_pkgnum;
2170 qsearchs('cust_pkg', { 'pkgnum' => $self->change_pkgnum } );
2173 =item change_cust_main
2175 Returns the customter this package was detached to, if any.
2179 sub change_cust_main {
2181 return '' unless $self->change_custnum;
2182 qsearchs('cust_main', { 'custnum' => $self->change_custnum } );
2187 Calls the I<calc_setup> of the FS::part_pkg object associated with this billing
2194 $self->part_pkg->calc_setup($self, @_);
2199 Calls the I<calc_recur> of the FS::part_pkg object associated with this billing
2206 $self->part_pkg->calc_recur($self, @_);
2211 Calls the I<base_setup> of the FS::part_pkg object associated with this billing
2218 $self->part_pkg->base_setup($self, @_);
2223 Calls the I<base_recur> of the FS::part_pkg object associated with this billing
2230 $self->part_pkg->base_recur($self, @_);
2235 Calls the I<calc_remain> of the FS::part_pkg object associated with this
2242 $self->part_pkg->calc_remain($self, @_);
2247 Calls the I<calc_cancel> of the FS::part_pkg object associated with this
2254 $self->part_pkg->calc_cancel($self, @_);
2259 Returns any invoice line items for this package (see L<FS::cust_bill_pkg>).
2265 qsearch( 'cust_bill_pkg', { 'pkgnum' => $self->pkgnum } );
2268 =item cust_pkg_detail [ DETAILTYPE ]
2270 Returns any customer package details for this package (see
2271 L<FS::cust_pkg_detail>).
2273 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
2277 sub cust_pkg_detail {
2279 my %hash = ( 'pkgnum' => $self->pkgnum );
2280 $hash{detailtype} = shift if @_;
2282 'table' => 'cust_pkg_detail',
2283 'hashref' => \%hash,
2284 'order_by' => 'ORDER BY weight, pkgdetailnum',
2288 =item set_cust_pkg_detail DETAILTYPE [ DETAIL, DETAIL, ... ]
2290 Sets customer package details for this package (see L<FS::cust_pkg_detail>).
2292 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
2294 If there is an error, returns the error, otherwise returns false.
2298 sub set_cust_pkg_detail {
2299 my( $self, $detailtype, @details ) = @_;
2301 local $SIG{HUP} = 'IGNORE';
2302 local $SIG{INT} = 'IGNORE';
2303 local $SIG{QUIT} = 'IGNORE';
2304 local $SIG{TERM} = 'IGNORE';
2305 local $SIG{TSTP} = 'IGNORE';
2306 local $SIG{PIPE} = 'IGNORE';
2308 my $oldAutoCommit = $FS::UID::AutoCommit;
2309 local $FS::UID::AutoCommit = 0;
2312 foreach my $current ( $self->cust_pkg_detail($detailtype) ) {
2313 my $error = $current->delete;
2315 $dbh->rollback if $oldAutoCommit;
2316 return "error removing old detail: $error";
2320 foreach my $detail ( @details ) {
2321 my $cust_pkg_detail = new FS::cust_pkg_detail {
2322 'pkgnum' => $self->pkgnum,
2323 'detailtype' => $detailtype,
2324 'detail' => $detail,
2326 my $error = $cust_pkg_detail->insert;
2328 $dbh->rollback if $oldAutoCommit;
2329 return "error adding new detail: $error";
2334 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2341 Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.
2345 #false laziness w/cust_bill.pm
2349 'table' => 'cust_event',
2350 'addl_from' => 'JOIN part_event USING ( eventpart )',
2351 'hashref' => { 'tablenum' => $self->pkgnum },
2352 'extra_sql' => " AND eventtable = 'cust_pkg' ",
2356 =item num_cust_event
2358 Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.
2362 #false laziness w/cust_bill.pm
2363 sub num_cust_event {
2366 "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
2367 " WHERE tablenum = ? AND eventtable = 'cust_pkg'";
2368 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
2369 $sth->execute($self->pkgnum) or die $sth->errstr. " executing $sql";
2370 $sth->fetchrow_arrayref->[0];
2373 =item part_pkg_currency_option OPTIONNAME
2375 Returns a two item list consisting of the currency of this customer, if any,
2376 and a value for the provided option. If the customer has a currency, the value
2377 is the option value the given name and the currency (see
2378 L<FS::part_pkg_currency>). Otherwise, if the customer has no currency, is the
2379 regular option value for the given name (see L<FS::part_pkg_option>).
2383 sub part_pkg_currency_option {
2384 my( $self, $optionname ) = @_;
2385 my $part_pkg = $self->part_pkg;
2386 if ( my $currency = $self->cust_main->currency ) {
2387 ($currency, $part_pkg->part_pkg_currency_option($currency, $optionname) );
2389 ('', $part_pkg->option($optionname) );
2393 =item cust_svc [ SVCPART ] (old, deprecated usage)
2395 =item cust_svc [ OPTION => VALUE ... ] (current usage)
2397 Returns the services for this package, as FS::cust_svc objects (see
2398 L<FS::cust_svc>). Available options are svcpart and svcdb. If either is
2399 spcififed, returns only the matching services.
2406 return () unless $self->num_cust_svc(@_);
2409 if ( @_ && $_[0] =~ /^\d+/ ) {
2410 $opt{svcpart} = shift;
2411 } elsif ( @_ && ref($_[0]) eq 'HASH' ) {
2418 'table' => 'cust_svc',
2419 'hashref' => { 'pkgnum' => $self->pkgnum },
2421 if ( $opt{svcpart} ) {
2422 $search{hashref}->{svcpart} = $opt{'svcpart'};
2424 if ( $opt{'svcdb'} ) {
2425 $search{addl_from} = ' LEFT JOIN part_svc USING ( svcpart ) ';
2426 $search{extra_sql} = ' AND svcdb = '. dbh->quote( $opt{'svcdb'} );
2429 cluck "cust_pkg->cust_svc called" if $DEBUG > 2;
2431 #if ( $self->{'_svcnum'} ) {
2432 # values %{ $self->{'_svcnum'}->cache };
2434 $self->_sort_cust_svc( [ qsearch(\%search) ] );
2439 =item overlimit [ SVCPART ]
2441 Returns the services for this package which have exceeded their
2442 usage limit as FS::cust_svc objects (see L<FS::cust_svc>). If a svcpart
2443 is specified, return only the matching services.
2449 return () unless $self->num_cust_svc(@_);
2450 grep { $_->overlimit } $self->cust_svc(@_);
2453 =item h_cust_svc END_TIMESTAMP [ START_TIMESTAMP ] [ MODE ]
2455 Returns historical services for this package created before END TIMESTAMP and
2456 (optionally) not cancelled before START_TIMESTAMP, as FS::h_cust_svc objects
2457 (see L<FS::h_cust_svc>). If MODE is 'I' (for 'invoice'), services with the
2458 I<pkg_svc.hidden> flag will be omitted.
2464 warn "$me _h_cust_svc called on $self\n"
2467 my ($end, $start, $mode) = @_;
2468 my @cust_svc = $self->_sort_cust_svc(
2469 [ qsearch( 'h_cust_svc',
2470 { 'pkgnum' => $self->pkgnum, },
2471 FS::h_cust_svc->sql_h_search(@_),
2474 if ( defined($mode) && $mode eq 'I' ) {
2475 my %hidden_svcpart = map { $_->svcpart => $_->hidden } $self->part_svc;
2476 return grep { !$hidden_svcpart{$_->svcpart} } @cust_svc;
2482 sub _sort_cust_svc {
2483 my( $self, $arrayref ) = @_;
2486 sub ($$) { my ($a, $b) = @_; $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] };
2491 my $pkg_svc = qsearchs( 'pkg_svc', { 'pkgpart' => $self->pkgpart,
2492 'svcpart' => $_->svcpart } );
2494 $pkg_svc ? $pkg_svc->primary_svc : '',
2495 $pkg_svc ? $pkg_svc->quantity : 0,
2502 =item num_cust_svc [ SVCPART ] (old, deprecated usage)
2504 =item num_cust_svc [ OPTION => VALUE ... ] (current usage)
2506 Returns the number of services for this package. Available options are svcpart
2507 and svcdb. If either is spcififed, returns only the matching services.
2514 return $self->{'_num_cust_svc'}
2516 && exists($self->{'_num_cust_svc'})
2517 && $self->{'_num_cust_svc'} =~ /\d/;
2519 cluck "cust_pkg->num_cust_svc called, _num_cust_svc:".$self->{'_num_cust_svc'}
2523 if ( @_ && $_[0] =~ /^\d+/ ) {
2524 $opt{svcpart} = shift;
2525 } elsif ( @_ && ref($_[0]) eq 'HASH' ) {
2531 my $select = 'SELECT COUNT(*) FROM cust_svc ';
2532 my $where = ' WHERE pkgnum = ? ';
2533 my @param = ($self->pkgnum);
2535 if ( $opt{'svcpart'} ) {
2536 $where .= ' AND svcpart = ? ';
2537 push @param, $opt{'svcpart'};
2539 if ( $opt{'svcdb'} ) {
2540 $select .= ' LEFT JOIN part_svc USING ( svcpart ) ';
2541 $where .= ' AND svcdb = ? ';
2542 push @param, $opt{'svcdb'};
2545 my $sth = dbh->prepare("$select $where") or die dbh->errstr;
2546 $sth->execute(@param) or die $sth->errstr;
2547 $sth->fetchrow_arrayref->[0];
2550 =item available_part_svc
2552 Returns a list of FS::part_svc objects representing services included in this
2553 package but not yet provisioned. Each FS::part_svc object also has an extra
2554 field, I<num_avail>, which specifies the number of available services.
2558 sub available_part_svc {
2561 my $pkg_quantity = $self->quantity || 1;
2563 grep { $_->num_avail > 0 }
2565 my $part_svc = $_->part_svc;
2566 $part_svc->{'Hash'}{'num_avail'} = #evil encapsulation-breaking
2567 $pkg_quantity * $_->quantity - $self->num_cust_svc($_->svcpart);
2569 # more evil encapsulation breakage
2570 if($part_svc->{'Hash'}{'num_avail'} > 0) {
2571 my @exports = $part_svc->part_export_did;
2572 $part_svc->{'Hash'}{'can_get_dids'} = scalar(@exports);
2577 $self->part_pkg->pkg_svc;
2580 =item part_svc [ OPTION => VALUE ... ]
2582 Returns a list of FS::part_svc objects representing provisioned and available
2583 services included in this package. Each FS::part_svc object also has the
2584 following extra fields:
2588 =item num_cust_svc (count)
2590 =item num_avail (quantity - count)
2592 =item cust_pkg_svc (services) - array reference containing the provisioned services, as cust_svc objects
2596 Accepts one option: summarize_size. If specified and non-zero, will omit the
2597 extra cust_pkg_svc option for objects where num_cust_svc is this size or
2603 #label -> ($cust_svc->label)[1]
2609 my $pkg_quantity = $self->quantity || 1;
2611 #XXX some sort of sort order besides numeric by svcpart...
2612 my @part_svc = sort { $a->svcpart <=> $b->svcpart } map {
2614 my $part_svc = $pkg_svc->part_svc;
2615 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
2616 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #more evil
2617 $part_svc->{'Hash'}{'num_avail'} =
2618 max( 0, $pkg_quantity * $pkg_svc->quantity - $num_cust_svc );
2619 $part_svc->{'Hash'}{'cust_pkg_svc'} =
2620 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : []
2621 unless exists($opt{summarize_size}) && $opt{summarize_size} > 0
2622 && $num_cust_svc >= $opt{summarize_size};
2623 $part_svc->{'Hash'}{'hidden'} = $pkg_svc->hidden;
2625 } $self->part_pkg->pkg_svc;
2628 push @part_svc, map {
2630 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
2631 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #speak no evail
2632 $part_svc->{'Hash'}{'num_avail'} = 0; #0-$num_cust_svc ?
2633 $part_svc->{'Hash'}{'cust_pkg_svc'} =
2634 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : [];
2636 } $self->extra_part_svc;
2642 =item extra_part_svc
2644 Returns a list of FS::part_svc objects corresponding to services in this
2645 package which are still provisioned but not (any longer) available in the
2650 sub extra_part_svc {
2653 my $pkgnum = $self->pkgnum;
2654 #my $pkgpart = $self->pkgpart;
2657 # 'table' => 'part_svc',
2660 # "WHERE 0 = ( SELECT COUNT(*) FROM pkg_svc
2661 # WHERE pkg_svc.svcpart = part_svc.svcpart
2662 # AND pkg_svc.pkgpart = ?
2665 # AND 0 < ( SELECT COUNT(*) FROM cust_svc
2666 # LEFT JOIN cust_pkg USING ( pkgnum )
2667 # WHERE cust_svc.svcpart = part_svc.svcpart
2670 # 'extra_param' => [ [$self->pkgpart=>'int'], [$self->pkgnum=>'int'] ],
2673 #seems to benchmark slightly faster... (or did?)
2675 my @pkgparts = map $_->pkgpart, $self->part_pkg->self_and_svc_linked;
2676 my $pkgparts = join(',', @pkgparts);
2679 #'select' => 'DISTINCT ON (svcpart) part_svc.*',
2680 #MySQL doesn't grok DISINCT ON
2681 'select' => 'DISTINCT part_svc.*',
2682 'table' => 'part_svc',
2684 "LEFT JOIN pkg_svc ON ( pkg_svc.svcpart = part_svc.svcpart
2685 AND pkg_svc.pkgpart IN ($pkgparts)
2688 LEFT JOIN cust_svc ON ( cust_svc.svcpart = part_svc.svcpart )
2689 LEFT JOIN cust_pkg USING ( pkgnum )
2692 'extra_sql' => "WHERE pkgsvcnum IS NULL AND cust_pkg.pkgnum = ? ",
2693 'extra_param' => [ [$self->pkgnum=>'int'] ],
2699 Returns a short status string for this package, currently:
2703 =item not yet billed
2705 =item one-time charge
2720 my $freq = length($self->freq) ? $self->freq : $self->part_pkg->freq;
2722 return 'cancelled' if $self->get('cancel');
2723 return 'suspended' if $self->susp;
2724 return 'not yet billed' unless $self->setup;
2725 return 'one-time charge' if $freq =~ /^(0|$)/;
2729 =item ucfirst_status
2731 Returns the status with the first character capitalized.
2735 sub ucfirst_status {
2736 ucfirst(shift->status);
2741 Class method that returns the list of possible status strings for packages
2742 (see L<the status method|/status>). For example:
2744 @statuses = FS::cust_pkg->statuses();
2748 tie my %statuscolor, 'Tie::IxHash',
2749 'not yet billed' => '009999', #teal? cyan?
2750 'one-time charge' => '000000',
2751 'active' => '00CC00',
2752 'suspended' => 'FF9900',
2753 'cancelled' => 'FF0000',
2757 my $self = shift; #could be class...
2758 #grep { $_ !~ /^(not yet billed)$/ } #this is a dumb status anyway
2759 # # mayble split btw one-time vs. recur
2765 Returns a hex triplet color string for this package's status.
2771 $statuscolor{$self->status};
2776 Returns a label for this package. (Currently "pkgnum: pkg - comment" or
2777 "pkg - comment" depending on user preference).
2783 my $label = $self->part_pkg->pkg_comment( 'nopkgpart' => 1 );
2784 $label = $self->pkgnum. ": $label"
2785 if $FS::CurrentUser::CurrentUser->option('show_pkgnum');
2789 =item pkg_label_long
2791 Returns a long label for this package, adding the primary service's label to
2796 sub pkg_label_long {
2798 my $label = $self->pkg_label;
2799 my $cust_svc = $self->primary_cust_svc;
2800 $label .= ' ('. ($cust_svc->label)[1]. ')' if $cust_svc;
2806 Returns a customer-localized label for this package.
2812 $self->part_pkg->pkg_locale( $self->cust_main->locale );
2815 =item primary_cust_svc
2817 Returns a primary service (as FS::cust_svc object) if one can be identified.
2821 #for labeling purposes - might not 100% match up with part_pkg->svcpart's idea
2823 sub primary_cust_svc {
2826 my @cust_svc = $self->cust_svc;
2828 return '' unless @cust_svc; #no serivces - irrelevant then
2830 return $cust_svc[0] if scalar(@cust_svc) == 1; #always return a single service
2832 # primary service as specified in the package definition
2833 # or exactly one service definition with quantity one
2834 my $svcpart = $self->part_pkg->svcpart;
2835 @cust_svc = grep { $_->svcpart == $svcpart } @cust_svc;
2836 return $cust_svc[0] if scalar(@cust_svc) == 1;
2838 #couldn't identify one thing..
2844 Returns a list of lists, calling the label method for all services
2845 (see L<FS::cust_svc>) of this billing item.
2851 map { [ $_->label ] } $self->cust_svc;
2854 =item h_labels END_TIMESTAMP [ START_TIMESTAMP ] [ MODE ]
2856 Like the labels method, but returns historical information on services that
2857 were active as of END_TIMESTAMP and (optionally) not cancelled before
2858 START_TIMESTAMP. If MODE is 'I' (for 'invoice'), services with the
2859 I<pkg_svc.hidden> flag will be omitted.
2861 Returns a list of lists, calling the label method for all (historical) services
2862 (see L<FS::h_cust_svc>) of this billing item.
2868 warn "$me _h_labels called on $self\n"
2870 map { [ $_->label(@_) ] } $self->h_cust_svc(@_);
2875 Like labels, except returns a simple flat list, and shortens long
2876 (currently >5 or the cust_bill-max_same_services configuration value) lists of
2877 identical services to one line that lists the service label and the number of
2878 individual services rather than individual items.
2883 shift->_labels_short( 'labels', @_ );
2886 =item h_labels_short END_TIMESTAMP [ START_TIMESTAMP ]
2888 Like h_labels, except returns a simple flat list, and shortens long
2889 (currently >5 or the cust_bill-max_same_services configuration value) lists of
2890 identical services to one line that lists the service label and the number of
2891 individual services rather than individual items.
2895 sub h_labels_short {
2896 shift->_labels_short( 'h_labels', @_ );
2900 my( $self, $method ) = ( shift, shift );
2902 warn "$me _labels_short called on $self with $method method\n"
2905 my $conf = new FS::Conf;
2906 my $max_same_services = $conf->config('cust_bill-max_same_services') || 5;
2908 warn "$me _labels_short populating \%labels\n"
2912 #tie %labels, 'Tie::IxHash';
2913 push @{ $labels{$_->[0]} }, $_->[1]
2914 foreach $self->$method(@_);
2916 warn "$me _labels_short populating \@labels\n"
2920 foreach my $label ( keys %labels ) {
2922 my @values = grep { ! $seen{$_}++ } @{ $labels{$label} };
2923 my $num = scalar(@values);
2924 warn "$me _labels_short $num items for $label\n"
2927 if ( $num > $max_same_services ) {
2928 warn "$me _labels_short more than $max_same_services, so summarizing\n"
2930 push @labels, "$label ($num)";
2932 if ( $conf->exists('cust_bill-consolidate_services') ) {
2933 warn "$me _labels_short consolidating services\n"
2935 # push @labels, "$label: ". join(', ', @values);
2937 my $detail = "$label: ";
2938 $detail .= shift(@values). ', '
2940 && ( length($detail.$values[0]) < 78 || $detail eq "$label: " );
2942 push @labels, $detail;
2944 warn "$me _labels_short done consolidating services\n"
2947 warn "$me _labels_short adding service data\n"
2949 push @labels, map { "$label: $_" } @values;
2960 Returns the parent customer object (see L<FS::cust_main>).
2966 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
2971 Returns the balance for this specific package, when using
2972 experimental package balance.
2978 $self->cust_main->balance_pkgnum( $self->pkgnum );
2981 #these subs are in location_Mixin.pm now... unfortunately the POD doesn't mixin
2985 Returns the location object, if any (see L<FS::cust_location>).
2987 =item cust_location_or_main
2989 If this package is associated with a location, returns the locaiton (see
2990 L<FS::cust_location>), otherwise returns the customer (see L<FS::cust_main>).
2992 =item location_label [ OPTION => VALUE ... ]
2994 Returns the label of the location object (see L<FS::cust_location>).
2998 #end of subs in location_Mixin.pm now... unfortunately the POD doesn't mixin
3000 =item tax_locationnum
3002 Returns the foreign key to a L<FS::cust_location> object for calculating
3003 tax on this package, as determined by the C<tax-pkg_address> and
3004 C<tax-ship_address> configuration flags.
3008 sub tax_locationnum {
3010 my $conf = FS::Conf->new;
3011 if ( $conf->exists('tax-pkg_address') ) {
3012 return $self->locationnum;
3014 elsif ( $conf->exists('tax-ship_address') ) {
3015 return $self->cust_main->ship_locationnum;
3018 return $self->cust_main->bill_locationnum;
3024 Returns the L<FS::cust_location> object for tax_locationnum.
3030 FS::cust_location->by_key( $self->tax_locationnum )
3033 =item seconds_since TIMESTAMP
3035 Returns the number of seconds all accounts (see L<FS::svc_acct>) in this
3036 package have been online since TIMESTAMP, according to the session monitor.
3038 TIMESTAMP is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
3039 L<Time::Local> and L<Date::Parse> for conversion functions.
3044 my($self, $since) = @_;
3047 foreach my $cust_svc (
3048 grep { $_->part_svc->svcdb eq 'svc_acct' } $self->cust_svc
3050 $seconds += $cust_svc->seconds_since($since);
3057 =item seconds_since_sqlradacct TIMESTAMP_START TIMESTAMP_END
3059 Returns the numbers of seconds all accounts (see L<FS::svc_acct>) in this
3060 package have been online between TIMESTAMP_START (inclusive) and TIMESTAMP_END
3063 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
3064 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
3070 sub seconds_since_sqlradacct {
3071 my($self, $start, $end) = @_;
3075 foreach my $cust_svc (
3077 my $part_svc = $_->part_svc;
3078 $part_svc->svcdb eq 'svc_acct'
3079 && scalar($part_svc->part_export_usage);
3082 $seconds += $cust_svc->seconds_since_sqlradacct($start, $end);
3089 =item attribute_since_sqlradacct TIMESTAMP_START TIMESTAMP_END ATTRIBUTE
3091 Returns the sum of the given attribute for all accounts (see L<FS::svc_acct>)
3092 in this package for sessions ending between TIMESTAMP_START (inclusive) and
3096 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
3097 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
3102 sub attribute_since_sqlradacct {
3103 my($self, $start, $end, $attrib) = @_;
3107 foreach my $cust_svc (
3109 my $part_svc = $_->part_svc;
3110 $part_svc->svcdb eq 'svc_acct'
3111 && scalar($part_svc->part_export_usage);
3114 $sum += $cust_svc->attribute_since_sqlradacct($start, $end, $attrib);
3126 my( $self, $value ) = @_;
3127 if ( defined($value) ) {
3128 $self->setfield('quantity', $value);
3130 $self->getfield('quantity') || 1;
3133 =item transfer DEST_PKGNUM | DEST_CUST_PKG, [ OPTION => VALUE ... ]
3135 Transfers as many services as possible from this package to another package.
3137 The destination package can be specified by pkgnum by passing an FS::cust_pkg
3138 object. The destination package must already exist.
3140 Services are moved only if the destination allows services with the correct
3141 I<svcpart> (not svcdb), unless the B<change_svcpart> option is set true. Use
3142 this option with caution! No provision is made for export differences
3143 between the old and new service definitions. Probably only should be used
3144 when your exports for all service definitions of a given svcdb are identical.
3145 (attempt a transfer without it first, to move all possible svcpart-matching
3148 Any services that can't be moved remain in the original package.
3150 Returns an error, if there is one; otherwise, returns the number of services
3151 that couldn't be moved.
3156 my ($self, $dest_pkgnum, %opt) = @_;
3162 if (ref ($dest_pkgnum) eq 'FS::cust_pkg') {
3163 $dest = $dest_pkgnum;
3164 $dest_pkgnum = $dest->pkgnum;
3166 $dest = qsearchs('cust_pkg', { pkgnum => $dest_pkgnum });
3169 return ('Package does not exist: '.$dest_pkgnum) unless $dest;
3171 foreach my $pkg_svc ( $dest->part_pkg->pkg_svc ) {
3172 $target{$pkg_svc->svcpart} = $pkg_svc->quantity;
3175 foreach my $cust_svc ($dest->cust_svc) {
3176 $target{$cust_svc->svcpart}--;
3179 my %svcpart2svcparts = ();
3180 if ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
3181 warn "change_svcpart option received, creating alternates list\n" if $DEBUG;
3182 foreach my $svcpart ( map { $_->svcpart } $self->cust_svc ) {
3183 next if exists $svcpart2svcparts{$svcpart};
3184 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
3185 $svcpart2svcparts{$svcpart} = [
3187 sort { $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] }
3189 my $pkg_svc = qsearchs( 'pkg_svc', { 'pkgpart' => $dest->pkgpart,
3190 'svcpart' => $_ } );
3192 $pkg_svc ? $pkg_svc->primary_svc : '',
3193 $pkg_svc ? $pkg_svc->quantity : 0,
3197 grep { $_ != $svcpart }
3199 qsearch('part_svc', { 'svcdb' => $part_svc->svcdb } )
3201 warn "alternates for svcpart $svcpart: ".
3202 join(', ', @{$svcpart2svcparts{$svcpart}}). "\n"
3207 foreach my $cust_svc ($self->cust_svc) {
3208 if($target{$cust_svc->svcpart} > 0
3209 or $FS::cust_svc::ignore_quantity) { # maybe should be a 'force' option
3210 $target{$cust_svc->svcpart}--;
3211 my $new = new FS::cust_svc { $cust_svc->hash };
3212 $new->pkgnum($dest_pkgnum);
3213 my $error = $new->replace($cust_svc);
3214 return $error if $error;
3215 } elsif ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
3217 warn "looking for alternates for svcpart ". $cust_svc->svcpart. "\n";
3218 warn "alternates to consider: ".
3219 join(', ', @{$svcpart2svcparts{$cust_svc->svcpart}}). "\n";
3221 my @alternate = grep {
3222 warn "considering alternate svcpart $_: ".
3223 "$target{$_} available in new package\n"
3226 } @{$svcpart2svcparts{$cust_svc->svcpart}};
3228 warn "alternate(s) found\n" if $DEBUG;
3229 my $change_svcpart = $alternate[0];
3230 $target{$change_svcpart}--;
3231 my $new = new FS::cust_svc { $cust_svc->hash };
3232 $new->svcpart($change_svcpart);
3233 $new->pkgnum($dest_pkgnum);
3234 my $error = $new->replace($cust_svc);
3235 return $error if $error;
3246 =item grab_svcnums SVCNUM, SVCNUM ...
3248 Change the pkgnum for the provided services to this packages. If there is an
3249 error, returns the error, otherwise returns false.
3257 local $SIG{HUP} = 'IGNORE';
3258 local $SIG{INT} = 'IGNORE';
3259 local $SIG{QUIT} = 'IGNORE';
3260 local $SIG{TERM} = 'IGNORE';
3261 local $SIG{TSTP} = 'IGNORE';
3262 local $SIG{PIPE} = 'IGNORE';
3264 my $oldAutoCommit = $FS::UID::AutoCommit;
3265 local $FS::UID::AutoCommit = 0;
3268 foreach my $svcnum (@svcnum) {
3269 my $cust_svc = qsearchs('cust_svc', { svcnum=>$svcnum } ) or do {
3270 $dbh->rollback if $oldAutoCommit;
3271 return "unknown svcnum $svcnum";
3273 $cust_svc->pkgnum( $self->pkgnum );
3274 my $error = $cust_svc->replace;
3276 $dbh->rollback if $oldAutoCommit;
3281 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3288 This method is deprecated. See the I<depend_jobnum> option to the insert and
3289 order_pkgs methods in FS::cust_main for a better way to defer provisioning.
3293 #looks like this is still used by the order_pkg and change_pkg methods in
3294 # ClientAPI/MyAccount, need to look into those before removing
3298 local $SIG{HUP} = 'IGNORE';
3299 local $SIG{INT} = 'IGNORE';
3300 local $SIG{QUIT} = 'IGNORE';
3301 local $SIG{TERM} = 'IGNORE';
3302 local $SIG{TSTP} = 'IGNORE';
3303 local $SIG{PIPE} = 'IGNORE';
3305 my $oldAutoCommit = $FS::UID::AutoCommit;
3306 local $FS::UID::AutoCommit = 0;
3309 foreach my $cust_svc ( $self->cust_svc ) {
3310 #false laziness w/svc_Common::insert
3311 my $svc_x = $cust_svc->svc_x;
3312 foreach my $part_export ( $cust_svc->part_svc->part_export ) {
3313 my $error = $part_export->export_insert($svc_x);
3315 $dbh->rollback if $oldAutoCommit;
3321 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3326 =item export_pkg_change OLD_CUST_PKG
3328 Calls the "pkg_change" export action for all services attached to this package.
3332 sub export_pkg_change {
3333 my( $self, $old ) = ( shift, shift );
3335 local $SIG{HUP} = 'IGNORE';
3336 local $SIG{INT} = 'IGNORE';
3337 local $SIG{QUIT} = 'IGNORE';
3338 local $SIG{TERM} = 'IGNORE';
3339 local $SIG{TSTP} = 'IGNORE';
3340 local $SIG{PIPE} = 'IGNORE';
3342 my $oldAutoCommit = $FS::UID::AutoCommit;
3343 local $FS::UID::AutoCommit = 0;
3346 foreach my $svc_x ( map $_->svc_x, $self->cust_svc ) {
3347 my $error = $svc_x->export('pkg_change', $self, $old);
3349 $dbh->rollback if $oldAutoCommit;
3354 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3361 Associates this package with a (suspension or cancellation) reason (see
3362 L<FS::cust_pkg_reason>, possibly inserting a new reason on the fly (see
3365 Available options are:
3371 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.
3375 the access_user (see L<FS::access_user>) providing the reason
3383 the action (cancel, susp, adjourn, expire) associated with the reason
3387 If there is an error, returns the error, otherwise returns false.
3392 my ($self, %options) = @_;
3394 my $otaker = $options{reason_otaker} ||
3395 $FS::CurrentUser::CurrentUser->username;
3398 if ( $options{'reason'} =~ /^(\d+)$/ ) {
3402 } elsif ( ref($options{'reason'}) ) {
3404 return 'Enter a new reason (or select an existing one)'
3405 unless $options{'reason'}->{'reason'} !~ /^\s*$/;
3407 my $reason = new FS::reason({
3408 'reason_type' => $options{'reason'}->{'typenum'},
3409 'reason' => $options{'reason'}->{'reason'},
3411 my $error = $reason->insert;
3412 return $error if $error;
3414 $reasonnum = $reason->reasonnum;
3417 return "Unparsable reason: ". $options{'reason'};
3420 my $cust_pkg_reason =
3421 new FS::cust_pkg_reason({ 'pkgnum' => $self->pkgnum,
3422 'reasonnum' => $reasonnum,
3423 'otaker' => $otaker,
3424 'action' => substr(uc($options{'action'}),0,1),
3425 'date' => $options{'date'}
3430 $cust_pkg_reason->insert;
3433 =item insert_discount
3435 Associates this package with a discount (see L<FS::cust_pkg_discount>, possibly
3436 inserting a new discount on the fly (see L<FS::discount>).
3438 Available options are:
3446 If there is an error, returns the error, otherwise returns false.
3450 sub insert_discount {
3451 #my ($self, %options) = @_;
3454 my $cust_pkg_discount = new FS::cust_pkg_discount {
3455 'pkgnum' => $self->pkgnum,
3456 'discountnum' => $self->discountnum,
3458 'end_date' => '', #XXX
3459 #for the create a new discount case
3460 '_type' => $self->discountnum__type,
3461 'amount' => $self->discountnum_amount,
3462 'percent' => $self->discountnum_percent,
3463 'months' => $self->discountnum_months,
3464 'setup' => $self->discountnum_setup,
3465 #'disabled' => $self->discountnum_disabled,
3468 $cust_pkg_discount->insert;
3471 =item set_usage USAGE_VALUE_HASHREF
3473 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
3474 to which they should be set (see L<FS::svc_acct>). Currently seconds,
3475 upbytes, downbytes, and totalbytes are appropriate keys.
3477 All svc_accts which are part of this package have their values reset.
3482 my ($self, $valueref, %opt) = @_;
3484 #only svc_acct can set_usage for now
3485 foreach my $cust_svc ( $self->cust_svc( 'svcdb'=>'svc_acct' ) ) {
3486 my $svc_x = $cust_svc->svc_x;
3487 $svc_x->set_usage($valueref, %opt)
3488 if $svc_x->can("set_usage");
3492 =item recharge USAGE_VALUE_HASHREF
3494 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
3495 to which they should be set (see L<FS::svc_acct>). Currently seconds,
3496 upbytes, downbytes, and totalbytes are appropriate keys.
3498 All svc_accts which are part of this package have their values incremented.
3503 my ($self, $valueref) = @_;
3505 #only svc_acct can set_usage for now
3506 foreach my $cust_svc ( $self->cust_svc( 'svcdb'=>'svc_acct' ) ) {
3507 my $svc_x = $cust_svc->svc_x;
3508 $svc_x->recharge($valueref)
3509 if $svc_x->can("recharge");
3513 =item cust_pkg_discount
3517 sub cust_pkg_discount {
3519 qsearch('cust_pkg_discount', { 'pkgnum' => $self->pkgnum } );
3522 =item cust_pkg_discount_active
3526 sub cust_pkg_discount_active {
3528 grep { $_->status eq 'active' } $self->cust_pkg_discount;
3531 =item cust_pkg_usage
3533 Returns a list of all voice usage counters attached to this package.
3537 sub cust_pkg_usage {
3539 qsearch('cust_pkg_usage', { pkgnum => $self->pkgnum });
3542 =item apply_usage OPTIONS
3544 Takes the following options:
3545 - cdr: a call detail record (L<FS::cdr>)
3546 - rate_detail: the rate determined for this call (L<FS::rate_detail>)
3547 - minutes: the maximum number of minutes to be charged
3549 Finds available usage minutes for a call of this class, and subtracts
3550 up to that many minutes from the usage pool. If the usage pool is empty,
3551 and the C<cdr-minutes_priority> global config option is set, minutes may
3552 be taken from other calls as well. Either way, an allocation record will
3553 be created (L<FS::cdr_cust_pkg_usage>) and this method will return the
3554 number of minutes of usage applied to the call.
3559 my ($self, %opt) = @_;
3560 my $cdr = $opt{cdr};
3561 my $rate_detail = $opt{rate_detail};
3562 my $minutes = $opt{minutes};
3563 my $classnum = $rate_detail->classnum;
3564 my $pkgnum = $self->pkgnum;
3565 my $custnum = $self->custnum;
3567 local $SIG{HUP} = 'IGNORE';
3568 local $SIG{INT} = 'IGNORE';
3569 local $SIG{QUIT} = 'IGNORE';
3570 local $SIG{TERM} = 'IGNORE';
3571 local $SIG{TSTP} = 'IGNORE';
3572 local $SIG{PIPE} = 'IGNORE';
3574 my $oldAutoCommit = $FS::UID::AutoCommit;
3575 local $FS::UID::AutoCommit = 0;
3577 my $order = FS::Conf->new->config('cdr-minutes_priority');
3581 $is_classnum = ' part_pkg_usage_class.classnum = '.$classnum;
3583 $is_classnum = ' part_pkg_usage_class.classnum IS NULL';
3585 my @usage_recs = qsearch({
3586 'table' => 'cust_pkg_usage',
3587 'addl_from' => ' JOIN part_pkg_usage USING (pkgusagepart)'.
3588 ' JOIN cust_pkg USING (pkgnum)'.
3589 ' JOIN part_pkg_usage_class USING (pkgusagepart)',
3590 'select' => 'cust_pkg_usage.*',
3591 'extra_sql' => " WHERE ( cust_pkg.pkgnum = $pkgnum OR ".
3592 " ( cust_pkg.custnum = $custnum AND ".
3593 " part_pkg_usage.shared IS NOT NULL ) ) AND ".
3594 $is_classnum . ' AND '.
3595 " cust_pkg_usage.minutes > 0",
3596 'order_by' => " ORDER BY priority ASC",
3599 my $orig_minutes = $minutes;
3601 while (!$error and $minutes > 0 and @usage_recs) {
3602 my $cust_pkg_usage = shift @usage_recs;
3603 $cust_pkg_usage->select_for_update;
3604 my $cdr_cust_pkg_usage = FS::cdr_cust_pkg_usage->new({
3605 pkgusagenum => $cust_pkg_usage->pkgusagenum,
3606 acctid => $cdr->acctid,
3607 minutes => min($cust_pkg_usage->minutes, $minutes),
3609 $cust_pkg_usage->set('minutes',
3610 sprintf('%.0f', $cust_pkg_usage->minutes - $cdr_cust_pkg_usage->minutes)
3612 $error = $cust_pkg_usage->replace || $cdr_cust_pkg_usage->insert;
3613 $minutes -= $cdr_cust_pkg_usage->minutes;
3615 if ( $order and $minutes > 0 and !$error ) {
3616 # then try to steal minutes from another call
3618 'table' => 'cdr_cust_pkg_usage',
3619 'addl_from' => ' JOIN cust_pkg_usage USING (pkgusagenum)'.
3620 ' JOIN part_pkg_usage USING (pkgusagepart)'.
3621 ' JOIN cust_pkg USING (pkgnum)'.
3622 ' JOIN part_pkg_usage_class USING (pkgusagepart)'.
3623 ' JOIN cdr USING (acctid)',
3624 'select' => 'cdr_cust_pkg_usage.*',
3625 'extra_sql' => " WHERE cdr.freesidestatus = 'rated' AND ".
3626 " ( cust_pkg.pkgnum = $pkgnum OR ".
3627 " ( cust_pkg.custnum = $custnum AND ".
3628 " part_pkg_usage.shared IS NOT NULL ) ) AND ".
3629 " part_pkg_usage_class.classnum = $classnum",
3630 'order_by' => ' ORDER BY part_pkg_usage.priority ASC',
3632 if ( $order eq 'time' ) {
3633 # find CDRs that are using minutes, but have a later startdate
3635 my $startdate = $cdr->startdate;
3636 if ($startdate !~ /^\d+$/) {
3637 die "bad cdr startdate '$startdate'";
3639 $search{'extra_sql'} .= " AND cdr.startdate > $startdate";
3640 # minimize needless reshuffling
3641 $search{'order_by'} .= ', cdr.startdate DESC';
3643 # XXX may not work correctly with rate_time schedules. Could
3644 # fix this by storing ratedetailnum in cdr_cust_pkg_usage, I
3646 $search{'addl_from'} .=
3647 ' JOIN rate_detail'.
3648 ' ON (cdr.rated_ratedetailnum = rate_detail.ratedetailnum)';
3649 if ( $order eq 'rate_high' ) {
3650 $search{'extra_sql'} .= ' AND rate_detail.min_charge < '.
3651 $rate_detail->min_charge;
3652 $search{'order_by'} .= ', rate_detail.min_charge ASC';
3653 } elsif ( $order eq 'rate_low' ) {
3654 $search{'extra_sql'} .= ' AND rate_detail.min_charge > '.
3655 $rate_detail->min_charge;
3656 $search{'order_by'} .= ', rate_detail.min_charge DESC';
3658 # this should really never happen
3659 die "invalid cdr-minutes_priority value '$order'\n";
3662 my @cdr_usage_recs = qsearch(\%search);
3664 while (!$error and @cdr_usage_recs and $minutes > 0) {
3665 my $cdr_cust_pkg_usage = shift @cdr_usage_recs;
3666 my $cust_pkg_usage = $cdr_cust_pkg_usage->cust_pkg_usage;
3667 my $old_cdr = $cdr_cust_pkg_usage->cdr;
3668 $reproc_cdrs{$old_cdr->acctid} = $old_cdr;
3669 $cdr_cust_pkg_usage->select_for_update;
3670 $old_cdr->select_for_update;
3671 $cust_pkg_usage->select_for_update;
3672 # in case someone else stole the usage from this CDR
3673 # while waiting for the lock...
3674 next if $old_cdr->acctid != $cdr_cust_pkg_usage->acctid;
3675 # steal the usage allocation and flag the old CDR for reprocessing
3676 $cdr_cust_pkg_usage->set('acctid', $cdr->acctid);
3677 # if the allocation is more minutes than we need, adjust it...
3678 my $delta = $cdr_cust_pkg_usage->minutes - $minutes;
3680 $cdr_cust_pkg_usage->set('minutes', $minutes);
3681 $cust_pkg_usage->set('minutes', $cust_pkg_usage->minutes + $delta);
3682 $error = $cust_pkg_usage->replace;
3684 #warn 'CDR '.$cdr->acctid . ' stealing allocation '.$cdr_cust_pkg_usage->cdrusagenum.' from CDR '.$old_cdr->acctid."\n";
3685 $error ||= $cdr_cust_pkg_usage->replace;
3686 # deduct the stolen minutes
3687 $minutes -= $cdr_cust_pkg_usage->minutes;
3689 # after all minute-stealing is done, reset the affected CDRs
3690 foreach (values %reproc_cdrs) {
3691 $error ||= $_->set_status('');
3692 # XXX or should we just call $cdr->rate right here?
3693 # it's not like we can create a loop this way, since the min_charge
3694 # or call time has to go monotonically in one direction.
3695 # we COULD get some very deep recursions going, though...
3697 } # if $order and $minutes
3700 die "error applying included minutes\npkgnum ".$self->pkgnum.", class $classnum, acctid ".$cdr->acctid."\n$error\n"
3702 $dbh->commit if $oldAutoCommit;
3703 return $orig_minutes - $minutes;
3707 =item supplemental_pkgs
3709 Returns a list of all packages supplemental to this one.
3713 sub supplemental_pkgs {
3715 qsearch('cust_pkg', { 'main_pkgnum' => $self->pkgnum });
3720 Returns the package that this one is supplemental to, if any.
3726 if ( $self->main_pkgnum ) {
3727 return FS::cust_pkg->by_key($self->main_pkgnum);
3734 =head1 CLASS METHODS
3740 Returns an SQL expression identifying recurring packages.
3744 sub recurring_sql { "
3745 '0' != ( select freq from part_pkg
3746 where cust_pkg.pkgpart = part_pkg.pkgpart )
3751 Returns an SQL expression identifying one-time packages.
3756 '0' = ( select freq from part_pkg
3757 where cust_pkg.pkgpart = part_pkg.pkgpart )
3762 Returns an SQL expression identifying ordered packages (recurring packages not
3768 $_[0]->recurring_sql. " AND ". $_[0]->not_yet_billed_sql;
3773 Returns an SQL expression identifying active packages.
3778 $_[0]->recurring_sql. "
3779 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
3780 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
3781 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
3784 =item not_yet_billed_sql
3786 Returns an SQL expression identifying packages which have not yet been billed.
3790 sub not_yet_billed_sql { "
3791 ( cust_pkg.setup IS NULL OR cust_pkg.setup = 0 )
3792 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
3793 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
3798 Returns an SQL expression identifying inactive packages (one-time packages
3799 that are otherwise unsuspended/uncancelled).
3803 sub inactive_sql { "
3804 ". $_[0]->onetime_sql(). "
3805 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
3806 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
3807 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
3813 Returns an SQL expression identifying suspended packages.
3817 sub suspended_sql { susp_sql(@_); }
3819 #$_[0]->recurring_sql(). ' AND '.
3821 ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
3822 AND cust_pkg.susp IS NOT NULL AND cust_pkg.susp != 0
3829 Returns an SQL exprression identifying cancelled packages.
3833 sub cancelled_sql { cancel_sql(@_); }
3835 #$_[0]->recurring_sql(). ' AND '.
3836 "cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0";
3841 Returns an SQL expression to give the package status as a string.
3847 WHEN cust_pkg.cancel IS NOT NULL THEN 'cancelled'
3848 WHEN cust_pkg.susp IS NOT NULL THEN 'suspended'
3849 WHEN cust_pkg.setup IS NULL THEN 'not yet billed'
3850 WHEN ".onetime_sql()." THEN 'one-time charge'
3855 =item search HASHREF
3859 Returns a qsearch hash expression to search for parameters specified in HASHREF.
3860 Valid parameters are
3868 active, inactive, suspended, cancel (or cancelled)
3872 active, inactive, suspended, one-time charge, inactive, cancel (or cancelled)
3876 boolean selects custom packages
3882 pkgpart or arrayref or hashref of pkgparts
3886 arrayref of beginning and ending epoch date
3890 arrayref of beginning and ending epoch date
3894 arrayref of beginning and ending epoch date
3898 arrayref of beginning and ending epoch date
3902 arrayref of beginning and ending epoch date
3906 arrayref of beginning and ending epoch date
3910 arrayref of beginning and ending epoch date
3914 pkgnum or APKG_pkgnum
3918 a value suited to passing to FS::UI::Web::cust_header
3922 specifies the user for agent virtualization
3926 boolean; if true, returns only packages with more than 0 FCC phone lines.
3928 =item state, country
3930 Limit to packages with a service location in the specified state and country.
3931 For FCC 477 reporting, mostly.
3938 my ($class, $params) = @_;
3945 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
3947 "cust_main.agentnum = $1";
3954 if ( $params->{'custnum'} =~ /^(\d+)$/ and $1 ) {
3956 "cust_pkg.custnum = $1";
3963 if ( $params->{'pkgbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
3965 "cust_pkg.pkgbatch = '$1'";
3972 if ( $params->{'magic'} eq 'active'
3973 || $params->{'status'} eq 'active' ) {
3975 push @where, FS::cust_pkg->active_sql();
3977 } elsif ( $params->{'magic'} =~ /^not[ _]yet[ _]billed$/
3978 || $params->{'status'} =~ /^not[ _]yet[ _]billed$/ ) {
3980 push @where, FS::cust_pkg->not_yet_billed_sql();
3982 } elsif ( $params->{'magic'} =~ /^(one-time charge|inactive)/
3983 || $params->{'status'} =~ /^(one-time charge|inactive)/ ) {
3985 push @where, FS::cust_pkg->inactive_sql();
3987 } elsif ( $params->{'magic'} eq 'suspended'
3988 || $params->{'status'} eq 'suspended' ) {
3990 push @where, FS::cust_pkg->suspended_sql();
3992 } elsif ( $params->{'magic'} =~ /^cancell?ed$/
3993 || $params->{'status'} =~ /^cancell?ed$/ ) {
3995 push @where, FS::cust_pkg->cancelled_sql();
4000 # parse package class
4003 if ( exists($params->{'classnum'}) ) {
4006 if ( ref($params->{'classnum'}) ) {
4008 if ( ref($params->{'classnum'}) eq 'HASH' ) {
4009 @classnum = grep $params->{'classnum'}{$_}, keys %{ $params->{'classnum'} };
4010 } elsif ( ref($params->{'classnum'}) eq 'ARRAY' ) {
4011 @classnum = @{ $params->{'classnum'} };
4013 die 'unhandled classnum ref '. $params->{'classnum'};
4017 } elsif ( $params->{'classnum'} =~ /^(\d*)$/ && $1 ne '0' ) {
4024 my @nums = grep $_, @classnum;
4025 push @c_where, 'part_pkg.classnum IN ('. join(',',@nums). ')' if @nums;
4026 my $null = scalar( grep { $_ eq '' } @classnum );
4027 push @c_where, 'part_pkg.classnum IS NULL' if $null;
4029 if ( scalar(@c_where) == 1 ) {
4030 push @where, @c_where;
4031 } elsif ( @c_where ) {
4032 push @where, ' ( '. join(' OR ', @c_where). ' ) ';
4041 # parse package report options
4044 my @report_option = ();
4045 if ( exists($params->{'report_option'}) ) {
4046 if ( ref($params->{'report_option'}) eq 'ARRAY' ) {
4047 @report_option = @{ $params->{'report_option'} };
4048 } elsif ( $params->{'report_option'} =~ /^([,\d]*)$/ ) {
4049 @report_option = split(',', $1);
4054 if (@report_option) {
4055 # this will result in the empty set for the dangling comma case as it should
4057 map{ "0 < ( SELECT count(*) FROM part_pkg_option
4058 WHERE part_pkg_option.pkgpart = part_pkg.pkgpart
4059 AND optionname = 'report_option_$_'
4060 AND optionvalue = '1' )"
4064 foreach my $any ( grep /^report_option_any/, keys %$params ) {
4066 my @report_option_any = ();
4067 if ( ref($params->{$any}) eq 'ARRAY' ) {
4068 @report_option_any = @{ $params->{$any} };
4069 } elsif ( $params->{$any} =~ /^([,\d]*)$/ ) {
4070 @report_option_any = split(',', $1);
4073 if (@report_option_any) {
4074 # this will result in the empty set for the dangling comma case as it should
4075 push @where, ' ( '. join(' OR ',
4076 map{ "0 < ( SELECT count(*) FROM part_pkg_option
4077 WHERE part_pkg_option.pkgpart = part_pkg.pkgpart
4078 AND optionname = 'report_option_$_'
4079 AND optionvalue = '1' )"
4080 } @report_option_any
4090 push @where, "part_pkg.custom = 'Y'" if $params->{custom};
4096 push @where, "(part_pkg.fcc_ds0s > 0 OR pkg_class.fcc_ds0s > 0)"
4097 if $params->{fcc_line};
4103 if ( exists($params->{'censustract'}) ) {
4104 $params->{'censustract'} =~ /^([.\d]*)$/;
4105 my $censustract = "cust_location.censustract = '$1'";
4106 $censustract .= ' OR cust_location.censustract is NULL' unless $1;
4107 push @where, "( $censustract )";
4111 # parse censustract2
4113 if ( exists($params->{'censustract2'})
4114 && $params->{'censustract2'} =~ /^(\d*)$/
4118 push @where, "cust_location.censustract LIKE '$1%'";
4121 "( cust_location.censustract = '' OR cust_location.censustract IS NULL )";
4126 # parse country/state
4128 for (qw(state country)) { # parsing rules are the same for these
4129 if ( exists($params->{$_})
4130 && uc($params->{$_}) =~ /^([A-Z]{2})$/ )
4132 # XXX post-2.3 only--before that, state/country may be in cust_main
4133 push @where, "cust_location.$_ = '$1'";
4141 if ( ref($params->{'pkgpart'}) ) {
4144 if ( ref($params->{'pkgpart'}) eq 'HASH' ) {
4145 @pkgpart = grep $params->{'pkgpart'}{$_}, keys %{ $params->{'pkgpart'} };
4146 } elsif ( ref($params->{'pkgpart'}) eq 'ARRAY' ) {
4147 @pkgpart = @{ $params->{'pkgpart'} };
4149 die 'unhandled pkgpart ref '. $params->{'pkgpart'};
4152 @pkgpart = grep /^(\d+)$/, @pkgpart;
4154 push @where, 'pkgpart IN ('. join(',', @pkgpart). ')' if scalar(@pkgpart);
4156 } elsif ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
4157 push @where, "pkgpart = $1";
4166 #false laziness w/report_cust_pkg.html
4169 'one-time charge' => { 'last_bill'=>1, 'bill'=>1, 'adjourn'=>1, 'susp'=>1, 'expire'=>1, 'cancel'=>1, },
4170 'active' => { 'susp'=>1, 'cancel'=>1 },
4171 'suspended' => { 'cancel' => 1 },
4176 if( exists($params->{'active'} ) ) {
4177 # This overrides all the other date-related fields
4178 my($beginning, $ending) = @{$params->{'active'}};
4180 "cust_pkg.setup IS NOT NULL",
4181 "cust_pkg.setup <= $ending",
4182 "(cust_pkg.cancel IS NULL OR cust_pkg.cancel >= $beginning )",
4183 "NOT (".FS::cust_pkg->onetime_sql . ")";
4186 foreach my $field (qw( setup last_bill bill adjourn susp expire contract_end change_date cancel )) {
4188 next unless exists($params->{$field});
4190 my($beginning, $ending) = @{$params->{$field}};
4192 next if $beginning == 0 && $ending == 4294967295;
4195 "cust_pkg.$field IS NOT NULL",
4196 "cust_pkg.$field >= $beginning",
4197 "cust_pkg.$field <= $ending";
4199 $orderby ||= "ORDER BY cust_pkg.$field";
4204 $orderby ||= 'ORDER BY bill';
4207 # parse magic, legacy, etc.
4210 if ( $params->{'magic'} &&
4211 $params->{'magic'} =~ /^(active|inactive|suspended|cancell?ed)$/
4214 $orderby = 'ORDER BY pkgnum';
4216 if ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
4217 push @where, "pkgpart = $1";
4220 } elsif ( $params->{'query'} eq 'pkgnum' ) {
4222 $orderby = 'ORDER BY pkgnum';
4224 } elsif ( $params->{'query'} eq 'APKG_pkgnum' ) {
4226 $orderby = 'ORDER BY pkgnum';
4229 SELECT count(*) FROM pkg_svc
4230 WHERE pkg_svc.pkgpart = cust_pkg.pkgpart
4231 AND pkg_svc.quantity > ( SELECT count(*) FROM cust_svc
4232 WHERE cust_svc.pkgnum = cust_pkg.pkgnum
4233 AND cust_svc.svcpart = pkg_svc.svcpart
4240 # setup queries, links, subs, etc. for the search
4243 # here is the agent virtualization
4244 if ($params->{CurrentUser}) {
4246 qsearchs('access_user', { username => $params->{CurrentUser} });
4249 push @where, $access_user->agentnums_sql('table'=>'cust_main');
4254 push @where, $FS::CurrentUser::CurrentUser->agentnums_sql('table'=>'cust_main');
4257 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
4259 my $addl_from = 'LEFT JOIN part_pkg USING ( pkgpart ) '.
4260 'LEFT JOIN pkg_class ON ( part_pkg.classnum = pkg_class.classnum ) '.
4261 'LEFT JOIN cust_location USING ( locationnum ) '.
4262 FS::UI::Web::join_cust_main('cust_pkg', 'cust_pkg');
4266 if ( $params->{'select_zip5'} ) {
4267 my $zip = 'cust_location.zip';
4269 $select = "DISTINCT substr($zip,1,5) as zip";
4270 $orderby = "ORDER BY substr($zip,1,5)";
4271 $count_query = "SELECT COUNT( DISTINCT substr($zip,1,5) )";
4273 $select = join(', ',
4275 ( map "part_pkg.$_", qw( pkg freq ) ),
4276 'pkg_class.classname',
4277 'cust_main.custnum AS cust_main_custnum',
4278 FS::UI::Web::cust_sql_fields(
4279 $params->{'cust_fields'}
4282 $count_query = 'SELECT COUNT(*)';
4285 $count_query .= " FROM cust_pkg $addl_from $extra_sql";
4288 'table' => 'cust_pkg',
4290 'select' => $select,
4291 'extra_sql' => $extra_sql,
4292 'order_by' => $orderby,
4293 'addl_from' => $addl_from,
4294 'count_query' => $count_query,
4301 Returns a list of two package counts. The first is a count of packages
4302 based on the supplied criteria and the second is the count of residential
4303 packages with those same criteria. Criteria are specified as in the search
4309 my ($class, $params) = @_;
4311 my $sql_query = $class->search( $params );
4313 my $count_sql = delete($sql_query->{'count_query'});
4314 $count_sql =~ s/ FROM/,count(CASE WHEN cust_main.company IS NULL OR cust_main.company = '' THEN 1 END) FROM/
4315 or die "couldn't parse count_sql";
4317 my $count_sth = dbh->prepare($count_sql)
4318 or die "Error preparing $count_sql: ". dbh->errstr;
4320 or die "Error executing $count_sql: ". $count_sth->errstr;
4321 my $count_arrayref = $count_sth->fetchrow_arrayref;
4323 return ( @$count_arrayref );
4327 =item tax_locationnum_sql
4329 Returns an SQL expression for the tax location for a package, based
4330 on the settings of 'tax-pkg_address' and 'tax-ship_address'.
4334 sub tax_locationnum_sql {
4335 my $conf = FS::Conf->new;
4336 if ( $conf->exists('tax-pkg_address') ) {
4337 'cust_pkg.locationnum';
4339 elsif ( $conf->exists('tax-ship_address') ) {
4340 'cust_main.ship_locationnum';
4343 'cust_main.bill_locationnum';
4349 Returns a list: the first item is an SQL fragment identifying matching
4350 packages/customers via location (taking into account shipping and package
4351 address taxation, if enabled), and subsequent items are the parameters to
4352 substitute for the placeholders in that fragment.
4357 my($class, %opt) = @_;
4358 my $ornull = $opt{'ornull'};
4360 my $conf = new FS::Conf;
4362 # '?' placeholders in _location_sql_where
4363 my $x = $ornull ? 3 : 2;
4374 if ( $conf->exists('tax-ship_address') ) {
4377 ( ( ship_last IS NULL OR ship_last = '' )
4378 AND ". _location_sql_where('cust_main', '', $ornull ). "
4380 OR ( ship_last IS NOT NULL AND ship_last != ''
4381 AND ". _location_sql_where('cust_main', 'ship_', $ornull ). "
4384 # AND payby != 'COMP'
4386 @main_param = ( @bill_param, @bill_param );
4390 $main_where = _location_sql_where('cust_main'); # AND payby != 'COMP'
4391 @main_param = @bill_param;
4397 if ( $conf->exists('tax-pkg_address') ) {
4399 my $loc_where = _location_sql_where( 'cust_location', '', $ornull );
4402 ( cust_pkg.locationnum IS NULL AND $main_where )
4403 OR ( cust_pkg.locationnum IS NOT NULL AND $loc_where )
4406 @param = ( @main_param, @bill_param );
4410 $where = $main_where;
4411 @param = @main_param;
4419 #subroutine, helper for location_sql
4420 sub _location_sql_where {
4422 my $prefix = @_ ? shift : '';
4423 my $ornull = @_ ? shift : '';
4425 # $ornull = $ornull ? " OR ( ? IS NULL AND $table.${prefix}county IS NULL ) " : '';
4427 $ornull = $ornull ? ' OR ? IS NULL ' : '';
4429 my $or_empty_city = " OR ( ? = '' AND $table.${prefix}city IS NULL )";
4430 my $or_empty_county = " OR ( ? = '' AND $table.${prefix}county IS NULL )";
4431 my $or_empty_state = " OR ( ? = '' AND $table.${prefix}state IS NULL )";
4433 my $text = (driver_name =~ /^mysql/i) ? 'char' : 'text';
4435 # ( $table.${prefix}city = ? $or_empty_city $ornull )
4437 ( $table.district = ? OR ? = '' OR CAST(? AS $text) IS NULL )
4438 AND ( $table.${prefix}city = ? OR ? = '' OR CAST(? AS $text) IS NULL )
4439 AND ( $table.${prefix}county = ? $or_empty_county $ornull )
4440 AND ( $table.${prefix}state = ? $or_empty_state $ornull )
4441 AND $table.${prefix}country = ?
4446 my( $self, $what ) = @_;
4448 my $what_show_zero = $what. '_show_zero';
4449 length($self->$what_show_zero())
4450 ? ($self->$what_show_zero() eq 'Y')
4451 : $self->part_pkg->$what_show_zero();
4458 =item order CUSTNUM, PKGPARTS_ARYREF, [ REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF [ REFNUM ] ] ]
4460 CUSTNUM is a customer (see L<FS::cust_main>)
4462 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
4463 L<FS::part_pkg>) to order for this customer. Duplicates are of course
4466 REMOVE_PKGNUMS is an optional list of pkgnums specifying the billing items to
4467 remove for this customer. The services (see L<FS::cust_svc>) are moved to the
4468 new billing items. An error is returned if this is not possible (see
4469 L<FS::pkg_svc>). An empty arrayref is equivalent to not specifying this
4472 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
4473 newly-created cust_pkg objects.
4475 REFNUM, if specified, will specify the FS::pkg_referral record to be created
4476 and inserted. Multiple FS::pkg_referral records can be created by
4477 setting I<refnum> to an array reference of refnums or a hash reference with
4478 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
4479 record will be created corresponding to cust_main.refnum.
4484 my ($custnum, $pkgparts, $remove_pkgnum, $return_cust_pkg, $refnum) = @_;
4486 my $conf = new FS::Conf;
4488 # Transactionize this whole mess
4489 local $SIG{HUP} = 'IGNORE';
4490 local $SIG{INT} = 'IGNORE';
4491 local $SIG{QUIT} = 'IGNORE';
4492 local $SIG{TERM} = 'IGNORE';
4493 local $SIG{TSTP} = 'IGNORE';
4494 local $SIG{PIPE} = 'IGNORE';
4496 my $oldAutoCommit = $FS::UID::AutoCommit;
4497 local $FS::UID::AutoCommit = 0;
4501 # my $cust_main = qsearchs('cust_main', { custnum => $custnum });
4502 # return "Customer not found: $custnum" unless $cust_main;
4504 warn "$me order: pkgnums to remove: ". join(',', @$remove_pkgnum). "\n"
4507 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
4510 my $change = scalar(@old_cust_pkg) != 0;
4513 if ( scalar(@old_cust_pkg) == 1 && scalar(@$pkgparts) == 1 ) {
4515 warn "$me order: changing pkgnum ". $old_cust_pkg[0]->pkgnum.
4516 " to pkgpart ". $pkgparts->[0]. "\n"
4519 my $err_or_cust_pkg =
4520 $old_cust_pkg[0]->change( 'pkgpart' => $pkgparts->[0],
4521 'refnum' => $refnum,
4524 unless (ref($err_or_cust_pkg)) {
4525 $dbh->rollback if $oldAutoCommit;
4526 return $err_or_cust_pkg;
4529 push @$return_cust_pkg, $err_or_cust_pkg;
4530 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4535 # Create the new packages.
4536 foreach my $pkgpart (@$pkgparts) {
4538 warn "$me order: inserting pkgpart $pkgpart\n" if $DEBUG;
4540 my $cust_pkg = new FS::cust_pkg { custnum => $custnum,
4541 pkgpart => $pkgpart,
4545 $error = $cust_pkg->insert( 'change' => $change );
4546 push @$return_cust_pkg, $cust_pkg;
4548 foreach my $link ($cust_pkg->part_pkg->supp_part_pkg_link) {
4549 my $supp_pkg = FS::cust_pkg->new({
4550 custnum => $custnum,
4551 pkgpart => $link->dst_pkgpart,
4553 main_pkgnum => $cust_pkg->pkgnum,
4556 $error ||= $supp_pkg->insert( 'change' => $change );
4557 push @$return_cust_pkg, $supp_pkg;
4561 $dbh->rollback if $oldAutoCommit;
4566 # $return_cust_pkg now contains refs to all of the newly
4569 # Transfer services and cancel old packages.
4570 foreach my $old_pkg (@old_cust_pkg) {
4572 warn "$me order: transferring services from pkgnum ". $old_pkg->pkgnum. "\n"
4575 foreach my $new_pkg (@$return_cust_pkg) {
4576 $error = $old_pkg->transfer($new_pkg);
4577 if ($error and $error == 0) {
4578 # $old_pkg->transfer failed.
4579 $dbh->rollback if $oldAutoCommit;
4584 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
4585 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
4586 foreach my $new_pkg (@$return_cust_pkg) {
4587 $error = $old_pkg->transfer($new_pkg, 'change_svcpart'=>1 );
4588 if ($error and $error == 0) {
4589 # $old_pkg->transfer failed.
4590 $dbh->rollback if $oldAutoCommit;
4597 # Transfers were successful, but we went through all of the
4598 # new packages and still had services left on the old package.
4599 # We can't cancel the package under the circumstances, so abort.
4600 $dbh->rollback if $oldAutoCommit;
4601 return "Unable to transfer all services from package ".$old_pkg->pkgnum;
4603 $error = $old_pkg->cancel( quiet=>1 );
4609 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4613 =item bulk_change PKGPARTS_ARYREF, REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF ]
4615 A bulk change method to change packages for multiple customers.
4617 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
4618 L<FS::part_pkg>) to order for each customer. Duplicates are of course
4621 REMOVE_PKGNUMS is an list of pkgnums specifying the billing items to
4622 replace. The services (see L<FS::cust_svc>) are moved to the
4623 new billing items. An error is returned if this is not possible (see
4626 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
4627 newly-created cust_pkg objects.
4632 my ($pkgparts, $remove_pkgnum, $return_cust_pkg) = @_;
4634 # Transactionize this whole mess
4635 local $SIG{HUP} = 'IGNORE';
4636 local $SIG{INT} = 'IGNORE';
4637 local $SIG{QUIT} = 'IGNORE';
4638 local $SIG{TERM} = 'IGNORE';
4639 local $SIG{TSTP} = 'IGNORE';
4640 local $SIG{PIPE} = 'IGNORE';
4642 my $oldAutoCommit = $FS::UID::AutoCommit;
4643 local $FS::UID::AutoCommit = 0;
4647 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
4650 while(scalar(@old_cust_pkg)) {
4652 my $custnum = $old_cust_pkg[0]->custnum;
4653 my (@remove) = map { $_->pkgnum }
4654 grep { $_->custnum == $custnum } @old_cust_pkg;
4655 @old_cust_pkg = grep { $_->custnum != $custnum } @old_cust_pkg;
4657 my $error = order $custnum, $pkgparts, \@remove, \@return;
4659 push @errors, $error
4661 push @$return_cust_pkg, @return;
4664 if (scalar(@errors)) {
4665 $dbh->rollback if $oldAutoCommit;
4666 return join(' / ', @errors);
4669 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4673 # Used by FS::Upgrade to migrate to a new database.
4674 sub _upgrade_data { # class method
4675 my ($class, %opts) = @_;
4676 $class->_upgrade_otaker(%opts);
4678 # RT#10139, bug resulting in contract_end being set when it shouldn't
4679 'UPDATE cust_pkg SET contract_end = NULL WHERE contract_end = -1',
4680 # RT#10830, bad calculation of prorate date near end of year
4681 # the date range for bill is December 2009, and we move it forward
4682 # one year if it's before the previous bill date (which it should
4684 'UPDATE cust_pkg SET bill = bill + (365*24*60*60) WHERE bill < last_bill
4685 AND bill > 1259654400 AND bill < 1262332800 AND (SELECT plan FROM part_pkg
4686 WHERE part_pkg.pkgpart = cust_pkg.pkgpart) = \'prorate\'',
4687 # RT6628, add order_date to cust_pkg
4688 'update cust_pkg set order_date = (select history_date from h_cust_pkg
4689 where h_cust_pkg.pkgnum = cust_pkg.pkgnum and
4690 history_action = \'insert\') where order_date is null',
4692 foreach my $sql (@statements) {
4693 my $sth = dbh->prepare($sql);
4694 $sth->execute or die $sth->errstr;
4702 sub order is not OO. Perhaps it should be moved to FS::cust_main and made so?
4704 In sub order, the @pkgparts array (passed by reference) is clobbered.
4706 Also in sub order, no money is adjusted. Once FS::part_pkg defines a standard
4707 method to pass dates to the recur_prog expression, it should do so.
4709 FS::svc_acct, FS::svc_domain, FS::svc_www, FS::svc_ip and FS::svc_forward are
4710 loaded via 'use' at compile time, rather than via 'require' in sub { setup,
4711 suspend, unsuspend, cancel } because they use %FS::UID::callback to load
4712 configuration values. Probably need a subroutine which decides what to do
4713 based on whether or not we've fetched the user yet, rather than a hash. See
4714 FS::UID and the TODO.
4716 Now that things are transactional should the check in the insert method be
4721 L<FS::Record>, L<FS::cust_main>, L<FS::part_pkg>, L<FS::cust_svc>,
4722 L<FS::pkg_svc>, schema.html from the base documentation