2 use base qw( FS::cust_pkg::Search FS::cust_pkg::API
3 FS::otaker_Mixin FS::cust_main_Mixin FS::Sales_Mixin
4 FS::contact_Mixin FS::location_Mixin
5 FS::m2m_Common FS::option_Common
10 use Scalar::Util qw( blessed );
11 use List::Util qw(min max);
13 use Time::Local qw( timelocal timelocal_nocheck );
15 use FS::UID qw( dbh driver_name );
16 use FS::Misc qw( send_email );
17 use FS::Record qw( qsearch qsearchs fields );
23 use FS::cust_location;
25 use FS::cust_bill_pkg;
26 use FS::cust_pkg_detail;
27 use FS::cust_pkg_usage;
28 use FS::cdr_cust_pkg_usage;
33 use FS::cust_pkg_reason;
35 use FS::cust_pkg_usageprice;
36 use FS::cust_pkg_discount;
42 # need to 'use' these instead of 'require' in sub { cancel, suspend, unsuspend,
44 # because they load configuration by setting FS::UID::callback (see TODO)
50 # for sending cancel emails in sub cancel
53 our ($disable_agentcheck, $DEBUG, $me, $import) = (0, 0, '[FS::cust_pkg]', 0);
55 our $upgrade = 0; #go away after setup+start dates cleaned up for old customers
59 my ( $hashref, $cache ) = @_;
60 #if ( $hashref->{'pkgpart'} ) {
61 if ( $hashref->{'pkg'} ) {
62 # #@{ $self->{'_pkgnum'} } = ();
63 # my $subcache = $cache->subcache('pkgpart', 'part_pkg');
64 # $self->{'_pkgpart'} = $subcache;
65 # #push @{ $self->{'_pkgnum'} },
66 # FS::part_pkg->new_or_cached($hashref, $subcache);
67 $self->{'_pkgpart'} = FS::part_pkg->new($hashref);
69 if ( exists $hashref->{'svcnum'} ) {
70 #@{ $self->{'_pkgnum'} } = ();
71 my $subcache = $cache->subcache('svcnum', 'cust_svc', $hashref->{pkgnum});
72 $self->{'_svcnum'} = $subcache;
73 #push @{ $self->{'_pkgnum'} },
74 FS::cust_svc->new_or_cached($hashref, $subcache) if $hashref->{svcnum};
80 FS::cust_pkg - Object methods for cust_pkg objects
86 $record = new FS::cust_pkg \%hash;
87 $record = new FS::cust_pkg { 'column' => 'value' };
89 $error = $record->insert;
91 $error = $new_record->replace($old_record);
93 $error = $record->delete;
95 $error = $record->check;
97 $error = $record->cancel;
99 $error = $record->suspend;
101 $error = $record->unsuspend;
103 $part_pkg = $record->part_pkg;
105 @labels = $record->labels;
107 $seconds = $record->seconds_since($timestamp);
109 $error = FS::cust_pkg::order( $custnum, \@pkgparts );
110 $error = FS::cust_pkg::order( $custnum, \@pkgparts, \@remove_pkgnums ] );
114 An FS::cust_pkg object represents a customer billing item. FS::cust_pkg
115 inherits from FS::Record. The following fields are currently supported:
121 Primary key (assigned automatically for new billing items)
125 Customer (see L<FS::cust_main>)
129 Billing item definition (see L<FS::part_pkg>)
133 Optional link to package location (see L<FS::location>)
137 date package was ordered (also remains same on changes)
149 date (next bill date)
177 order taker (see L<FS::access_user>)
181 If this field is set to 1, disables the automatic
182 unsuspension of this package when using the B<unsuspendauto> config option.
186 If not set, defaults to 1
190 Date of change from previous package
200 =item change_locationnum
208 The pkgnum of the package that this package is supplemental to, if any.
212 The package link (L<FS::part_pkg_link>) that defines this supplemental
213 package, if it is one.
215 =item change_to_pkgnum
217 The pkgnum of the package this one will be "changed to" in the future
218 (on its expiration date).
222 Note: setup, last_bill, bill, adjourn, susp, expire, cancel and change_date
223 are specified as UNIX timestamps; see L<perlfunc/"time">. Also see
224 L<Time::Local> and L<Date::Parse> for conversion functions.
232 Create a new billing item. To add the item to the database, see L<"insert">.
236 sub table { 'cust_pkg'; }
237 sub cust_linked { $_[0]->cust_main_custnum || $_[0]->custnum }
238 sub cust_unlinked_msg {
240 "WARNING: can't find cust_main.custnum ". $self->custnum.
241 ' (cust_pkg.pkgnum '. $self->pkgnum. ')';
244 =item insert [ OPTION => VALUE ... ]
246 Adds this billing item to the database ("Orders" the item). If there is an
247 error, returns the error, otherwise returns false.
249 If the additional field I<promo_code> is defined instead of I<pkgpart>, it
250 will be used to look up the package definition and agent restrictions will be
253 If the additional field I<refnum> is defined, an FS::pkg_referral record will
254 be created and inserted. Multiple FS::pkg_referral records can be created by
255 setting I<refnum> to an array reference of refnums or a hash reference with
256 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
257 record will be created corresponding to cust_main.refnum.
259 If the additional field I<cust_pkg_usageprice> is defined, it will be treated
260 as an arrayref of FS::cust_pkg_usageprice objects, which will be inserted.
261 (Note that this field cannot be set with a usual ->cust_pkg_usageprice method.
262 It can be set as part of the hash when creating the object, or with the B<set>
265 The following options are available:
271 If set true, supresses actions that should only be taken for new package
272 orders. (Currently this includes: intro periods when delay_setup is on,
273 auto-adding a 1st start date, auto-adding expiration/adjourn/contract_end dates)
277 cust_pkg_option records will be created
281 a ticket will be added to this customer with this subject
285 an optional queue name for ticket additions
289 Don't check the legality of the package definition. This should be used
290 when performing a package change that doesn't change the pkgpart (i.e.
298 my( $self, %options ) = @_;
301 $error = $self->check_pkgpart unless $options{'allow_pkgpart'};
302 return $error if $error;
304 my $part_pkg = $self->part_pkg;
306 if ( ! $import && ! $options{'change'} ) {
308 # if the package def says to start only on the first of the month:
309 if ( $part_pkg->option('start_1st', 1) && !$self->start_date ) {
310 my ($sec,$min,$hour,$mday,$mon,$year) = (localtime(time) )[0,1,2,3,4,5];
311 $mon += 1 unless $mday == 1;
312 until ( $mon < 12 ) { $mon -= 12; $year++; }
313 $self->start_date( timelocal_nocheck(0,0,0,1,$mon,$year) );
316 # set up any automatic expire/adjourn/contract_end timers
317 # based on the start date
318 foreach my $action ( qw(expire adjourn contract_end) ) {
319 my $months = $part_pkg->option("${action}_months",1);
320 if($months and !$self->$action) {
321 my $start = $self->start_date || $self->setup || time;
322 $self->$action( $part_pkg->add_freq($start, $months) );
326 # if this package has "free days" and delayed setup fee, then
327 # set start date that many days in the future.
328 # (this should have been set in the UI, but enforce it here)
329 if ( ! $options{'change'}
330 && $part_pkg->option('free_days', 1)
331 && $part_pkg->option('delay_setup',1)
332 #&& ! $self->start_date
335 $self->start_date( $part_pkg->default_start_date );
339 # set order date unless it was specified as part of an import
340 # or this was previously a different package
341 $self->order_date(time) unless ($import && $self->order_date)
342 or $self->change_pkgnum;
344 $self->susp( $self->order_date ) if $self->susp eq 'now';
346 my $oldAutoCommit = $FS::UID::AutoCommit;
347 local $FS::UID::AutoCommit = 0;
350 $error = $self->SUPER::insert($options{options} ? %{$options{options}} : ());
352 $dbh->rollback if $oldAutoCommit;
356 $self->refnum($self->cust_main->refnum) unless $self->refnum;
357 $self->refnum( [ $self->refnum ] ) unless ref($self->refnum);
358 $self->process_m2m( 'link_table' => 'pkg_referral',
359 'target_table' => 'part_referral',
360 'params' => $self->refnum,
363 if ( $self->hashref->{cust_pkg_usageprice} ) {
364 for my $cust_pkg_usageprice ( @{ $self->hashref->{cust_pkg_usageprice} } ) {
365 $cust_pkg_usageprice->pkgnum( $self->pkgnum );
366 my $error = $cust_pkg_usageprice->insert;
368 $dbh->rollback if $oldAutoCommit;
374 if ( $self->discountnum ) {
375 my $error = $self->insert_discount();
377 $dbh->rollback if $oldAutoCommit;
382 my $conf = new FS::Conf;
384 if ( ! $import && $conf->config('ticket_system') && $options{ticket_subject} ) {
386 #this init stuff is still inefficient, but at least its limited to
387 # the small number (any?) folks using ticket emailing on pkg order
390 # use lib ( "/opt/rt3/local/lib", "/opt/rt3/lib" );
397 use FS::TicketSystem;
398 FS::TicketSystem->init();
400 my $q = new RT::Queue($RT::SystemUser);
401 $q->Load($options{ticket_queue}) if $options{ticket_queue};
402 my $t = new RT::Ticket($RT::SystemUser);
403 my $mime = new MIME::Entity;
404 $mime->build( Type => 'text/plain', Data => $options{ticket_subject} );
405 $t->Create( $options{ticket_queue} ? (Queue => $q) : (),
406 Subject => $options{ticket_subject},
409 $t->AddLink( Type => 'MemberOf',
410 Target => 'freeside://freeside/cust_main/'. $self->custnum,
414 if (! $import && $conf->config('welcome_letter') && $self->cust_main->num_pkgs == 1) {
415 my $queue = new FS::queue {
416 'job' => 'FS::cust_main::queueable_print',
418 $error = $queue->insert(
419 'custnum' => $self->custnum,
420 'template' => 'welcome_letter',
424 warn "can't send welcome letter: $error";
429 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
436 This method now works but you probably shouldn't use it.
438 You don't want to delete packages, because there would then be no record
439 the customer ever purchased the package. Instead, see the cancel method and
440 hide cancelled packages.
447 my $oldAutoCommit = $FS::UID::AutoCommit;
448 local $FS::UID::AutoCommit = 0;
451 foreach my $cust_pkg_discount ($self->cust_pkg_discount) {
452 my $error = $cust_pkg_discount->delete;
454 $dbh->rollback if $oldAutoCommit;
458 #cust_bill_pkg_discount?
460 foreach my $cust_pkg_detail ($self->cust_pkg_detail) {
461 my $error = $cust_pkg_detail->delete;
463 $dbh->rollback if $oldAutoCommit;
468 foreach my $cust_pkg_reason (
470 'table' => 'cust_pkg_reason',
471 'hashref' => { 'pkgnum' => $self->pkgnum },
475 my $error = $cust_pkg_reason->delete;
477 $dbh->rollback if $oldAutoCommit;
484 my $error = $self->SUPER::delete(@_);
486 $dbh->rollback if $oldAutoCommit;
490 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
496 =item replace [ OLD_RECORD ] [ HASHREF | OPTION => VALUE ... ]
498 Replaces the OLD_RECORD with this one in the database. If there is an error,
499 returns the error, otherwise returns false.
501 Currently, custnum, setup, bill, adjourn, susp, expire, and cancel may be changed.
503 Changing pkgpart may have disasterous effects. See the order subroutine.
505 setup and bill are normally updated by calling the bill method of a customer
506 object (see L<FS::cust_main>).
508 suspend is normally updated by the suspend and unsuspend methods.
510 cancel is normally updated by the cancel method (and also the order subroutine
513 Available options are:
519 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.
523 the access_user (see L<FS::access_user>) providing the reason
527 hashref of keys and values - cust_pkg_option records will be created, updated or removed as appopriate
536 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
541 ( ref($_[0]) eq 'HASH' )
545 #return "Can't (yet?) change pkgpart!" if $old->pkgpart != $new->pkgpart;
546 #return "Can't change otaker!" if $old->otaker ne $new->otaker;
549 #return "Can't change setup once it exists!"
550 # if $old->getfield('setup') &&
551 # $old->getfield('setup') != $new->getfield('setup');
553 #some logic for bill, susp, cancel?
555 local($disable_agentcheck) = 1 if $old->pkgpart == $new->pkgpart;
557 my $oldAutoCommit = $FS::UID::AutoCommit;
558 local $FS::UID::AutoCommit = 0;
561 foreach my $method ( qw(adjourn expire) ) { # How many reasons?
562 if ($options->{'reason'} && $new->$method && $old->$method ne $new->$method) {
563 my $error = $new->insert_reason(
564 'reason' => $options->{'reason'},
565 'date' => $new->$method,
567 'reason_otaker' => $options->{'reason_otaker'},
570 dbh->rollback if $oldAutoCommit;
571 return "Error inserting cust_pkg_reason: $error";
576 #save off and freeze RADIUS attributes for any associated svc_acct records
578 if ( $old->part_pkg->is_prepaid || $new->part_pkg->is_prepaid ) {
580 #also check for specific exports?
581 # to avoid spurious modify export events
582 @svc_acct = map { $_->svc_x }
583 grep { $_->part_svc->svcdb eq 'svc_acct' }
586 $_->snapshot foreach @svc_acct;
590 my $error = $new->export_pkg_change($old)
591 || $new->SUPER::replace( $old,
593 ? $options->{options}
597 $dbh->rollback if $oldAutoCommit;
601 #for prepaid packages,
602 #trigger export of new RADIUS Expiration attribute when cust_pkg.bill changes
603 foreach my $old_svc_acct ( @svc_acct ) {
604 my $new_svc_acct = new FS::svc_acct { $old_svc_acct->hash };
606 $new_svc_acct->replace( $old_svc_acct,
607 'depend_jobnum' => $options->{depend_jobnum},
610 $dbh->rollback if $oldAutoCommit;
615 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
622 Checks all fields to make sure this is a valid billing item. If there is an
623 error, returns the error, otherwise returns false. Called by the insert and
631 if ( !$self->locationnum or $self->locationnum == -1 ) {
632 $self->set('locationnum', $self->cust_main->ship_locationnum);
636 $self->ut_numbern('pkgnum')
637 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum')
638 || $self->ut_numbern('pkgpart')
639 || $self->ut_foreign_keyn('contactnum', 'contact', 'contactnum' )
640 || $self->ut_foreign_keyn('locationnum', 'cust_location', 'locationnum')
641 || $self->ut_foreign_keyn('salesnum', 'sales', 'salesnum')
642 || $self->ut_numbern('quantity')
643 || $self->ut_numbern('start_date')
644 || $self->ut_numbern('setup')
645 || $self->ut_numbern('bill')
646 || $self->ut_numbern('susp')
647 || $self->ut_numbern('cancel')
648 || $self->ut_numbern('adjourn')
649 || $self->ut_numbern('resume')
650 || $self->ut_numbern('expire')
651 || $self->ut_numbern('dundate')
652 || $self->ut_enum('no_auto', [ '', 'Y' ])
653 || $self->ut_enum('waive_setup', [ '', 'Y' ])
654 || $self->ut_textn('agent_pkgid')
655 || $self->ut_enum('recur_show_zero', [ '', 'Y', 'N', ])
656 || $self->ut_enum('setup_show_zero', [ '', 'Y', 'N', ])
657 || $self->ut_foreign_keyn('main_pkgnum', 'cust_pkg', 'pkgnum')
658 || $self->ut_foreign_keyn('pkglinknum', 'part_pkg_link', 'pkglinknum')
659 || $self->ut_foreign_keyn('change_to_pkgnum', 'cust_pkg', 'pkgnum')
661 return $error if $error;
663 return "A package with both start date (future start) and setup date (already started) will never bill"
664 if $self->start_date && $self->setup && ! $upgrade;
666 return "A future unsuspend date can only be set for a package with a suspend date"
667 if $self->resume and !$self->susp and !$self->adjourn;
669 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
671 if ( $self->dbdef_table->column('manual_flag') ) {
672 $self->manual_flag('') if $self->manual_flag eq ' ';
673 $self->manual_flag =~ /^([01]?)$/
674 or return "Illegal manual_flag ". $self->manual_flag;
675 $self->manual_flag($1);
683 Check the pkgpart to make sure it's allowed with the reg_code and/or
684 promo_code of the package (if present) and with the customer's agent.
685 Called from C<insert>, unless we are doing a package change that doesn't
693 # my $error = $self->ut_numbern('pkgpart'); # already done
696 if ( $self->reg_code ) {
698 unless ( grep { $self->pkgpart == $_->pkgpart }
699 map { $_->reg_code_pkg }
700 qsearchs( 'reg_code', { 'code' => $self->reg_code,
701 'agentnum' => $self->cust_main->agentnum })
703 return "Unknown registration code";
706 } elsif ( $self->promo_code ) {
709 qsearchs('part_pkg', {
710 'pkgpart' => $self->pkgpart,
711 'promo_code' => { op=>'ILIKE', value=>$self->promo_code },
713 return 'Unknown promotional code' unless $promo_part_pkg;
717 unless ( $disable_agentcheck ) {
719 qsearchs( 'agent', { 'agentnum' => $self->cust_main->agentnum } );
720 return "agent ". $agent->agentnum. ':'. $agent->agent.
721 " can't purchase pkgpart ". $self->pkgpart
722 unless $agent->pkgpart_hashref->{ $self->pkgpart }
723 || $agent->agentnum == $self->part_pkg->agentnum;
726 $error = $self->ut_foreign_key('pkgpart', 'part_pkg', 'pkgpart' );
727 return $error if $error;
735 =item cancel [ OPTION => VALUE ... ]
737 Cancels and removes all services (see L<FS::cust_svc> and L<FS::part_svc>)
738 in this package, then cancels the package itself (sets the cancel field to
741 Available options are:
745 =item quiet - can be set true to supress email cancellation notices.
747 =item time - can be set to cancel the package based on a specific future or
748 historical date. Using time ensures that the remaining amount is calculated
749 correctly. Note however that this is an immediate cancel and just changes
750 the date. You are PROBABLY looking to expire the account instead of using
753 =item reason - can be set to a cancellation reason (see L<FS:reason>),
754 either a reasonnum of an existing reason, or passing a hashref will create
755 a new reason. The hashref should have the following keys: typenum - Reason
756 type (see L<FS::reason_type>, reason - Text of the new reason.
758 =item date - can be set to a unix style timestamp to specify when to
761 =item nobill - can be set true to skip billing if it might otherwise be done.
763 =item unused_credit - can be set to 1 to credit the remaining time, or 0 to
764 not credit it. This must be set (by change()) when changing the package
765 to a different pkgpart or location, and probably shouldn't be in any other
766 case. If it's not set, the 'unused_credit_cancel' part_pkg option will
771 If there is an error, returns the error, otherwise returns false.
776 my( $self, %options ) = @_;
779 # pass all suspend/cancel actions to the main package
780 if ( $self->main_pkgnum and !$options{'from_main'} ) {
781 return $self->main_pkg->cancel(%options);
784 my $conf = new FS::Conf;
786 warn "cust_pkg::cancel called with options".
787 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
790 my $oldAutoCommit = $FS::UID::AutoCommit;
791 local $FS::UID::AutoCommit = 0;
794 my $old = $self->select_for_update;
796 if ( $old->get('cancel') || $self->get('cancel') ) {
797 dbh->rollback if $oldAutoCommit;
798 return ""; # no error
801 # XXX possibly set cancel_time to the expire date?
802 my $cancel_time = $options{'time'} || time;
803 my $date = $options{'date'} if $options{'date'}; # expire/cancel later
804 $date = '' if ($date && $date <= $cancel_time); # complain instead?
806 #race condition: usage could be ongoing until unprovisioned
807 #resolved by performing a change package instead (which unprovisions) and
809 if ( !$options{nobill} && !$date ) {
810 # && $conf->exists('bill_usage_on_cancel') ) { #calc_cancel checks this
811 my $copy = $self->new({$self->hash});
813 $copy->cust_main->bill( 'pkg_list' => [ $copy ],
815 'time' => $cancel_time );
816 warn "Error billing during cancel, custnum ".
817 #$self->cust_main->custnum. ": $error"
822 if ( $options{'reason'} ) {
823 $error = $self->insert_reason( 'reason' => $options{'reason'},
824 'action' => $date ? 'expire' : 'cancel',
825 'date' => $date ? $date : $cancel_time,
826 'reason_otaker' => $options{'reason_otaker'},
829 dbh->rollback if $oldAutoCommit;
830 return "Error inserting cust_pkg_reason: $error";
834 my %svc_cancel_opt = ();
835 $svc_cancel_opt{'date'} = $date if $date;
836 foreach my $cust_svc (
839 sort { $a->[1] <=> $b->[1] }
840 map { [ $_, $_->svc_x ? $_->svc_x->table_info->{'cancel_weight'} : -1 ]; }
841 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
843 my $part_svc = $cust_svc->part_svc;
844 next if ( defined($part_svc) and $part_svc->preserve );
845 my $error = $cust_svc->cancel( %svc_cancel_opt );
848 $dbh->rollback if $oldAutoCommit;
849 return 'Error '. ($svc_cancel_opt{'date'} ? 'expiring' : 'canceling' ).
855 # credit remaining time if appropriate
857 if ( exists($options{'unused_credit'}) ) {
858 $do_credit = $options{'unused_credit'};
861 $do_credit = $self->part_pkg->option('unused_credit_cancel', 1);
864 my $error = $self->credit_remaining('cancel', $cancel_time);
866 $dbh->rollback if $oldAutoCommit;
873 my %hash = $self->hash;
875 $hash{'expire'} = $date;
877 $hash{'cancel'} = $cancel_time;
879 $hash{'change_custnum'} = $options{'change_custnum'};
881 my $new = new FS::cust_pkg ( \%hash );
882 $error = $new->replace( $self, options => { $self->options } );
883 if ( $self->change_to_pkgnum ) {
884 my $change_to = FS::cust_pkg->by_key($self->change_to_pkgnum);
885 $error ||= $change_to->cancel || $change_to->delete;
888 $dbh->rollback if $oldAutoCommit;
892 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
893 $error = $supp_pkg->cancel(%options, 'from_main' => 1);
895 $dbh->rollback if $oldAutoCommit;
896 return "canceling supplemental pkg#".$supp_pkg->pkgnum.": $error";
900 foreach my $usage ( $self->cust_pkg_usage ) {
901 $error = $usage->delete;
903 $dbh->rollback if $oldAutoCommit;
904 return "deleting usage pools: $error";
908 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
909 return '' if $date; #no errors
911 my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ } $self->cust_main->invoicing_list;
912 if ( !$options{'quiet'} &&
913 $conf->exists('emailcancel', $self->cust_main->agentnum) &&
915 my $msgnum = $conf->config('cancel_msgnum', $self->cust_main->agentnum);
918 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum });
919 $error = $msg_template->send( 'cust_main' => $self->cust_main,
924 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
925 'to' => \@invoicing_list,
926 'subject' => ( $conf->config('cancelsubject') || 'Cancellation Notice' ),
927 'body' => [ map "$_\n", $conf->config('cancelmessage') ],
928 'custnum' => $self->custnum,
929 'msgtype' => '', #admin?
932 #should this do something on errors?
939 =item cancel_if_expired [ NOW_TIMESTAMP ]
941 Cancels this package if its expire date has been reached.
945 sub cancel_if_expired {
947 my $time = shift || time;
948 return '' unless $self->expire && $self->expire <= $time;
949 my $error = $self->cancel;
951 return "Error cancelling expired pkg ". $self->pkgnum. " for custnum ".
952 $self->custnum. ": $error";
959 "Un-cancels" this package: Orders a new package with the same custnum, pkgpart,
960 locationnum, (other fields?). Attempts to re-provision cancelled services
961 using history information (errors at this stage are not fatal).
963 cust_pkg: pass a scalar reference, will be filled in with the new cust_pkg object
965 svc_fatal: service provisioning errors are fatal
967 svc_errors: pass an array reference, will be filled in with any provisioning errors
969 main_pkgnum: link the package as a supplemental package of this one. For
975 my( $self, %options ) = @_;
977 #in case you try do do $uncancel-date = $cust_pkg->uncacel
978 return '' unless $self->get('cancel');
980 if ( $self->main_pkgnum and !$options{'main_pkgnum'} ) {
981 return $self->main_pkg->uncancel(%options);
988 my $oldAutoCommit = $FS::UID::AutoCommit;
989 local $FS::UID::AutoCommit = 0;
993 # insert the new package
996 my $cust_pkg = new FS::cust_pkg {
997 last_bill => ( $options{'last_bill'} || $self->get('last_bill') ),
998 bill => ( $options{'bill'} || $self->get('bill') ),
1000 uncancel_pkgnum => $self->pkgnum,
1001 main_pkgnum => ($options{'main_pkgnum'} || ''),
1002 map { $_ => $self->get($_) } qw(
1003 custnum pkgpart locationnum
1005 susp adjourn resume expire start_date contract_end dundate
1006 change_date change_pkgpart change_locationnum
1007 manual_flag no_auto quantity agent_pkgid recur_show_zero setup_show_zero
1011 my $error = $cust_pkg->insert(
1012 'change' => 1, #supresses any referral credit to a referring customer
1013 'allow_pkgpart' => 1, # allow this even if the package def is disabled
1016 $dbh->rollback if $oldAutoCommit;
1024 #find historical services within this timeframe before the package cancel
1025 # (incompatible with "time" option to cust_pkg->cancel?)
1026 my $fuzz = 2 * 60; #2 minutes? too much? (might catch separate unprovision)
1027 # too little? (unprovisioing export delay?)
1028 my($end, $start) = ( $self->get('cancel'), $self->get('cancel') - $fuzz );
1029 my @h_cust_svc = $self->h_cust_svc( $end, $start );
1032 foreach my $h_cust_svc (@h_cust_svc) {
1033 my $h_svc_x = $h_cust_svc->h_svc_x( $end, $start );
1034 #next unless $h_svc_x; #should this happen?
1035 (my $table = $h_svc_x->table) =~ s/^h_//;
1036 require "FS/$table.pm";
1037 my $class = "FS::$table";
1038 my $svc_x = $class->new( {
1039 'pkgnum' => $cust_pkg->pkgnum,
1040 'svcpart' => $h_cust_svc->svcpart,
1041 map { $_ => $h_svc_x->get($_) } fields($table)
1045 if ( $h_svc_x->isa('FS::h_svc_Radius_Mixin') ) {
1046 $svc_x->usergroup( [ $h_svc_x->h_usergroup($end, $start) ] );
1049 my $svc_error = $svc_x->insert;
1051 if ( $options{svc_fatal} ) {
1052 $dbh->rollback if $oldAutoCommit;
1055 # if we've failed to insert the svc_x object, svc_Common->insert
1056 # will have removed the cust_svc already. if not, then both records
1057 # were inserted but we failed for some other reason (export, most
1058 # likely). in that case, report the error and delete the records.
1059 push @svc_errors, $svc_error;
1060 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svc_x->svcnum });
1062 # except if export_insert failed, export_delete probably won't be
1064 local $FS::svc_Common::noexport_hack = 1;
1065 my $cleanup_error = $svc_x->delete; # also deletes cust_svc
1066 if ( $cleanup_error ) { # and if THAT fails, then run away
1067 $dbh->rollback if $oldAutoCommit;
1068 return $cleanup_error;
1073 } #foreach $h_cust_svc
1075 #these are pretty rare, but should handle them
1076 # - dsl_device (mac addresses)
1077 # - phone_device (mac addresses)
1078 # - dsl_note (ikano notes)
1079 # - domain_record (i.e. restore DNS information w/domains)
1080 # - inventory_item(?) (inventory w/un-cancelling service?)
1081 # - nas (svc_broaband nas stuff)
1082 #this stuff is unused in the wild afaik
1083 # - mailinglistmember
1085 # - svc_domain.parent_svcnum?
1086 # - acct_snarf (ancient mail fetching config)
1087 # - cgp_rule (communigate)
1088 # - cust_svc_option (used by our Tron stuff)
1089 # - acct_rt_transaction (used by our time worked stuff)
1092 # also move over any services that didn't unprovision at cancellation
1095 foreach my $cust_svc ( qsearch('cust_svc', { pkgnum => $self->pkgnum } ) ) {
1096 $cust_svc->pkgnum( $cust_pkg->pkgnum );
1097 my $error = $cust_svc->replace;
1099 $dbh->rollback if $oldAutoCommit;
1105 # Uncancel any supplemental packages, and make them supplemental to the
1109 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1111 $error = $supp_pkg->uncancel(%options, 'main_pkgnum' => $cust_pkg->pkgnum);
1113 $dbh->rollback if $oldAutoCommit;
1114 return "canceling supplemental pkg#".$supp_pkg->pkgnum.": $error";
1122 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1124 ${ $options{cust_pkg} } = $cust_pkg if ref($options{cust_pkg});
1125 @{ $options{svc_errors} } = @svc_errors if ref($options{svc_errors});
1132 Cancels any pending expiration (sets the expire field to null).
1134 If there is an error, returns the error, otherwise returns false.
1139 my( $self, %options ) = @_;
1142 my $oldAutoCommit = $FS::UID::AutoCommit;
1143 local $FS::UID::AutoCommit = 0;
1146 my $old = $self->select_for_update;
1148 my $pkgnum = $old->pkgnum;
1149 if ( $old->get('cancel') || $self->get('cancel') ) {
1150 dbh->rollback if $oldAutoCommit;
1151 return "Can't unexpire cancelled package $pkgnum";
1152 # or at least it's pointless
1155 unless ( $old->get('expire') && $self->get('expire') ) {
1156 dbh->rollback if $oldAutoCommit;
1157 return ""; # no error
1160 my %hash = $self->hash;
1161 $hash{'expire'} = '';
1162 my $new = new FS::cust_pkg ( \%hash );
1163 $error = $new->replace( $self, options => { $self->options } );
1165 $dbh->rollback if $oldAutoCommit;
1169 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1175 =item suspend [ OPTION => VALUE ... ]
1177 Suspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
1178 package, then suspends the package itself (sets the susp field to now).
1180 Available options are:
1184 =item reason - can be set to a cancellation reason (see L<FS:reason>),
1185 either a reasonnum of an existing reason, or passing a hashref will create
1186 a new reason. The hashref should have the following keys:
1187 - typenum - Reason type (see L<FS::reason_type>
1188 - reason - Text of the new reason.
1190 =item date - can be set to a unix style timestamp to specify when to
1193 =item time - can be set to override the current time, for calculation
1194 of final invoices or unused-time credits
1196 =item resume_date - can be set to a time when the package should be
1197 unsuspended. This may be more convenient than calling C<unsuspend()>
1200 =item from_main - allows a supplemental package to be suspended, rather
1201 than redirecting the method call to its main package. For internal use.
1205 If there is an error, returns the error, otherwise returns false.
1210 my( $self, %options ) = @_;
1213 # pass all suspend/cancel actions to the main package
1214 if ( $self->main_pkgnum and !$options{'from_main'} ) {
1215 return $self->main_pkg->suspend(%options);
1218 my $oldAutoCommit = $FS::UID::AutoCommit;
1219 local $FS::UID::AutoCommit = 0;
1222 my $old = $self->select_for_update;
1224 my $pkgnum = $old->pkgnum;
1225 if ( $old->get('cancel') || $self->get('cancel') ) {
1226 dbh->rollback if $oldAutoCommit;
1227 return "Can't suspend cancelled package $pkgnum";
1230 if ( $old->get('susp') || $self->get('susp') ) {
1231 dbh->rollback if $oldAutoCommit;
1232 return ""; # no error # complain on adjourn?
1235 my $suspend_time = $options{'time'} || time;
1236 my $date = $options{date} if $options{date}; # adjourn/suspend later
1237 $date = '' if ($date && $date <= $suspend_time); # complain instead?
1239 if ( $date && $old->get('expire') && $old->get('expire') < $date ) {
1240 dbh->rollback if $oldAutoCommit;
1241 return "Package $pkgnum expires before it would be suspended.";
1244 # some false laziness with sub cancel
1245 if ( !$options{nobill} && !$date &&
1246 $self->part_pkg->option('bill_suspend_as_cancel',1) ) {
1247 # kind of a kludge--'bill_suspend_as_cancel' to avoid having to
1248 # make the entire cust_main->bill path recognize 'suspend' and
1249 # 'cancel' separately.
1250 warn "Billing $pkgnum on suspension (at $suspend_time)\n" if $DEBUG;
1251 my $copy = $self->new({$self->hash});
1253 $copy->cust_main->bill( 'pkg_list' => [ $copy ],
1255 'time' => $suspend_time );
1256 warn "Error billing during suspend, custnum ".
1257 #$self->cust_main->custnum. ": $error"
1262 if ( $options{'reason'} ) {
1263 $error = $self->insert_reason( 'reason' => $options{'reason'},
1264 'action' => $date ? 'adjourn' : 'suspend',
1265 'date' => $date ? $date : $suspend_time,
1266 'reason_otaker' => $options{'reason_otaker'},
1269 dbh->rollback if $oldAutoCommit;
1270 return "Error inserting cust_pkg_reason: $error";
1274 my %hash = $self->hash;
1276 $hash{'adjourn'} = $date;
1278 $hash{'susp'} = $suspend_time;
1281 my $resume_date = $options{'resume_date'} || 0;
1282 if ( $resume_date > ($date || $suspend_time) ) {
1283 $hash{'resume'} = $resume_date;
1286 $options{options} ||= {};
1288 my $new = new FS::cust_pkg ( \%hash );
1289 $error = $new->replace( $self, options => { $self->options,
1290 %{ $options{options} },
1294 $dbh->rollback if $oldAutoCommit;
1299 # credit remaining time if appropriate
1300 if ( $self->part_pkg->option('unused_credit_suspend', 1) ) {
1301 my $error = $self->credit_remaining('suspend', $suspend_time);
1303 $dbh->rollback if $oldAutoCommit;
1310 foreach my $cust_svc (
1311 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
1313 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
1315 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
1316 $dbh->rollback if $oldAutoCommit;
1317 return "Illegal svcdb value in part_svc!";
1320 require "FS/$svcdb.pm";
1322 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
1324 $error = $svc->suspend;
1326 $dbh->rollback if $oldAutoCommit;
1329 my( $label, $value ) = $cust_svc->label;
1330 push @labels, "$label: $value";
1334 my $conf = new FS::Conf;
1335 if ( $conf->config('suspend_email_admin') ) {
1337 my $error = send_email(
1338 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
1339 #invoice_from ??? well as good as any
1340 'to' => $conf->config('suspend_email_admin'),
1341 'subject' => 'FREESIDE NOTIFICATION: Customer package suspended',
1343 "This is an automatic message from your Freeside installation\n",
1344 "informing you that the following customer package has been suspended:\n",
1346 'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
1347 'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
1348 ( map { "Service : $_\n" } @labels ),
1350 'custnum' => $self->custnum,
1351 'msgtype' => 'admin'
1355 warn "WARNING: can't send suspension admin email (suspending anyway): ".
1363 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1364 $error = $supp_pkg->suspend(%options, 'from_main' => 1);
1366 $dbh->rollback if $oldAutoCommit;
1367 return "suspending supplemental pkg#".$supp_pkg->pkgnum.": $error";
1371 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1376 =item credit_remaining MODE TIME
1378 Generate a credit for this package for the time remaining in the current
1379 billing period. MODE is either "suspend" or "cancel" (determines the
1380 credit type). TIME is the time of suspension/cancellation. Both arguments
1385 sub credit_remaining {
1386 # Add a credit for remaining service
1387 my ($self, $mode, $time) = @_;
1388 die 'credit_remaining requires suspend or cancel'
1389 unless $mode eq 'suspend' or $mode eq 'cancel';
1390 die 'no suspend/cancel time' unless $time > 0;
1392 my $conf = FS::Conf->new;
1393 my $reason_type = $conf->config($mode.'_credit_type');
1395 my $last_bill = $self->getfield('last_bill') || 0;
1396 my $next_bill = $self->getfield('bill') || 0;
1397 if ( $last_bill > 0 # the package has been billed
1398 and $next_bill > 0 # the package has a next bill date
1399 and $next_bill >= $time # which is in the future
1401 my $remaining_value = $self->calc_remain('time' => $time);
1402 if ( $remaining_value > 0 ) {
1403 warn "Crediting for $remaining_value on package ".$self->pkgnum."\n"
1405 my $error = $self->cust_main->credit(
1407 'Credit for unused time on '. $self->part_pkg->pkg,
1408 'reason_type' => $reason_type,
1410 return "Error crediting customer \$$remaining_value for unused time".
1411 " on ". $self->part_pkg->pkg. ": $error"
1413 } #if $remaining_value
1414 } #if $last_bill, etc.
1418 =item unsuspend [ OPTION => VALUE ... ]
1420 Unsuspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
1421 package, then unsuspends the package itself (clears the susp field and the
1422 adjourn field if it is in the past). If the suspend reason includes an
1423 unsuspension package, that package will be ordered.
1425 Available options are:
1431 Can be set to a date to unsuspend the package in the future (the 'resume'
1434 =item adjust_next_bill
1436 Can be set true to adjust the next bill date forward by
1437 the amount of time the account was inactive. This was set true by default
1438 in the past (from 1.4.2 and 1.5.0pre6 through 1.7.0), but now needs to be
1439 explicitly requested with this option or in the price plan.
1443 If there is an error, returns the error, otherwise returns false.
1448 my( $self, %opt ) = @_;
1451 # pass all suspend/cancel actions to the main package
1452 if ( $self->main_pkgnum and !$opt{'from_main'} ) {
1453 return $self->main_pkg->unsuspend(%opt);
1456 my $oldAutoCommit = $FS::UID::AutoCommit;
1457 local $FS::UID::AutoCommit = 0;
1460 my $old = $self->select_for_update;
1462 my $pkgnum = $old->pkgnum;
1463 if ( $old->get('cancel') || $self->get('cancel') ) {
1464 $dbh->rollback if $oldAutoCommit;
1465 return "Can't unsuspend cancelled package $pkgnum";
1468 unless ( $old->get('susp') && $self->get('susp') ) {
1469 $dbh->rollback if $oldAutoCommit;
1470 return ""; # no error # complain instead?
1473 my $date = $opt{'date'};
1474 if ( $date and $date > time ) { # return an error if $date <= time?
1476 if ( $old->get('expire') && $old->get('expire') < $date ) {
1477 $dbh->rollback if $oldAutoCommit;
1478 return "Package $pkgnum expires before it would be unsuspended.";
1481 my $new = new FS::cust_pkg { $self->hash };
1482 $new->set('resume', $date);
1483 $error = $new->replace($self, options => $self->options);
1486 $dbh->rollback if $oldAutoCommit;
1490 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1498 foreach my $cust_svc (
1499 qsearch('cust_svc',{'pkgnum'=> $self->pkgnum } )
1501 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
1503 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
1504 $dbh->rollback if $oldAutoCommit;
1505 return "Illegal svcdb value in part_svc!";
1508 require "FS/$svcdb.pm";
1510 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
1512 $error = $svc->unsuspend;
1514 $dbh->rollback if $oldAutoCommit;
1517 my( $label, $value ) = $cust_svc->label;
1518 push @labels, "$label: $value";
1523 my $cust_pkg_reason = $self->last_cust_pkg_reason('susp');
1524 my $reason = $cust_pkg_reason ? $cust_pkg_reason->reason : '';
1526 my %hash = $self->hash;
1527 my $inactive = time - $hash{'susp'};
1529 my $conf = new FS::Conf;
1531 #adjust the next bill date forward
1532 $hash{'bill'} = ( $hash{'bill'} || $hash{'setup'} ) + $inactive
1534 && ( $hash{'bill'} || $hash{'setup'} )
1535 && ( $opt{'adjust_next_bill'}
1536 || $conf->exists('unsuspend-always_adjust_next_bill_date')
1537 || $self->part_pkg->option('unsuspend_adjust_bill', 1)
1539 && ! $self->option('suspend_bill',1)
1540 && ( ! $self->part_pkg->option('suspend_bill',1)
1541 || $self->option('no_suspend_bill',1)
1543 && $hash{'order_date'} != $hash{'susp'}
1547 $hash{'adjourn'} = '' if $hash{'adjourn'} and $hash{'adjourn'} < time;
1548 $hash{'resume'} = '' if !$hash{'adjourn'};
1549 my $new = new FS::cust_pkg ( \%hash );
1550 $error = $new->replace( $self, options => { $self->options } );
1552 $dbh->rollback if $oldAutoCommit;
1558 if ( $reason && $reason->unsuspend_pkgpart ) {
1559 my $part_pkg = FS::part_pkg->by_key($reason->unsuspend_pkgpart)
1560 or $error = "Unsuspend package definition ".$reason->unsuspend_pkgpart.
1562 my $start_date = $self->cust_main->next_bill_date
1563 if $reason->unsuspend_hold;
1566 $unsusp_pkg = FS::cust_pkg->new({
1567 'custnum' => $self->custnum,
1568 'pkgpart' => $reason->unsuspend_pkgpart,
1569 'start_date' => $start_date,
1570 'locationnum' => $self->locationnum,
1571 # discount? probably not...
1574 $error ||= $self->cust_main->order_pkg( 'cust_pkg' => $unsusp_pkg );
1578 $dbh->rollback if $oldAutoCommit;
1583 if ( $conf->config('unsuspend_email_admin') ) {
1585 my $error = send_email(
1586 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
1587 #invoice_from ??? well as good as any
1588 'to' => $conf->config('unsuspend_email_admin'),
1589 'subject' => 'FREESIDE NOTIFICATION: Customer package unsuspended', 'body' => [
1590 "This is an automatic message from your Freeside installation\n",
1591 "informing you that the following customer package has been unsuspended:\n",
1593 'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
1594 'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
1595 ( map { "Service : $_\n" } @labels ),
1597 "An unsuspension fee was charged: ".
1598 $unsusp_pkg->part_pkg->pkg_comment."\n"
1602 'custnum' => $self->custnum,
1603 'msgtype' => 'admin',
1607 warn "WARNING: can't send unsuspension admin email (unsuspending anyway): ".
1613 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1614 $error = $supp_pkg->unsuspend(%opt, 'from_main' => 1);
1616 $dbh->rollback if $oldAutoCommit;
1617 return "unsuspending supplemental pkg#".$supp_pkg->pkgnum.": $error";
1621 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1628 Cancels any pending suspension (sets the adjourn field to null).
1630 If there is an error, returns the error, otherwise returns false.
1635 my( $self, %options ) = @_;
1638 my $oldAutoCommit = $FS::UID::AutoCommit;
1639 local $FS::UID::AutoCommit = 0;
1642 my $old = $self->select_for_update;
1644 my $pkgnum = $old->pkgnum;
1645 if ( $old->get('cancel') || $self->get('cancel') ) {
1646 dbh->rollback if $oldAutoCommit;
1647 return "Can't unadjourn cancelled package $pkgnum";
1648 # or at least it's pointless
1651 if ( $old->get('susp') || $self->get('susp') ) {
1652 dbh->rollback if $oldAutoCommit;
1653 return "Can't unadjourn suspended package $pkgnum";
1654 # perhaps this is arbitrary
1657 unless ( $old->get('adjourn') && $self->get('adjourn') ) {
1658 dbh->rollback if $oldAutoCommit;
1659 return ""; # no error
1662 my %hash = $self->hash;
1663 $hash{'adjourn'} = '';
1664 $hash{'resume'} = '';
1665 my $new = new FS::cust_pkg ( \%hash );
1666 $error = $new->replace( $self, options => { $self->options } );
1668 $dbh->rollback if $oldAutoCommit;
1672 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1679 =item change HASHREF | OPTION => VALUE ...
1681 Changes this package: cancels it and creates a new one, with a different
1682 pkgpart or locationnum or both. All services are transferred to the new
1683 package (no change will be made if this is not possible).
1685 Options may be passed as a list of key/value pairs or as a hash reference.
1692 New locationnum, to change the location for this package.
1696 New FS::cust_location object, to create a new location and assign it
1701 New FS::cust_main object, to create a new customer and assign the new package
1706 New pkgpart (see L<FS::part_pkg>).
1710 New refnum (see L<FS::part_referral>).
1714 New quantity; if unspecified, the new package will have the same quantity
1719 "New" (existing) FS::cust_pkg object. The package's services and other
1720 attributes will be transferred to this package.
1724 Set to true to transfer billing dates (start_date, setup, last_bill, bill,
1725 susp, adjourn, cancel, expire, and contract_end) to the new package.
1727 =item unprotect_svcs
1729 Normally, change() will rollback and return an error if some services
1730 can't be transferred (also see the I<cust_pkg-change_svcpart> config option).
1731 If unprotect_svcs is true, this method will transfer as many services as
1732 it can and then unconditionally cancel the old package.
1736 At least one of locationnum, cust_location, pkgpart, refnum, cust_main, or
1737 cust_pkg must be specified (otherwise, what's the point?)
1739 Returns either the new FS::cust_pkg object or a scalar error.
1743 my $err_or_new_cust_pkg = $old_cust_pkg->change
1747 #some false laziness w/order
1750 my $opt = ref($_[0]) ? shift : { @_ };
1752 my $conf = new FS::Conf;
1754 # Transactionize this whole mess
1755 my $oldAutoCommit = $FS::UID::AutoCommit;
1756 local $FS::UID::AutoCommit = 0;
1765 $hash{'setup'} = $time if $self->setup;
1767 $hash{'change_date'} = $time;
1768 $hash{"change_$_"} = $self->$_()
1769 foreach qw( pkgnum pkgpart locationnum );
1771 if ( $opt->{'cust_location'} ) {
1772 $error = $opt->{'cust_location'}->find_or_insert;
1774 $dbh->rollback if $oldAutoCommit;
1775 return "creating location record: $error";
1777 $opt->{'locationnum'} = $opt->{'cust_location'}->locationnum;
1780 if ( $opt->{'cust_pkg'} ) {
1781 # treat changing to a package with a different pkgpart as a
1782 # pkgpart change (because it is)
1783 $opt->{'pkgpart'} = $opt->{'cust_pkg'}->pkgpart;
1786 # whether to override pkgpart checking on the new package
1787 my $same_pkgpart = 1;
1788 if ( $opt->{'pkgpart'} and ( $opt->{'pkgpart'} != $self->pkgpart ) ) {
1792 my $unused_credit = 0;
1793 my $keep_dates = $opt->{'keep_dates'};
1794 # Special case. If the pkgpart is changing, and the customer is
1795 # going to be credited for remaining time, don't keep setup, bill,
1796 # or last_bill dates, and DO pass the flag to cancel() to credit
1798 if ( $opt->{'pkgpart'}
1799 and $opt->{'pkgpart'} != $self->pkgpart
1800 and $self->part_pkg->option('unused_credit_change', 1) ) {
1803 $hash{$_} = '' foreach qw(setup bill last_bill);
1806 if ( $keep_dates ) {
1807 foreach my $date ( qw(setup bill last_bill susp adjourn cancel expire
1808 resume start_date contract_end ) ) {
1809 $hash{$date} = $self->getfield($date);
1812 # always keep this date, regardless of anything
1813 # (the date of the package change is in a different field)
1814 $hash{'order_date'} = $self->getfield('order_date');
1816 # allow $opt->{'locationnum'} = '' to specifically set it to null
1817 # (i.e. customer default location)
1818 $opt->{'locationnum'} = $self->locationnum if !exists($opt->{'locationnum'});
1820 # usually this doesn't matter. the two cases where it does are:
1821 # 1. unused_credit_change + pkgpart change + setup fee on the new package
1823 # 2. (more importantly) changing a package before it's billed
1824 $hash{'waive_setup'} = $self->waive_setup;
1826 my $custnum = $self->custnum;
1827 if ( $opt->{cust_main} ) {
1828 my $cust_main = $opt->{cust_main};
1829 unless ( $cust_main->custnum ) {
1830 my $error = $cust_main->insert( @{ $opt->{cust_main_insert_args}||[] } );
1832 $dbh->rollback if $oldAutoCommit;
1833 return "inserting customer record: $error";
1836 $custnum = $cust_main->custnum;
1839 $hash{'contactnum'} = $opt->{'contactnum'} if $opt->{'contactnum'};
1842 if ( $opt->{'cust_pkg'} ) {
1843 # The target package already exists; update it to show that it was
1844 # changed from this package.
1845 $cust_pkg = $opt->{'cust_pkg'};
1847 foreach ( qw( pkgnum pkgpart locationnum ) ) {
1848 $cust_pkg->set("change_$_", $self->get($_));
1850 $cust_pkg->set('change_date', $time);
1851 $error = $cust_pkg->replace;
1854 # Create the new package.
1855 $cust_pkg = new FS::cust_pkg {
1856 custnum => $custnum,
1857 locationnum => $opt->{'locationnum'},
1858 ( map { $_ => ( $opt->{$_} || $self->$_() ) }
1859 qw( pkgpart quantity refnum salesnum )
1863 $error = $cust_pkg->insert( 'change' => 1,
1864 'allow_pkgpart' => $same_pkgpart );
1867 $dbh->rollback if $oldAutoCommit;
1868 return "inserting new package: $error";
1871 # Transfer services and cancel old package.
1873 $error = $self->transfer($cust_pkg);
1874 if ($error and $error == 0) {
1875 # $old_pkg->transfer failed.
1876 $dbh->rollback if $oldAutoCommit;
1877 return "transferring $error";
1880 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
1881 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
1882 $error = $self->transfer($cust_pkg, 'change_svcpart'=>1 );
1883 if ($error and $error == 0) {
1884 # $old_pkg->transfer failed.
1885 $dbh->rollback if $oldAutoCommit;
1886 return "converting $error";
1890 # We set unprotect_svcs when executing a "future package change". It's
1891 # not a user-interactive operation, so returning an error means the
1892 # package change will just fail. Rather than have that happen, we'll
1893 # let leftover services be deleted.
1894 if ($error > 0 and !$opt->{'unprotect_svcs'}) {
1895 # Transfers were successful, but we still had services left on the old
1896 # package. We can't change the package under this circumstances, so abort.
1897 $dbh->rollback if $oldAutoCommit;
1898 return "unable to transfer all services";
1901 #reset usage if changing pkgpart
1902 # AND usage rollover is off (otherwise adds twice, now and at package bill)
1903 if ($self->pkgpart != $cust_pkg->pkgpart) {
1904 my $part_pkg = $cust_pkg->part_pkg;
1905 $error = $part_pkg->reset_usage($cust_pkg, $part_pkg->is_prepaid
1909 if $part_pkg->can('reset_usage') && ! $part_pkg->option('usage_rollover',1);
1912 $dbh->rollback if $oldAutoCommit;
1913 return "setting usage values: $error";
1916 # if NOT changing pkgpart, transfer any usage pools over
1917 foreach my $usage ($self->cust_pkg_usage) {
1918 $usage->set('pkgnum', $cust_pkg->pkgnum);
1919 $error = $usage->replace;
1921 $dbh->rollback if $oldAutoCommit;
1922 return "transferring usage pools: $error";
1927 # transfer usage pricing add-ons, if we're not changing pkgpart
1928 if ( $same_pkgpart ) {
1929 foreach my $old_cust_pkg_usageprice ($self->cust_pkg_usageprice) {
1930 my $new_cust_pkg_usageprice = new FS::cust_pkg_usageprice {
1931 'pkgnum' => $cust_pkg->pkgnum,
1932 'usagepricepart' => $old_cust_pkg_usageprice->usagepricepart,
1933 'quantity' => $old_cust_pkg_usageprice->quantity,
1935 $error = $new_cust_pkg_usageprice->insert;
1937 $dbh->rollback if $oldAutoCommit;
1938 return "Error transferring usage pricing add-on: $error";
1943 # transfer discounts, if we're not changing pkgpart
1944 if ( $same_pkgpart ) {
1945 foreach my $old_discount ($self->cust_pkg_discount_active) {
1946 # don't remove the old discount, we may still need to bill that package.
1947 my $new_discount = new FS::cust_pkg_discount {
1948 'pkgnum' => $cust_pkg->pkgnum,
1949 'discountnum' => $old_discount->discountnum,
1950 'months_used' => $old_discount->months_used,
1952 $error = $new_discount->insert;
1954 $dbh->rollback if $oldAutoCommit;
1955 return "transferring discounts: $error";
1960 # transfer (copy) invoice details
1961 foreach my $detail ($self->cust_pkg_detail) {
1962 my $new_detail = FS::cust_pkg_detail->new({ $detail->hash });
1963 $new_detail->set('pkgdetailnum', '');
1964 $new_detail->set('pkgnum', $cust_pkg->pkgnum);
1965 $error = $new_detail->insert;
1967 $dbh->rollback if $oldAutoCommit;
1968 return "transferring package notes: $error";
1974 if ( !$opt->{'cust_pkg'} ) {
1975 # Order any supplemental packages.
1976 my $part_pkg = $cust_pkg->part_pkg;
1977 my @old_supp_pkgs = $self->supplemental_pkgs;
1978 foreach my $link ($part_pkg->supp_part_pkg_link) {
1980 foreach (@old_supp_pkgs) {
1981 if ($_->pkgpart == $link->dst_pkgpart) {
1983 $_->pkgpart(0); # so that it can't match more than once
1987 # false laziness with FS::cust_main::Packages::order_pkg
1988 my $new = FS::cust_pkg->new({
1989 pkgpart => $link->dst_pkgpart,
1990 pkglinknum => $link->pkglinknum,
1991 custnum => $custnum,
1992 main_pkgnum => $cust_pkg->pkgnum,
1993 locationnum => $cust_pkg->locationnum,
1994 start_date => $cust_pkg->start_date,
1995 order_date => $cust_pkg->order_date,
1996 expire => $cust_pkg->expire,
1997 adjourn => $cust_pkg->adjourn,
1998 contract_end => $cust_pkg->contract_end,
1999 refnum => $cust_pkg->refnum,
2000 discountnum => $cust_pkg->discountnum,
2001 waive_setup => $cust_pkg->waive_setup,
2003 if ( $old and $opt->{'keep_dates'} ) {
2004 foreach (qw(setup bill last_bill)) {
2005 $new->set($_, $old->get($_));
2008 $error = $new->insert( allow_pkgpart => $same_pkgpart );
2011 $error ||= $old->transfer($new);
2013 if ( $error and $error > 0 ) {
2014 # no reason why this should ever fail, but still...
2015 $error = "Unable to transfer all services from supplemental package ".
2019 $dbh->rollback if $oldAutoCommit;
2022 push @new_supp_pkgs, $new;
2024 } # if !$opt->{'cust_pkg'}
2025 # because if there is one, then supplemental packages would already
2026 # have been created for it.
2028 #Good to go, cancel old package. Notify 'cancel' of whether to credit
2030 #Don't allow billing the package (preceding period packages and/or
2031 #outstanding usage) if we are keeping dates (i.e. location changing),
2032 #because the new package will be billed for the same date range.
2033 #Supplemental packages are also canceled here.
2035 # during scheduled changes, avoid canceling the package we just
2037 $self->set('change_to_pkgnum' => '');
2039 $error = $self->cancel(
2041 unused_credit => $unused_credit,
2042 nobill => $keep_dates,
2043 change_custnum => ( $self->custnum != $custnum ? $custnum : '' ),
2046 $dbh->rollback if $oldAutoCommit;
2047 return "canceling old package: $error";
2050 if ( $conf->exists('cust_pkg-change_pkgpart-bill_now') ) {
2052 my $error = $cust_pkg->cust_main->bill(
2053 'pkg_list' => [ $cust_pkg, @new_supp_pkgs ]
2056 $dbh->rollback if $oldAutoCommit;
2057 return "billing new package: $error";
2061 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2067 =item change_later OPTION => VALUE...
2069 Schedule a package change for a later date. This actually orders the new
2070 package immediately, but sets its start date for a future date, and sets
2071 the current package to expire on the same date.
2073 If the package is already scheduled for a change, this can be called with
2074 'start_date' to change the scheduled date, or with pkgpart and/or
2075 locationnum to modify the package change. To cancel the scheduled change
2076 entirely, see C<abort_change>.
2084 The date for the package change. Required, and must be in the future.
2092 The pkgpart. locationnum, and quantity of the new package, with the same
2093 meaning as in C<change>.
2101 my $opt = ref($_[0]) ? shift : { @_ };
2103 my $oldAutoCommit = $FS::UID::AutoCommit;
2104 local $FS::UID::AutoCommit = 0;
2107 my $cust_main = $self->cust_main;
2109 my $date = delete $opt->{'start_date'} or return 'start_date required';
2111 if ( $date <= time ) {
2112 $dbh->rollback if $oldAutoCommit;
2113 return "start_date $date is in the past";
2118 if ( $self->change_to_pkgnum ) {
2119 my $change_to = FS::cust_pkg->by_key($self->change_to_pkgnum);
2120 my $new_pkgpart = $opt->{'pkgpart'}
2121 if $opt->{'pkgpart'} and $opt->{'pkgpart'} != $change_to->pkgpart;
2122 my $new_locationnum = $opt->{'locationnum'}
2123 if $opt->{'locationnum'} and $opt->{'locationnum'} != $change_to->locationnum;
2124 my $new_quantity = $opt->{'quantity'}
2125 if $opt->{'quantity'} and $opt->{'quantity'} != $change_to->quantity;
2126 if ( $new_pkgpart or $new_locationnum or $new_quantity ) {
2127 # it hasn't been billed yet, so in principle we could just edit
2128 # it in place (w/o a package change), but that's bad form.
2129 # So change the package according to the new options...
2130 my $err_or_pkg = $change_to->change(%$opt);
2131 if ( ref $err_or_pkg ) {
2132 # Then set that package up for a future start.
2133 $self->set('change_to_pkgnum', $err_or_pkg->pkgnum);
2134 $self->set('expire', $date); # in case it's different
2135 $err_or_pkg->set('start_date', $date);
2136 $err_or_pkg->set('change_date', '');
2137 $err_or_pkg->set('change_pkgnum', '');
2139 $error = $self->replace ||
2140 $err_or_pkg->replace ||
2141 $change_to->cancel ||
2144 $error = $err_or_pkg;
2146 } else { # change the start date only.
2147 $self->set('expire', $date);
2148 $change_to->set('start_date', $date);
2149 $error = $self->replace || $change_to->replace;
2152 $dbh->rollback if $oldAutoCommit;
2155 $dbh->commit if $oldAutoCommit;
2158 } # if $self->change_to_pkgnum
2160 my $new_pkgpart = $opt->{'pkgpart'}
2161 if $opt->{'pkgpart'} and $opt->{'pkgpart'} != $self->pkgpart;
2162 my $new_locationnum = $opt->{'locationnum'}
2163 if $opt->{'locationnum'} and $opt->{'locationnum'} != $self->locationnum;
2164 my $new_quantity = $opt->{'quantity'}
2165 if $opt->{'quantity'} and $opt->{'quantity'} != $self->quantity;
2167 return '' unless $new_pkgpart or $new_locationnum or $new_quantity; # wouldn't do anything
2169 # allow $opt->{'locationnum'} = '' to specifically set it to null
2170 # (i.e. customer default location)
2171 $opt->{'locationnum'} = $self->locationnum if !exists($opt->{'locationnum'});
2173 my $new = FS::cust_pkg->new( {
2174 custnum => $self->custnum,
2175 locationnum => $opt->{'locationnum'},
2176 start_date => $date,
2177 map { $_ => ( $opt->{$_} || $self->$_() ) }
2178 qw( pkgpart quantity refnum salesnum )
2180 $error = $new->insert('change' => 1,
2181 'allow_pkgpart' => ($new_pkgpart ? 0 : 1));
2183 $self->set('change_to_pkgnum', $new->pkgnum);
2184 $self->set('expire', $date);
2185 $error = $self->replace;
2188 $dbh->rollback if $oldAutoCommit;
2190 $dbh->commit if $oldAutoCommit;
2198 Cancels a future package change scheduled by C<change_later>.
2204 my $pkgnum = $self->change_to_pkgnum;
2205 my $change_to = FS::cust_pkg->by_key($pkgnum) if $pkgnum;
2208 $error = $change_to->cancel || $change_to->delete;
2209 return $error if $error;
2211 $self->set('change_to_pkgnum', '');
2212 $self->set('expire', '');
2216 =item set_quantity QUANTITY
2218 Change the package's quantity field. This is one of the few package properties
2219 that can safely be changed without canceling and reordering the package
2220 (because it doesn't affect tax eligibility). Returns an error or an
2227 $self = $self->replace_old; # just to make sure
2228 $self->quantity(shift);
2232 =item set_salesnum SALESNUM
2234 Change the package's salesnum (sales person) field. This is one of the few
2235 package properties that can safely be changed without canceling and reordering
2236 the package (because it doesn't affect tax eligibility). Returns an error or
2243 $self = $self->replace_old; # just to make sure
2244 $self->salesnum(shift);
2246 # XXX this should probably reassign any credit that's already been given
2249 =item modify_charge OPTIONS
2251 Change the properties of a one-time charge. The following properties can
2252 be changed this way:
2253 - pkg: the package description
2254 - classnum: the package class
2255 - additional: arrayref of additional invoice details to add to this package
2257 and, I<if the charge has not yet been billed>:
2258 - start_date: the date when it will be billed
2259 - amount: the setup fee to be charged
2260 - quantity: the multiplier for the setup fee
2262 If you pass 'adjust_commission' => 1, and the classnum changes, and there are
2263 commission credits linked to this charge, they will be recalculated.
2270 my $part_pkg = $self->part_pkg;
2271 my $pkgnum = $self->pkgnum;
2274 my $oldAutoCommit = $FS::UID::AutoCommit;
2275 local $FS::UID::AutoCommit = 0;
2277 return "Can't use modify_charge except on one-time charges"
2278 unless $part_pkg->freq eq '0';
2280 if ( length($opt{'pkg'}) and $part_pkg->pkg ne $opt{'pkg'} ) {
2281 $part_pkg->set('pkg', $opt{'pkg'});
2284 my %pkg_opt = $part_pkg->options;
2285 my $pkg_opt_modified = 0;
2287 $opt{'additional'} ||= [];
2290 foreach (grep /^additional/, keys %pkg_opt) {
2291 ($i) = ($_ =~ /^additional_info(\d+)$/);
2292 $old_additional[$i] = $pkg_opt{$_} if $i;
2293 delete $pkg_opt{$_};
2296 for ( $i = 0; exists($opt{'additional'}->[$i]); $i++ ) {
2297 $pkg_opt{ "additional_info$i" } = $opt{'additional'}->[$i];
2298 if (!exists($old_additional[$i])
2299 or $old_additional[$i] ne $opt{'additional'}->[$i])
2301 $pkg_opt_modified = 1;
2304 $pkg_opt_modified = 1 if (scalar(@old_additional) - 1) != $i;
2305 $pkg_opt{'additional_count'} = $i if $i > 0;
2308 if ( exists($opt{'classnum'}) and $part_pkg->classnum ne $opt{'classnum'} )
2311 $old_classnum = $part_pkg->classnum;
2312 $part_pkg->set('classnum', $opt{'classnum'});
2315 if ( !$self->get('setup') ) {
2316 # not yet billed, so allow amount and quantity
2317 if ( exists($opt{'quantity'})
2318 and $opt{'quantity'} != $self->quantity
2319 and $opt{'quantity'} > 0 ) {
2321 $self->set('quantity', $opt{'quantity'});
2323 if ( exists($opt{'start_date'})
2324 and $opt{'start_date'} != $self->start_date ) {
2326 $self->set('start_date', $opt{'start_date'});
2329 if ( exists($opt{'amount'})
2330 and $part_pkg->option('setup_fee') != $opt{'amount'}
2331 and $opt{'amount'} > 0 ) {
2333 $pkg_opt{'setup_fee'} = $opt{'amount'};
2334 $pkg_opt_modified = 1;
2337 } # else simply ignore them; the UI shouldn't allow editing the fields
2340 if ( $part_pkg->modified or $pkg_opt_modified ) {
2341 # can we safely modify the package def?
2342 # Yes, if it's not available for purchase, and this is the only instance
2344 if ( $part_pkg->disabled
2345 and FS::cust_pkg->count('pkgpart = '.$part_pkg->pkgpart) == 1
2346 and FS::quotation_pkg->count('pkgpart = '.$part_pkg->pkgpart) == 0
2348 $error = $part_pkg->replace( options => \%pkg_opt );
2351 $part_pkg = $part_pkg->clone;
2352 $part_pkg->set('disabled' => 'Y');
2353 $error = $part_pkg->insert( options => \%pkg_opt );
2354 # and associate this as yet-unbilled package to the new package def
2355 $self->set('pkgpart' => $part_pkg->pkgpart);
2358 $dbh->rollback if $oldAutoCommit;
2363 if ($self->modified) { # for quantity or start_date change, or if we had
2364 # to clone the existing package def
2365 my $error = $self->replace;
2366 return $error if $error;
2368 if (defined $old_classnum) {
2369 # fix invoice grouping records
2370 my $old_catname = $old_classnum
2371 ? FS::pkg_class->by_key($old_classnum)->categoryname
2373 my $new_catname = $opt{'classnum'}
2374 ? $part_pkg->pkg_class->categoryname
2376 if ( $old_catname ne $new_catname ) {
2377 foreach my $cust_bill_pkg ($self->cust_bill_pkg) {
2378 # (there should only be one...)
2379 my @display = qsearch( 'cust_bill_pkg_display', {
2380 'billpkgnum' => $cust_bill_pkg->billpkgnum,
2381 'section' => $old_catname,
2383 foreach (@display) {
2384 $_->set('section', $new_catname);
2385 $error = $_->replace;
2387 $dbh->rollback if $oldAutoCommit;
2391 } # foreach $cust_bill_pkg
2394 if ( $opt{'adjust_commission'} ) {
2395 # fix commission credits...tricky.
2396 foreach my $cust_event ($self->cust_event) {
2397 my $part_event = $cust_event->part_event;
2398 foreach my $table (qw(sales agent)) {
2400 "FS::part_event::Action::Mixin::credit_${table}_pkg_class";
2401 my $credit = qsearchs('cust_credit', {
2402 'eventnum' => $cust_event->eventnum,
2404 if ( $part_event->isa($class) ) {
2405 # Yes, this results in current commission rates being applied
2406 # retroactively to a one-time charge. For accounting purposes
2407 # there ought to be some kind of time limit on doing this.
2408 my $amount = $part_event->_calc_credit($self);
2409 if ( $credit and $credit->amount ne $amount ) {
2410 # Void the old credit.
2411 $error = $credit->void('Package class changed');
2413 $dbh->rollback if $oldAutoCommit;
2414 return "$error (adjusting commission credit)";
2417 # redo the event action to recreate the credit.
2419 eval { $part_event->do_action( $self, $cust_event ) };
2421 $dbh->rollback if $oldAutoCommit;
2424 } # if $part_event->isa($class)
2426 } # foreach $cust_event
2427 } # if $opt{'adjust_commission'}
2428 } # if defined $old_classnum
2430 $dbh->commit if $oldAutoCommit;
2436 use Storable 'thaw';
2439 sub process_bulk_cust_pkg {
2441 my $param = thaw(decode_base64(shift));
2442 warn Dumper($param) if $DEBUG;
2444 my $old_part_pkg = qsearchs('part_pkg',
2445 { pkgpart => $param->{'old_pkgpart'} });
2446 my $new_part_pkg = qsearchs('part_pkg',
2447 { pkgpart => $param->{'new_pkgpart'} });
2448 die "Must select a new package type\n" unless $new_part_pkg;
2449 #my $keep_dates = $param->{'keep_dates'} || 0;
2450 my $keep_dates = 1; # there is no good reason to turn this off
2452 my $oldAutoCommit = $FS::UID::AutoCommit;
2453 local $FS::UID::AutoCommit = 0;
2456 my @cust_pkgs = qsearch('cust_pkg', { 'pkgpart' => $param->{'old_pkgpart'} } );
2459 foreach my $old_cust_pkg ( @cust_pkgs ) {
2461 $job->update_statustext(int(100*$i/(scalar @cust_pkgs)));
2462 if ( $old_cust_pkg->getfield('cancel') ) {
2463 warn '[process_bulk_cust_pkg ] skipping canceled pkgnum '.
2464 $old_cust_pkg->pkgnum."\n"
2468 warn '[process_bulk_cust_pkg] changing pkgnum '.$old_cust_pkg->pkgnum."\n"
2470 my $error = $old_cust_pkg->change(
2471 'pkgpart' => $param->{'new_pkgpart'},
2472 'keep_dates' => $keep_dates
2474 if ( !ref($error) ) { # change returns the cust_pkg on success
2476 die "Error changing pkgnum ".$old_cust_pkg->pkgnum.": '$error'\n";
2479 $dbh->commit if $oldAutoCommit;
2485 Returns the last bill date, or if there is no last bill date, the setup date.
2486 Useful for billing metered services.
2492 return $self->setfield('last_bill', $_[0]) if @_;
2493 return $self->getfield('last_bill') if $self->getfield('last_bill');
2494 my $cust_bill_pkg = qsearchs('cust_bill_pkg', { 'pkgnum' => $self->pkgnum,
2495 'edate' => $self->bill, } );
2496 $cust_bill_pkg ? $cust_bill_pkg->sdate : $self->setup || 0;
2499 =item last_cust_pkg_reason ACTION
2501 Returns the most recent ACTION FS::cust_pkg_reason associated with the package.
2502 Returns false if there is no reason or the package is not currenly ACTION'd
2503 ACTION is one of adjourn, susp, cancel, or expire.
2507 sub last_cust_pkg_reason {
2508 my ( $self, $action ) = ( shift, shift );
2509 my $date = $self->get($action);
2511 'table' => 'cust_pkg_reason',
2512 'hashref' => { 'pkgnum' => $self->pkgnum,
2513 'action' => substr(uc($action), 0, 1),
2516 'order_by' => 'ORDER BY num DESC LIMIT 1',
2520 =item last_reason ACTION
2522 Returns the most recent ACTION FS::reason associated with the package.
2523 Returns false if there is no reason or the package is not currenly ACTION'd
2524 ACTION is one of adjourn, susp, cancel, or expire.
2529 my $cust_pkg_reason = shift->last_cust_pkg_reason(@_);
2530 $cust_pkg_reason->reason
2531 if $cust_pkg_reason;
2536 Returns the definition for this billing item, as an FS::part_pkg object (see
2543 return $self->{'_pkgpart'} if $self->{'_pkgpart'};
2544 cluck "cust_pkg->part_pkg called" if $DEBUG > 1;
2545 qsearchs( 'part_pkg', { 'pkgpart' => $self->pkgpart } );
2550 Returns the cancelled package this package was changed from, if any.
2556 return '' unless $self->change_pkgnum;
2557 qsearchs('cust_pkg', { 'pkgnum' => $self->change_pkgnum } );
2560 =item change_cust_main
2562 Returns the customter this package was detached to, if any.
2566 sub change_cust_main {
2568 return '' unless $self->change_custnum;
2569 qsearchs('cust_main', { 'custnum' => $self->change_custnum } );
2574 Calls the I<calc_setup> of the FS::part_pkg object associated with this billing
2581 $self->part_pkg->calc_setup($self, @_);
2586 Calls the I<calc_recur> of the FS::part_pkg object associated with this billing
2593 $self->part_pkg->calc_recur($self, @_);
2598 Calls the I<base_setup> of the FS::part_pkg object associated with this billing
2605 $self->part_pkg->base_setup($self, @_);
2610 Calls the I<base_recur> of the FS::part_pkg object associated with this billing
2617 $self->part_pkg->base_recur($self, @_);
2622 Calls the I<calc_remain> of the FS::part_pkg object associated with this
2629 $self->part_pkg->calc_remain($self, @_);
2634 Calls the I<calc_cancel> of the FS::part_pkg object associated with this
2641 $self->part_pkg->calc_cancel($self, @_);
2646 Returns any invoice line items for this package (see L<FS::cust_bill_pkg>).
2652 qsearch( 'cust_bill_pkg', { 'pkgnum' => $self->pkgnum } );
2655 =item cust_pkg_detail [ DETAILTYPE ]
2657 Returns any customer package details for this package (see
2658 L<FS::cust_pkg_detail>).
2660 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
2664 sub cust_pkg_detail {
2666 my %hash = ( 'pkgnum' => $self->pkgnum );
2667 $hash{detailtype} = shift if @_;
2669 'table' => 'cust_pkg_detail',
2670 'hashref' => \%hash,
2671 'order_by' => 'ORDER BY weight, pkgdetailnum',
2675 =item set_cust_pkg_detail DETAILTYPE [ DETAIL, DETAIL, ... ]
2677 Sets customer package details for this package (see L<FS::cust_pkg_detail>).
2679 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
2681 If there is an error, returns the error, otherwise returns false.
2685 sub set_cust_pkg_detail {
2686 my( $self, $detailtype, @details ) = @_;
2688 my $oldAutoCommit = $FS::UID::AutoCommit;
2689 local $FS::UID::AutoCommit = 0;
2692 foreach my $current ( $self->cust_pkg_detail($detailtype) ) {
2693 my $error = $current->delete;
2695 $dbh->rollback if $oldAutoCommit;
2696 return "error removing old detail: $error";
2700 foreach my $detail ( @details ) {
2701 my $cust_pkg_detail = new FS::cust_pkg_detail {
2702 'pkgnum' => $self->pkgnum,
2703 'detailtype' => $detailtype,
2704 'detail' => $detail,
2706 my $error = $cust_pkg_detail->insert;
2708 $dbh->rollback if $oldAutoCommit;
2709 return "error adding new detail: $error";
2714 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2721 Returns the customer billing events (see L<FS::cust_event>) for this invoice.
2725 #false laziness w/cust_bill.pm
2729 'table' => 'cust_event',
2730 'addl_from' => 'JOIN part_event USING ( eventpart )',
2731 'hashref' => { 'tablenum' => $self->pkgnum },
2732 'extra_sql' => " AND eventtable = 'cust_pkg' ",
2736 =item num_cust_event
2738 Returns the number of customer billing events (see L<FS::cust_event>) for this package.
2742 #false laziness w/cust_bill.pm
2743 sub num_cust_event {
2745 my $sql = "SELECT COUNT(*) ". $self->_from_cust_event_where;
2746 $self->_prep_ex($sql, $self->pkgnum)->fetchrow_arrayref->[0];
2749 =item exists_cust_event
2751 Returns true if there are customer billing events (see L<FS::cust_event>) for this package. More efficient than using num_cust_event.
2755 sub exists_cust_event {
2757 my $sql = "SELECT 1 ". $self->_from_cust_event_where. " LIMIT 1";
2758 my $row = $self->_prep_ex($sql, $self->pkgnum)->fetchrow_arrayref;
2759 $row ? $row->[0] : '';
2762 sub _from_cust_event_where {
2764 " FROM cust_event JOIN part_event USING ( eventpart ) ".
2765 " WHERE tablenum = ? AND eventtable = 'cust_pkg' ";
2769 my( $self, $sql, @args ) = @_;
2770 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
2771 $sth->execute(@args) or die $sth->errstr. " executing $sql";
2775 =item part_pkg_currency_option OPTIONNAME
2777 Returns a two item list consisting of the currency of this customer, if any,
2778 and a value for the provided option. If the customer has a currency, the value
2779 is the option value the given name and the currency (see
2780 L<FS::part_pkg_currency>). Otherwise, if the customer has no currency, is the
2781 regular option value for the given name (see L<FS::part_pkg_option>).
2785 sub part_pkg_currency_option {
2786 my( $self, $optionname ) = @_;
2787 my $part_pkg = $self->part_pkg;
2788 if ( my $currency = $self->cust_main->currency ) {
2789 ($currency, $part_pkg->part_pkg_currency_option($currency, $optionname) );
2791 ('', $part_pkg->option($optionname) );
2795 =item cust_svc [ SVCPART ] (old, deprecated usage)
2797 =item cust_svc [ OPTION => VALUE ... ] (current usage)
2799 =item cust_svc_unsorted [ OPTION => VALUE ... ]
2801 Returns the services for this package, as FS::cust_svc objects (see
2802 L<FS::cust_svc>). Available options are svcpart and svcdb. If either is
2803 spcififed, returns only the matching services.
2805 As an optimization, use the cust_svc_unsorted version if you are not displaying
2812 cluck "cust_pkg->cust_svc called" if $DEBUG > 2;
2813 $self->_sort_cust_svc( $self->cust_svc_unsorted_arrayref(@_) );
2816 sub cust_svc_unsorted {
2818 @{ $self->cust_svc_unsorted_arrayref(@_) };
2821 sub cust_svc_unsorted_arrayref {
2824 return [] unless $self->num_cust_svc(@_);
2827 if ( @_ && $_[0] =~ /^\d+/ ) {
2828 $opt{svcpart} = shift;
2829 } elsif ( @_ && ref($_[0]) eq 'HASH' ) {
2836 'table' => 'cust_svc',
2837 'hashref' => { 'pkgnum' => $self->pkgnum },
2839 if ( $opt{svcpart} ) {
2840 $search{hashref}->{svcpart} = $opt{'svcpart'};
2842 if ( $opt{'svcdb'} ) {
2843 $search{addl_from} = ' LEFT JOIN part_svc USING ( svcpart ) ';
2844 $search{extra_sql} = ' AND svcdb = '. dbh->quote( $opt{'svcdb'} );
2847 [ qsearch(\%search) ];
2851 =item overlimit [ SVCPART ]
2853 Returns the services for this package which have exceeded their
2854 usage limit as FS::cust_svc objects (see L<FS::cust_svc>). If a svcpart
2855 is specified, return only the matching services.
2861 return () unless $self->num_cust_svc(@_);
2862 grep { $_->overlimit } $self->cust_svc(@_);
2865 =item h_cust_svc END_TIMESTAMP [ START_TIMESTAMP ] [ MODE ]
2867 Returns historical services for this package created before END TIMESTAMP and
2868 (optionally) not cancelled before START_TIMESTAMP, as FS::h_cust_svc objects
2869 (see L<FS::h_cust_svc>). If MODE is 'I' (for 'invoice'), services with the
2870 I<pkg_svc.hidden> flag will be omitted.
2876 warn "$me _h_cust_svc called on $self\n"
2879 my ($end, $start, $mode) = @_;
2880 my @cust_svc = $self->_sort_cust_svc(
2881 [ qsearch( 'h_cust_svc',
2882 { 'pkgnum' => $self->pkgnum, },
2883 FS::h_cust_svc->sql_h_search(@_),
2886 if ( defined($mode) && $mode eq 'I' ) {
2887 my %hidden_svcpart = map { $_->svcpart => $_->hidden } $self->part_svc;
2888 return grep { !$hidden_svcpart{$_->svcpart} } @cust_svc;
2894 sub _sort_cust_svc {
2895 my( $self, $arrayref ) = @_;
2898 sub ($$) { my ($a, $b) = @_; $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] };
2900 my %pkg_svc = map { $_->svcpart => $_ }
2901 qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
2906 my $pkg_svc = $pkg_svc{ $_->svcpart } || '';
2908 $pkg_svc ? $pkg_svc->primary_svc : '',
2909 $pkg_svc ? $pkg_svc->quantity : 0,
2916 =item num_cust_svc [ SVCPART ] (old, deprecated usage)
2918 =item num_cust_svc [ OPTION => VALUE ... ] (current usage)
2920 Returns the number of services for this package. Available options are svcpart
2921 and svcdb. If either is spcififed, returns only the matching services.
2928 return $self->{'_num_cust_svc'}
2930 && exists($self->{'_num_cust_svc'})
2931 && $self->{'_num_cust_svc'} =~ /\d/;
2933 cluck "cust_pkg->num_cust_svc called, _num_cust_svc:".$self->{'_num_cust_svc'}
2937 if ( @_ && $_[0] =~ /^\d+/ ) {
2938 $opt{svcpart} = shift;
2939 } elsif ( @_ && ref($_[0]) eq 'HASH' ) {
2945 my $select = 'SELECT COUNT(*) FROM cust_svc ';
2946 my $where = ' WHERE pkgnum = ? ';
2947 my @param = ($self->pkgnum);
2949 if ( $opt{'svcpart'} ) {
2950 $where .= ' AND svcpart = ? ';
2951 push @param, $opt{'svcpart'};
2953 if ( $opt{'svcdb'} ) {
2954 $select .= ' LEFT JOIN part_svc USING ( svcpart ) ';
2955 $where .= ' AND svcdb = ? ';
2956 push @param, $opt{'svcdb'};
2959 my $sth = dbh->prepare("$select $where") or die dbh->errstr;
2960 $sth->execute(@param) or die $sth->errstr;
2961 $sth->fetchrow_arrayref->[0];
2964 =item available_part_svc
2966 Returns a list of FS::part_svc objects representing services included in this
2967 package but not yet provisioned. Each FS::part_svc object also has an extra
2968 field, I<num_avail>, which specifies the number of available services.
2972 sub available_part_svc {
2975 my $pkg_quantity = $self->quantity || 1;
2977 grep { $_->num_avail > 0 }
2979 my $part_svc = $_->part_svc;
2980 $part_svc->{'Hash'}{'num_avail'} = #evil encapsulation-breaking
2981 $pkg_quantity * $_->quantity - $self->num_cust_svc($_->svcpart);
2983 # more evil encapsulation breakage
2984 if($part_svc->{'Hash'}{'num_avail'} > 0) {
2985 my @exports = $part_svc->part_export_did;
2986 $part_svc->{'Hash'}{'can_get_dids'} = scalar(@exports);
2991 $self->part_pkg->pkg_svc;
2994 =item part_svc [ OPTION => VALUE ... ]
2996 Returns a list of FS::part_svc objects representing provisioned and available
2997 services included in this package. Each FS::part_svc object also has the
2998 following extra fields:
3012 (services) - array reference containing the provisioned services, as cust_svc objects
3016 Accepts two options:
3020 =item summarize_size
3022 If true, will omit the extra cust_pkg_svc option for objects where num_cust_svc
3023 is this size or greater.
3025 =item hide_discontinued
3027 If true, will omit looking for services that are no longer avaialble in the
3035 #label -> ($cust_svc->label)[1]
3041 my $pkg_quantity = $self->quantity || 1;
3043 #XXX some sort of sort order besides numeric by svcpart...
3044 my @part_svc = sort { $a->svcpart <=> $b->svcpart } map {
3046 my $part_svc = $pkg_svc->part_svc;
3047 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
3048 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #more evil
3049 $part_svc->{'Hash'}{'num_avail'} =
3050 max( 0, $pkg_quantity * $pkg_svc->quantity - $num_cust_svc );
3051 $part_svc->{'Hash'}{'cust_pkg_svc'} =
3052 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : []
3053 unless exists($opt{summarize_size}) && $opt{summarize_size} > 0
3054 && $num_cust_svc >= $opt{summarize_size};
3055 $part_svc->{'Hash'}{'hidden'} = $pkg_svc->hidden;
3057 } $self->part_pkg->pkg_svc;
3059 unless ( $opt{hide_discontinued} ) {
3061 push @part_svc, map {
3063 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
3064 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #speak no evail
3065 $part_svc->{'Hash'}{'num_avail'} = 0; #0-$num_cust_svc ?
3066 $part_svc->{'Hash'}{'cust_pkg_svc'} =
3067 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : [];
3069 } $self->extra_part_svc;
3076 =item extra_part_svc
3078 Returns a list of FS::part_svc objects corresponding to services in this
3079 package which are still provisioned but not (any longer) available in the
3084 sub extra_part_svc {
3087 my $pkgnum = $self->pkgnum;
3088 #my $pkgpart = $self->pkgpart;
3091 # 'table' => 'part_svc',
3094 # "WHERE 0 = ( SELECT COUNT(*) FROM pkg_svc
3095 # WHERE pkg_svc.svcpart = part_svc.svcpart
3096 # AND pkg_svc.pkgpart = ?
3099 # AND 0 < ( SELECT COUNT(*) FROM cust_svc
3100 # LEFT JOIN cust_pkg USING ( pkgnum )
3101 # WHERE cust_svc.svcpart = part_svc.svcpart
3104 # 'extra_param' => [ [$self->pkgpart=>'int'], [$self->pkgnum=>'int'] ],
3107 #seems to benchmark slightly faster... (or did?)
3109 my @pkgparts = map $_->pkgpart, $self->part_pkg->self_and_svc_linked;
3110 my $pkgparts = join(',', @pkgparts);
3113 #'select' => 'DISTINCT ON (svcpart) part_svc.*',
3114 #MySQL doesn't grok DISINCT ON
3115 'select' => 'DISTINCT part_svc.*',
3116 'table' => 'part_svc',
3118 "LEFT JOIN pkg_svc ON ( pkg_svc.svcpart = part_svc.svcpart
3119 AND pkg_svc.pkgpart IN ($pkgparts)
3122 LEFT JOIN cust_svc ON ( cust_svc.svcpart = part_svc.svcpart )
3123 LEFT JOIN cust_pkg USING ( pkgnum )
3126 'extra_sql' => "WHERE pkgsvcnum IS NULL AND cust_pkg.pkgnum = ? ",
3127 'extra_param' => [ [$self->pkgnum=>'int'] ],
3133 Returns a short status string for this package, currently:
3139 =item not yet billed
3141 =item one-time charge
3156 my $freq = length($self->freq) ? $self->freq : $self->part_pkg->freq;
3158 return 'cancelled' if $self->get('cancel');
3159 return 'on hold' if $self->susp && ! $self->setup;
3160 return 'suspended' if $self->susp;
3161 return 'not yet billed' unless $self->setup;
3162 return 'one-time charge' if $freq =~ /^(0|$)/;
3166 =item ucfirst_status
3168 Returns the status with the first character capitalized.
3172 sub ucfirst_status {
3173 ucfirst(shift->status);
3178 Class method that returns the list of possible status strings for packages
3179 (see L<the status method|/status>). For example:
3181 @statuses = FS::cust_pkg->statuses();
3185 tie my %statuscolor, 'Tie::IxHash',
3186 'on hold' => '7E0079', #purple!
3187 'not yet billed' => '009999', #teal? cyan?
3188 'one-time charge' => '0000CC', #blue #'000000',
3189 'active' => '00CC00',
3190 'suspended' => 'FF9900',
3191 'cancelled' => 'FF0000',
3195 my $self = shift; #could be class...
3196 #grep { $_ !~ /^(not yet billed)$/ } #this is a dumb status anyway
3197 # # mayble split btw one-time vs. recur
3208 Returns a hex triplet color string for this package's status.
3214 $statuscolor{$self->status};
3219 Returns a label for this package. (Currently "pkgnum: pkg - comment" or
3220 "pkg - comment" depending on user preference).
3226 my $label = $self->part_pkg->pkg_comment( cust_pkg=>$self, nopkgpart=>1 );
3227 $label = $self->pkgnum. ": $label"
3228 if $FS::CurrentUser::CurrentUser->option('show_pkgnum');
3232 =item pkg_label_long
3234 Returns a long label for this package, adding the primary service's label to
3239 sub pkg_label_long {
3241 my $label = $self->pkg_label;
3242 my $cust_svc = $self->primary_cust_svc;
3243 $label .= ' ('. ($cust_svc->label)[1]. ')' if $cust_svc;
3249 Returns a customer-localized label for this package.
3255 $self->part_pkg->pkg_locale( $self->cust_main->locale );
3258 =item primary_cust_svc
3260 Returns a primary service (as FS::cust_svc object) if one can be identified.
3264 #for labeling purposes - might not 100% match up with part_pkg->svcpart's idea
3266 sub primary_cust_svc {
3269 my @cust_svc = $self->cust_svc;
3271 return '' unless @cust_svc; #no serivces - irrelevant then
3273 return $cust_svc[0] if scalar(@cust_svc) == 1; #always return a single service
3275 # primary service as specified in the package definition
3276 # or exactly one service definition with quantity one
3277 my $svcpart = $self->part_pkg->svcpart;
3278 @cust_svc = grep { $_->svcpart == $svcpart } @cust_svc;
3279 return $cust_svc[0] if scalar(@cust_svc) == 1;
3281 #couldn't identify one thing..
3287 Returns a list of lists, calling the label method for all services
3288 (see L<FS::cust_svc>) of this billing item.
3294 map { [ $_->label ] } $self->cust_svc;
3297 =item h_labels END_TIMESTAMP [ START_TIMESTAMP ] [ MODE ]
3299 Like the labels method, but returns historical information on services that
3300 were active as of END_TIMESTAMP and (optionally) not cancelled before
3301 START_TIMESTAMP. If MODE is 'I' (for 'invoice'), services with the
3302 I<pkg_svc.hidden> flag will be omitted.
3304 Returns a list of lists, calling the label method for all (historical) services
3305 (see L<FS::h_cust_svc>) of this billing item.
3311 warn "$me _h_labels called on $self\n"
3313 map { [ $_->label(@_) ] } $self->h_cust_svc(@_);
3318 Like labels, except returns a simple flat list, and shortens long
3319 (currently >5 or the cust_bill-max_same_services configuration value) lists of
3320 identical services to one line that lists the service label and the number of
3321 individual services rather than individual items.
3326 shift->_labels_short( 'labels', @_ );
3329 =item h_labels_short END_TIMESTAMP [ START_TIMESTAMP ]
3331 Like h_labels, except returns a simple flat list, and shortens long
3332 (currently >5 or the cust_bill-max_same_services configuration value) lists of
3333 identical services to one line that lists the service label and the number of
3334 individual services rather than individual items.
3338 sub h_labels_short {
3339 shift->_labels_short( 'h_labels', @_ );
3343 my( $self, $method ) = ( shift, shift );
3345 warn "$me _labels_short called on $self with $method method\n"
3348 my $conf = new FS::Conf;
3349 my $max_same_services = $conf->config('cust_bill-max_same_services') || 5;
3351 warn "$me _labels_short populating \%labels\n"
3355 #tie %labels, 'Tie::IxHash';
3356 push @{ $labels{$_->[0]} }, $_->[1]
3357 foreach $self->$method(@_);
3359 warn "$me _labels_short populating \@labels\n"
3363 foreach my $label ( keys %labels ) {
3365 my @values = grep { ! $seen{$_}++ } @{ $labels{$label} };
3366 my $num = scalar(@values);
3367 warn "$me _labels_short $num items for $label\n"
3370 if ( $num > $max_same_services ) {
3371 warn "$me _labels_short more than $max_same_services, so summarizing\n"
3373 push @labels, "$label ($num)";
3375 if ( $conf->exists('cust_bill-consolidate_services') ) {
3376 warn "$me _labels_short consolidating services\n"
3378 # push @labels, "$label: ". join(', ', @values);
3380 my $detail = "$label: ";
3381 $detail .= shift(@values). ', '
3383 && ( length($detail.$values[0]) < 78 || $detail eq "$label: " );
3385 push @labels, $detail;
3387 warn "$me _labels_short done consolidating services\n"
3390 warn "$me _labels_short adding service data\n"
3392 push @labels, map { "$label: $_" } @values;
3403 Returns the parent customer object (see L<FS::cust_main>).
3407 Returns the balance for this specific package, when using
3408 experimental package balance.
3414 $self->cust_main->balance_pkgnum( $self->pkgnum );
3417 #these subs are in location_Mixin.pm now... unfortunately the POD doesn't mixin
3421 Returns the location object, if any (see L<FS::cust_location>).
3423 =item cust_location_or_main
3425 If this package is associated with a location, returns the locaiton (see
3426 L<FS::cust_location>), otherwise returns the customer (see L<FS::cust_main>).
3428 =item location_label [ OPTION => VALUE ... ]
3430 Returns the label of the location object (see L<FS::cust_location>).
3434 #end of subs in location_Mixin.pm now... unfortunately the POD doesn't mixin
3436 =item tax_locationnum
3438 Returns the foreign key to a L<FS::cust_location> object for calculating
3439 tax on this package, as determined by the C<tax-pkg_address> and
3440 C<tax-ship_address> configuration flags.
3444 sub tax_locationnum {
3446 my $conf = FS::Conf->new;
3447 if ( $conf->exists('tax-pkg_address') ) {
3448 return $self->locationnum;
3450 elsif ( $conf->exists('tax-ship_address') ) {
3451 return $self->cust_main->ship_locationnum;
3454 return $self->cust_main->bill_locationnum;
3460 Returns the L<FS::cust_location> object for tax_locationnum.
3466 my $conf = FS::Conf->new;
3467 if ( $conf->exists('tax-pkg_address') and $self->locationnum ) {
3468 return FS::cust_location->by_key($self->locationnum);
3470 elsif ( $conf->exists('tax-ship_address') ) {
3471 return $self->cust_main->ship_location;
3474 return $self->cust_main->bill_location;
3478 =item seconds_since TIMESTAMP
3480 Returns the number of seconds all accounts (see L<FS::svc_acct>) in this
3481 package have been online since TIMESTAMP, according to the session monitor.
3483 TIMESTAMP is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
3484 L<Time::Local> and L<Date::Parse> for conversion functions.
3489 my($self, $since) = @_;
3492 foreach my $cust_svc (
3493 grep { $_->part_svc->svcdb eq 'svc_acct' } $self->cust_svc
3495 $seconds += $cust_svc->seconds_since($since);
3502 =item seconds_since_sqlradacct TIMESTAMP_START TIMESTAMP_END
3504 Returns the numbers of seconds all accounts (see L<FS::svc_acct>) in this
3505 package have been online between TIMESTAMP_START (inclusive) and TIMESTAMP_END
3508 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
3509 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
3515 sub seconds_since_sqlradacct {
3516 my($self, $start, $end) = @_;
3520 foreach my $cust_svc (
3522 my $part_svc = $_->part_svc;
3523 $part_svc->svcdb eq 'svc_acct'
3524 && scalar($part_svc->part_export_usage);
3527 $seconds += $cust_svc->seconds_since_sqlradacct($start, $end);
3534 =item attribute_since_sqlradacct TIMESTAMP_START TIMESTAMP_END ATTRIBUTE
3536 Returns the sum of the given attribute for all accounts (see L<FS::svc_acct>)
3537 in this package for sessions ending between TIMESTAMP_START (inclusive) and
3541 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
3542 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
3547 sub attribute_since_sqlradacct {
3548 my($self, $start, $end, $attrib) = @_;
3552 foreach my $cust_svc (
3554 my $part_svc = $_->part_svc;
3555 scalar($part_svc->part_export_usage);
3558 $sum += $cust_svc->attribute_since_sqlradacct($start, $end, $attrib);
3570 my( $self, $value ) = @_;
3571 if ( defined($value) ) {
3572 $self->setfield('quantity', $value);
3574 $self->getfield('quantity') || 1;
3577 =item transfer DEST_PKGNUM | DEST_CUST_PKG, [ OPTION => VALUE ... ]
3579 Transfers as many services as possible from this package to another package.
3581 The destination package can be specified by pkgnum by passing an FS::cust_pkg
3582 object. The destination package must already exist.
3584 Services are moved only if the destination allows services with the correct
3585 I<svcpart> (not svcdb), unless the B<change_svcpart> option is set true. Use
3586 this option with caution! No provision is made for export differences
3587 between the old and new service definitions. Probably only should be used
3588 when your exports for all service definitions of a given svcdb are identical.
3589 (attempt a transfer without it first, to move all possible svcpart-matching
3592 Any services that can't be moved remain in the original package.
3594 Returns an error, if there is one; otherwise, returns the number of services
3595 that couldn't be moved.
3600 my ($self, $dest_pkgnum, %opt) = @_;
3606 if (ref ($dest_pkgnum) eq 'FS::cust_pkg') {
3607 $dest = $dest_pkgnum;
3608 $dest_pkgnum = $dest->pkgnum;
3610 $dest = qsearchs('cust_pkg', { pkgnum => $dest_pkgnum });
3613 return ('Package does not exist: '.$dest_pkgnum) unless $dest;
3615 foreach my $pkg_svc ( $dest->part_pkg->pkg_svc ) {
3616 $target{$pkg_svc->svcpart} = $pkg_svc->quantity;
3619 foreach my $cust_svc ($dest->cust_svc) {
3620 $target{$cust_svc->svcpart}--;
3623 my %svcpart2svcparts = ();
3624 if ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
3625 warn "change_svcpart option received, creating alternates list\n" if $DEBUG;
3626 foreach my $svcpart ( map { $_->svcpart } $self->cust_svc ) {
3627 next if exists $svcpart2svcparts{$svcpart};
3628 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
3629 $svcpart2svcparts{$svcpart} = [
3631 sort { $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] }
3633 my $pkg_svc = qsearchs( 'pkg_svc', { 'pkgpart' => $dest->pkgpart,
3634 'svcpart' => $_ } );
3636 $pkg_svc ? $pkg_svc->primary_svc : '',
3637 $pkg_svc ? $pkg_svc->quantity : 0,
3641 grep { $_ != $svcpart }
3643 qsearch('part_svc', { 'svcdb' => $part_svc->svcdb } )
3645 warn "alternates for svcpart $svcpart: ".
3646 join(', ', @{$svcpart2svcparts{$svcpart}}). "\n"
3652 foreach my $cust_svc ($self->cust_svc) {
3653 my $svcnum = $cust_svc->svcnum;
3654 if($target{$cust_svc->svcpart} > 0
3655 or $FS::cust_svc::ignore_quantity) { # maybe should be a 'force' option
3656 $target{$cust_svc->svcpart}--;
3657 my $new = new FS::cust_svc { $cust_svc->hash };
3658 $new->pkgnum($dest_pkgnum);
3659 $error = $new->replace($cust_svc);
3660 } elsif ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
3662 warn "looking for alternates for svcpart ". $cust_svc->svcpart. "\n";
3663 warn "alternates to consider: ".
3664 join(', ', @{$svcpart2svcparts{$cust_svc->svcpart}}). "\n";
3666 my @alternate = grep {
3667 warn "considering alternate svcpart $_: ".
3668 "$target{$_} available in new package\n"
3671 } @{$svcpart2svcparts{$cust_svc->svcpart}};
3673 warn "alternate(s) found\n" if $DEBUG;
3674 my $change_svcpart = $alternate[0];
3675 $target{$change_svcpart}--;
3676 my $new = new FS::cust_svc { $cust_svc->hash };
3677 $new->svcpart($change_svcpart);
3678 $new->pkgnum($dest_pkgnum);
3679 $error = $new->replace($cust_svc);
3687 my @label = $cust_svc->label;
3688 return "$label[0] $label[1]: $error";
3694 =item grab_svcnums SVCNUM, SVCNUM ...
3696 Change the pkgnum for the provided services to this packages. If there is an
3697 error, returns the error, otherwise returns false.
3705 my $oldAutoCommit = $FS::UID::AutoCommit;
3706 local $FS::UID::AutoCommit = 0;
3709 foreach my $svcnum (@svcnum) {
3710 my $cust_svc = qsearchs('cust_svc', { svcnum=>$svcnum } ) or do {
3711 $dbh->rollback if $oldAutoCommit;
3712 return "unknown svcnum $svcnum";
3714 $cust_svc->pkgnum( $self->pkgnum );
3715 my $error = $cust_svc->replace;
3717 $dbh->rollback if $oldAutoCommit;
3722 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3729 This method is deprecated. See the I<depend_jobnum> option to the insert and
3730 order_pkgs methods in FS::cust_main for a better way to defer provisioning.
3734 #looks like this is still used by the order_pkg and change_pkg methods in
3735 # ClientAPI/MyAccount, need to look into those before removing
3739 my $oldAutoCommit = $FS::UID::AutoCommit;
3740 local $FS::UID::AutoCommit = 0;
3743 foreach my $cust_svc ( $self->cust_svc ) {
3744 #false laziness w/svc_Common::insert
3745 my $svc_x = $cust_svc->svc_x;
3746 foreach my $part_export ( $cust_svc->part_svc->part_export ) {
3747 my $error = $part_export->export_insert($svc_x);
3749 $dbh->rollback if $oldAutoCommit;
3755 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3760 =item export_pkg_change OLD_CUST_PKG
3762 Calls the "pkg_change" export action for all services attached to this package.
3766 sub export_pkg_change {
3767 my( $self, $old ) = ( shift, shift );
3769 my $oldAutoCommit = $FS::UID::AutoCommit;
3770 local $FS::UID::AutoCommit = 0;
3773 foreach my $svc_x ( map $_->svc_x, $self->cust_svc ) {
3774 my $error = $svc_x->export('pkg_change', $self, $old);
3776 $dbh->rollback if $oldAutoCommit;
3781 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3788 Associates this package with a (suspension or cancellation) reason (see
3789 L<FS::cust_pkg_reason>, possibly inserting a new reason on the fly (see
3792 Available options are:
3798 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.
3802 the access_user (see L<FS::access_user>) providing the reason
3810 the action (cancel, susp, adjourn, expire) associated with the reason
3814 If there is an error, returns the error, otherwise returns false.
3819 my ($self, %options) = @_;
3821 my $otaker = $options{reason_otaker} ||
3822 $FS::CurrentUser::CurrentUser->username;
3825 if ( $options{'reason'} =~ /^(\d+)$/ ) {
3829 } elsif ( ref($options{'reason'}) ) {
3831 return 'Enter a new reason (or select an existing one)'
3832 unless $options{'reason'}->{'reason'} !~ /^\s*$/;
3834 my $reason = new FS::reason({
3835 'reason_type' => $options{'reason'}->{'typenum'},
3836 'reason' => $options{'reason'}->{'reason'},
3838 my $error = $reason->insert;
3839 return $error if $error;
3841 $reasonnum = $reason->reasonnum;
3844 return "Unparsable reason: ". $options{'reason'};
3847 my $cust_pkg_reason =
3848 new FS::cust_pkg_reason({ 'pkgnum' => $self->pkgnum,
3849 'reasonnum' => $reasonnum,
3850 'otaker' => $otaker,
3851 'action' => substr(uc($options{'action'}),0,1),
3852 'date' => $options{'date'}
3857 $cust_pkg_reason->insert;
3860 =item insert_discount
3862 Associates this package with a discount (see L<FS::cust_pkg_discount>, possibly
3863 inserting a new discount on the fly (see L<FS::discount>).
3865 Available options are:
3873 If there is an error, returns the error, otherwise returns false.
3877 sub insert_discount {
3878 #my ($self, %options) = @_;
3881 my $cust_pkg_discount = new FS::cust_pkg_discount {
3882 'pkgnum' => $self->pkgnum,
3883 'discountnum' => $self->discountnum,
3885 'end_date' => '', #XXX
3886 #for the create a new discount case
3887 '_type' => $self->discountnum__type,
3888 'amount' => $self->discountnum_amount,
3889 'percent' => $self->discountnum_percent,
3890 'months' => $self->discountnum_months,
3891 'setup' => $self->discountnum_setup,
3892 #'disabled' => $self->discountnum_disabled,
3895 $cust_pkg_discount->insert;
3898 =item set_usage USAGE_VALUE_HASHREF
3900 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
3901 to which they should be set (see L<FS::svc_acct>). Currently seconds,
3902 upbytes, downbytes, and totalbytes are appropriate keys.
3904 All svc_accts which are part of this package have their values reset.
3909 my ($self, $valueref, %opt) = @_;
3911 #only svc_acct can set_usage for now
3912 foreach my $cust_svc ( $self->cust_svc( 'svcdb'=>'svc_acct' ) ) {
3913 my $svc_x = $cust_svc->svc_x;
3914 $svc_x->set_usage($valueref, %opt)
3915 if $svc_x->can("set_usage");
3919 =item recharge USAGE_VALUE_HASHREF
3921 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
3922 to which they should be set (see L<FS::svc_acct>). Currently seconds,
3923 upbytes, downbytes, and totalbytes are appropriate keys.
3925 All svc_accts which are part of this package have their values incremented.
3930 my ($self, $valueref) = @_;
3932 #only svc_acct can set_usage for now
3933 foreach my $cust_svc ( $self->cust_svc( 'svcdb'=>'svc_acct' ) ) {
3934 my $svc_x = $cust_svc->svc_x;
3935 $svc_x->recharge($valueref)
3936 if $svc_x->can("recharge");
3940 =item apply_usageprice
3944 sub apply_usageprice {
3947 my $oldAutoCommit = $FS::UID::AutoCommit;
3948 local $FS::UID::AutoCommit = 0;
3953 foreach my $cust_pkg_usageprice ( $self->cust_pkg_usageprice ) {
3954 $error ||= $cust_pkg_usageprice->apply;
3958 $dbh->rollback if $oldAutoCommit;
3959 die "error applying part_pkg_usageprice add-ons, pkgnum ". $self->pkgnum.
3962 $dbh->commit if $oldAutoCommit;
3968 =item cust_pkg_discount
3970 =item cust_pkg_discount_active
3974 sub cust_pkg_discount_active {
3976 grep { $_->status eq 'active' } $self->cust_pkg_discount;
3979 =item cust_pkg_usage
3981 Returns a list of all voice usage counters attached to this package.
3983 =item apply_usage OPTIONS
3985 Takes the following options:
3986 - cdr: a call detail record (L<FS::cdr>)
3987 - rate_detail: the rate determined for this call (L<FS::rate_detail>)
3988 - minutes: the maximum number of minutes to be charged
3990 Finds available usage minutes for a call of this class, and subtracts
3991 up to that many minutes from the usage pool. If the usage pool is empty,
3992 and the C<cdr-minutes_priority> global config option is set, minutes may
3993 be taken from other calls as well. Either way, an allocation record will
3994 be created (L<FS::cdr_cust_pkg_usage>) and this method will return the
3995 number of minutes of usage applied to the call.
4000 my ($self, %opt) = @_;
4001 my $cdr = $opt{cdr};
4002 my $rate_detail = $opt{rate_detail};
4003 my $minutes = $opt{minutes};
4004 my $classnum = $rate_detail->classnum;
4005 my $pkgnum = $self->pkgnum;
4006 my $custnum = $self->custnum;
4008 my $oldAutoCommit = $FS::UID::AutoCommit;
4009 local $FS::UID::AutoCommit = 0;
4012 my $order = FS::Conf->new->config('cdr-minutes_priority');
4016 $is_classnum = ' part_pkg_usage_class.classnum = '.$classnum;
4018 $is_classnum = ' part_pkg_usage_class.classnum IS NULL';
4020 my @usage_recs = qsearch({
4021 'table' => 'cust_pkg_usage',
4022 'addl_from' => ' JOIN part_pkg_usage USING (pkgusagepart)'.
4023 ' JOIN cust_pkg USING (pkgnum)'.
4024 ' JOIN part_pkg_usage_class USING (pkgusagepart)',
4025 'select' => 'cust_pkg_usage.*',
4026 'extra_sql' => " WHERE ( cust_pkg.pkgnum = $pkgnum OR ".
4027 " ( cust_pkg.custnum = $custnum AND ".
4028 " part_pkg_usage.shared IS NOT NULL ) ) AND ".
4029 $is_classnum . ' AND '.
4030 " cust_pkg_usage.minutes > 0",
4031 'order_by' => " ORDER BY priority ASC",
4034 my $orig_minutes = $minutes;
4036 while (!$error and $minutes > 0 and @usage_recs) {
4037 my $cust_pkg_usage = shift @usage_recs;
4038 $cust_pkg_usage->select_for_update;
4039 my $cdr_cust_pkg_usage = FS::cdr_cust_pkg_usage->new({
4040 pkgusagenum => $cust_pkg_usage->pkgusagenum,
4041 acctid => $cdr->acctid,
4042 minutes => min($cust_pkg_usage->minutes, $minutes),
4044 $cust_pkg_usage->set('minutes',
4045 $cust_pkg_usage->minutes - $cdr_cust_pkg_usage->minutes
4047 $error = $cust_pkg_usage->replace || $cdr_cust_pkg_usage->insert;
4048 $minutes -= $cdr_cust_pkg_usage->minutes;
4050 if ( $order and $minutes > 0 and !$error ) {
4051 # then try to steal minutes from another call
4053 'table' => 'cdr_cust_pkg_usage',
4054 'addl_from' => ' JOIN cust_pkg_usage USING (pkgusagenum)'.
4055 ' JOIN part_pkg_usage USING (pkgusagepart)'.
4056 ' JOIN cust_pkg USING (pkgnum)'.
4057 ' JOIN part_pkg_usage_class USING (pkgusagepart)'.
4058 ' JOIN cdr USING (acctid)',
4059 'select' => 'cdr_cust_pkg_usage.*',
4060 'extra_sql' => " WHERE cdr.freesidestatus = 'rated' AND ".
4061 " ( cust_pkg.pkgnum = $pkgnum OR ".
4062 " ( cust_pkg.custnum = $custnum AND ".
4063 " part_pkg_usage.shared IS NOT NULL ) ) AND ".
4064 " part_pkg_usage_class.classnum = $classnum",
4065 'order_by' => ' ORDER BY part_pkg_usage.priority ASC',
4067 if ( $order eq 'time' ) {
4068 # find CDRs that are using minutes, but have a later startdate
4070 my $startdate = $cdr->startdate;
4071 if ($startdate !~ /^\d+$/) {
4072 die "bad cdr startdate '$startdate'";
4074 $search{'extra_sql'} .= " AND cdr.startdate > $startdate";
4075 # minimize needless reshuffling
4076 $search{'order_by'} .= ', cdr.startdate DESC';
4078 # XXX may not work correctly with rate_time schedules. Could
4079 # fix this by storing ratedetailnum in cdr_cust_pkg_usage, I
4081 $search{'addl_from'} .=
4082 ' JOIN rate_detail'.
4083 ' ON (cdr.rated_ratedetailnum = rate_detail.ratedetailnum)';
4084 if ( $order eq 'rate_high' ) {
4085 $search{'extra_sql'} .= ' AND rate_detail.min_charge < '.
4086 $rate_detail->min_charge;
4087 $search{'order_by'} .= ', rate_detail.min_charge ASC';
4088 } elsif ( $order eq 'rate_low' ) {
4089 $search{'extra_sql'} .= ' AND rate_detail.min_charge > '.
4090 $rate_detail->min_charge;
4091 $search{'order_by'} .= ', rate_detail.min_charge DESC';
4093 # this should really never happen
4094 die "invalid cdr-minutes_priority value '$order'\n";
4097 my @cdr_usage_recs = qsearch(\%search);
4099 while (!$error and @cdr_usage_recs and $minutes > 0) {
4100 my $cdr_cust_pkg_usage = shift @cdr_usage_recs;
4101 my $cust_pkg_usage = $cdr_cust_pkg_usage->cust_pkg_usage;
4102 my $old_cdr = $cdr_cust_pkg_usage->cdr;
4103 $reproc_cdrs{$old_cdr->acctid} = $old_cdr;
4104 $cdr_cust_pkg_usage->select_for_update;
4105 $old_cdr->select_for_update;
4106 $cust_pkg_usage->select_for_update;
4107 # in case someone else stole the usage from this CDR
4108 # while waiting for the lock...
4109 next if $old_cdr->acctid != $cdr_cust_pkg_usage->acctid;
4110 # steal the usage allocation and flag the old CDR for reprocessing
4111 $cdr_cust_pkg_usage->set('acctid', $cdr->acctid);
4112 # if the allocation is more minutes than we need, adjust it...
4113 my $delta = $cdr_cust_pkg_usage->minutes - $minutes;
4115 $cdr_cust_pkg_usage->set('minutes', $minutes);
4116 $cust_pkg_usage->set('minutes', $cust_pkg_usage->minutes + $delta);
4117 $error = $cust_pkg_usage->replace;
4119 #warn 'CDR '.$cdr->acctid . ' stealing allocation '.$cdr_cust_pkg_usage->cdrusagenum.' from CDR '.$old_cdr->acctid."\n";
4120 $error ||= $cdr_cust_pkg_usage->replace;
4121 # deduct the stolen minutes
4122 $minutes -= $cdr_cust_pkg_usage->minutes;
4124 # after all minute-stealing is done, reset the affected CDRs
4125 foreach (values %reproc_cdrs) {
4126 $error ||= $_->set_status('');
4127 # XXX or should we just call $cdr->rate right here?
4128 # it's not like we can create a loop this way, since the min_charge
4129 # or call time has to go monotonically in one direction.
4130 # we COULD get some very deep recursions going, though...
4132 } # if $order and $minutes
4135 die "error applying included minutes\npkgnum ".$self->pkgnum.", class $classnum, acctid ".$cdr->acctid."\n$error\n"
4137 $dbh->commit if $oldAutoCommit;
4138 return $orig_minutes - $minutes;
4142 =item supplemental_pkgs
4144 Returns a list of all packages supplemental to this one.
4148 sub supplemental_pkgs {
4150 qsearch('cust_pkg', { 'main_pkgnum' => $self->pkgnum });
4155 Returns the package that this one is supplemental to, if any.
4161 if ( $self->main_pkgnum ) {
4162 return FS::cust_pkg->by_key($self->main_pkgnum);
4169 =head1 CLASS METHODS
4175 Returns an SQL expression identifying recurring packages.
4179 sub recurring_sql { "
4180 '0' != ( select freq from part_pkg
4181 where cust_pkg.pkgpart = part_pkg.pkgpart )
4186 Returns an SQL expression identifying one-time packages.
4191 '0' = ( select freq from part_pkg
4192 where cust_pkg.pkgpart = part_pkg.pkgpart )
4197 Returns an SQL expression identifying ordered packages (recurring packages not
4203 $_[0]->recurring_sql. " AND ". $_[0]->not_yet_billed_sql;
4208 Returns an SQL expression identifying active packages.
4213 $_[0]->recurring_sql. "
4214 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
4215 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4216 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
4219 =item not_yet_billed_sql
4221 Returns an SQL expression identifying packages which have not yet been billed.
4225 sub not_yet_billed_sql { "
4226 ( cust_pkg.setup IS NULL OR cust_pkg.setup = 0 )
4227 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4228 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
4233 Returns an SQL expression identifying inactive packages (one-time packages
4234 that are otherwise unsuspended/uncancelled).
4238 sub inactive_sql { "
4239 ". $_[0]->onetime_sql(). "
4240 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
4241 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4242 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
4247 Returns an SQL expression identifying on-hold packages.
4252 #$_[0]->recurring_sql(). ' AND '.
4254 ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4255 AND cust_pkg.susp IS NOT NULL AND cust_pkg.susp != 0
4256 AND ( cust_pkg.setup IS NULL OR cust_pkg.setup = 0 )
4263 Returns an SQL expression identifying suspended packages.
4267 sub suspended_sql { susp_sql(@_); }
4269 #$_[0]->recurring_sql(). ' AND '.
4271 ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4272 AND cust_pkg.susp IS NOT NULL AND cust_pkg.susp != 0
4273 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
4280 Returns an SQL exprression identifying cancelled packages.
4284 sub cancelled_sql { cancel_sql(@_); }
4286 #$_[0]->recurring_sql(). ' AND '.
4287 "cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0";
4292 Returns an SQL expression to give the package status as a string.
4298 WHEN cust_pkg.cancel IS NOT NULL THEN 'cancelled'
4299 WHEN ( cust_pkg.susp IS NOT NULL AND cust_pkg.setup IS NULL ) THEN 'on hold'
4300 WHEN cust_pkg.susp IS NOT NULL THEN 'suspended'
4301 WHEN cust_pkg.setup IS NULL THEN 'not yet billed'
4302 WHEN ".onetime_sql()." THEN 'one-time charge'
4309 Returns a list of two package counts. The first is a count of packages
4310 based on the supplied criteria and the second is the count of residential
4311 packages with those same criteria. Criteria are specified as in the search
4317 my ($class, $params) = @_;
4319 my $sql_query = $class->search( $params );
4321 my $count_sql = delete($sql_query->{'count_query'});
4322 $count_sql =~ s/ FROM/,count(CASE WHEN cust_main.company IS NULL OR cust_main.company = '' THEN 1 END) FROM/
4323 or die "couldn't parse count_sql";
4325 my $count_sth = dbh->prepare($count_sql)
4326 or die "Error preparing $count_sql: ". dbh->errstr;
4328 or die "Error executing $count_sql: ". $count_sth->errstr;
4329 my $count_arrayref = $count_sth->fetchrow_arrayref;
4331 return ( @$count_arrayref );
4335 =item tax_locationnum_sql
4337 Returns an SQL expression for the tax location for a package, based
4338 on the settings of 'tax-pkg_address' and 'tax-ship_address'.
4342 sub tax_locationnum_sql {
4343 my $conf = FS::Conf->new;
4344 if ( $conf->exists('tax-pkg_address') ) {
4345 'cust_pkg.locationnum';
4347 elsif ( $conf->exists('tax-ship_address') ) {
4348 'cust_main.ship_locationnum';
4351 'cust_main.bill_locationnum';
4357 Returns a list: the first item is an SQL fragment identifying matching
4358 packages/customers via location (taking into account shipping and package
4359 address taxation, if enabled), and subsequent items are the parameters to
4360 substitute for the placeholders in that fragment.
4365 my($class, %opt) = @_;
4366 my $ornull = $opt{'ornull'};
4368 my $conf = new FS::Conf;
4370 # '?' placeholders in _location_sql_where
4371 my $x = $ornull ? 3 : 2;
4382 if ( $conf->exists('tax-ship_address') ) {
4385 ( ( ship_last IS NULL OR ship_last = '' )
4386 AND ". _location_sql_where('cust_main', '', $ornull ). "
4388 OR ( ship_last IS NOT NULL AND ship_last != ''
4389 AND ". _location_sql_where('cust_main', 'ship_', $ornull ). "
4392 # AND payby != 'COMP'
4394 @main_param = ( @bill_param, @bill_param );
4398 $main_where = _location_sql_where('cust_main'); # AND payby != 'COMP'
4399 @main_param = @bill_param;
4405 if ( $conf->exists('tax-pkg_address') ) {
4407 my $loc_where = _location_sql_where( 'cust_location', '', $ornull );
4410 ( cust_pkg.locationnum IS NULL AND $main_where )
4411 OR ( cust_pkg.locationnum IS NOT NULL AND $loc_where )
4414 @param = ( @main_param, @bill_param );
4418 $where = $main_where;
4419 @param = @main_param;
4427 #subroutine, helper for location_sql
4428 sub _location_sql_where {
4430 my $prefix = @_ ? shift : '';
4431 my $ornull = @_ ? shift : '';
4433 # $ornull = $ornull ? " OR ( ? IS NULL AND $table.${prefix}county IS NULL ) " : '';
4435 $ornull = $ornull ? ' OR ? IS NULL ' : '';
4437 my $or_empty_city = " OR ( ? = '' AND $table.${prefix}city IS NULL )";
4438 my $or_empty_county = " OR ( ? = '' AND $table.${prefix}county IS NULL )";
4439 my $or_empty_state = " OR ( ? = '' AND $table.${prefix}state IS NULL )";
4441 my $text = (driver_name =~ /^mysql/i) ? 'char' : 'text';
4443 # ( $table.${prefix}city = ? $or_empty_city $ornull )
4445 ( $table.district = ? OR ? = '' OR CAST(? AS $text) IS NULL )
4446 AND ( $table.${prefix}city = ? OR ? = '' OR CAST(? AS $text) IS NULL )
4447 AND ( $table.${prefix}county = ? $or_empty_county $ornull )
4448 AND ( $table.${prefix}state = ? $or_empty_state $ornull )
4449 AND $table.${prefix}country = ?
4454 my( $self, $what ) = @_;
4456 my $what_show_zero = $what. '_show_zero';
4457 length($self->$what_show_zero())
4458 ? ($self->$what_show_zero() eq 'Y')
4459 : $self->part_pkg->$what_show_zero();
4466 =item order CUSTNUM, PKGPARTS_ARYREF, [ REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF [ REFNUM ] ] ]
4468 CUSTNUM is a customer (see L<FS::cust_main>)
4470 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
4471 L<FS::part_pkg>) to order for this customer. Duplicates are of course
4474 REMOVE_PKGNUMS is an optional list of pkgnums specifying the billing items to
4475 remove for this customer. The services (see L<FS::cust_svc>) are moved to the
4476 new billing items. An error is returned if this is not possible (see
4477 L<FS::pkg_svc>). An empty arrayref is equivalent to not specifying this
4480 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
4481 newly-created cust_pkg objects.
4483 REFNUM, if specified, will specify the FS::pkg_referral record to be created
4484 and inserted. Multiple FS::pkg_referral records can be created by
4485 setting I<refnum> to an array reference of refnums or a hash reference with
4486 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
4487 record will be created corresponding to cust_main.refnum.
4492 my ($custnum, $pkgparts, $remove_pkgnum, $return_cust_pkg, $refnum) = @_;
4494 my $conf = new FS::Conf;
4496 # Transactionize this whole mess
4497 my $oldAutoCommit = $FS::UID::AutoCommit;
4498 local $FS::UID::AutoCommit = 0;
4502 # my $cust_main = qsearchs('cust_main', { custnum => $custnum });
4503 # return "Customer not found: $custnum" unless $cust_main;
4505 warn "$me order: pkgnums to remove: ". join(',', @$remove_pkgnum). "\n"
4508 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
4511 my $change = scalar(@old_cust_pkg) != 0;
4514 if ( scalar(@old_cust_pkg) == 1 && scalar(@$pkgparts) == 1 ) {
4516 warn "$me order: changing pkgnum ". $old_cust_pkg[0]->pkgnum.
4517 " to pkgpart ". $pkgparts->[0]. "\n"
4520 my $err_or_cust_pkg =
4521 $old_cust_pkg[0]->change( 'pkgpart' => $pkgparts->[0],
4522 'refnum' => $refnum,
4525 unless (ref($err_or_cust_pkg)) {
4526 $dbh->rollback if $oldAutoCommit;
4527 return $err_or_cust_pkg;
4530 push @$return_cust_pkg, $err_or_cust_pkg;
4531 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4536 # Create the new packages.
4537 foreach my $pkgpart (@$pkgparts) {
4539 warn "$me order: inserting pkgpart $pkgpart\n" if $DEBUG;
4541 my $cust_pkg = new FS::cust_pkg { custnum => $custnum,
4542 pkgpart => $pkgpart,
4546 $error = $cust_pkg->insert( 'change' => $change );
4547 push @$return_cust_pkg, $cust_pkg;
4549 foreach my $link ($cust_pkg->part_pkg->supp_part_pkg_link) {
4550 my $supp_pkg = FS::cust_pkg->new({
4551 custnum => $custnum,
4552 pkgpart => $link->dst_pkgpart,
4554 main_pkgnum => $cust_pkg->pkgnum,
4557 $error ||= $supp_pkg->insert( 'change' => $change );
4558 push @$return_cust_pkg, $supp_pkg;
4562 $dbh->rollback if $oldAutoCommit;
4567 # $return_cust_pkg now contains refs to all of the newly
4570 # Transfer services and cancel old packages.
4571 foreach my $old_pkg (@old_cust_pkg) {
4573 warn "$me order: transferring services from pkgnum ". $old_pkg->pkgnum. "\n"
4576 foreach my $new_pkg (@$return_cust_pkg) {
4577 $error = $old_pkg->transfer($new_pkg);
4578 if ($error and $error == 0) {
4579 # $old_pkg->transfer failed.
4580 $dbh->rollback if $oldAutoCommit;
4585 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
4586 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
4587 foreach my $new_pkg (@$return_cust_pkg) {
4588 $error = $old_pkg->transfer($new_pkg, 'change_svcpart'=>1 );
4589 if ($error and $error == 0) {
4590 # $old_pkg->transfer failed.
4591 $dbh->rollback if $oldAutoCommit;
4598 # Transfers were successful, but we went through all of the
4599 # new packages and still had services left on the old package.
4600 # We can't cancel the package under the circumstances, so abort.
4601 $dbh->rollback if $oldAutoCommit;
4602 return "Unable to transfer all services from package ".$old_pkg->pkgnum;
4604 $error = $old_pkg->cancel( quiet=>1 );
4610 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4614 =item bulk_change PKGPARTS_ARYREF, REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF ]
4616 A bulk change method to change packages for multiple customers.
4618 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
4619 L<FS::part_pkg>) to order for each customer. Duplicates are of course
4622 REMOVE_PKGNUMS is an list of pkgnums specifying the billing items to
4623 replace. The services (see L<FS::cust_svc>) are moved to the
4624 new billing items. An error is returned if this is not possible (see
4627 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
4628 newly-created cust_pkg objects.
4633 my ($pkgparts, $remove_pkgnum, $return_cust_pkg) = @_;
4635 # Transactionize this whole mess
4636 my $oldAutoCommit = $FS::UID::AutoCommit;
4637 local $FS::UID::AutoCommit = 0;
4641 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
4644 while(scalar(@old_cust_pkg)) {
4646 my $custnum = $old_cust_pkg[0]->custnum;
4647 my (@remove) = map { $_->pkgnum }
4648 grep { $_->custnum == $custnum } @old_cust_pkg;
4649 @old_cust_pkg = grep { $_->custnum != $custnum } @old_cust_pkg;
4651 my $error = order $custnum, $pkgparts, \@remove, \@return;
4653 push @errors, $error
4655 push @$return_cust_pkg, @return;
4658 if (scalar(@errors)) {
4659 $dbh->rollback if $oldAutoCommit;
4660 return join(' / ', @errors);
4663 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4667 # Used by FS::Upgrade to migrate to a new database.
4668 sub _upgrade_data { # class method
4669 my ($class, %opts) = @_;
4670 $class->_upgrade_otaker(%opts);
4672 # RT#10139, bug resulting in contract_end being set when it shouldn't
4673 'UPDATE cust_pkg SET contract_end = NULL WHERE contract_end = -1',
4674 # RT#10830, bad calculation of prorate date near end of year
4675 # the date range for bill is December 2009, and we move it forward
4676 # one year if it's before the previous bill date (which it should
4678 'UPDATE cust_pkg SET bill = bill + (365*24*60*60) WHERE bill < last_bill
4679 AND bill > 1259654400 AND bill < 1262332800 AND (SELECT plan FROM part_pkg
4680 WHERE part_pkg.pkgpart = cust_pkg.pkgpart) = \'prorate\'',
4681 # RT6628, add order_date to cust_pkg
4682 'update cust_pkg set order_date = (select history_date from h_cust_pkg
4683 where h_cust_pkg.pkgnum = cust_pkg.pkgnum and
4684 history_action = \'insert\') where order_date is null',
4686 foreach my $sql (@statements) {
4687 my $sth = dbh->prepare($sql);
4688 $sth->execute or die $sth->errstr;
4696 sub order is not OO. Perhaps it should be moved to FS::cust_main and made so?
4698 In sub order, the @pkgparts array (passed by reference) is clobbered.
4700 Also in sub order, no money is adjusted. Once FS::part_pkg defines a standard
4701 method to pass dates to the recur_prog expression, it should do so.
4703 FS::svc_acct, FS::svc_domain, FS::svc_www, FS::svc_ip and FS::svc_forward are
4704 loaded via 'use' at compile time, rather than via 'require' in sub { setup,
4705 suspend, unsuspend, cancel } because they use %FS::UID::callback to load
4706 configuration values. Probably need a subroutine which decides what to do
4707 based on whether or not we've fetched the user yet, rather than a hash. See
4708 FS::UID and the TODO.
4710 Now that things are transactional should the check in the insert method be
4715 L<FS::Record>, L<FS::cust_main>, L<FS::part_pkg>, L<FS::cust_svc>,
4716 L<FS::pkg_svc>, schema.html from the base documentation