2 use base qw( FS::otaker_Mixin FS::cust_main_Mixin FS::Sales_Mixin
3 FS::contact_Mixin FS::location_Mixin
4 FS::m2m_Common FS::option_Common );
7 use vars qw( $disable_agentcheck $DEBUG $me $upgrade );
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( getotaker dbh driver_name );
15 use FS::Misc qw( send_email );
16 use FS::Record qw( qsearch qsearchs fields );
22 use FS::cust_location;
24 use FS::cust_bill_pkg;
25 use FS::cust_pkg_detail;
26 use FS::cust_pkg_usage;
27 use FS::cdr_cust_pkg_usage;
32 use FS::cust_pkg_reason;
34 use FS::cust_pkg_discount;
41 # need to 'use' these instead of 'require' in sub { cancel, suspend, unsuspend,
43 # because they load configuration by setting FS::UID::callback (see TODO)
49 # for sending cancel emails in sub cancel
53 $me = '[FS::cust_pkg]';
55 $disable_agentcheck = 0;
57 $upgrade = 0; #go away after setup+start dates cleaned up for old customers
61 my ( $hashref, $cache ) = @_;
62 #if ( $hashref->{'pkgpart'} ) {
63 if ( $hashref->{'pkg'} ) {
64 # #@{ $self->{'_pkgnum'} } = ();
65 # my $subcache = $cache->subcache('pkgpart', 'part_pkg');
66 # $self->{'_pkgpart'} = $subcache;
67 # #push @{ $self->{'_pkgnum'} },
68 # FS::part_pkg->new_or_cached($hashref, $subcache);
69 $self->{'_pkgpart'} = FS::part_pkg->new($hashref);
71 if ( exists $hashref->{'svcnum'} ) {
72 #@{ $self->{'_pkgnum'} } = ();
73 my $subcache = $cache->subcache('svcnum', 'cust_svc', $hashref->{pkgnum});
74 $self->{'_svcnum'} = $subcache;
75 #push @{ $self->{'_pkgnum'} },
76 FS::cust_svc->new_or_cached($hashref, $subcache) if $hashref->{svcnum};
82 FS::cust_pkg - Object methods for cust_pkg objects
88 $record = new FS::cust_pkg \%hash;
89 $record = new FS::cust_pkg { 'column' => 'value' };
91 $error = $record->insert;
93 $error = $new_record->replace($old_record);
95 $error = $record->delete;
97 $error = $record->check;
99 $error = $record->cancel;
101 $error = $record->suspend;
103 $error = $record->unsuspend;
105 $part_pkg = $record->part_pkg;
107 @labels = $record->labels;
109 $seconds = $record->seconds_since($timestamp);
111 $error = FS::cust_pkg::order( $custnum, \@pkgparts );
112 $error = FS::cust_pkg::order( $custnum, \@pkgparts, \@remove_pkgnums ] );
116 An FS::cust_pkg object represents a customer billing item. FS::cust_pkg
117 inherits from FS::Record. The following fields are currently supported:
123 Primary key (assigned automatically for new billing items)
127 Customer (see L<FS::cust_main>)
131 Billing item definition (see L<FS::part_pkg>)
135 Optional link to package location (see L<FS::location>)
139 date package was ordered (also remains same on changes)
151 date (next bill date)
179 order taker (see L<FS::access_user>)
183 If this field is set to 1, disables the automatic
184 unsuspension of this package when using the B<unsuspendauto> config option.
188 If not set, defaults to 1
192 Date of change from previous package
202 =item change_locationnum
210 The pkgnum of the package that this package is supplemental to, if any.
214 The package link (L<FS::part_pkg_link>) that defines this supplemental
215 package, if it is one.
217 =item change_to_pkgnum
219 The pkgnum of the package this one will be "changed to" in the future
220 (on its expiration date).
224 Note: setup, last_bill, bill, adjourn, susp, expire, cancel and change_date
225 are specified as UNIX timestamps; see L<perlfunc/"time">. Also see
226 L<Time::Local> and L<Date::Parse> for conversion functions.
234 Create a new billing item. To add the item to the database, see L<"insert">.
238 sub table { 'cust_pkg'; }
239 sub cust_linked { $_[0]->cust_main_custnum || $_[0]->custnum }
240 sub cust_unlinked_msg {
242 "WARNING: can't find cust_main.custnum ". $self->custnum.
243 ' (cust_pkg.pkgnum '. $self->pkgnum. ')';
246 =item insert [ OPTION => VALUE ... ]
248 Adds this billing item to the database ("Orders" the item). If there is an
249 error, returns the error, otherwise returns false.
251 If the additional field I<promo_code> is defined instead of I<pkgpart>, it
252 will be used to look up the package definition and agent restrictions will be
255 If the additional field I<refnum> is defined, an FS::pkg_referral record will
256 be created and inserted. Multiple FS::pkg_referral records can be created by
257 setting I<refnum> to an array reference of refnums or a hash reference with
258 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
259 record will be created corresponding to cust_main.refnum.
261 The following options are available:
267 If set true, supresses actions that should only be taken for new package
268 orders. (Currently this includes: intro periods when delay_setup is on,
269 auto-adding a 1st start date, auto-adding expiration/adjourn/contract_end dates)
273 cust_pkg_option records will be created
277 a ticket will be added to this customer with this subject
281 an optional queue name for ticket additions
285 Don't check the legality of the package definition. This should be used
286 when performing a package change that doesn't change the pkgpart (i.e.
294 my( $self, %options ) = @_;
297 $error = $self->check_pkgpart unless $options{'allow_pkgpart'};
298 return $error if $error;
300 my $part_pkg = $self->part_pkg;
302 if ( ! $options{'change'} ) {
304 # if the package def says to start only on the first of the month:
305 if ( $part_pkg->option('start_1st', 1) && !$self->start_date ) {
306 my ($sec,$min,$hour,$mday,$mon,$year) = (localtime(time) )[0,1,2,3,4,5];
307 $mon += 1 unless $mday == 1;
308 until ( $mon < 12 ) { $mon -= 12; $year++; }
309 $self->start_date( timelocal_nocheck(0,0,0,1,$mon,$year) );
312 # set up any automatic expire/adjourn/contract_end timers
313 # based on the start date
314 foreach my $action ( qw(expire adjourn contract_end) ) {
315 my $months = $part_pkg->option("${action}_months",1);
316 if($months and !$self->$action) {
317 my $start = $self->start_date || $self->setup || time;
318 $self->$action( $part_pkg->add_freq($start, $months) );
322 # if this package has "free days" and delayed setup fee, then
323 # set start date that many days in the future.
324 # (this should have been set in the UI, but enforce it here)
325 if ( ! $options{'change'}
326 && $part_pkg->option('free_days',1)
327 && $part_pkg->option('delay_setup',1)
328 #&& ! $self->start_date
331 $self->start_date( $part_pkg->default_start_date );
336 # set order date unless this was previously a different package
337 $self->order_date(time) unless $self->change_pkgnum;
339 local $SIG{HUP} = 'IGNORE';
340 local $SIG{INT} = 'IGNORE';
341 local $SIG{QUIT} = 'IGNORE';
342 local $SIG{TERM} = 'IGNORE';
343 local $SIG{TSTP} = 'IGNORE';
344 local $SIG{PIPE} = 'IGNORE';
346 $self->susp( $self->order_date ) if $self->susp eq 'now';
348 my $oldAutoCommit = $FS::UID::AutoCommit;
349 local $FS::UID::AutoCommit = 0;
352 $error = $self->SUPER::insert($options{options} ? %{$options{options}} : ());
354 $dbh->rollback if $oldAutoCommit;
358 $self->refnum($self->cust_main->refnum) unless $self->refnum;
359 $self->refnum( [ $self->refnum ] ) unless ref($self->refnum);
360 $self->process_m2m( 'link_table' => 'pkg_referral',
361 'target_table' => 'part_referral',
362 'params' => $self->refnum,
365 if ( $self->discountnum ) {
366 my $error = $self->insert_discount();
368 $dbh->rollback if $oldAutoCommit;
373 my $conf = new FS::Conf;
375 if ( $conf->config('ticket_system') && $options{ticket_subject} ) {
377 #this init stuff is still inefficient, but at least its limited to
378 # the small number (any?) folks using ticket emailing on pkg order
381 # use lib ( "/opt/rt3/local/lib", "/opt/rt3/lib" );
388 use FS::TicketSystem;
389 FS::TicketSystem->init();
391 my $q = new RT::Queue($RT::SystemUser);
392 $q->Load($options{ticket_queue}) if $options{ticket_queue};
393 my $t = new RT::Ticket($RT::SystemUser);
394 my $mime = new MIME::Entity;
395 $mime->build( Type => 'text/plain', Data => $options{ticket_subject} );
396 $t->Create( $options{ticket_queue} ? (Queue => $q) : (),
397 Subject => $options{ticket_subject},
400 $t->AddLink( Type => 'MemberOf',
401 Target => 'freeside://freeside/cust_main/'. $self->custnum,
405 if ($conf->config('welcome_letter') && $self->cust_main->num_pkgs == 1) {
406 my $queue = new FS::queue {
407 'job' => 'FS::cust_main::queueable_print',
409 $error = $queue->insert(
410 'custnum' => $self->custnum,
411 'template' => 'welcome_letter',
415 warn "can't send welcome letter: $error";
420 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
427 This method now works but you probably shouldn't use it.
429 You don't want to delete packages, because there would then be no record
430 the customer ever purchased the package. Instead, see the cancel method and
431 hide cancelled packages.
438 local $SIG{HUP} = 'IGNORE';
439 local $SIG{INT} = 'IGNORE';
440 local $SIG{QUIT} = 'IGNORE';
441 local $SIG{TERM} = 'IGNORE';
442 local $SIG{TSTP} = 'IGNORE';
443 local $SIG{PIPE} = 'IGNORE';
445 my $oldAutoCommit = $FS::UID::AutoCommit;
446 local $FS::UID::AutoCommit = 0;
449 foreach my $cust_pkg_discount ($self->cust_pkg_discount) {
450 my $error = $cust_pkg_discount->delete;
452 $dbh->rollback if $oldAutoCommit;
456 #cust_bill_pkg_discount?
458 foreach my $cust_pkg_detail ($self->cust_pkg_detail) {
459 my $error = $cust_pkg_detail->delete;
461 $dbh->rollback if $oldAutoCommit;
466 foreach my $cust_pkg_reason (
468 'table' => 'cust_pkg_reason',
469 'hashref' => { 'pkgnum' => $self->pkgnum },
473 my $error = $cust_pkg_reason->delete;
475 $dbh->rollback if $oldAutoCommit;
482 my $error = $self->SUPER::delete(@_);
484 $dbh->rollback if $oldAutoCommit;
488 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
494 =item replace [ OLD_RECORD ] [ HASHREF | OPTION => VALUE ... ]
496 Replaces the OLD_RECORD with this one in the database. If there is an error,
497 returns the error, otherwise returns false.
499 Currently, custnum, setup, bill, adjourn, susp, expire, and cancel may be changed.
501 Changing pkgpart may have disasterous effects. See the order subroutine.
503 setup and bill are normally updated by calling the bill method of a customer
504 object (see L<FS::cust_main>).
506 suspend is normally updated by the suspend and unsuspend methods.
508 cancel is normally updated by the cancel method (and also the order subroutine
511 Available options are:
517 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.
521 the access_user (see L<FS::access_user>) providing the reason
525 hashref of keys and values - cust_pkg_option records will be created, updated or removed as appopriate
534 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
539 ( ref($_[0]) eq 'HASH' )
543 #return "Can't (yet?) change pkgpart!" if $old->pkgpart != $new->pkgpart;
544 #return "Can't change otaker!" if $old->otaker ne $new->otaker;
547 #return "Can't change setup once it exists!"
548 # if $old->getfield('setup') &&
549 # $old->getfield('setup') != $new->getfield('setup');
551 #some logic for bill, susp, cancel?
553 local($disable_agentcheck) = 1 if $old->pkgpart == $new->pkgpart;
555 local $SIG{HUP} = 'IGNORE';
556 local $SIG{INT} = 'IGNORE';
557 local $SIG{QUIT} = 'IGNORE';
558 local $SIG{TERM} = 'IGNORE';
559 local $SIG{TSTP} = 'IGNORE';
560 local $SIG{PIPE} = 'IGNORE';
562 my $oldAutoCommit = $FS::UID::AutoCommit;
563 local $FS::UID::AutoCommit = 0;
566 foreach my $method ( qw(adjourn expire) ) { # How many reasons?
567 if ($options->{'reason'} && $new->$method && $old->$method ne $new->$method) {
568 my $error = $new->insert_reason(
569 'reason' => $options->{'reason'},
570 'date' => $new->$method,
572 'reason_otaker' => $options->{'reason_otaker'},
575 dbh->rollback if $oldAutoCommit;
576 return "Error inserting cust_pkg_reason: $error";
581 #save off and freeze RADIUS attributes for any associated svc_acct records
583 if ( $old->part_pkg->is_prepaid || $new->part_pkg->is_prepaid ) {
585 #also check for specific exports?
586 # to avoid spurious modify export events
587 @svc_acct = map { $_->svc_x }
588 grep { $_->part_svc->svcdb eq 'svc_acct' }
591 $_->snapshot foreach @svc_acct;
595 my $error = $new->export_pkg_change($old)
596 || $new->SUPER::replace( $old,
598 ? $options->{options}
602 $dbh->rollback if $oldAutoCommit;
606 #for prepaid packages,
607 #trigger export of new RADIUS Expiration attribute when cust_pkg.bill changes
608 foreach my $old_svc_acct ( @svc_acct ) {
609 my $new_svc_acct = new FS::svc_acct { $old_svc_acct->hash };
611 $new_svc_acct->replace( $old_svc_acct,
612 'depend_jobnum' => $options->{depend_jobnum},
615 $dbh->rollback if $oldAutoCommit;
620 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
627 Checks all fields to make sure this is a valid billing item. If there is an
628 error, returns the error, otherwise returns false. Called by the insert and
636 if ( !$self->locationnum or $self->locationnum == -1 ) {
637 $self->set('locationnum', $self->cust_main->ship_locationnum);
641 $self->ut_numbern('pkgnum')
642 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum')
643 || $self->ut_numbern('pkgpart')
644 || $self->ut_foreign_keyn('contactnum', 'contact', 'contactnum' )
645 || $self->ut_foreign_keyn('locationnum', 'cust_location', 'locationnum')
646 || $self->ut_foreign_keyn('salesnum', 'sales', 'salesnum')
647 || $self->ut_numbern('quantity')
648 || $self->ut_numbern('start_date')
649 || $self->ut_numbern('setup')
650 || $self->ut_numbern('bill')
651 || $self->ut_numbern('susp')
652 || $self->ut_numbern('cancel')
653 || $self->ut_numbern('adjourn')
654 || $self->ut_numbern('resume')
655 || $self->ut_numbern('expire')
656 || $self->ut_numbern('dundate')
657 || $self->ut_enum('no_auto', [ '', 'Y' ])
658 || $self->ut_enum('waive_setup', [ '', 'Y' ])
659 || $self->ut_textn('agent_pkgid')
660 || $self->ut_enum('recur_show_zero', [ '', 'Y', 'N', ])
661 || $self->ut_enum('setup_show_zero', [ '', 'Y', 'N', ])
662 || $self->ut_foreign_keyn('main_pkgnum', 'cust_pkg', 'pkgnum')
663 || $self->ut_foreign_keyn('pkglinknum', 'part_pkg_link', 'pkglinknum')
664 || $self->ut_foreign_keyn('change_to_pkgnum', 'cust_pkg', 'pkgnum')
666 return $error if $error;
668 return "A package with both start date (future start) and setup date (already started) will never bill"
669 if $self->start_date && $self->setup && ! $upgrade;
671 return "A future unsuspend date can only be set for a package with a suspend date"
672 if $self->resume and !$self->susp and !$self->adjourn;
674 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
676 if ( $self->dbdef_table->column('manual_flag') ) {
677 $self->manual_flag('') if $self->manual_flag eq ' ';
678 $self->manual_flag =~ /^([01]?)$/
679 or return "Illegal manual_flag ". $self->manual_flag;
680 $self->manual_flag($1);
688 Check the pkgpart to make sure it's allowed with the reg_code and/or
689 promo_code of the package (if present) and with the customer's agent.
690 Called from C<insert>, unless we are doing a package change that doesn't
698 # my $error = $self->ut_numbern('pkgpart'); # already done
701 if ( $self->reg_code ) {
703 unless ( grep { $self->pkgpart == $_->pkgpart }
704 map { $_->reg_code_pkg }
705 qsearchs( 'reg_code', { 'code' => $self->reg_code,
706 'agentnum' => $self->cust_main->agentnum })
708 return "Unknown registration code";
711 } elsif ( $self->promo_code ) {
714 qsearchs('part_pkg', {
715 'pkgpart' => $self->pkgpart,
716 'promo_code' => { op=>'ILIKE', value=>$self->promo_code },
718 return 'Unknown promotional code' unless $promo_part_pkg;
722 unless ( $disable_agentcheck ) {
724 qsearchs( 'agent', { 'agentnum' => $self->cust_main->agentnum } );
725 return "agent ". $agent->agentnum. ':'. $agent->agent.
726 " can't purchase pkgpart ". $self->pkgpart
727 unless $agent->pkgpart_hashref->{ $self->pkgpart }
728 || $agent->agentnum == $self->part_pkg->agentnum;
731 $error = $self->ut_foreign_key('pkgpart', 'part_pkg', 'pkgpart' );
732 return $error if $error;
740 =item cancel [ OPTION => VALUE ... ]
742 Cancels and removes all services (see L<FS::cust_svc> and L<FS::part_svc>)
743 in this package, then cancels the package itself (sets the cancel field to
746 Available options are:
750 =item quiet - can be set true to supress email cancellation notices.
752 =item time - can be set to cancel the package based on a specific future or
753 historical date. Using time ensures that the remaining amount is calculated
754 correctly. Note however that this is an immediate cancel and just changes
755 the date. You are PROBABLY looking to expire the account instead of using
758 =item reason - can be set to a cancellation reason (see L<FS:reason>),
759 either a reasonnum of an existing reason, or passing a hashref will create
760 a new reason. The hashref should have the following keys: typenum - Reason
761 type (see L<FS::reason_type>, reason - Text of the new reason.
763 =item date - can be set to a unix style timestamp to specify when to
766 =item nobill - can be set true to skip billing if it might otherwise be done.
768 =item unused_credit - can be set to 1 to credit the remaining time, or 0 to
769 not credit it. This must be set (by change()) when changing the package
770 to a different pkgpart or location, and probably shouldn't be in any other
771 case. If it's not set, the 'unused_credit_cancel' part_pkg option will
776 If there is an error, returns the error, otherwise returns false.
781 my( $self, %options ) = @_;
784 # pass all suspend/cancel actions to the main package
785 if ( $self->main_pkgnum and !$options{'from_main'} ) {
786 return $self->main_pkg->cancel(%options);
789 my $conf = new FS::Conf;
791 warn "cust_pkg::cancel called with options".
792 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
795 local $SIG{HUP} = 'IGNORE';
796 local $SIG{INT} = 'IGNORE';
797 local $SIG{QUIT} = 'IGNORE';
798 local $SIG{TERM} = 'IGNORE';
799 local $SIG{TSTP} = 'IGNORE';
800 local $SIG{PIPE} = 'IGNORE';
802 my $oldAutoCommit = $FS::UID::AutoCommit;
803 local $FS::UID::AutoCommit = 0;
806 my $old = $self->select_for_update;
808 if ( $old->get('cancel') || $self->get('cancel') ) {
809 dbh->rollback if $oldAutoCommit;
810 return ""; # no error
813 # XXX possibly set cancel_time to the expire date?
814 my $cancel_time = $options{'time'} || time;
815 my $date = $options{'date'} if $options{'date'}; # expire/cancel later
816 $date = '' if ($date && $date <= $cancel_time); # complain instead?
818 #race condition: usage could be ongoing until unprovisioned
819 #resolved by performing a change package instead (which unprovisions) and
821 if ( !$options{nobill} && !$date ) {
822 # && $conf->exists('bill_usage_on_cancel') ) { #calc_cancel checks this
823 my $copy = $self->new({$self->hash});
825 $copy->cust_main->bill( 'pkg_list' => [ $copy ],
827 'time' => $cancel_time );
828 warn "Error billing during cancel, custnum ".
829 #$self->cust_main->custnum. ": $error"
834 if ( $options{'reason'} ) {
835 $error = $self->insert_reason( 'reason' => $options{'reason'},
836 'action' => $date ? 'expire' : 'cancel',
837 'date' => $date ? $date : $cancel_time,
838 'reason_otaker' => $options{'reason_otaker'},
841 dbh->rollback if $oldAutoCommit;
842 return "Error inserting cust_pkg_reason: $error";
846 my %svc_cancel_opt = ();
847 $svc_cancel_opt{'date'} = $date if $date;
848 foreach my $cust_svc (
851 sort { $a->[1] <=> $b->[1] }
852 map { [ $_, $_->svc_x ? $_->svc_x->table_info->{'cancel_weight'} : -1 ]; }
853 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
855 my $part_svc = $cust_svc->part_svc;
856 next if ( defined($part_svc) and $part_svc->preserve );
857 my $error = $cust_svc->cancel( %svc_cancel_opt );
860 $dbh->rollback if $oldAutoCommit;
861 return 'Error '. ($svc_cancel_opt{'date'} ? 'expiring' : 'canceling' ).
867 # credit remaining time if appropriate
869 if ( exists($options{'unused_credit'}) ) {
870 $do_credit = $options{'unused_credit'};
873 $do_credit = $self->part_pkg->option('unused_credit_cancel', 1);
876 my $error = $self->credit_remaining('cancel', $cancel_time);
878 $dbh->rollback if $oldAutoCommit;
885 my %hash = $self->hash;
887 $hash{'expire'} = $date;
889 $hash{'cancel'} = $cancel_time;
891 $hash{'change_custnum'} = $options{'change_custnum'};
893 my $new = new FS::cust_pkg ( \%hash );
894 $error = $new->replace( $self, options => { $self->options } );
895 if ( $self->change_to_pkgnum ) {
896 my $change_to = FS::cust_pkg->by_key($self->change_to_pkgnum);
897 $error ||= $change_to->cancel || $change_to->delete;
900 $dbh->rollback if $oldAutoCommit;
904 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
905 $error = $supp_pkg->cancel(%options, 'from_main' => 1);
907 $dbh->rollback if $oldAutoCommit;
908 return "canceling supplemental pkg#".$supp_pkg->pkgnum.": $error";
912 foreach my $usage ( $self->cust_pkg_usage ) {
913 $error = $usage->delete;
915 $dbh->rollback if $oldAutoCommit;
916 return "deleting usage pools: $error";
920 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
921 return '' if $date; #no errors
923 my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ } $self->cust_main->invoicing_list;
924 if ( !$options{'quiet'} &&
925 $conf->exists('emailcancel', $self->cust_main->agentnum) &&
927 my $msgnum = $conf->config('cancel_msgnum', $self->cust_main->agentnum);
930 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum });
931 $error = $msg_template->send( 'cust_main' => $self->cust_main,
936 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
937 'to' => \@invoicing_list,
938 'subject' => ( $conf->config('cancelsubject') || 'Cancellation Notice' ),
939 'body' => [ map "$_\n", $conf->config('cancelmessage') ],
940 'custnum' => $self->custnum,
941 'msgtype' => '', #admin?
944 #should this do something on errors?
951 =item cancel_if_expired [ NOW_TIMESTAMP ]
953 Cancels this package if its expire date has been reached.
957 sub cancel_if_expired {
959 my $time = shift || time;
960 return '' unless $self->expire && $self->expire <= $time;
961 my $error = $self->cancel;
963 return "Error cancelling expired pkg ". $self->pkgnum. " for custnum ".
964 $self->custnum. ": $error";
971 "Un-cancels" this package: Orders a new package with the same custnum, pkgpart,
972 locationnum, (other fields?). Attempts to re-provision cancelled services
973 using history information (errors at this stage are not fatal).
975 cust_pkg: pass a scalar reference, will be filled in with the new cust_pkg object
977 svc_fatal: service provisioning errors are fatal
979 svc_errors: pass an array reference, will be filled in with any provisioning errors
981 main_pkgnum: link the package as a supplemental package of this one. For
987 my( $self, %options ) = @_;
989 #in case you try do do $uncancel-date = $cust_pkg->uncacel
990 return '' unless $self->get('cancel');
992 if ( $self->main_pkgnum and !$options{'main_pkgnum'} ) {
993 return $self->main_pkg->uncancel(%options);
1000 local $SIG{HUP} = 'IGNORE';
1001 local $SIG{INT} = 'IGNORE';
1002 local $SIG{QUIT} = 'IGNORE';
1003 local $SIG{TERM} = 'IGNORE';
1004 local $SIG{TSTP} = 'IGNORE';
1005 local $SIG{PIPE} = 'IGNORE';
1007 my $oldAutoCommit = $FS::UID::AutoCommit;
1008 local $FS::UID::AutoCommit = 0;
1012 # insert the new package
1015 my $cust_pkg = new FS::cust_pkg {
1016 last_bill => ( $options{'last_bill'} || $self->get('last_bill') ),
1017 bill => ( $options{'bill'} || $self->get('bill') ),
1019 uncancel_pkgnum => $self->pkgnum,
1020 main_pkgnum => ($options{'main_pkgnum'} || ''),
1021 map { $_ => $self->get($_) } qw(
1022 custnum pkgpart locationnum
1024 susp adjourn resume expire start_date contract_end dundate
1025 change_date change_pkgpart change_locationnum
1026 manual_flag no_auto quantity agent_pkgid recur_show_zero setup_show_zero
1030 my $error = $cust_pkg->insert(
1031 'change' => 1, #supresses any referral credit to a referring customer
1032 'allow_pkgpart' => 1, # allow this even if the package def is disabled
1035 $dbh->rollback if $oldAutoCommit;
1043 #find historical services within this timeframe before the package cancel
1044 # (incompatible with "time" option to cust_pkg->cancel?)
1045 my $fuzz = 2 * 60; #2 minutes? too much? (might catch separate unprovision)
1046 # too little? (unprovisioing export delay?)
1047 my($end, $start) = ( $self->get('cancel'), $self->get('cancel') - $fuzz );
1048 my @h_cust_svc = $self->h_cust_svc( $end, $start );
1051 foreach my $h_cust_svc (@h_cust_svc) {
1052 my $h_svc_x = $h_cust_svc->h_svc_x( $end, $start );
1053 #next unless $h_svc_x; #should this happen?
1054 (my $table = $h_svc_x->table) =~ s/^h_//;
1055 require "FS/$table.pm";
1056 my $class = "FS::$table";
1057 my $svc_x = $class->new( {
1058 'pkgnum' => $cust_pkg->pkgnum,
1059 'svcpart' => $h_cust_svc->svcpart,
1060 map { $_ => $h_svc_x->get($_) } fields($table)
1064 if ( $h_svc_x->isa('FS::h_svc_Radius_Mixin') ) {
1065 $svc_x->usergroup( [ $h_svc_x->h_usergroup($end, $start) ] );
1068 my $svc_error = $svc_x->insert;
1070 if ( $options{svc_fatal} ) {
1071 $dbh->rollback if $oldAutoCommit;
1074 # if we've failed to insert the svc_x object, svc_Common->insert
1075 # will have removed the cust_svc already. if not, then both records
1076 # were inserted but we failed for some other reason (export, most
1077 # likely). in that case, report the error and delete the records.
1078 push @svc_errors, $svc_error;
1079 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svc_x->svcnum });
1081 # except if export_insert failed, export_delete probably won't be
1083 local $FS::svc_Common::noexport_hack = 1;
1084 my $cleanup_error = $svc_x->delete; # also deletes cust_svc
1085 if ( $cleanup_error ) { # and if THAT fails, then run away
1086 $dbh->rollback if $oldAutoCommit;
1087 return $cleanup_error;
1092 } #foreach $h_cust_svc
1094 #these are pretty rare, but should handle them
1095 # - dsl_device (mac addresses)
1096 # - phone_device (mac addresses)
1097 # - dsl_note (ikano notes)
1098 # - domain_record (i.e. restore DNS information w/domains)
1099 # - inventory_item(?) (inventory w/un-cancelling service?)
1100 # - nas (svc_broaband nas stuff)
1101 #this stuff is unused in the wild afaik
1102 # - mailinglistmember
1104 # - svc_domain.parent_svcnum?
1105 # - acct_snarf (ancient mail fetching config)
1106 # - cgp_rule (communigate)
1107 # - cust_svc_option (used by our Tron stuff)
1108 # - acct_rt_transaction (used by our time worked stuff)
1111 # also move over any services that didn't unprovision at cancellation
1114 foreach my $cust_svc ( qsearch('cust_svc', { pkgnum => $self->pkgnum } ) ) {
1115 $cust_svc->pkgnum( $cust_pkg->pkgnum );
1116 my $error = $cust_svc->replace;
1118 $dbh->rollback if $oldAutoCommit;
1124 # Uncancel any supplemental packages, and make them supplemental to the
1128 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1130 $error = $supp_pkg->uncancel(%options, 'main_pkgnum' => $cust_pkg->pkgnum);
1132 $dbh->rollback if $oldAutoCommit;
1133 return "canceling supplemental pkg#".$supp_pkg->pkgnum.": $error";
1141 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1143 ${ $options{cust_pkg} } = $cust_pkg if ref($options{cust_pkg});
1144 @{ $options{svc_errors} } = @svc_errors if ref($options{svc_errors});
1151 Cancels any pending expiration (sets the expire field to null).
1153 If there is an error, returns the error, otherwise returns false.
1158 my( $self, %options ) = @_;
1161 local $SIG{HUP} = 'IGNORE';
1162 local $SIG{INT} = 'IGNORE';
1163 local $SIG{QUIT} = 'IGNORE';
1164 local $SIG{TERM} = 'IGNORE';
1165 local $SIG{TSTP} = 'IGNORE';
1166 local $SIG{PIPE} = 'IGNORE';
1168 my $oldAutoCommit = $FS::UID::AutoCommit;
1169 local $FS::UID::AutoCommit = 0;
1172 my $old = $self->select_for_update;
1174 my $pkgnum = $old->pkgnum;
1175 if ( $old->get('cancel') || $self->get('cancel') ) {
1176 dbh->rollback if $oldAutoCommit;
1177 return "Can't unexpire cancelled package $pkgnum";
1178 # or at least it's pointless
1181 unless ( $old->get('expire') && $self->get('expire') ) {
1182 dbh->rollback if $oldAutoCommit;
1183 return ""; # no error
1186 my %hash = $self->hash;
1187 $hash{'expire'} = '';
1188 my $new = new FS::cust_pkg ( \%hash );
1189 $error = $new->replace( $self, options => { $self->options } );
1191 $dbh->rollback if $oldAutoCommit;
1195 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1201 =item suspend [ OPTION => VALUE ... ]
1203 Suspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
1204 package, then suspends the package itself (sets the susp field to now).
1206 Available options are:
1210 =item reason - can be set to a cancellation reason (see L<FS:reason>),
1211 either a reasonnum of an existing reason, or passing a hashref will create
1212 a new reason. The hashref should have the following keys:
1213 - typenum - Reason type (see L<FS::reason_type>
1214 - reason - Text of the new reason.
1216 =item date - can be set to a unix style timestamp to specify when to
1219 =item time - can be set to override the current time, for calculation
1220 of final invoices or unused-time credits
1222 =item resume_date - can be set to a time when the package should be
1223 unsuspended. This may be more convenient than calling C<unsuspend()>
1226 =item from_main - allows a supplemental package to be suspended, rather
1227 than redirecting the method call to its main package. For internal use.
1231 If there is an error, returns the error, otherwise returns false.
1236 my( $self, %options ) = @_;
1239 # pass all suspend/cancel actions to the main package
1240 if ( $self->main_pkgnum and !$options{'from_main'} ) {
1241 return $self->main_pkg->suspend(%options);
1244 local $SIG{HUP} = 'IGNORE';
1245 local $SIG{INT} = 'IGNORE';
1246 local $SIG{QUIT} = 'IGNORE';
1247 local $SIG{TERM} = 'IGNORE';
1248 local $SIG{TSTP} = 'IGNORE';
1249 local $SIG{PIPE} = 'IGNORE';
1251 my $oldAutoCommit = $FS::UID::AutoCommit;
1252 local $FS::UID::AutoCommit = 0;
1255 my $old = $self->select_for_update;
1257 my $pkgnum = $old->pkgnum;
1258 if ( $old->get('cancel') || $self->get('cancel') ) {
1259 dbh->rollback if $oldAutoCommit;
1260 return "Can't suspend cancelled package $pkgnum";
1263 if ( $old->get('susp') || $self->get('susp') ) {
1264 dbh->rollback if $oldAutoCommit;
1265 return ""; # no error # complain on adjourn?
1268 my $suspend_time = $options{'time'} || time;
1269 my $date = $options{date} if $options{date}; # adjourn/suspend later
1270 $date = '' if ($date && $date <= $suspend_time); # complain instead?
1272 if ( $date && $old->get('expire') && $old->get('expire') < $date ) {
1273 dbh->rollback if $oldAutoCommit;
1274 return "Package $pkgnum expires before it would be suspended.";
1277 # some false laziness with sub cancel
1278 if ( !$options{nobill} && !$date &&
1279 $self->part_pkg->option('bill_suspend_as_cancel',1) ) {
1280 # kind of a kludge--'bill_suspend_as_cancel' to avoid having to
1281 # make the entire cust_main->bill path recognize 'suspend' and
1282 # 'cancel' separately.
1283 warn "Billing $pkgnum on suspension (at $suspend_time)\n" if $DEBUG;
1284 my $copy = $self->new({$self->hash});
1286 $copy->cust_main->bill( 'pkg_list' => [ $copy ],
1288 'time' => $suspend_time );
1289 warn "Error billing during suspend, custnum ".
1290 #$self->cust_main->custnum. ": $error"
1295 if ( $options{'reason'} ) {
1296 $error = $self->insert_reason( 'reason' => $options{'reason'},
1297 'action' => $date ? 'adjourn' : 'suspend',
1298 'date' => $date ? $date : $suspend_time,
1299 'reason_otaker' => $options{'reason_otaker'},
1302 dbh->rollback if $oldAutoCommit;
1303 return "Error inserting cust_pkg_reason: $error";
1307 my %hash = $self->hash;
1309 $hash{'adjourn'} = $date;
1311 $hash{'susp'} = $suspend_time;
1314 my $resume_date = $options{'resume_date'} || 0;
1315 if ( $resume_date > ($date || $suspend_time) ) {
1316 $hash{'resume'} = $resume_date;
1319 $options{options} ||= {};
1321 my $new = new FS::cust_pkg ( \%hash );
1322 $error = $new->replace( $self, options => { $self->options,
1323 %{ $options{options} },
1327 $dbh->rollback if $oldAutoCommit;
1332 # credit remaining time if appropriate
1333 if ( $self->part_pkg->option('unused_credit_suspend', 1) ) {
1334 my $error = $self->credit_remaining('suspend', $suspend_time);
1336 $dbh->rollback if $oldAutoCommit;
1343 foreach my $cust_svc (
1344 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
1346 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
1348 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
1349 $dbh->rollback if $oldAutoCommit;
1350 return "Illegal svcdb value in part_svc!";
1353 require "FS/$svcdb.pm";
1355 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
1357 $error = $svc->suspend;
1359 $dbh->rollback if $oldAutoCommit;
1362 my( $label, $value ) = $cust_svc->label;
1363 push @labels, "$label: $value";
1367 my $conf = new FS::Conf;
1368 if ( $conf->config('suspend_email_admin') ) {
1370 my $error = send_email(
1371 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
1372 #invoice_from ??? well as good as any
1373 'to' => $conf->config('suspend_email_admin'),
1374 'subject' => 'FREESIDE NOTIFICATION: Customer package suspended',
1376 "This is an automatic message from your Freeside installation\n",
1377 "informing you that the following customer package has been suspended:\n",
1379 'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
1380 'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
1381 ( map { "Service : $_\n" } @labels ),
1383 'custnum' => $self->custnum,
1384 'msgtype' => 'admin'
1388 warn "WARNING: can't send suspension admin email (suspending anyway): ".
1396 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1397 $error = $supp_pkg->suspend(%options, 'from_main' => 1);
1399 $dbh->rollback if $oldAutoCommit;
1400 return "suspending supplemental pkg#".$supp_pkg->pkgnum.": $error";
1404 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1409 =item credit_remaining MODE TIME
1411 Generate a credit for this package for the time remaining in the current
1412 billing period. MODE is either "suspend" or "cancel" (determines the
1413 credit type). TIME is the time of suspension/cancellation. Both arguments
1418 sub credit_remaining {
1419 # Add a credit for remaining service
1420 my ($self, $mode, $time) = @_;
1421 die 'credit_remaining requires suspend or cancel'
1422 unless $mode eq 'suspend' or $mode eq 'cancel';
1423 die 'no suspend/cancel time' unless $time > 0;
1425 my $conf = FS::Conf->new;
1426 my $reason_type = $conf->config($mode.'_credit_type');
1428 my $last_bill = $self->getfield('last_bill') || 0;
1429 my $next_bill = $self->getfield('bill') || 0;
1430 if ( $last_bill > 0 # the package has been billed
1431 and $next_bill > 0 # the package has a next bill date
1432 and $next_bill >= $time # which is in the future
1434 my $remaining_value = $self->calc_remain('time' => $time);
1435 if ( $remaining_value > 0 ) {
1436 warn "Crediting for $remaining_value on package ".$self->pkgnum."\n"
1438 my $error = $self->cust_main->credit(
1440 'Credit for unused time on '. $self->part_pkg->pkg,
1441 'reason_type' => $reason_type,
1443 return "Error crediting customer \$$remaining_value for unused time".
1444 " on ". $self->part_pkg->pkg. ": $error"
1446 } #if $remaining_value
1447 } #if $last_bill, etc.
1451 =item unsuspend [ OPTION => VALUE ... ]
1453 Unsuspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
1454 package, then unsuspends the package itself (clears the susp field and the
1455 adjourn field if it is in the past). If the suspend reason includes an
1456 unsuspension package, that package will be ordered.
1458 Available options are:
1464 Can be set to a date to unsuspend the package in the future (the 'resume'
1467 =item adjust_next_bill
1469 Can be set true to adjust the next bill date forward by
1470 the amount of time the account was inactive. This was set true by default
1471 in the past (from 1.4.2 and 1.5.0pre6 through 1.7.0), but now needs to be
1472 explicitly requested with this option or in the price plan.
1476 If there is an error, returns the error, otherwise returns false.
1481 my( $self, %opt ) = @_;
1484 # pass all suspend/cancel actions to the main package
1485 if ( $self->main_pkgnum and !$opt{'from_main'} ) {
1486 return $self->main_pkg->unsuspend(%opt);
1489 local $SIG{HUP} = 'IGNORE';
1490 local $SIG{INT} = 'IGNORE';
1491 local $SIG{QUIT} = 'IGNORE';
1492 local $SIG{TERM} = 'IGNORE';
1493 local $SIG{TSTP} = 'IGNORE';
1494 local $SIG{PIPE} = 'IGNORE';
1496 my $oldAutoCommit = $FS::UID::AutoCommit;
1497 local $FS::UID::AutoCommit = 0;
1500 my $old = $self->select_for_update;
1502 my $pkgnum = $old->pkgnum;
1503 if ( $old->get('cancel') || $self->get('cancel') ) {
1504 $dbh->rollback if $oldAutoCommit;
1505 return "Can't unsuspend cancelled package $pkgnum";
1508 unless ( $old->get('susp') && $self->get('susp') ) {
1509 $dbh->rollback if $oldAutoCommit;
1510 return ""; # no error # complain instead?
1513 my $date = $opt{'date'};
1514 if ( $date and $date > time ) { # return an error if $date <= time?
1516 if ( $old->get('expire') && $old->get('expire') < $date ) {
1517 $dbh->rollback if $oldAutoCommit;
1518 return "Package $pkgnum expires before it would be unsuspended.";
1521 my $new = new FS::cust_pkg { $self->hash };
1522 $new->set('resume', $date);
1523 $error = $new->replace($self, options => $self->options);
1526 $dbh->rollback if $oldAutoCommit;
1530 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1538 foreach my $cust_svc (
1539 qsearch('cust_svc',{'pkgnum'=> $self->pkgnum } )
1541 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
1543 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
1544 $dbh->rollback if $oldAutoCommit;
1545 return "Illegal svcdb value in part_svc!";
1548 require "FS/$svcdb.pm";
1550 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
1552 $error = $svc->unsuspend;
1554 $dbh->rollback if $oldAutoCommit;
1557 my( $label, $value ) = $cust_svc->label;
1558 push @labels, "$label: $value";
1563 my $cust_pkg_reason = $self->last_cust_pkg_reason('susp');
1564 my $reason = $cust_pkg_reason ? $cust_pkg_reason->reason : '';
1566 my %hash = $self->hash;
1567 my $inactive = time - $hash{'susp'};
1569 my $conf = new FS::Conf;
1571 $hash{'bill'} = ( $hash{'bill'} || $hash{'setup'} ) + $inactive
1573 && ( $hash{'bill'} || $hash{'setup'} )
1574 && ( $opt{'adjust_next_bill'}
1575 || $conf->exists('unsuspend-always_adjust_next_bill_date')
1576 || $self->part_pkg->option('unsuspend_adjust_bill', 1)
1578 && ! $self->option('suspend_bill',1)
1579 && ( ! $self->part_pkg->option('suspend_bill',1)
1580 || $self->option('no_suspend_bill',1)
1582 && $hash{'order_date'} != $hash{'susp'}
1586 $hash{'adjourn'} = '' if $hash{'adjourn'} and $hash{'adjourn'} < time;
1587 $hash{'resume'} = '' if !$hash{'adjourn'};
1588 my $new = new FS::cust_pkg ( \%hash );
1589 $error = $new->replace( $self, options => { $self->options } );
1591 $dbh->rollback if $oldAutoCommit;
1597 if ( $reason && $reason->unsuspend_pkgpart ) {
1598 my $part_pkg = FS::part_pkg->by_key($reason->unsuspend_pkgpart)
1599 or $error = "Unsuspend package definition ".$reason->unsuspend_pkgpart.
1601 my $start_date = $self->cust_main->next_bill_date
1602 if $reason->unsuspend_hold;
1605 $unsusp_pkg = FS::cust_pkg->new({
1606 'custnum' => $self->custnum,
1607 'pkgpart' => $reason->unsuspend_pkgpart,
1608 'start_date' => $start_date,
1609 'locationnum' => $self->locationnum,
1610 # discount? probably not...
1613 $error ||= $self->cust_main->order_pkg( 'cust_pkg' => $unsusp_pkg );
1617 $dbh->rollback if $oldAutoCommit;
1622 if ( $conf->config('unsuspend_email_admin') ) {
1624 my $error = send_email(
1625 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
1626 #invoice_from ??? well as good as any
1627 'to' => $conf->config('unsuspend_email_admin'),
1628 'subject' => 'FREESIDE NOTIFICATION: Customer package unsuspended', 'body' => [
1629 "This is an automatic message from your Freeside installation\n",
1630 "informing you that the following customer package has been unsuspended:\n",
1632 'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
1633 'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
1634 ( map { "Service : $_\n" } @labels ),
1636 "An unsuspension fee was charged: ".
1637 $unsusp_pkg->part_pkg->pkg_comment."\n"
1641 'custnum' => $self->custnum,
1642 'msgtype' => 'admin',
1646 warn "WARNING: can't send unsuspension admin email (unsuspending anyway): ".
1652 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1653 $error = $supp_pkg->unsuspend(%opt, 'from_main' => 1);
1655 $dbh->rollback if $oldAutoCommit;
1656 return "unsuspending supplemental pkg#".$supp_pkg->pkgnum.": $error";
1660 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1667 Cancels any pending suspension (sets the adjourn field to null).
1669 If there is an error, returns the error, otherwise returns false.
1674 my( $self, %options ) = @_;
1677 local $SIG{HUP} = 'IGNORE';
1678 local $SIG{INT} = 'IGNORE';
1679 local $SIG{QUIT} = 'IGNORE';
1680 local $SIG{TERM} = 'IGNORE';
1681 local $SIG{TSTP} = 'IGNORE';
1682 local $SIG{PIPE} = 'IGNORE';
1684 my $oldAutoCommit = $FS::UID::AutoCommit;
1685 local $FS::UID::AutoCommit = 0;
1688 my $old = $self->select_for_update;
1690 my $pkgnum = $old->pkgnum;
1691 if ( $old->get('cancel') || $self->get('cancel') ) {
1692 dbh->rollback if $oldAutoCommit;
1693 return "Can't unadjourn cancelled package $pkgnum";
1694 # or at least it's pointless
1697 if ( $old->get('susp') || $self->get('susp') ) {
1698 dbh->rollback if $oldAutoCommit;
1699 return "Can't unadjourn suspended package $pkgnum";
1700 # perhaps this is arbitrary
1703 unless ( $old->get('adjourn') && $self->get('adjourn') ) {
1704 dbh->rollback if $oldAutoCommit;
1705 return ""; # no error
1708 my %hash = $self->hash;
1709 $hash{'adjourn'} = '';
1710 $hash{'resume'} = '';
1711 my $new = new FS::cust_pkg ( \%hash );
1712 $error = $new->replace( $self, options => { $self->options } );
1714 $dbh->rollback if $oldAutoCommit;
1718 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1725 =item change HASHREF | OPTION => VALUE ...
1727 Changes this package: cancels it and creates a new one, with a different
1728 pkgpart or locationnum or both. All services are transferred to the new
1729 package (no change will be made if this is not possible).
1731 Options may be passed as a list of key/value pairs or as a hash reference.
1738 New locationnum, to change the location for this package.
1742 New FS::cust_location object, to create a new location and assign it
1747 New FS::cust_main object, to create a new customer and assign the new package
1752 New pkgpart (see L<FS::part_pkg>).
1756 New refnum (see L<FS::part_referral>).
1760 New quantity; if unspecified, the new package will have the same quantity
1765 "New" (existing) FS::cust_pkg object. The package's services and other
1766 attributes will be transferred to this package.
1770 Set to true to transfer billing dates (start_date, setup, last_bill, bill,
1771 susp, adjourn, cancel, expire, and contract_end) to the new package.
1773 =item unprotect_svcs
1775 Normally, change() will rollback and return an error if some services
1776 can't be transferred (also see the I<cust_pkg-change_svcpart> config option).
1777 If unprotect_svcs is true, this method will transfer as many services as
1778 it can and then unconditionally cancel the old package.
1782 At least one of locationnum, cust_location, pkgpart, refnum, cust_main, or
1783 cust_pkg must be specified (otherwise, what's the point?)
1785 Returns either the new FS::cust_pkg object or a scalar error.
1789 my $err_or_new_cust_pkg = $old_cust_pkg->change
1793 #some false laziness w/order
1796 my $opt = ref($_[0]) ? shift : { @_ };
1798 my $conf = new FS::Conf;
1800 # Transactionize this whole mess
1801 local $SIG{HUP} = 'IGNORE';
1802 local $SIG{INT} = 'IGNORE';
1803 local $SIG{QUIT} = 'IGNORE';
1804 local $SIG{TERM} = 'IGNORE';
1805 local $SIG{TSTP} = 'IGNORE';
1806 local $SIG{PIPE} = 'IGNORE';
1808 my $oldAutoCommit = $FS::UID::AutoCommit;
1809 local $FS::UID::AutoCommit = 0;
1818 $hash{'setup'} = $time if $self->setup;
1820 $hash{'change_date'} = $time;
1821 $hash{"change_$_"} = $self->$_()
1822 foreach qw( pkgnum pkgpart locationnum );
1824 if ( $opt->{'cust_location'} ) {
1825 $error = $opt->{'cust_location'}->find_or_insert;
1827 $dbh->rollback if $oldAutoCommit;
1828 return "creating location record: $error";
1830 $opt->{'locationnum'} = $opt->{'cust_location'}->locationnum;
1833 if ( $opt->{'cust_pkg'} ) {
1834 # treat changing to a package with a different pkgpart as a
1835 # pkgpart change (because it is)
1836 $opt->{'pkgpart'} = $opt->{'cust_pkg'}->pkgpart;
1839 # whether to override pkgpart checking on the new package
1840 my $same_pkgpart = 1;
1841 if ( $opt->{'pkgpart'} and ( $opt->{'pkgpart'} != $self->pkgpart ) ) {
1845 my $unused_credit = 0;
1846 my $keep_dates = $opt->{'keep_dates'};
1847 # Special case. If the pkgpart is changing, and the customer is
1848 # going to be credited for remaining time, don't keep setup, bill,
1849 # or last_bill dates, and DO pass the flag to cancel() to credit
1851 if ( $opt->{'pkgpart'}
1852 and $opt->{'pkgpart'} != $self->pkgpart
1853 and $self->part_pkg->option('unused_credit_change', 1) ) {
1856 $hash{$_} = '' foreach qw(setup bill last_bill);
1859 if ( $keep_dates ) {
1860 foreach my $date ( qw(setup bill last_bill susp adjourn cancel expire
1861 resume start_date contract_end ) ) {
1862 $hash{$date} = $self->getfield($date);
1865 # always keep this date, regardless of anything
1866 # (the date of the package change is in a different field)
1867 $hash{'order_date'} = $self->getfield('order_date');
1869 # allow $opt->{'locationnum'} = '' to specifically set it to null
1870 # (i.e. customer default location)
1871 $opt->{'locationnum'} = $self->locationnum if !exists($opt->{'locationnum'});
1873 # usually this doesn't matter. the two cases where it does are:
1874 # 1. unused_credit_change + pkgpart change + setup fee on the new package
1876 # 2. (more importantly) changing a package before it's billed
1877 $hash{'waive_setup'} = $self->waive_setup;
1879 my $custnum = $self->custnum;
1880 if ( $opt->{cust_main} ) {
1881 my $cust_main = $opt->{cust_main};
1882 unless ( $cust_main->custnum ) {
1883 my $error = $cust_main->insert( @{ $opt->{cust_main_insert_args}||[] } );
1885 $dbh->rollback if $oldAutoCommit;
1886 return "inserting customer record: $error";
1889 $custnum = $cust_main->custnum;
1892 $hash{'contactnum'} = $opt->{'contactnum'} if $opt->{'contactnum'};
1895 if ( $opt->{'cust_pkg'} ) {
1896 # The target package already exists; update it to show that it was
1897 # changed from this package.
1898 $cust_pkg = $opt->{'cust_pkg'};
1900 foreach ( qw( pkgnum pkgpart locationnum ) ) {
1901 $cust_pkg->set("change_$_", $self->get($_));
1903 $cust_pkg->set('change_date', $time);
1904 $error = $cust_pkg->replace;
1907 # Create the new package.
1908 $cust_pkg = new FS::cust_pkg {
1909 custnum => $custnum,
1910 locationnum => $opt->{'locationnum'},
1911 ( map { $_ => ( $opt->{$_} || $self->$_() ) }
1912 qw( pkgpart quantity refnum salesnum )
1916 $error = $cust_pkg->insert( 'change' => 1,
1917 'allow_pkgpart' => $same_pkgpart );
1920 $dbh->rollback if $oldAutoCommit;
1921 return "inserting new package: $error";
1924 # Transfer services and cancel old package.
1926 $error = $self->transfer($cust_pkg);
1927 if ($error and $error == 0) {
1928 # $old_pkg->transfer failed.
1929 $dbh->rollback if $oldAutoCommit;
1930 return "transferring $error";
1933 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
1934 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
1935 $error = $self->transfer($cust_pkg, 'change_svcpart'=>1 );
1936 if ($error and $error == 0) {
1937 # $old_pkg->transfer failed.
1938 $dbh->rollback if $oldAutoCommit;
1939 return "converting $error";
1943 # We set unprotect_svcs when executing a "future package change". It's
1944 # not a user-interactive operation, so returning an error means the
1945 # package change will just fail. Rather than have that happen, we'll
1946 # let leftover services be deleted.
1947 if ($error > 0 and !$opt->{'unprotect_svcs'}) {
1948 # Transfers were successful, but we still had services left on the old
1949 # package. We can't change the package under this circumstances, so abort.
1950 $dbh->rollback if $oldAutoCommit;
1951 return "unable to transfer all services";
1954 #reset usage if changing pkgpart
1955 # AND usage rollover is off (otherwise adds twice, now and at package bill)
1956 if ($self->pkgpart != $cust_pkg->pkgpart) {
1957 my $part_pkg = $cust_pkg->part_pkg;
1958 $error = $part_pkg->reset_usage($cust_pkg, $part_pkg->is_prepaid
1962 if $part_pkg->can('reset_usage') && ! $part_pkg->option('usage_rollover',1);
1965 $dbh->rollback if $oldAutoCommit;
1966 return "setting usage values: $error";
1969 # if NOT changing pkgpart, transfer any usage pools over
1970 foreach my $usage ($self->cust_pkg_usage) {
1971 $usage->set('pkgnum', $cust_pkg->pkgnum);
1972 $error = $usage->replace;
1974 $dbh->rollback if $oldAutoCommit;
1975 return "transferring usage pools: $error";
1980 # transfer discounts, if we're not changing pkgpart
1981 if ( $same_pkgpart ) {
1982 foreach my $old_discount ($self->cust_pkg_discount_active) {
1983 # don't remove the old discount, we may still need to bill that package.
1984 my $new_discount = new FS::cust_pkg_discount {
1985 'pkgnum' => $cust_pkg->pkgnum,
1986 'discountnum' => $old_discount->discountnum,
1987 'months_used' => $old_discount->months_used,
1989 $error = $new_discount->insert;
1991 $dbh->rollback if $oldAutoCommit;
1992 return "transferring discounts: $error";
1997 # transfer (copy) invoice details
1998 foreach my $detail ($self->cust_pkg_detail) {
1999 my $new_detail = FS::cust_pkg_detail->new({ $detail->hash });
2000 $new_detail->set('pkgdetailnum', '');
2001 $new_detail->set('pkgnum', $cust_pkg->pkgnum);
2002 $error = $new_detail->insert;
2004 $dbh->rollback if $oldAutoCommit;
2005 return "transferring package notes: $error";
2011 if ( !$opt->{'cust_pkg'} ) {
2012 # Order any supplemental packages.
2013 my $part_pkg = $cust_pkg->part_pkg;
2014 my @old_supp_pkgs = $self->supplemental_pkgs;
2015 foreach my $link ($part_pkg->supp_part_pkg_link) {
2017 foreach (@old_supp_pkgs) {
2018 if ($_->pkgpart == $link->dst_pkgpart) {
2020 $_->pkgpart(0); # so that it can't match more than once
2024 # false laziness with FS::cust_main::Packages::order_pkg
2025 my $new = FS::cust_pkg->new({
2026 pkgpart => $link->dst_pkgpart,
2027 pkglinknum => $link->pkglinknum,
2028 custnum => $custnum,
2029 main_pkgnum => $cust_pkg->pkgnum,
2030 locationnum => $cust_pkg->locationnum,
2031 start_date => $cust_pkg->start_date,
2032 order_date => $cust_pkg->order_date,
2033 expire => $cust_pkg->expire,
2034 adjourn => $cust_pkg->adjourn,
2035 contract_end => $cust_pkg->contract_end,
2036 refnum => $cust_pkg->refnum,
2037 discountnum => $cust_pkg->discountnum,
2038 waive_setup => $cust_pkg->waive_setup,
2040 if ( $old and $opt->{'keep_dates'} ) {
2041 foreach (qw(setup bill last_bill)) {
2042 $new->set($_, $old->get($_));
2045 $error = $new->insert( allow_pkgpart => $same_pkgpart );
2048 $error ||= $old->transfer($new);
2050 if ( $error and $error > 0 ) {
2051 # no reason why this should ever fail, but still...
2052 $error = "Unable to transfer all services from supplemental package ".
2056 $dbh->rollback if $oldAutoCommit;
2059 push @new_supp_pkgs, $new;
2061 } # if !$opt->{'cust_pkg'}
2062 # because if there is one, then supplemental packages would already
2063 # have been created for it.
2065 #Good to go, cancel old package. Notify 'cancel' of whether to credit
2067 #Don't allow billing the package (preceding period packages and/or
2068 #outstanding usage) if we are keeping dates (i.e. location changing),
2069 #because the new package will be billed for the same date range.
2070 #Supplemental packages are also canceled here.
2072 # during scheduled changes, avoid canceling the package we just
2074 $self->set('change_to_pkgnum' => '');
2076 $error = $self->cancel(
2078 unused_credit => $unused_credit,
2079 nobill => $keep_dates,
2080 change_custnum => ( $self->custnum != $custnum ? $custnum : '' ),
2083 $dbh->rollback if $oldAutoCommit;
2084 return "canceling old package: $error";
2087 if ( $conf->exists('cust_pkg-change_pkgpart-bill_now') ) {
2089 my $error = $cust_pkg->cust_main->bill(
2090 'pkg_list' => [ $cust_pkg, @new_supp_pkgs ]
2093 $dbh->rollback if $oldAutoCommit;
2094 return "billing new package: $error";
2098 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2104 =item change_later OPTION => VALUE...
2106 Schedule a package change for a later date. This actually orders the new
2107 package immediately, but sets its start date for a future date, and sets
2108 the current package to expire on the same date.
2110 If the package is already scheduled for a change, this can be called with
2111 'start_date' to change the scheduled date, or with pkgpart and/or
2112 locationnum to modify the package change. To cancel the scheduled change
2113 entirely, see C<abort_change>.
2121 The date for the package change. Required, and must be in the future.
2129 The pkgpart. locationnum, and quantity of the new package, with the same
2130 meaning as in C<change>.
2138 my $opt = ref($_[0]) ? shift : { @_ };
2140 my $oldAutoCommit = $FS::UID::AutoCommit;
2141 local $FS::UID::AutoCommit = 0;
2144 my $cust_main = $self->cust_main;
2146 my $date = delete $opt->{'start_date'} or return 'start_date required';
2148 if ( $date <= time ) {
2149 $dbh->rollback if $oldAutoCommit;
2150 return "start_date $date is in the past";
2155 if ( $self->change_to_pkgnum ) {
2156 my $change_to = FS::cust_pkg->by_key($self->change_to_pkgnum);
2157 my $new_pkgpart = $opt->{'pkgpart'}
2158 if $opt->{'pkgpart'} and $opt->{'pkgpart'} != $change_to->pkgpart;
2159 my $new_locationnum = $opt->{'locationnum'}
2160 if $opt->{'locationnum'} and $opt->{'locationnum'} != $change_to->locationnum;
2161 my $new_quantity = $opt->{'quantity'}
2162 if $opt->{'quantity'} and $opt->{'quantity'} != $change_to->quantity;
2163 if ( $new_pkgpart or $new_locationnum or $new_quantity ) {
2164 # it hasn't been billed yet, so in principle we could just edit
2165 # it in place (w/o a package change), but that's bad form.
2166 # So change the package according to the new options...
2167 my $err_or_pkg = $change_to->change(%$opt);
2168 if ( ref $err_or_pkg ) {
2169 # Then set that package up for a future start.
2170 $self->set('change_to_pkgnum', $err_or_pkg->pkgnum);
2171 $self->set('expire', $date); # in case it's different
2172 $err_or_pkg->set('start_date', $date);
2173 $err_or_pkg->set('change_date', '');
2174 $err_or_pkg->set('change_pkgnum', '');
2176 $error = $self->replace ||
2177 $err_or_pkg->replace ||
2178 $change_to->cancel ||
2181 $error = $err_or_pkg;
2183 } else { # change the start date only.
2184 $self->set('expire', $date);
2185 $change_to->set('start_date', $date);
2186 $error = $self->replace || $change_to->replace;
2189 $dbh->rollback if $oldAutoCommit;
2192 $dbh->commit if $oldAutoCommit;
2195 } # if $self->change_to_pkgnum
2197 my $new_pkgpart = $opt->{'pkgpart'}
2198 if $opt->{'pkgpart'} and $opt->{'pkgpart'} != $self->pkgpart;
2199 my $new_locationnum = $opt->{'locationnum'}
2200 if $opt->{'locationnum'} and $opt->{'locationnum'} != $self->locationnum;
2201 my $new_quantity = $opt->{'quantity'}
2202 if $opt->{'quantity'} and $opt->{'quantity'} != $self->quantity;
2204 return '' unless $new_pkgpart or $new_locationnum or $new_quantity; # wouldn't do anything
2206 # allow $opt->{'locationnum'} = '' to specifically set it to null
2207 # (i.e. customer default location)
2208 $opt->{'locationnum'} = $self->locationnum if !exists($opt->{'locationnum'});
2210 my $new = FS::cust_pkg->new( {
2211 custnum => $self->custnum,
2212 locationnum => $opt->{'locationnum'},
2213 start_date => $date,
2214 map { $_ => ( $opt->{$_} || $self->$_() ) }
2215 qw( pkgpart quantity refnum salesnum )
2217 $error = $new->insert('change' => 1,
2218 'allow_pkgpart' => ($new_pkgpart ? 0 : 1));
2220 $self->set('change_to_pkgnum', $new->pkgnum);
2221 $self->set('expire', $date);
2222 $error = $self->replace;
2225 $dbh->rollback if $oldAutoCommit;
2227 $dbh->commit if $oldAutoCommit;
2235 Cancels a future package change scheduled by C<change_later>.
2241 my $pkgnum = $self->change_to_pkgnum;
2242 my $change_to = FS::cust_pkg->by_key($pkgnum) if $pkgnum;
2245 $error = $change_to->cancel || $change_to->delete;
2246 return $error if $error;
2248 $self->set('change_to_pkgnum', '');
2249 $self->set('expire', '');
2253 =item set_quantity QUANTITY
2255 Change the package's quantity field. This is one of the few package properties
2256 that can safely be changed without canceling and reordering the package
2257 (because it doesn't affect tax eligibility). Returns an error or an
2264 $self = $self->replace_old; # just to make sure
2265 $self->quantity(shift);
2269 =item set_salesnum SALESNUM
2271 Change the package's salesnum (sales person) field. This is one of the few
2272 package properties that can safely be changed without canceling and reordering
2273 the package (because it doesn't affect tax eligibility). Returns an error or
2280 $self = $self->replace_old; # just to make sure
2281 $self->salesnum(shift);
2283 # XXX this should probably reassign any credit that's already been given
2286 =item modify_charge OPTIONS
2288 Change the properties of a one-time charge. The following properties can
2289 be changed this way:
2290 - pkg: the package description
2291 - classnum: the package class
2292 - additional: arrayref of additional invoice details to add to this package
2294 and, I<if the charge has not yet been billed>:
2295 - start_date: the date when it will be billed
2296 - amount: the setup fee to be charged
2297 - quantity: the multiplier for the setup fee
2299 If you pass 'adjust_commission' => 1, and the classnum changes, and there are
2300 commission credits linked to this charge, they will be recalculated.
2307 my $part_pkg = $self->part_pkg;
2308 my $pkgnum = $self->pkgnum;
2311 my $oldAutoCommit = $FS::UID::AutoCommit;
2312 local $FS::UID::AutoCommit = 0;
2314 return "Can't use modify_charge except on one-time charges"
2315 unless $part_pkg->freq eq '0';
2317 if ( length($opt{'pkg'}) and $part_pkg->pkg ne $opt{'pkg'} ) {
2318 $part_pkg->set('pkg', $opt{'pkg'});
2321 my %pkg_opt = $part_pkg->options;
2322 my $pkg_opt_modified = 0;
2324 $opt{'additional'} ||= [];
2327 foreach (grep /^additional/, keys %pkg_opt) {
2328 ($i) = ($_ =~ /^additional_info(\d+)$/);
2329 $old_additional[$i] = $pkg_opt{$_} if $i;
2330 delete $pkg_opt{$_};
2333 for ( $i = 0; exists($opt{'additional'}->[$i]); $i++ ) {
2334 $pkg_opt{ "additional_info$i" } = $opt{'additional'}->[$i];
2335 if (!exists($old_additional[$i])
2336 or $old_additional[$i] ne $opt{'additional'}->[$i])
2338 $pkg_opt_modified = 1;
2341 $pkg_opt_modified = 1 if (scalar(@old_additional) - 1) != $i;
2342 $pkg_opt{'additional_count'} = $i if $i > 0;
2345 if ( exists($opt{'classnum'}) and $part_pkg->classnum ne $opt{'classnum'} )
2348 $old_classnum = $part_pkg->classnum;
2349 $part_pkg->set('classnum', $opt{'classnum'});
2352 if ( !$self->get('setup') ) {
2353 # not yet billed, so allow amount and quantity
2354 if ( exists($opt{'quantity'})
2355 and $opt{'quantity'} != $self->quantity
2356 and $opt{'quantity'} > 0 ) {
2358 $self->set('quantity', $opt{'quantity'});
2360 if ( exists($opt{'start_date'})
2361 and $opt{'start_date'} != $self->start_date ) {
2363 $self->set('start_date', $opt{'start_date'});
2366 if ( exists($opt{'amount'})
2367 and $part_pkg->option('setup_fee') != $opt{'amount'}
2368 and $opt{'amount'} > 0 ) {
2370 $pkg_opt{'setup_fee'} = $opt{'amount'};
2371 $pkg_opt_modified = 1;
2374 } # else simply ignore them; the UI shouldn't allow editing the fields
2377 if ( $part_pkg->modified or $pkg_opt_modified ) {
2378 # can we safely modify the package def?
2379 # Yes, if it's not available for purchase, and this is the only instance
2381 if ( $part_pkg->disabled
2382 and FS::cust_pkg->count('pkgpart = '.$part_pkg->pkgpart) == 1
2383 and FS::quotation_pkg->count('pkgpart = '.$part_pkg->pkgpart) == 0
2385 $error = $part_pkg->replace( options => \%pkg_opt );
2388 $part_pkg = $part_pkg->clone;
2389 $part_pkg->set('disabled' => 'Y');
2390 $error = $part_pkg->insert( options => \%pkg_opt );
2391 # and associate this as yet-unbilled package to the new package def
2392 $self->set('pkgpart' => $part_pkg->pkgpart);
2395 $dbh->rollback if $oldAutoCommit;
2400 if ($self->modified) { # for quantity or start_date change, or if we had
2401 # to clone the existing package def
2402 my $error = $self->replace;
2403 return $error if $error;
2405 if (defined $old_classnum) {
2406 # fix invoice grouping records
2407 my $old_catname = $old_classnum
2408 ? FS::pkg_class->by_key($old_classnum)->categoryname
2410 my $new_catname = $opt{'classnum'}
2411 ? $part_pkg->pkg_class->categoryname
2413 if ( $old_catname ne $new_catname ) {
2414 foreach my $cust_bill_pkg ($self->cust_bill_pkg) {
2415 # (there should only be one...)
2416 my @display = qsearch( 'cust_bill_pkg_display', {
2417 'billpkgnum' => $cust_bill_pkg->billpkgnum,
2418 'section' => $old_catname,
2420 foreach (@display) {
2421 $_->set('section', $new_catname);
2422 $error = $_->replace;
2424 $dbh->rollback if $oldAutoCommit;
2428 } # foreach $cust_bill_pkg
2431 if ( $opt{'adjust_commission'} ) {
2432 # fix commission credits...tricky.
2433 foreach my $cust_event ($self->cust_event) {
2434 my $part_event = $cust_event->part_event;
2435 foreach my $table (qw(sales agent)) {
2437 "FS::part_event::Action::Mixin::credit_${table}_pkg_class";
2438 my $credit = qsearchs('cust_credit', {
2439 'eventnum' => $cust_event->eventnum,
2441 if ( $part_event->isa($class) ) {
2442 # Yes, this results in current commission rates being applied
2443 # retroactively to a one-time charge. For accounting purposes
2444 # there ought to be some kind of time limit on doing this.
2445 my $amount = $part_event->_calc_credit($self);
2446 if ( $credit and $credit->amount ne $amount ) {
2447 # Void the old credit.
2448 $error = $credit->void('Package class changed');
2450 $dbh->rollback if $oldAutoCommit;
2451 return "$error (adjusting commission credit)";
2454 # redo the event action to recreate the credit.
2456 eval { $part_event->do_action( $self, $cust_event ) };
2458 $dbh->rollback if $oldAutoCommit;
2461 } # if $part_event->isa($class)
2463 } # foreach $cust_event
2464 } # if $opt{'adjust_commission'}
2465 } # if defined $old_classnum
2467 $dbh->commit if $oldAutoCommit;
2473 use Storable 'thaw';
2476 sub process_bulk_cust_pkg {
2478 my $param = thaw(decode_base64(shift));
2479 warn Dumper($param) if $DEBUG;
2481 my $old_part_pkg = qsearchs('part_pkg',
2482 { pkgpart => $param->{'old_pkgpart'} });
2483 my $new_part_pkg = qsearchs('part_pkg',
2484 { pkgpart => $param->{'new_pkgpart'} });
2485 die "Must select a new package type\n" unless $new_part_pkg;
2486 #my $keep_dates = $param->{'keep_dates'} || 0;
2487 my $keep_dates = 1; # there is no good reason to turn this off
2489 local $SIG{HUP} = 'IGNORE';
2490 local $SIG{INT} = 'IGNORE';
2491 local $SIG{QUIT} = 'IGNORE';
2492 local $SIG{TERM} = 'IGNORE';
2493 local $SIG{TSTP} = 'IGNORE';
2494 local $SIG{PIPE} = 'IGNORE';
2496 my $oldAutoCommit = $FS::UID::AutoCommit;
2497 local $FS::UID::AutoCommit = 0;
2500 my @cust_pkgs = qsearch('cust_pkg', { 'pkgpart' => $param->{'old_pkgpart'} } );
2503 foreach my $old_cust_pkg ( @cust_pkgs ) {
2505 $job->update_statustext(int(100*$i/(scalar @cust_pkgs)));
2506 if ( $old_cust_pkg->getfield('cancel') ) {
2507 warn '[process_bulk_cust_pkg ] skipping canceled pkgnum '.
2508 $old_cust_pkg->pkgnum."\n"
2512 warn '[process_bulk_cust_pkg] changing pkgnum '.$old_cust_pkg->pkgnum."\n"
2514 my $error = $old_cust_pkg->change(
2515 'pkgpart' => $param->{'new_pkgpart'},
2516 'keep_dates' => $keep_dates
2518 if ( !ref($error) ) { # change returns the cust_pkg on success
2520 die "Error changing pkgnum ".$old_cust_pkg->pkgnum.": '$error'\n";
2523 $dbh->commit if $oldAutoCommit;
2529 Returns the last bill date, or if there is no last bill date, the setup date.
2530 Useful for billing metered services.
2536 return $self->setfield('last_bill', $_[0]) if @_;
2537 return $self->getfield('last_bill') if $self->getfield('last_bill');
2538 my $cust_bill_pkg = qsearchs('cust_bill_pkg', { 'pkgnum' => $self->pkgnum,
2539 'edate' => $self->bill, } );
2540 $cust_bill_pkg ? $cust_bill_pkg->sdate : $self->setup || 0;
2543 =item last_cust_pkg_reason ACTION
2545 Returns the most recent ACTION FS::cust_pkg_reason associated with the package.
2546 Returns false if there is no reason or the package is not currenly ACTION'd
2547 ACTION is one of adjourn, susp, cancel, or expire.
2551 sub last_cust_pkg_reason {
2552 my ( $self, $action ) = ( shift, shift );
2553 my $date = $self->get($action);
2555 'table' => 'cust_pkg_reason',
2556 'hashref' => { 'pkgnum' => $self->pkgnum,
2557 'action' => substr(uc($action), 0, 1),
2560 'order_by' => 'ORDER BY num DESC LIMIT 1',
2564 =item last_reason ACTION
2566 Returns the most recent ACTION FS::reason associated with the package.
2567 Returns false if there is no reason or the package is not currenly ACTION'd
2568 ACTION is one of adjourn, susp, cancel, or expire.
2573 my $cust_pkg_reason = shift->last_cust_pkg_reason(@_);
2574 $cust_pkg_reason->reason
2575 if $cust_pkg_reason;
2580 Returns the definition for this billing item, as an FS::part_pkg object (see
2587 return $self->{'_pkgpart'} if $self->{'_pkgpart'};
2588 cluck "cust_pkg->part_pkg called" if $DEBUG > 1;
2589 qsearchs( 'part_pkg', { 'pkgpart' => $self->pkgpart } );
2594 Returns the cancelled package this package was changed from, if any.
2600 return '' unless $self->change_pkgnum;
2601 qsearchs('cust_pkg', { 'pkgnum' => $self->change_pkgnum } );
2604 =item change_cust_main
2606 Returns the customter this package was detached to, if any.
2610 sub change_cust_main {
2612 return '' unless $self->change_custnum;
2613 qsearchs('cust_main', { 'custnum' => $self->change_custnum } );
2618 Calls the I<calc_setup> of the FS::part_pkg object associated with this billing
2625 $self->part_pkg->calc_setup($self, @_);
2630 Calls the I<calc_recur> of the FS::part_pkg object associated with this billing
2637 $self->part_pkg->calc_recur($self, @_);
2642 Calls the I<base_recur> of the FS::part_pkg object associated with this billing
2649 $self->part_pkg->base_recur($self, @_);
2654 Calls the I<calc_remain> of the FS::part_pkg object associated with this
2661 $self->part_pkg->calc_remain($self, @_);
2666 Calls the I<calc_cancel> of the FS::part_pkg object associated with this
2673 $self->part_pkg->calc_cancel($self, @_);
2678 Returns any invoice line items for this package (see L<FS::cust_bill_pkg>).
2684 qsearch( 'cust_bill_pkg', { 'pkgnum' => $self->pkgnum } );
2687 =item cust_pkg_detail [ DETAILTYPE ]
2689 Returns any customer package details for this package (see
2690 L<FS::cust_pkg_detail>).
2692 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
2696 sub cust_pkg_detail {
2698 my %hash = ( 'pkgnum' => $self->pkgnum );
2699 $hash{detailtype} = shift if @_;
2701 'table' => 'cust_pkg_detail',
2702 'hashref' => \%hash,
2703 'order_by' => 'ORDER BY weight, pkgdetailnum',
2707 =item set_cust_pkg_detail DETAILTYPE [ DETAIL, DETAIL, ... ]
2709 Sets customer package details for this package (see L<FS::cust_pkg_detail>).
2711 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
2713 If there is an error, returns the error, otherwise returns false.
2717 sub set_cust_pkg_detail {
2718 my( $self, $detailtype, @details ) = @_;
2720 local $SIG{HUP} = 'IGNORE';
2721 local $SIG{INT} = 'IGNORE';
2722 local $SIG{QUIT} = 'IGNORE';
2723 local $SIG{TERM} = 'IGNORE';
2724 local $SIG{TSTP} = 'IGNORE';
2725 local $SIG{PIPE} = 'IGNORE';
2727 my $oldAutoCommit = $FS::UID::AutoCommit;
2728 local $FS::UID::AutoCommit = 0;
2731 foreach my $current ( $self->cust_pkg_detail($detailtype) ) {
2732 my $error = $current->delete;
2734 $dbh->rollback if $oldAutoCommit;
2735 return "error removing old detail: $error";
2739 foreach my $detail ( @details ) {
2740 my $cust_pkg_detail = new FS::cust_pkg_detail {
2741 'pkgnum' => $self->pkgnum,
2742 'detailtype' => $detailtype,
2743 'detail' => $detail,
2745 my $error = $cust_pkg_detail->insert;
2747 $dbh->rollback if $oldAutoCommit;
2748 return "error adding new detail: $error";
2753 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2760 Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.
2764 #false laziness w/cust_bill.pm
2768 'table' => 'cust_event',
2769 'addl_from' => 'JOIN part_event USING ( eventpart )',
2770 'hashref' => { 'tablenum' => $self->pkgnum },
2771 'extra_sql' => " AND eventtable = 'cust_pkg' ",
2775 =item num_cust_event
2777 Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.
2781 #false laziness w/cust_bill.pm
2782 sub num_cust_event {
2785 "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
2786 " WHERE tablenum = ? AND eventtable = 'cust_pkg'";
2787 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
2788 $sth->execute($self->pkgnum) or die $sth->errstr. " executing $sql";
2789 $sth->fetchrow_arrayref->[0];
2792 =item cust_svc [ SVCPART ] (old, deprecated usage)
2794 =item cust_svc [ OPTION => VALUE ... ] (current usage)
2796 =item cust_svc_unsorted [ OPTION => VALUE ... ]
2798 Returns the services for this package, as FS::cust_svc objects (see
2799 L<FS::cust_svc>). Available options are svcpart and svcdb. If either is
2800 spcififed, returns only the matching services.
2802 As an optimization, use the cust_svc_unsorted version if you are not displaying
2809 cluck "cust_pkg->cust_svc called" if $DEBUG > 2;
2810 $self->_sort_cust_svc( $self->cust_svc_unsorted_arrayref(@_) );
2813 sub cust_svc_unsorted {
2815 @{ $self->cust_svc_unsorted_arrayref(@_) };
2818 sub cust_svc_unsorted_arrayref {
2821 return [] unless $self->num_cust_svc(@_);
2824 if ( @_ && $_[0] =~ /^\d+/ ) {
2825 $opt{svcpart} = shift;
2826 } elsif ( @_ && ref($_[0]) eq 'HASH' ) {
2833 'table' => 'cust_svc',
2834 'hashref' => { 'pkgnum' => $self->pkgnum },
2836 if ( $opt{svcpart} ) {
2837 $search{hashref}->{svcpart} = $opt{'svcpart'};
2839 if ( $opt{'svcdb'} ) {
2840 $search{addl_from} = ' LEFT JOIN part_svc USING ( svcpart ) ';
2841 $search{extra_sql} = ' AND svcdb = '. dbh->quote( $opt{'svcdb'} );
2844 [ qsearch(\%search) ];
2848 =item overlimit [ SVCPART ]
2850 Returns the services for this package which have exceeded their
2851 usage limit as FS::cust_svc objects (see L<FS::cust_svc>). If a svcpart
2852 is specified, return only the matching services.
2858 return () unless $self->num_cust_svc(@_);
2859 grep { $_->overlimit } $self->cust_svc(@_);
2862 =item h_cust_svc END_TIMESTAMP [ START_TIMESTAMP ] [ MODE ]
2864 Returns historical services for this package created before END TIMESTAMP and
2865 (optionally) not cancelled before START_TIMESTAMP, as FS::h_cust_svc objects
2866 (see L<FS::h_cust_svc>). If MODE is 'I' (for 'invoice'), services with the
2867 I<pkg_svc.hidden> flag will be omitted.
2873 warn "$me _h_cust_svc called on $self\n"
2876 my ($end, $start, $mode) = @_;
2877 my @cust_svc = $self->_sort_cust_svc(
2878 [ qsearch( 'h_cust_svc',
2879 { 'pkgnum' => $self->pkgnum, },
2880 FS::h_cust_svc->sql_h_search(@_),
2883 if ( defined($mode) && $mode eq 'I' ) {
2884 my %hidden_svcpart = map { $_->svcpart => $_->hidden } $self->part_svc;
2885 return grep { !$hidden_svcpart{$_->svcpart} } @cust_svc;
2891 sub _sort_cust_svc {
2892 my( $self, $arrayref ) = @_;
2895 sub ($$) { my ($a, $b) = @_; $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] };
2897 my %pkg_svc = map { $_->svcpart => $_ }
2898 qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
2903 my $pkg_svc = $pkg_svc{ $_->svcpart } || '';
2905 $pkg_svc ? $pkg_svc->primary_svc : '',
2906 $pkg_svc ? $pkg_svc->quantity : 0,
2913 =item num_cust_svc [ SVCPART ] (old, deprecated usage)
2915 =item num_cust_svc [ OPTION => VALUE ... ] (current usage)
2917 Returns the number of services for this package. Available options are svcpart
2918 and svcdb. If either is spcififed, returns only the matching services.
2925 return $self->{'_num_cust_svc'}
2927 && exists($self->{'_num_cust_svc'})
2928 && $self->{'_num_cust_svc'} =~ /\d/;
2930 cluck "cust_pkg->num_cust_svc called, _num_cust_svc:".$self->{'_num_cust_svc'}
2934 if ( @_ && $_[0] =~ /^\d+/ ) {
2935 $opt{svcpart} = shift;
2936 } elsif ( @_ && ref($_[0]) eq 'HASH' ) {
2942 my $select = 'SELECT COUNT(*) FROM cust_svc ';
2943 my $where = ' WHERE pkgnum = ? ';
2944 my @param = ($self->pkgnum);
2946 if ( $opt{'svcpart'} ) {
2947 $where .= ' AND svcpart = ? ';
2948 push @param, $opt{'svcpart'};
2950 if ( $opt{'svcdb'} ) {
2951 $select .= ' LEFT JOIN part_svc USING ( svcpart ) ';
2952 $where .= ' AND svcdb = ? ';
2953 push @param, $opt{'svcdb'};
2956 my $sth = dbh->prepare("$select $where") or die dbh->errstr;
2957 $sth->execute(@param) or die $sth->errstr;
2958 $sth->fetchrow_arrayref->[0];
2961 =item available_part_svc
2963 Returns a list of FS::part_svc objects representing services included in this
2964 package but not yet provisioned. Each FS::part_svc object also has an extra
2965 field, I<num_avail>, which specifies the number of available services.
2969 sub available_part_svc {
2972 my $pkg_quantity = $self->quantity || 1;
2974 grep { $_->num_avail > 0 }
2976 my $part_svc = $_->part_svc;
2977 $part_svc->{'Hash'}{'num_avail'} = #evil encapsulation-breaking
2978 $pkg_quantity * $_->quantity - $self->num_cust_svc($_->svcpart);
2980 # more evil encapsulation breakage
2981 if($part_svc->{'Hash'}{'num_avail'} > 0) {
2982 my @exports = $part_svc->part_export_did;
2983 $part_svc->{'Hash'}{'can_get_dids'} = scalar(@exports);
2988 $self->part_pkg->pkg_svc;
2991 =item part_svc [ OPTION => VALUE ... ]
2993 Returns a list of FS::part_svc objects representing provisioned and available
2994 services included in this package. Each FS::part_svc object also has the
2995 following extra fields:
3009 (services) - array reference containing the provisioned services, as cust_svc objects
3013 Accepts two options:
3017 =item summarize_size
3019 If true, will omit the extra cust_pkg_svc option for objects where num_cust_svc
3020 is this size or greater.
3022 =item hide_discontinued
3024 If true, will omit looking for services that are no longer avaialble in the
3032 #label -> ($cust_svc->label)[1]
3038 my $pkg_quantity = $self->quantity || 1;
3040 #XXX some sort of sort order besides numeric by svcpart...
3041 my @part_svc = sort { $a->svcpart <=> $b->svcpart } map {
3043 my $part_svc = $pkg_svc->part_svc;
3044 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
3045 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #more evil
3046 $part_svc->{'Hash'}{'num_avail'} =
3047 max( 0, $pkg_quantity * $pkg_svc->quantity - $num_cust_svc );
3048 $part_svc->{'Hash'}{'cust_pkg_svc'} =
3049 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : []
3050 unless exists($opt{summarize_size}) && $opt{summarize_size} > 0
3051 && $num_cust_svc >= $opt{summarize_size};
3052 $part_svc->{'Hash'}{'hidden'} = $pkg_svc->hidden;
3054 } $self->part_pkg->pkg_svc;
3056 unless ( $opt{hide_discontinued} ) {
3058 push @part_svc, map {
3060 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
3061 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #speak no evail
3062 $part_svc->{'Hash'}{'num_avail'} = 0; #0-$num_cust_svc ?
3063 $part_svc->{'Hash'}{'cust_pkg_svc'} =
3064 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : [];
3066 } $self->extra_part_svc;
3073 =item extra_part_svc
3075 Returns a list of FS::part_svc objects corresponding to services in this
3076 package which are still provisioned but not (any longer) available in the
3081 sub extra_part_svc {
3084 my $pkgnum = $self->pkgnum;
3085 #my $pkgpart = $self->pkgpart;
3088 # 'table' => 'part_svc',
3091 # "WHERE 0 = ( SELECT COUNT(*) FROM pkg_svc
3092 # WHERE pkg_svc.svcpart = part_svc.svcpart
3093 # AND pkg_svc.pkgpart = ?
3096 # AND 0 < ( SELECT COUNT(*) FROM cust_svc
3097 # LEFT JOIN cust_pkg USING ( pkgnum )
3098 # WHERE cust_svc.svcpart = part_svc.svcpart
3101 # 'extra_param' => [ [$self->pkgpart=>'int'], [$self->pkgnum=>'int'] ],
3104 #seems to benchmark slightly faster... (or did?)
3106 my @pkgparts = map $_->pkgpart, $self->part_pkg->self_and_svc_linked;
3107 my $pkgparts = join(',', @pkgparts);
3110 #'select' => 'DISTINCT ON (svcpart) part_svc.*',
3111 #MySQL doesn't grok DISINCT ON
3112 'select' => 'DISTINCT part_svc.*',
3113 'table' => 'part_svc',
3115 "LEFT JOIN pkg_svc ON ( pkg_svc.svcpart = part_svc.svcpart
3116 AND pkg_svc.pkgpart IN ($pkgparts)
3119 LEFT JOIN cust_svc ON ( cust_svc.svcpart = part_svc.svcpart )
3120 LEFT JOIN cust_pkg USING ( pkgnum )
3123 'extra_sql' => "WHERE pkgsvcnum IS NULL AND cust_pkg.pkgnum = ? ",
3124 'extra_param' => [ [$self->pkgnum=>'int'] ],
3130 Returns a short status string for this package, currently:
3136 =item not yet billed
3138 =item one-time charge
3153 my $freq = length($self->freq) ? $self->freq : $self->part_pkg->freq;
3155 return 'cancelled' if $self->get('cancel');
3156 return 'on hold' if $self->susp && ! $self->setup;
3157 return 'suspended' if $self->susp;
3158 return 'not yet billed' unless $self->setup;
3159 return 'one-time charge' if $freq =~ /^(0|$)/;
3163 =item ucfirst_status
3165 Returns the status with the first character capitalized.
3169 sub ucfirst_status {
3170 ucfirst(shift->status);
3175 Class method that returns the list of possible status strings for packages
3176 (see L<the status method|/status>). For example:
3178 @statuses = FS::cust_pkg->statuses();
3182 tie my %statuscolor, 'Tie::IxHash',
3183 'on hold' => '7E0079', #purple!
3184 'not yet billed' => '009999', #teal? cyan?
3185 'one-time charge' => '0000CC', #blue #'000000',
3186 'active' => '00CC00',
3187 'suspended' => 'FF9900',
3188 'cancelled' => 'FF0000',
3192 my $self = shift; #could be class...
3193 #grep { $_ !~ /^(not yet billed)$/ } #this is a dumb status anyway
3194 # # mayble split btw one-time vs. recur
3205 Returns a hex triplet color string for this package's status.
3211 $statuscolor{$self->status};
3216 Returns a label for this package. (Currently "pkgnum: pkg - comment" or
3217 "pkg - comment" depending on user preference).
3223 my $label = $self->part_pkg->pkg_comment( 'nopkgpart' => 1 );
3224 $label = $self->pkgnum. ": $label"
3225 if $FS::CurrentUser::CurrentUser->option('show_pkgnum');
3229 =item pkg_label_long
3231 Returns a long label for this package, adding the primary service's label to
3236 sub pkg_label_long {
3238 my $label = $self->pkg_label;
3239 my $cust_svc = $self->primary_cust_svc;
3240 $label .= ' ('. ($cust_svc->label)[1]. ')' if $cust_svc;
3246 Returns a customer-localized label for this package.
3252 $self->part_pkg->pkg_locale( $self->cust_main->locale );
3255 =item primary_cust_svc
3257 Returns a primary service (as FS::cust_svc object) if one can be identified.
3261 #for labeling purposes - might not 100% match up with part_pkg->svcpart's idea
3263 sub primary_cust_svc {
3266 my @cust_svc = $self->cust_svc;
3268 return '' unless @cust_svc; #no serivces - irrelevant then
3270 return $cust_svc[0] if scalar(@cust_svc) == 1; #always return a single service
3272 # primary service as specified in the package definition
3273 # or exactly one service definition with quantity one
3274 my $svcpart = $self->part_pkg->svcpart;
3275 @cust_svc = grep { $_->svcpart == $svcpart } @cust_svc;
3276 return $cust_svc[0] if scalar(@cust_svc) == 1;
3278 #couldn't identify one thing..
3284 Returns a list of lists, calling the label method for all services
3285 (see L<FS::cust_svc>) of this billing item.
3291 map { [ $_->label ] } $self->cust_svc;
3294 =item h_labels END_TIMESTAMP [ START_TIMESTAMP ] [ MODE ]
3296 Like the labels method, but returns historical information on services that
3297 were active as of END_TIMESTAMP and (optionally) not cancelled before
3298 START_TIMESTAMP. If MODE is 'I' (for 'invoice'), services with the
3299 I<pkg_svc.hidden> flag will be omitted.
3301 Returns a list of lists, calling the label method for all (historical) services
3302 (see L<FS::h_cust_svc>) of this billing item.
3308 warn "$me _h_labels called on $self\n"
3310 map { [ $_->label(@_) ] } $self->h_cust_svc(@_);
3315 Like labels, except returns a simple flat list, and shortens long
3316 (currently >5 or the cust_bill-max_same_services configuration value) lists of
3317 identical services to one line that lists the service label and the number of
3318 individual services rather than individual items.
3323 shift->_labels_short( 'labels', @_ );
3326 =item h_labels_short END_TIMESTAMP [ START_TIMESTAMP ]
3328 Like h_labels, except returns a simple flat list, and shortens long
3329 (currently >5 or the cust_bill-max_same_services configuration value) lists of
3330 identical services to one line that lists the service label and the number of
3331 individual services rather than individual items.
3335 sub h_labels_short {
3336 shift->_labels_short( 'h_labels', @_ );
3340 my( $self, $method ) = ( shift, shift );
3342 warn "$me _labels_short called on $self with $method method\n"
3345 my $conf = new FS::Conf;
3346 my $max_same_services = $conf->config('cust_bill-max_same_services') || 5;
3348 warn "$me _labels_short populating \%labels\n"
3352 #tie %labels, 'Tie::IxHash';
3353 push @{ $labels{$_->[0]} }, $_->[1]
3354 foreach $self->$method(@_);
3356 warn "$me _labels_short populating \@labels\n"
3360 foreach my $label ( keys %labels ) {
3362 my @values = grep { ! $seen{$_}++ } @{ $labels{$label} };
3363 my $num = scalar(@values);
3364 warn "$me _labels_short $num items for $label\n"
3367 if ( $num > $max_same_services ) {
3368 warn "$me _labels_short more than $max_same_services, so summarizing\n"
3370 push @labels, "$label ($num)";
3372 if ( $conf->exists('cust_bill-consolidate_services') ) {
3373 warn "$me _labels_short consolidating services\n"
3375 # push @labels, "$label: ". join(', ', @values);
3377 my $detail = "$label: ";
3378 $detail .= shift(@values). ', '
3380 && ( length($detail.$values[0]) < 78 || $detail eq "$label: " );
3382 push @labels, $detail;
3384 warn "$me _labels_short done consolidating services\n"
3387 warn "$me _labels_short adding service data\n"
3389 push @labels, map { "$label: $_" } @values;
3400 Returns the parent customer object (see L<FS::cust_main>).
3406 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
3411 Returns the balance for this specific package, when using
3412 experimental package balance.
3418 $self->cust_main->balance_pkgnum( $self->pkgnum );
3421 #these subs are in location_Mixin.pm now... unfortunately the POD doesn't mixin
3425 Returns the location object, if any (see L<FS::cust_location>).
3427 =item cust_location_or_main
3429 If this package is associated with a location, returns the locaiton (see
3430 L<FS::cust_location>), otherwise returns the customer (see L<FS::cust_main>).
3432 =item location_label [ OPTION => VALUE ... ]
3434 Returns the label of the location object (see L<FS::cust_location>).
3438 #end of subs in location_Mixin.pm now... unfortunately the POD doesn't mixin
3440 =item tax_locationnum
3442 Returns the foreign key to a L<FS::cust_location> object for calculating
3443 tax on this package, as determined by the C<tax-pkg_address> and
3444 C<tax-ship_address> configuration flags.
3448 sub tax_locationnum {
3450 my $conf = FS::Conf->new;
3451 if ( $conf->exists('tax-pkg_address') ) {
3452 return $self->locationnum;
3454 elsif ( $conf->exists('tax-ship_address') ) {
3455 return $self->cust_main->ship_locationnum;
3458 return $self->cust_main->bill_locationnum;
3464 Returns the L<FS::cust_location> object for tax_locationnum.
3470 my $conf = FS::Conf->new;
3471 if ( $conf->exists('tax-pkg_address') and $self->locationnum ) {
3472 return FS::cust_location->by_key($self->locationnum);
3474 elsif ( $conf->exists('tax-ship_address') ) {
3475 return $self->cust_main->ship_location;
3478 return $self->cust_main->bill_location;
3482 =item seconds_since TIMESTAMP
3484 Returns the number of seconds all accounts (see L<FS::svc_acct>) in this
3485 package have been online since TIMESTAMP, according to the session monitor.
3487 TIMESTAMP is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
3488 L<Time::Local> and L<Date::Parse> for conversion functions.
3493 my($self, $since) = @_;
3496 foreach my $cust_svc (
3497 grep { $_->part_svc->svcdb eq 'svc_acct' } $self->cust_svc
3499 $seconds += $cust_svc->seconds_since($since);
3506 =item seconds_since_sqlradacct TIMESTAMP_START TIMESTAMP_END
3508 Returns the numbers of seconds all accounts (see L<FS::svc_acct>) in this
3509 package have been online between TIMESTAMP_START (inclusive) and TIMESTAMP_END
3512 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
3513 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
3519 sub seconds_since_sqlradacct {
3520 my($self, $start, $end) = @_;
3524 foreach my $cust_svc (
3526 my $part_svc = $_->part_svc;
3527 $part_svc->svcdb eq 'svc_acct'
3528 && scalar($part_svc->part_export_usage);
3531 $seconds += $cust_svc->seconds_since_sqlradacct($start, $end);
3538 =item attribute_since_sqlradacct TIMESTAMP_START TIMESTAMP_END ATTRIBUTE
3540 Returns the sum of the given attribute for all accounts (see L<FS::svc_acct>)
3541 in this package for sessions ending between TIMESTAMP_START (inclusive) and
3545 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
3546 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
3551 sub attribute_since_sqlradacct {
3552 my($self, $start, $end, $attrib) = @_;
3556 foreach my $cust_svc (
3558 my $part_svc = $_->part_svc;
3559 scalar($part_svc->part_export_usage);
3562 $sum += $cust_svc->attribute_since_sqlradacct($start, $end, $attrib);
3574 my( $self, $value ) = @_;
3575 if ( defined($value) ) {
3576 $self->setfield('quantity', $value);
3578 $self->getfield('quantity') || 1;
3581 =item transfer DEST_PKGNUM | DEST_CUST_PKG, [ OPTION => VALUE ... ]
3583 Transfers as many services as possible from this package to another package.
3585 The destination package can be specified by pkgnum by passing an FS::cust_pkg
3586 object. The destination package must already exist.
3588 Services are moved only if the destination allows services with the correct
3589 I<svcpart> (not svcdb), unless the B<change_svcpart> option is set true. Use
3590 this option with caution! No provision is made for export differences
3591 between the old and new service definitions. Probably only should be used
3592 when your exports for all service definitions of a given svcdb are identical.
3593 (attempt a transfer without it first, to move all possible svcpart-matching
3596 Any services that can't be moved remain in the original package.
3598 Returns an error, if there is one; otherwise, returns the number of services
3599 that couldn't be moved.
3604 my ($self, $dest_pkgnum, %opt) = @_;
3610 if (ref ($dest_pkgnum) eq 'FS::cust_pkg') {
3611 $dest = $dest_pkgnum;
3612 $dest_pkgnum = $dest->pkgnum;
3614 $dest = qsearchs('cust_pkg', { pkgnum => $dest_pkgnum });
3617 return ('Package does not exist: '.$dest_pkgnum) unless $dest;
3619 foreach my $pkg_svc ( $dest->part_pkg->pkg_svc ) {
3620 $target{$pkg_svc->svcpart} = $pkg_svc->quantity;
3623 foreach my $cust_svc ($dest->cust_svc) {
3624 $target{$cust_svc->svcpart}--;
3627 my %svcpart2svcparts = ();
3628 if ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
3629 warn "change_svcpart option received, creating alternates list\n" if $DEBUG;
3630 foreach my $svcpart ( map { $_->svcpart } $self->cust_svc ) {
3631 next if exists $svcpart2svcparts{$svcpart};
3632 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
3633 $svcpart2svcparts{$svcpart} = [
3635 sort { $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] }
3637 my $pkg_svc = qsearchs( 'pkg_svc', { 'pkgpart' => $dest->pkgpart,
3638 'svcpart' => $_ } );
3640 $pkg_svc ? $pkg_svc->primary_svc : '',
3641 $pkg_svc ? $pkg_svc->quantity : 0,
3645 grep { $_ != $svcpart }
3647 qsearch('part_svc', { 'svcdb' => $part_svc->svcdb } )
3649 warn "alternates for svcpart $svcpart: ".
3650 join(', ', @{$svcpart2svcparts{$svcpart}}). "\n"
3656 foreach my $cust_svc ($self->cust_svc) {
3657 my $svcnum = $cust_svc->svcnum;
3658 if($target{$cust_svc->svcpart} > 0
3659 or $FS::cust_svc::ignore_quantity) { # maybe should be a 'force' option
3660 $target{$cust_svc->svcpart}--;
3661 my $new = new FS::cust_svc { $cust_svc->hash };
3662 $new->pkgnum($dest_pkgnum);
3663 $error = $new->replace($cust_svc);
3664 } elsif ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
3666 warn "looking for alternates for svcpart ". $cust_svc->svcpart. "\n";
3667 warn "alternates to consider: ".
3668 join(', ', @{$svcpart2svcparts{$cust_svc->svcpart}}). "\n";
3670 my @alternate = grep {
3671 warn "considering alternate svcpart $_: ".
3672 "$target{$_} available in new package\n"
3675 } @{$svcpart2svcparts{$cust_svc->svcpart}};
3677 warn "alternate(s) found\n" if $DEBUG;
3678 my $change_svcpart = $alternate[0];
3679 $target{$change_svcpart}--;
3680 my $new = new FS::cust_svc { $cust_svc->hash };
3681 $new->svcpart($change_svcpart);
3682 $new->pkgnum($dest_pkgnum);
3683 $error = $new->replace($cust_svc);
3691 my @label = $cust_svc->label;
3692 return "service $label[1]: $error";
3698 =item grab_svcnums SVCNUM, SVCNUM ...
3700 Change the pkgnum for the provided services to this packages. If there is an
3701 error, returns the error, otherwise returns false.
3709 local $SIG{HUP} = 'IGNORE';
3710 local $SIG{INT} = 'IGNORE';
3711 local $SIG{QUIT} = 'IGNORE';
3712 local $SIG{TERM} = 'IGNORE';
3713 local $SIG{TSTP} = 'IGNORE';
3714 local $SIG{PIPE} = 'IGNORE';
3716 my $oldAutoCommit = $FS::UID::AutoCommit;
3717 local $FS::UID::AutoCommit = 0;
3720 foreach my $svcnum (@svcnum) {
3721 my $cust_svc = qsearchs('cust_svc', { svcnum=>$svcnum } ) or do {
3722 $dbh->rollback if $oldAutoCommit;
3723 return "unknown svcnum $svcnum";
3725 $cust_svc->pkgnum( $self->pkgnum );
3726 my $error = $cust_svc->replace;
3728 $dbh->rollback if $oldAutoCommit;
3733 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3740 This method is deprecated. See the I<depend_jobnum> option to the insert and
3741 order_pkgs methods in FS::cust_main for a better way to defer provisioning.
3748 local $SIG{HUP} = 'IGNORE';
3749 local $SIG{INT} = 'IGNORE';
3750 local $SIG{QUIT} = 'IGNORE';
3751 local $SIG{TERM} = 'IGNORE';
3752 local $SIG{TSTP} = 'IGNORE';
3753 local $SIG{PIPE} = 'IGNORE';
3755 my $oldAutoCommit = $FS::UID::AutoCommit;
3756 local $FS::UID::AutoCommit = 0;
3759 foreach my $cust_svc ( $self->cust_svc ) {
3760 #false laziness w/svc_Common::insert
3761 my $svc_x = $cust_svc->svc_x;
3762 foreach my $part_export ( $cust_svc->part_svc->part_export ) {
3763 my $error = $part_export->export_insert($svc_x);
3765 $dbh->rollback if $oldAutoCommit;
3771 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3776 =item export_pkg_change OLD_CUST_PKG
3778 Calls the "pkg_change" export action for all services attached to this package.
3782 sub export_pkg_change {
3783 my( $self, $old ) = ( shift, shift );
3785 local $SIG{HUP} = 'IGNORE';
3786 local $SIG{INT} = 'IGNORE';
3787 local $SIG{QUIT} = 'IGNORE';
3788 local $SIG{TERM} = 'IGNORE';
3789 local $SIG{TSTP} = 'IGNORE';
3790 local $SIG{PIPE} = 'IGNORE';
3792 my $oldAutoCommit = $FS::UID::AutoCommit;
3793 local $FS::UID::AutoCommit = 0;
3796 foreach my $svc_x ( map $_->svc_x, $self->cust_svc ) {
3797 my $error = $svc_x->export('pkg_change', $self, $old);
3799 $dbh->rollback if $oldAutoCommit;
3804 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3811 Associates this package with a (suspension or cancellation) reason (see
3812 L<FS::cust_pkg_reason>, possibly inserting a new reason on the fly (see
3815 Available options are:
3821 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.
3825 the access_user (see L<FS::access_user>) providing the reason
3833 the action (cancel, susp, adjourn, expire) associated with the reason
3837 If there is an error, returns the error, otherwise returns false.
3842 my ($self, %options) = @_;
3844 my $otaker = $options{reason_otaker} ||
3845 $FS::CurrentUser::CurrentUser->username;
3848 if ( $options{'reason'} =~ /^(\d+)$/ ) {
3852 } elsif ( ref($options{'reason'}) ) {
3854 return 'Enter a new reason (or select an existing one)'
3855 unless $options{'reason'}->{'reason'} !~ /^\s*$/;
3857 my $reason = new FS::reason({
3858 'reason_type' => $options{'reason'}->{'typenum'},
3859 'reason' => $options{'reason'}->{'reason'},
3861 my $error = $reason->insert;
3862 return $error if $error;
3864 $reasonnum = $reason->reasonnum;
3867 return "Unparsable reason: ". $options{'reason'};
3870 my $cust_pkg_reason =
3871 new FS::cust_pkg_reason({ 'pkgnum' => $self->pkgnum,
3872 'reasonnum' => $reasonnum,
3873 'otaker' => $otaker,
3874 'action' => substr(uc($options{'action'}),0,1),
3875 'date' => $options{'date'}
3880 $cust_pkg_reason->insert;
3883 =item insert_discount
3885 Associates this package with a discount (see L<FS::cust_pkg_discount>, possibly
3886 inserting a new discount on the fly (see L<FS::discount>).
3888 Available options are:
3896 If there is an error, returns the error, otherwise returns false.
3900 sub insert_discount {
3901 #my ($self, %options) = @_;
3904 my $cust_pkg_discount = new FS::cust_pkg_discount {
3905 'pkgnum' => $self->pkgnum,
3906 'discountnum' => $self->discountnum,
3908 'end_date' => '', #XXX
3909 #for the create a new discount case
3910 '_type' => $self->discountnum__type,
3911 'amount' => $self->discountnum_amount,
3912 'percent' => $self->discountnum_percent,
3913 'months' => $self->discountnum_months,
3914 'setup' => $self->discountnum_setup,
3915 #'disabled' => $self->discountnum_disabled,
3918 $cust_pkg_discount->insert;
3921 =item set_usage USAGE_VALUE_HASHREF
3923 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
3924 to which they should be set (see L<FS::svc_acct>). Currently seconds,
3925 upbytes, downbytes, and totalbytes are appropriate keys.
3927 All svc_accts which are part of this package have their values reset.
3932 my ($self, $valueref, %opt) = @_;
3934 #only svc_acct can set_usage for now
3935 foreach my $cust_svc ( $self->cust_svc( 'svcdb'=>'svc_acct' ) ) {
3936 my $svc_x = $cust_svc->svc_x;
3937 $svc_x->set_usage($valueref, %opt)
3938 if $svc_x->can("set_usage");
3942 =item recharge USAGE_VALUE_HASHREF
3944 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
3945 to which they should be set (see L<FS::svc_acct>). Currently seconds,
3946 upbytes, downbytes, and totalbytes are appropriate keys.
3948 All svc_accts which are part of this package have their values incremented.
3953 my ($self, $valueref) = @_;
3955 #only svc_acct can set_usage for now
3956 foreach my $cust_svc ( $self->cust_svc( 'svcdb'=>'svc_acct' ) ) {
3957 my $svc_x = $cust_svc->svc_x;
3958 $svc_x->recharge($valueref)
3959 if $svc_x->can("recharge");
3963 =item cust_pkg_discount
3967 sub cust_pkg_discount {
3969 qsearch('cust_pkg_discount', { 'pkgnum' => $self->pkgnum } );
3972 =item cust_pkg_discount_active
3976 sub cust_pkg_discount_active {
3978 grep { $_->status eq 'active' } $self->cust_pkg_discount;
3981 =item cust_pkg_usage
3983 Returns a list of all voice usage counters attached to this package.
3987 sub cust_pkg_usage {
3989 qsearch('cust_pkg_usage', { pkgnum => $self->pkgnum });
3992 =item apply_usage OPTIONS
3994 Takes the following options:
3995 - cdr: a call detail record (L<FS::cdr>)
3996 - rate_detail: the rate determined for this call (L<FS::rate_detail>)
3997 - minutes: the maximum number of minutes to be charged
3999 Finds available usage minutes for a call of this class, and subtracts
4000 up to that many minutes from the usage pool. If the usage pool is empty,
4001 and the C<cdr-minutes_priority> global config option is set, minutes may
4002 be taken from other calls as well. Either way, an allocation record will
4003 be created (L<FS::cdr_cust_pkg_usage>) and this method will return the
4004 number of minutes of usage applied to the call.
4009 my ($self, %opt) = @_;
4010 my $cdr = $opt{cdr};
4011 my $rate_detail = $opt{rate_detail};
4012 my $minutes = $opt{minutes};
4013 my $classnum = $rate_detail->classnum;
4014 my $pkgnum = $self->pkgnum;
4015 my $custnum = $self->custnum;
4017 local $SIG{HUP} = 'IGNORE';
4018 local $SIG{INT} = 'IGNORE';
4019 local $SIG{QUIT} = 'IGNORE';
4020 local $SIG{TERM} = 'IGNORE';
4021 local $SIG{TSTP} = 'IGNORE';
4022 local $SIG{PIPE} = 'IGNORE';
4024 my $oldAutoCommit = $FS::UID::AutoCommit;
4025 local $FS::UID::AutoCommit = 0;
4027 my $order = FS::Conf->new->config('cdr-minutes_priority');
4031 $is_classnum = ' part_pkg_usage_class.classnum = '.$classnum;
4033 $is_classnum = ' part_pkg_usage_class.classnum IS NULL';
4035 my @usage_recs = qsearch({
4036 'table' => 'cust_pkg_usage',
4037 'addl_from' => ' JOIN part_pkg_usage USING (pkgusagepart)'.
4038 ' JOIN cust_pkg USING (pkgnum)'.
4039 ' JOIN part_pkg_usage_class USING (pkgusagepart)',
4040 'select' => 'cust_pkg_usage.*',
4041 'extra_sql' => " WHERE ( cust_pkg.pkgnum = $pkgnum OR ".
4042 " ( cust_pkg.custnum = $custnum AND ".
4043 " part_pkg_usage.shared IS NOT NULL ) ) AND ".
4044 $is_classnum . ' AND '.
4045 " cust_pkg_usage.minutes > 0",
4046 'order_by' => " ORDER BY priority ASC",
4049 my $orig_minutes = $minutes;
4051 while (!$error and $minutes > 0 and @usage_recs) {
4052 my $cust_pkg_usage = shift @usage_recs;
4053 $cust_pkg_usage->select_for_update;
4054 my $cdr_cust_pkg_usage = FS::cdr_cust_pkg_usage->new({
4055 pkgusagenum => $cust_pkg_usage->pkgusagenum,
4056 acctid => $cdr->acctid,
4057 minutes => min($cust_pkg_usage->minutes, $minutes),
4059 $cust_pkg_usage->set('minutes',
4060 $cust_pkg_usage->minutes - $cdr_cust_pkg_usage->minutes
4062 $error = $cust_pkg_usage->replace || $cdr_cust_pkg_usage->insert;
4063 $minutes -= $cdr_cust_pkg_usage->minutes;
4065 if ( $order and $minutes > 0 and !$error ) {
4066 # then try to steal minutes from another call
4068 'table' => 'cdr_cust_pkg_usage',
4069 'addl_from' => ' JOIN cust_pkg_usage USING (pkgusagenum)'.
4070 ' JOIN part_pkg_usage USING (pkgusagepart)'.
4071 ' JOIN cust_pkg USING (pkgnum)'.
4072 ' JOIN part_pkg_usage_class USING (pkgusagepart)'.
4073 ' JOIN cdr USING (acctid)',
4074 'select' => 'cdr_cust_pkg_usage.*',
4075 'extra_sql' => " WHERE cdr.freesidestatus = 'rated' AND ".
4076 " ( cust_pkg.pkgnum = $pkgnum OR ".
4077 " ( cust_pkg.custnum = $custnum AND ".
4078 " part_pkg_usage.shared IS NOT NULL ) ) AND ".
4079 " part_pkg_usage_class.classnum = $classnum",
4080 'order_by' => ' ORDER BY part_pkg_usage.priority ASC',
4082 if ( $order eq 'time' ) {
4083 # find CDRs that are using minutes, but have a later startdate
4085 my $startdate = $cdr->startdate;
4086 if ($startdate !~ /^\d+$/) {
4087 die "bad cdr startdate '$startdate'";
4089 $search{'extra_sql'} .= " AND cdr.startdate > $startdate";
4090 # minimize needless reshuffling
4091 $search{'order_by'} .= ', cdr.startdate DESC';
4093 # XXX may not work correctly with rate_time schedules. Could
4094 # fix this by storing ratedetailnum in cdr_cust_pkg_usage, I
4096 $search{'addl_from'} .=
4097 ' JOIN rate_detail'.
4098 ' ON (cdr.rated_ratedetailnum = rate_detail.ratedetailnum)';
4099 if ( $order eq 'rate_high' ) {
4100 $search{'extra_sql'} .= ' AND rate_detail.min_charge < '.
4101 $rate_detail->min_charge;
4102 $search{'order_by'} .= ', rate_detail.min_charge ASC';
4103 } elsif ( $order eq 'rate_low' ) {
4104 $search{'extra_sql'} .= ' AND rate_detail.min_charge > '.
4105 $rate_detail->min_charge;
4106 $search{'order_by'} .= ', rate_detail.min_charge DESC';
4108 # this should really never happen
4109 die "invalid cdr-minutes_priority value '$order'\n";
4112 my @cdr_usage_recs = qsearch(\%search);
4114 while (!$error and @cdr_usage_recs and $minutes > 0) {
4115 my $cdr_cust_pkg_usage = shift @cdr_usage_recs;
4116 my $cust_pkg_usage = $cdr_cust_pkg_usage->cust_pkg_usage;
4117 my $old_cdr = $cdr_cust_pkg_usage->cdr;
4118 $reproc_cdrs{$old_cdr->acctid} = $old_cdr;
4119 $cdr_cust_pkg_usage->select_for_update;
4120 $old_cdr->select_for_update;
4121 $cust_pkg_usage->select_for_update;
4122 # in case someone else stole the usage from this CDR
4123 # while waiting for the lock...
4124 next if $old_cdr->acctid != $cdr_cust_pkg_usage->acctid;
4125 # steal the usage allocation and flag the old CDR for reprocessing
4126 $cdr_cust_pkg_usage->set('acctid', $cdr->acctid);
4127 # if the allocation is more minutes than we need, adjust it...
4128 my $delta = $cdr_cust_pkg_usage->minutes - $minutes;
4130 $cdr_cust_pkg_usage->set('minutes', $minutes);
4131 $cust_pkg_usage->set('minutes', $cust_pkg_usage->minutes + $delta);
4132 $error = $cust_pkg_usage->replace;
4134 #warn 'CDR '.$cdr->acctid . ' stealing allocation '.$cdr_cust_pkg_usage->cdrusagenum.' from CDR '.$old_cdr->acctid."\n";
4135 $error ||= $cdr_cust_pkg_usage->replace;
4136 # deduct the stolen minutes
4137 $minutes -= $cdr_cust_pkg_usage->minutes;
4139 # after all minute-stealing is done, reset the affected CDRs
4140 foreach (values %reproc_cdrs) {
4141 $error ||= $_->set_status('');
4142 # XXX or should we just call $cdr->rate right here?
4143 # it's not like we can create a loop this way, since the min_charge
4144 # or call time has to go monotonically in one direction.
4145 # we COULD get some very deep recursions going, though...
4147 } # if $order and $minutes
4150 die "error applying included minutes\npkgnum ".$self->pkgnum.", class $classnum, acctid ".$cdr->acctid."\n$error\n"
4152 $dbh->commit if $oldAutoCommit;
4153 return $orig_minutes - $minutes;
4157 =item supplemental_pkgs
4159 Returns a list of all packages supplemental to this one.
4163 sub supplemental_pkgs {
4165 qsearch('cust_pkg', { 'main_pkgnum' => $self->pkgnum });
4170 Returns the package that this one is supplemental to, if any.
4176 if ( $self->main_pkgnum ) {
4177 return FS::cust_pkg->by_key($self->main_pkgnum);
4184 =head1 CLASS METHODS
4190 Returns an SQL expression identifying recurring packages.
4194 sub recurring_sql { "
4195 '0' != ( select freq from part_pkg
4196 where cust_pkg.pkgpart = part_pkg.pkgpart )
4201 Returns an SQL expression identifying one-time packages.
4206 '0' = ( select freq from part_pkg
4207 where cust_pkg.pkgpart = part_pkg.pkgpart )
4212 Returns an SQL expression identifying ordered packages (recurring packages not
4218 $_[0]->recurring_sql. " AND ". $_[0]->not_yet_billed_sql;
4223 Returns an SQL expression identifying active packages.
4228 $_[0]->recurring_sql. "
4229 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
4230 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4231 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
4234 =item not_yet_billed_sql
4236 Returns an SQL expression identifying packages which have not yet been billed.
4240 sub not_yet_billed_sql { "
4241 ( cust_pkg.setup IS NULL OR cust_pkg.setup = 0 )
4242 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4243 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
4248 Returns an SQL expression identifying inactive packages (one-time packages
4249 that are otherwise unsuspended/uncancelled).
4253 sub inactive_sql { "
4254 ". $_[0]->onetime_sql(). "
4255 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
4256 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4257 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
4262 Returns an SQL expression identifying on-hold packages.
4267 #$_[0]->recurring_sql(). ' AND '.
4269 ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4270 AND cust_pkg.susp IS NOT NULL AND cust_pkg.susp != 0
4271 AND ( cust_pkg.setup IS NULL OR cust_pkg.setup = 0 )
4278 Returns an SQL expression identifying suspended packages.
4282 sub suspended_sql { susp_sql(@_); }
4284 #$_[0]->recurring_sql(). ' AND '.
4286 ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4287 AND cust_pkg.susp IS NOT NULL AND cust_pkg.susp != 0
4288 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
4295 Returns an SQL exprression identifying cancelled packages.
4299 sub cancelled_sql { cancel_sql(@_); }
4301 #$_[0]->recurring_sql(). ' AND '.
4302 "cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0";
4307 Returns an SQL expression to give the package status as a string.
4313 WHEN cust_pkg.cancel IS NOT NULL THEN 'cancelled'
4314 WHEN ( cust_pkg.susp IS NOT NULL AND cust_pkg.setup IS NULL ) THEN 'on hold'
4315 WHEN cust_pkg.susp IS NOT NULL THEN 'suspended'
4316 WHEN cust_pkg.setup IS NULL THEN 'not yet billed'
4317 WHEN ".onetime_sql()." THEN 'one-time charge'
4322 =item search HASHREF
4326 Returns a qsearch hash expression to search for parameters specified in HASHREF.
4327 Valid parameters are
4335 on hold, active, inactive (or one-time charge), suspended, cancel (or cancelled)
4339 on hold, active, inactive (or one-time charge), suspended, cancel (or cancelled)
4343 boolean selects custom packages
4349 pkgpart or arrayref or hashref of pkgparts
4353 arrayref of beginning and ending epoch date
4357 arrayref of beginning and ending epoch date
4361 arrayref of beginning and ending epoch date
4365 arrayref of beginning and ending epoch date
4369 arrayref of beginning and ending epoch date
4373 arrayref of beginning and ending epoch date
4377 arrayref of beginning and ending epoch date
4381 pkgnum or APKG_pkgnum
4385 a value suited to passing to FS::UI::Web::cust_header
4389 specifies the user for agent virtualization
4393 boolean; if true, returns only packages with more than 0 FCC phone lines.
4395 =item state, country
4397 Limit to packages with a service location in the specified state and country.
4398 For FCC 477 reporting, mostly.
4402 Limit to packages whose service locations are the same as the customer's
4403 default service location.
4405 =item location_nocust
4407 Limit to packages whose service locations are not the customer's default
4410 =item location_census
4412 Limit to packages whose service locations have census tracts.
4414 =item location_nocensus
4416 Limit to packages whose service locations do not have a census tract.
4418 =item location_geocode
4420 Limit to packages whose locations have geocodes.
4422 =item location_geocode
4424 Limit to packages whose locations do not have geocodes.
4431 my ($class, $params) = @_;
4438 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
4440 "cust_main.agentnum = $1";
4447 if ( $params->{'cust_status'} =~ /^([a-z]+)$/ ) {
4448 push @where, FS::cust_main->cust_status_sql . " = '$1' ";
4452 # parse customer sales person
4455 if ( $params->{'cust_main_salesnum'} =~ /^(\d+)$/ ) {
4456 push @where, ($1 > 0) ? "cust_main.salesnum = $1"
4457 : 'cust_main.salesnum IS NULL';
4462 # parse sales person
4465 if ( $params->{'salesnum'} =~ /^(\d+)$/ ) {
4466 push @where, ($1 > 0) ? "cust_pkg.salesnum = $1"
4467 : 'cust_pkg.salesnum IS NULL';
4474 if ( $params->{'custnum'} =~ /^(\d+)$/ and $1 ) {
4476 "cust_pkg.custnum = $1";
4483 if ( $params->{'pkgbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
4485 "cust_pkg.pkgbatch = '$1'";
4492 if ( $params->{'magic'} eq 'active'
4493 || $params->{'status'} eq 'active' ) {
4495 push @where, FS::cust_pkg->active_sql();
4497 } elsif ( $params->{'magic'} =~ /^not[ _]yet[ _]billed$/
4498 || $params->{'status'} =~ /^not[ _]yet[ _]billed$/ ) {
4500 push @where, FS::cust_pkg->not_yet_billed_sql();
4502 } elsif ( $params->{'magic'} =~ /^(one-time charge|inactive)/
4503 || $params->{'status'} =~ /^(one-time charge|inactive)/ ) {
4505 push @where, FS::cust_pkg->inactive_sql();
4507 } elsif ( $params->{'magic'} =~ /^on[ _]hold$/
4508 || $params->{'status'} =~ /^on[ _]hold$/ ) {
4510 push @where, FS::cust_pkg->on_hold_sql();
4513 } elsif ( $params->{'magic'} eq 'suspended'
4514 || $params->{'status'} eq 'suspended' ) {
4516 push @where, FS::cust_pkg->suspended_sql();
4518 } elsif ( $params->{'magic'} =~ /^cancell?ed$/
4519 || $params->{'status'} =~ /^cancell?ed$/ ) {
4521 push @where, FS::cust_pkg->cancelled_sql();
4526 # parse package class
4529 if ( exists($params->{'classnum'}) ) {
4532 if ( ref($params->{'classnum'}) ) {
4534 if ( ref($params->{'classnum'}) eq 'HASH' ) {
4535 @classnum = grep $params->{'classnum'}{$_}, keys %{ $params->{'classnum'} };
4536 } elsif ( ref($params->{'classnum'}) eq 'ARRAY' ) {
4537 @classnum = @{ $params->{'classnum'} };
4539 die 'unhandled classnum ref '. $params->{'classnum'};
4543 } elsif ( $params->{'classnum'} =~ /^(\d*)$/ && $1 ne '0' ) {
4550 my @nums = grep $_, @classnum;
4551 push @c_where, 'part_pkg.classnum IN ('. join(',',@nums). ')' if @nums;
4552 my $null = scalar( grep { $_ eq '' } @classnum );
4553 push @c_where, 'part_pkg.classnum IS NULL' if $null;
4555 if ( scalar(@c_where) == 1 ) {
4556 push @where, @c_where;
4557 } elsif ( @c_where ) {
4558 push @where, ' ( '. join(' OR ', @c_where). ' ) ';
4567 # parse package report options
4570 my @report_option = ();
4571 if ( exists($params->{'report_option'}) ) {
4572 if ( ref($params->{'report_option'}) eq 'ARRAY' ) {
4573 @report_option = @{ $params->{'report_option'} };
4574 } elsif ( $params->{'report_option'} =~ /^([,\d]*)$/ ) {
4575 @report_option = split(',', $1);
4580 if (@report_option) {
4581 # this will result in the empty set for the dangling comma case as it should
4583 map{ "0 < ( SELECT count(*) FROM part_pkg_option
4584 WHERE part_pkg_option.pkgpart = part_pkg.pkgpart
4585 AND optionname = 'report_option_$_'
4586 AND optionvalue = '1' )"
4590 foreach my $any ( grep /^report_option_any/, keys %$params ) {
4592 my @report_option_any = ();
4593 if ( ref($params->{$any}) eq 'ARRAY' ) {
4594 @report_option_any = @{ $params->{$any} };
4595 } elsif ( $params->{$any} =~ /^([,\d]*)$/ ) {
4596 @report_option_any = split(',', $1);
4599 if (@report_option_any) {
4600 # this will result in the empty set for the dangling comma case as it should
4601 push @where, ' ( '. join(' OR ',
4602 map{ "0 < ( SELECT count(*) FROM part_pkg_option
4603 WHERE part_pkg_option.pkgpart = part_pkg.pkgpart
4604 AND optionname = 'report_option_$_'
4605 AND optionvalue = '1' )"
4606 } @report_option_any
4616 push @where, "part_pkg.custom = 'Y'" if $params->{custom};
4622 push @where, "(part_pkg.fcc_ds0s > 0 OR pkg_class.fcc_ds0s > 0)"
4623 if $params->{fcc_line};
4629 if ( exists($params->{'censustract'}) ) {
4630 $params->{'censustract'} =~ /^([.\d]*)$/;
4631 my $censustract = "cust_location.censustract = '$1'";
4632 $censustract .= ' OR cust_location.censustract is NULL' unless $1;
4633 push @where, "( $censustract )";
4637 # parse censustract2
4639 if ( exists($params->{'censustract2'})
4640 && $params->{'censustract2'} =~ /^(\d*)$/
4644 push @where, "cust_location.censustract LIKE '$1%'";
4647 "( cust_location.censustract = '' OR cust_location.censustract IS NULL )";
4652 # parse country/state
4654 for (qw(state country)) { # parsing rules are the same for these
4655 if ( exists($params->{$_})
4656 && uc($params->{$_}) =~ /^([A-Z]{2})$/ )
4658 # XXX post-2.3 only--before that, state/country may be in cust_main
4659 push @where, "cust_location.$_ = '$1'";
4666 if ( $params->{location_cust} xor $params->{location_nocust} ) {
4667 my $op = $params->{location_cust} ? '=' : '!=';
4668 push @where, "cust_location.locationnum $op cust_main.ship_locationnum";
4670 if ( $params->{location_census} xor $params->{location_nocensus} ) {
4671 my $op = $params->{location_census} ? "IS NOT NULL" : "IS NULL";
4672 push @where, "cust_location.censustract $op";
4674 if ( $params->{location_geocode} xor $params->{location_nogeocode} ) {
4675 my $op = $params->{location_geocode} ? "IS NOT NULL" : "IS NULL";
4676 push @where, "cust_location.geocode $op";
4683 if ( ref($params->{'pkgpart'}) ) {
4686 if ( ref($params->{'pkgpart'}) eq 'HASH' ) {
4687 @pkgpart = grep $params->{'pkgpart'}{$_}, keys %{ $params->{'pkgpart'} };
4688 } elsif ( ref($params->{'pkgpart'}) eq 'ARRAY' ) {
4689 @pkgpart = @{ $params->{'pkgpart'} };
4691 die 'unhandled pkgpart ref '. $params->{'pkgpart'};
4694 @pkgpart = grep /^(\d+)$/, @pkgpart;
4696 push @where, 'pkgpart IN ('. join(',', @pkgpart). ')' if scalar(@pkgpart);
4698 } elsif ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
4699 push @where, "pkgpart = $1";
4708 #false laziness w/report_cust_pkg.html
4711 'one-time charge' => { 'last_bill'=>1, 'bill'=>1, 'adjourn'=>1, 'susp'=>1, 'expire'=>1, 'cancel'=>1, },
4712 'active' => { 'susp'=>1, 'cancel'=>1 },
4713 'suspended' => { 'cancel' => 1 },
4718 if( exists($params->{'active'} ) ) {
4719 # This overrides all the other date-related fields, and includes packages
4720 # that were active at some time during the interval. It excludes:
4721 # - packages that were set up after the end of the interval
4722 # - packages that were canceled before the start of the interval
4723 # - packages that were suspended before the start of the interval
4724 # and are still suspended now
4725 my($beginning, $ending) = @{$params->{'active'}};
4727 "cust_pkg.setup IS NOT NULL",
4728 "cust_pkg.setup <= $ending",
4729 "(cust_pkg.cancel IS NULL OR cust_pkg.cancel >= $beginning )",
4730 "(cust_pkg.susp IS NULL OR cust_pkg.susp >= $beginning )",
4731 "NOT (".FS::cust_pkg->onetime_sql . ")";
4734 foreach my $field (qw( setup last_bill bill adjourn susp expire contract_end change_date cancel )) {
4736 next unless exists($params->{$field});
4738 my($beginning, $ending) = @{$params->{$field}};
4740 next if $beginning == 0 && $ending == 4294967295;
4743 "cust_pkg.$field IS NOT NULL",
4744 "cust_pkg.$field >= $beginning",
4745 "cust_pkg.$field <= $ending";
4747 $orderby ||= "ORDER BY cust_pkg.$field";
4752 $orderby ||= 'ORDER BY bill';
4755 # parse magic, legacy, etc.
4758 if ( $params->{'magic'} &&
4759 $params->{'magic'} =~ /^(active|inactive|suspended|cancell?ed)$/
4762 $orderby = 'ORDER BY pkgnum';
4764 if ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
4765 push @where, "pkgpart = $1";
4768 } elsif ( $params->{'query'} eq 'pkgnum' ) {
4770 $orderby = 'ORDER BY pkgnum';
4772 } elsif ( $params->{'query'} eq 'APKG_pkgnum' ) {
4774 $orderby = 'ORDER BY pkgnum';
4777 SELECT count(*) FROM pkg_svc
4778 WHERE pkg_svc.pkgpart = cust_pkg.pkgpart
4779 AND pkg_svc.quantity > ( SELECT count(*) FROM cust_svc
4780 WHERE cust_svc.pkgnum = cust_pkg.pkgnum
4781 AND cust_svc.svcpart = pkg_svc.svcpart
4788 # setup queries, links, subs, etc. for the search
4791 # here is the agent virtualization
4792 if ($params->{CurrentUser}) {
4794 qsearchs('access_user', { username => $params->{CurrentUser} });
4797 push @where, $access_user->agentnums_sql('table'=>'cust_main');
4802 push @where, $FS::CurrentUser::CurrentUser->agentnums_sql('table'=>'cust_main');
4805 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
4807 my $addl_from = 'LEFT JOIN part_pkg USING ( pkgpart ) '.
4808 'LEFT JOIN pkg_class ON ( part_pkg.classnum = pkg_class.classnum ) '.
4809 'LEFT JOIN cust_location USING ( locationnum ) '.
4810 FS::UI::Web::join_cust_main('cust_pkg', 'cust_pkg');
4814 if ( $params->{'select_zip5'} ) {
4815 my $zip = 'cust_location.zip';
4817 $select = "DISTINCT substr($zip,1,5) as zip";
4818 $orderby = "ORDER BY substr($zip,1,5)";
4819 $count_query = "SELECT COUNT( DISTINCT substr($zip,1,5) )";
4821 $select = join(', ',
4823 ( map "part_pkg.$_", qw( pkg freq ) ),
4824 'pkg_class.classname',
4825 'cust_main.custnum AS cust_main_custnum',
4826 FS::UI::Web::cust_sql_fields(
4827 $params->{'cust_fields'}
4830 $count_query = 'SELECT COUNT(*)';
4833 $count_query .= " FROM cust_pkg $addl_from $extra_sql";
4836 'table' => 'cust_pkg',
4838 'select' => $select,
4839 'extra_sql' => $extra_sql,
4840 'order_by' => $orderby,
4841 'addl_from' => $addl_from,
4842 'count_query' => $count_query,
4849 Returns a list of two package counts. The first is a count of packages
4850 based on the supplied criteria and the second is the count of residential
4851 packages with those same criteria. Criteria are specified as in the search
4857 my ($class, $params) = @_;
4859 my $sql_query = $class->search( $params );
4861 my $count_sql = delete($sql_query->{'count_query'});
4862 $count_sql =~ s/ FROM/,count(CASE WHEN cust_main.company IS NULL OR cust_main.company = '' THEN 1 END) FROM/
4863 or die "couldn't parse count_sql";
4865 my $count_sth = dbh->prepare($count_sql)
4866 or die "Error preparing $count_sql: ". dbh->errstr;
4868 or die "Error executing $count_sql: ". $count_sth->errstr;
4869 my $count_arrayref = $count_sth->fetchrow_arrayref;
4871 return ( @$count_arrayref );
4875 =item tax_locationnum_sql
4877 Returns an SQL expression for the tax location for a package, based
4878 on the settings of 'tax-pkg_address' and 'tax-ship_address'.
4882 sub tax_locationnum_sql {
4883 my $conf = FS::Conf->new;
4884 if ( $conf->exists('tax-pkg_address') ) {
4885 'cust_pkg.locationnum';
4887 elsif ( $conf->exists('tax-ship_address') ) {
4888 'cust_main.ship_locationnum';
4891 'cust_main.bill_locationnum';
4897 Returns a list: the first item is an SQL fragment identifying matching
4898 packages/customers via location (taking into account shipping and package
4899 address taxation, if enabled), and subsequent items are the parameters to
4900 substitute for the placeholders in that fragment.
4905 my($class, %opt) = @_;
4906 my $ornull = $opt{'ornull'};
4908 my $conf = new FS::Conf;
4910 # '?' placeholders in _location_sql_where
4911 my $x = $ornull ? 3 : 2;
4922 if ( $conf->exists('tax-ship_address') ) {
4925 ( ( ship_last IS NULL OR ship_last = '' )
4926 AND ". _location_sql_where('cust_main', '', $ornull ). "
4928 OR ( ship_last IS NOT NULL AND ship_last != ''
4929 AND ". _location_sql_where('cust_main', 'ship_', $ornull ). "
4932 # AND payby != 'COMP'
4934 @main_param = ( @bill_param, @bill_param );
4938 $main_where = _location_sql_where('cust_main'); # AND payby != 'COMP'
4939 @main_param = @bill_param;
4945 if ( $conf->exists('tax-pkg_address') ) {
4947 my $loc_where = _location_sql_where( 'cust_location', '', $ornull );
4950 ( cust_pkg.locationnum IS NULL AND $main_where )
4951 OR ( cust_pkg.locationnum IS NOT NULL AND $loc_where )
4954 @param = ( @main_param, @bill_param );
4958 $where = $main_where;
4959 @param = @main_param;
4967 #subroutine, helper for location_sql
4968 sub _location_sql_where {
4970 my $prefix = @_ ? shift : '';
4971 my $ornull = @_ ? shift : '';
4973 # $ornull = $ornull ? " OR ( ? IS NULL AND $table.${prefix}county IS NULL ) " : '';
4975 $ornull = $ornull ? ' OR ? IS NULL ' : '';
4977 my $or_empty_city = " OR ( ? = '' AND $table.${prefix}city IS NULL )";
4978 my $or_empty_county = " OR ( ? = '' AND $table.${prefix}county IS NULL )";
4979 my $or_empty_state = " OR ( ? = '' AND $table.${prefix}state IS NULL )";
4981 my $text = (driver_name =~ /^mysql/i) ? 'char' : 'text';
4983 # ( $table.${prefix}city = ? $or_empty_city $ornull )
4985 ( $table.district = ? OR ? = '' OR CAST(? AS $text) IS NULL )
4986 AND ( $table.${prefix}city = ? OR ? = '' OR CAST(? AS $text) IS NULL )
4987 AND ( $table.${prefix}county = ? $or_empty_county $ornull )
4988 AND ( $table.${prefix}state = ? $or_empty_state $ornull )
4989 AND $table.${prefix}country = ?
4994 my( $self, $what ) = @_;
4996 my $what_show_zero = $what. '_show_zero';
4997 length($self->$what_show_zero())
4998 ? ($self->$what_show_zero() eq 'Y')
4999 : $self->part_pkg->$what_show_zero();
5006 =item order CUSTNUM, PKGPARTS_ARYREF, [ REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF [ REFNUM ] ] ]
5008 CUSTNUM is a customer (see L<FS::cust_main>)
5010 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
5011 L<FS::part_pkg>) to order for this customer. Duplicates are of course
5014 REMOVE_PKGNUMS is an optional list of pkgnums specifying the billing items to
5015 remove for this customer. The services (see L<FS::cust_svc>) are moved to the
5016 new billing items. An error is returned if this is not possible (see
5017 L<FS::pkg_svc>). An empty arrayref is equivalent to not specifying this
5020 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
5021 newly-created cust_pkg objects.
5023 REFNUM, if specified, will specify the FS::pkg_referral record to be created
5024 and inserted. Multiple FS::pkg_referral records can be created by
5025 setting I<refnum> to an array reference of refnums or a hash reference with
5026 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
5027 record will be created corresponding to cust_main.refnum.
5032 my ($custnum, $pkgparts, $remove_pkgnum, $return_cust_pkg, $refnum) = @_;
5034 my $conf = new FS::Conf;
5036 # Transactionize this whole mess
5037 local $SIG{HUP} = 'IGNORE';
5038 local $SIG{INT} = 'IGNORE';
5039 local $SIG{QUIT} = 'IGNORE';
5040 local $SIG{TERM} = 'IGNORE';
5041 local $SIG{TSTP} = 'IGNORE';
5042 local $SIG{PIPE} = 'IGNORE';
5044 my $oldAutoCommit = $FS::UID::AutoCommit;
5045 local $FS::UID::AutoCommit = 0;
5049 # my $cust_main = qsearchs('cust_main', { custnum => $custnum });
5050 # return "Customer not found: $custnum" unless $cust_main;
5052 warn "$me order: pkgnums to remove: ". join(',', @$remove_pkgnum). "\n"
5055 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
5058 my $change = scalar(@old_cust_pkg) != 0;
5061 if ( scalar(@old_cust_pkg) == 1 && scalar(@$pkgparts) == 1 ) {
5063 warn "$me order: changing pkgnum ". $old_cust_pkg[0]->pkgnum.
5064 " to pkgpart ". $pkgparts->[0]. "\n"
5067 my $err_or_cust_pkg =
5068 $old_cust_pkg[0]->change( 'pkgpart' => $pkgparts->[0],
5069 'refnum' => $refnum,
5072 unless (ref($err_or_cust_pkg)) {
5073 $dbh->rollback if $oldAutoCommit;
5074 return $err_or_cust_pkg;
5077 push @$return_cust_pkg, $err_or_cust_pkg;
5078 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5083 # Create the new packages.
5084 foreach my $pkgpart (@$pkgparts) {
5086 warn "$me order: inserting pkgpart $pkgpart\n" if $DEBUG;
5088 my $cust_pkg = new FS::cust_pkg { custnum => $custnum,
5089 pkgpart => $pkgpart,
5093 $error = $cust_pkg->insert( 'change' => $change );
5094 push @$return_cust_pkg, $cust_pkg;
5096 foreach my $link ($cust_pkg->part_pkg->supp_part_pkg_link) {
5097 my $supp_pkg = FS::cust_pkg->new({
5098 custnum => $custnum,
5099 pkgpart => $link->dst_pkgpart,
5101 main_pkgnum => $cust_pkg->pkgnum,
5104 $error ||= $supp_pkg->insert( 'change' => $change );
5105 push @$return_cust_pkg, $supp_pkg;
5109 $dbh->rollback if $oldAutoCommit;
5114 # $return_cust_pkg now contains refs to all of the newly
5117 # Transfer services and cancel old packages.
5118 foreach my $old_pkg (@old_cust_pkg) {
5120 warn "$me order: transferring services from pkgnum ". $old_pkg->pkgnum. "\n"
5123 foreach my $new_pkg (@$return_cust_pkg) {
5124 $error = $old_pkg->transfer($new_pkg);
5125 if ($error and $error == 0) {
5126 # $old_pkg->transfer failed.
5127 $dbh->rollback if $oldAutoCommit;
5132 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
5133 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
5134 foreach my $new_pkg (@$return_cust_pkg) {
5135 $error = $old_pkg->transfer($new_pkg, 'change_svcpart'=>1 );
5136 if ($error and $error == 0) {
5137 # $old_pkg->transfer failed.
5138 $dbh->rollback if $oldAutoCommit;
5145 # Transfers were successful, but we went through all of the
5146 # new packages and still had services left on the old package.
5147 # We can't cancel the package under the circumstances, so abort.
5148 $dbh->rollback if $oldAutoCommit;
5149 return "Unable to transfer all services from package ".$old_pkg->pkgnum;
5151 $error = $old_pkg->cancel( quiet=>1 );
5157 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5161 =item bulk_change PKGPARTS_ARYREF, REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF ]
5163 A bulk change method to change packages for multiple customers.
5165 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
5166 L<FS::part_pkg>) to order for each customer. Duplicates are of course
5169 REMOVE_PKGNUMS is an list of pkgnums specifying the billing items to
5170 replace. The services (see L<FS::cust_svc>) are moved to the
5171 new billing items. An error is returned if this is not possible (see
5174 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
5175 newly-created cust_pkg objects.
5180 my ($pkgparts, $remove_pkgnum, $return_cust_pkg) = @_;
5182 # Transactionize this whole mess
5183 local $SIG{HUP} = 'IGNORE';
5184 local $SIG{INT} = 'IGNORE';
5185 local $SIG{QUIT} = 'IGNORE';
5186 local $SIG{TERM} = 'IGNORE';
5187 local $SIG{TSTP} = 'IGNORE';
5188 local $SIG{PIPE} = 'IGNORE';
5190 my $oldAutoCommit = $FS::UID::AutoCommit;
5191 local $FS::UID::AutoCommit = 0;
5195 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
5198 while(scalar(@old_cust_pkg)) {
5200 my $custnum = $old_cust_pkg[0]->custnum;
5201 my (@remove) = map { $_->pkgnum }
5202 grep { $_->custnum == $custnum } @old_cust_pkg;
5203 @old_cust_pkg = grep { $_->custnum != $custnum } @old_cust_pkg;
5205 my $error = order $custnum, $pkgparts, \@remove, \@return;
5207 push @errors, $error
5209 push @$return_cust_pkg, @return;
5212 if (scalar(@errors)) {
5213 $dbh->rollback if $oldAutoCommit;
5214 return join(' / ', @errors);
5217 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5221 # Used by FS::Upgrade to migrate to a new database.
5222 sub _upgrade_data { # class method
5223 my ($class, %opts) = @_;
5224 $class->_upgrade_otaker(%opts);
5226 # RT#10139, bug resulting in contract_end being set when it shouldn't
5227 'UPDATE cust_pkg SET contract_end = NULL WHERE contract_end = -1',
5228 # RT#10830, bad calculation of prorate date near end of year
5229 # the date range for bill is December 2009, and we move it forward
5230 # one year if it's before the previous bill date (which it should
5232 'UPDATE cust_pkg SET bill = bill + (365*24*60*60) WHERE bill < last_bill
5233 AND bill > 1259654400 AND bill < 1262332800 AND (SELECT plan FROM part_pkg
5234 WHERE part_pkg.pkgpart = cust_pkg.pkgpart) = \'prorate\'',
5235 # RT6628, add order_date to cust_pkg
5236 'update cust_pkg set order_date = (select history_date from h_cust_pkg
5237 where h_cust_pkg.pkgnum = cust_pkg.pkgnum and
5238 history_action = \'insert\') where order_date is null',
5240 foreach my $sql (@statements) {
5241 my $sth = dbh->prepare($sql);
5242 $sth->execute or die $sth->errstr;
5250 sub order is not OO. Perhaps it should be moved to FS::cust_main and made so?
5252 In sub order, the @pkgparts array (passed by reference) is clobbered.
5254 Also in sub order, no money is adjusted. Once FS::part_pkg defines a standard
5255 method to pass dates to the recur_prog expression, it should do so.
5257 FS::svc_acct, FS::svc_domain, FS::svc_www, FS::svc_ip and FS::svc_forward are
5258 loaded via 'use' at compile time, rather than via 'require' in sub { setup,
5259 suspend, unsuspend, cancel } because they use %FS::UID::callback to load
5260 configuration values. Probably need a subroutine which decides what to do
5261 based on whether or not we've fetched the user yet, rather than a hash. See
5262 FS::UID and the TODO.
5264 Now that things are transactional should the check in the insert method be
5269 L<FS::Record>, L<FS::cust_main>, L<FS::part_pkg>, L<FS::cust_svc>,
5270 L<FS::pkg_svc>, schema.html from the base documentation