2 use base qw( FS::otaker_Mixin FS::cust_main_Mixin FS::Sales_Mixin
3 FS::contact_Mixin FS::location_Mixin
4 FS::m2m_Common FS::option_Common );
7 use vars qw( $disable_agentcheck $DEBUG $me $upgrade );
9 use Scalar::Util qw( blessed );
10 use List::Util qw(min max);
12 use Time::Local qw( timelocal timelocal_nocheck );
14 use FS::UID qw( getotaker dbh driver_name );
15 use FS::Misc qw( send_email );
16 use FS::Record qw( qsearch qsearchs fields );
22 use FS::cust_location;
24 use FS::cust_bill_pkg;
25 use FS::cust_pkg_detail;
26 use FS::cust_pkg_usage;
27 use FS::cdr_cust_pkg_usage;
32 use FS::cust_pkg_reason;
34 use FS::cust_pkg_discount;
41 # need to 'use' these instead of 'require' in sub { cancel, suspend, unsuspend,
43 # because they load configuration by setting FS::UID::callback (see TODO)
49 # for sending cancel emails in sub cancel
53 $me = '[FS::cust_pkg]';
55 $disable_agentcheck = 0;
57 $upgrade = 0; #go away after setup+start dates cleaned up for old customers
60 my( $self, $hashref ) = @_;
61 if ( $hashref->{'pkg'} ) {
62 $self->{'_pkgpart'} = FS::part_pkg->new($hashref);
68 my ( $hashref, $cache ) = @_;
69 # #if ( $hashref->{'pkgpart'} ) {
70 # if ( $hashref->{'pkg'} ) {
71 # # #@{ $self->{'_pkgnum'} } = ();
72 # # my $subcache = $cache->subcache('pkgpart', 'part_pkg');
73 # # $self->{'_pkgpart'} = $subcache;
74 # # #push @{ $self->{'_pkgnum'} },
75 # # FS::part_pkg->new_or_cached($hashref, $subcache);
76 # $self->{'_pkgpart'} = FS::part_pkg->new($hashref);
78 if ( exists $hashref->{'svcnum'} ) {
79 #@{ $self->{'_pkgnum'} } = ();
80 my $subcache = $cache->subcache('svcnum', 'cust_svc', $hashref->{pkgnum});
81 $self->{'_svcnum'} = $subcache;
82 #push @{ $self->{'_pkgnum'} },
83 FS::cust_svc->new_or_cached($hashref, $subcache) if $hashref->{svcnum};
89 FS::cust_pkg - Object methods for cust_pkg objects
95 $record = new FS::cust_pkg \%hash;
96 $record = new FS::cust_pkg { 'column' => 'value' };
98 $error = $record->insert;
100 $error = $new_record->replace($old_record);
102 $error = $record->delete;
104 $error = $record->check;
106 $error = $record->cancel;
108 $error = $record->suspend;
110 $error = $record->unsuspend;
112 $part_pkg = $record->part_pkg;
114 @labels = $record->labels;
116 $seconds = $record->seconds_since($timestamp);
118 #bulk cancel+order... perhaps slightly deprecated, only used by the bulk
119 # cancel+order in the web UI and nowhere else (edit/process/cust_pkg.cgi)
120 $error = FS::cust_pkg::order( $custnum, \@pkgparts );
121 $error = FS::cust_pkg::order( $custnum, \@pkgparts, \@remove_pkgnums ] );
125 An FS::cust_pkg object represents a customer billing item. FS::cust_pkg
126 inherits from FS::Record. The following fields are currently supported:
132 Primary key (assigned automatically for new billing items)
136 Customer (see L<FS::cust_main>)
140 Billing item definition (see L<FS::part_pkg>)
144 Optional link to package location (see L<FS::location>)
148 date package was ordered (also remains same on changes)
160 date (next bill date)
188 order taker (see L<FS::access_user>)
192 If this field is set to 1, disables the automatic
193 unsuspension of this package when using the B<unsuspendauto> config option.
197 If not set, defaults to 1
201 Date of change from previous package
211 =item change_locationnum
219 The pkgnum of the package that this package is supplemental to, if any.
223 The package link (L<FS::part_pkg_link>) that defines this supplemental
224 package, if it is one.
226 =item change_to_pkgnum
228 The pkgnum of the package this one will be "changed to" in the future
229 (on its expiration date).
233 Note: setup, last_bill, bill, adjourn, susp, expire, cancel and change_date
234 are specified as UNIX timestamps; see L<perlfunc/"time">. Also see
235 L<Time::Local> and L<Date::Parse> for conversion functions.
243 Create a new billing item. To add the item to the database, see L<"insert">.
247 sub table { 'cust_pkg'; }
248 sub cust_linked { $_[0]->cust_main_custnum || $_[0]->custnum }
249 sub cust_unlinked_msg {
251 "WARNING: can't find cust_main.custnum ". $self->custnum.
252 ' (cust_pkg.pkgnum '. $self->pkgnum. ')';
255 =item set_initial_timers
257 If required by the package definition, sets any automatic expire, adjourn,
258 or contract_end timers to some number of months after the start date
259 (or setup date, if the package has already been setup). If the package has
260 a delayed setup fee after a period of "free days", will also set the
261 start date to the end of that period.
265 sub set_initial_timers {
267 my $part_pkg = $self->part_pkg;
268 foreach my $action ( qw(expire adjourn contract_end) ) {
269 my $months = $part_pkg->option("${action}_months",1);
270 if($months and !$self->get($action)) {
271 my $start = $self->start_date || $self->setup || time;
272 $self->set($action, $part_pkg->add_freq($start, $months) );
276 # if this package has "free days" and delayed setup fee, then
277 # set start date that many days in the future.
278 # (this should have been set in the UI, but enforce it here)
279 if ( $part_pkg->option('free_days',1)
280 && $part_pkg->option('delay_setup',1)
283 $self->start_date( $part_pkg->default_start_date );
288 =item insert [ OPTION => VALUE ... ]
290 Adds this billing item to the database ("Orders" the item). If there is an
291 error, returns the error, otherwise returns false.
293 If the additional field I<promo_code> is defined instead of I<pkgpart>, it
294 will be used to look up the package definition and agent restrictions will be
297 If the additional field I<refnum> is defined, an FS::pkg_referral record will
298 be created and inserted. Multiple FS::pkg_referral records can be created by
299 setting I<refnum> to an array reference of refnums or a hash reference with
300 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
301 record will be created corresponding to cust_main.refnum.
303 The following options are available:
309 If set true, supresses actions that should only be taken for new package
310 orders. (Currently this includes: intro periods when delay_setup is on,
311 auto-adding a 1st start date, auto-adding expiration/adjourn/contract_end dates)
315 cust_pkg_option records will be created
319 a ticket will be added to this customer with this subject
323 an optional queue name for ticket additions
327 Don't check the legality of the package definition. This should be used
328 when performing a package change that doesn't change the pkgpart (i.e.
336 my( $self, %options ) = @_;
339 $error = $self->check_pkgpart unless $options{'allow_pkgpart'};
340 return $error if $error;
342 my $part_pkg = $self->part_pkg;
344 if ( ! $options{'change'} ) {
346 # set order date to now
347 $self->order_date(time);
349 # if the package def says to start only on the first of the month:
350 if ( $part_pkg->option('start_1st', 1) && !$self->start_date ) {
351 my ($sec,$min,$hour,$mday,$mon,$year) = (localtime(time) )[0,1,2,3,4,5];
352 $mon += 1 unless $mday == 1;
353 until ( $mon < 12 ) { $mon -= 12; $year++; }
354 $self->start_date( timelocal_nocheck(0,0,0,1,$mon,$year) );
357 if ($self->susp eq 'now' or $part_pkg->start_on_hold) {
358 # if the package was ordered on hold:
360 # - don't set the start date (it will be started manually)
361 $self->set('susp', $self->order_date);
362 $self->set('start_date', '');
364 # set expire/adjourn/contract_end timers, and free days, if appropriate
365 $self->set_initial_timers;
367 } # else this is a package change, and shouldn't have "new package" behavior
369 local $SIG{HUP} = 'IGNORE';
370 local $SIG{INT} = 'IGNORE';
371 local $SIG{QUIT} = 'IGNORE';
372 local $SIG{TERM} = 'IGNORE';
373 local $SIG{TSTP} = 'IGNORE';
374 local $SIG{PIPE} = 'IGNORE';
376 my $oldAutoCommit = $FS::UID::AutoCommit;
377 local $FS::UID::AutoCommit = 0;
380 $error = $self->SUPER::insert($options{options} ? %{$options{options}} : ());
382 $dbh->rollback if $oldAutoCommit;
386 $self->refnum($self->cust_main->refnum) unless $self->refnum;
387 $self->refnum( [ $self->refnum ] ) unless ref($self->refnum);
388 $self->process_m2m( 'link_table' => 'pkg_referral',
389 'target_table' => 'part_referral',
390 'params' => $self->refnum,
393 if ( $self->discountnum ) {
394 my $error = $self->insert_discount();
396 $dbh->rollback if $oldAutoCommit;
401 my $conf = new FS::Conf;
403 if ( $conf->config('ticket_system') && $options{ticket_subject} ) {
405 #this init stuff is still inefficient, but at least its limited to
406 # the small number (any?) folks using ticket emailing on pkg order
409 # use lib ( "/opt/rt3/local/lib", "/opt/rt3/lib" );
416 use FS::TicketSystem;
417 FS::TicketSystem->init();
419 my $q = new RT::Queue($RT::SystemUser);
420 $q->Load($options{ticket_queue}) if $options{ticket_queue};
421 my $t = new RT::Ticket($RT::SystemUser);
422 my $mime = new MIME::Entity;
423 $mime->build( Type => 'text/plain', Data => $options{ticket_subject} );
424 $t->Create( $options{ticket_queue} ? (Queue => $q) : (),
425 Subject => $options{ticket_subject},
428 $t->AddLink( Type => 'MemberOf',
429 Target => 'freeside://freeside/cust_main/'. $self->custnum,
433 if ($conf->config('welcome_letter') && $self->cust_main->num_pkgs == 1) {
434 my $queue = new FS::queue {
435 'job' => 'FS::cust_main::queueable_print',
437 $error = $queue->insert(
438 'custnum' => $self->custnum,
439 'template' => 'welcome_letter',
443 warn "can't send welcome letter: $error";
448 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
455 This method now works but you probably shouldn't use it.
457 You don't want to delete packages, because there would then be no record
458 the customer ever purchased the package. Instead, see the cancel method and
459 hide cancelled packages.
466 local $SIG{HUP} = 'IGNORE';
467 local $SIG{INT} = 'IGNORE';
468 local $SIG{QUIT} = 'IGNORE';
469 local $SIG{TERM} = 'IGNORE';
470 local $SIG{TSTP} = 'IGNORE';
471 local $SIG{PIPE} = 'IGNORE';
473 my $oldAutoCommit = $FS::UID::AutoCommit;
474 local $FS::UID::AutoCommit = 0;
477 foreach my $cust_pkg_discount ($self->cust_pkg_discount) {
478 my $error = $cust_pkg_discount->delete;
480 $dbh->rollback if $oldAutoCommit;
484 #cust_bill_pkg_discount?
486 foreach my $cust_pkg_detail ($self->cust_pkg_detail) {
487 my $error = $cust_pkg_detail->delete;
489 $dbh->rollback if $oldAutoCommit;
494 foreach my $cust_pkg_reason (
496 'table' => 'cust_pkg_reason',
497 'hashref' => { 'pkgnum' => $self->pkgnum },
501 my $error = $cust_pkg_reason->delete;
503 $dbh->rollback if $oldAutoCommit;
510 my $error = $self->SUPER::delete(@_);
512 $dbh->rollback if $oldAutoCommit;
516 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
522 =item replace [ OLD_RECORD ] [ HASHREF | OPTION => VALUE ... ]
524 Replaces the OLD_RECORD with this one in the database. If there is an error,
525 returns the error, otherwise returns false.
527 Currently, custnum, setup, bill, adjourn, susp, expire, and cancel may be changed.
529 Changing pkgpart may have disasterous effects. See the order subroutine.
531 setup and bill are normally updated by calling the bill method of a customer
532 object (see L<FS::cust_main>).
534 suspend is normally updated by the suspend and unsuspend methods.
536 cancel is normally updated by the cancel method (and also the order subroutine
539 Available options are:
545 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.
549 the access_user (see L<FS::access_user>) providing the reason
553 hashref of keys and values - cust_pkg_option records will be created, updated or removed as appopriate
562 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
567 ( ref($_[0]) eq 'HASH' )
571 #return "Can't (yet?) change pkgpart!" if $old->pkgpart != $new->pkgpart;
572 #return "Can't change otaker!" if $old->otaker ne $new->otaker;
575 #return "Can't change setup once it exists!"
576 # if $old->getfield('setup') &&
577 # $old->getfield('setup') != $new->getfield('setup');
579 #some logic for bill, susp, cancel?
581 local($disable_agentcheck) = 1 if $old->pkgpart == $new->pkgpart;
583 local $SIG{HUP} = 'IGNORE';
584 local $SIG{INT} = 'IGNORE';
585 local $SIG{QUIT} = 'IGNORE';
586 local $SIG{TERM} = 'IGNORE';
587 local $SIG{TSTP} = 'IGNORE';
588 local $SIG{PIPE} = 'IGNORE';
590 my $oldAutoCommit = $FS::UID::AutoCommit;
591 local $FS::UID::AutoCommit = 0;
594 foreach my $method ( qw(adjourn expire) ) { # How many reasons?
595 if ($options->{'reason'} && $new->$method && $old->$method ne $new->$method) {
596 my $error = $new->insert_reason(
597 'reason' => $options->{'reason'},
598 'date' => $new->$method,
600 'reason_otaker' => $options->{'reason_otaker'},
603 dbh->rollback if $oldAutoCommit;
604 return "Error inserting cust_pkg_reason: $error";
609 #save off and freeze RADIUS attributes for any associated svc_acct records
611 if ( $old->part_pkg->is_prepaid || $new->part_pkg->is_prepaid ) {
613 #also check for specific exports?
614 # to avoid spurious modify export events
615 @svc_acct = map { $_->svc_x }
616 grep { $_->part_svc->svcdb eq 'svc_acct' }
619 $_->snapshot foreach @svc_acct;
623 my $error = $new->export_pkg_change($old)
624 || $new->SUPER::replace( $old,
626 ? $options->{options}
630 $dbh->rollback if $oldAutoCommit;
634 #for prepaid packages,
635 #trigger export of new RADIUS Expiration attribute when cust_pkg.bill changes
636 foreach my $old_svc_acct ( @svc_acct ) {
637 my $new_svc_acct = new FS::svc_acct { $old_svc_acct->hash };
639 $new_svc_acct->replace( $old_svc_acct,
640 'depend_jobnum' => $options->{depend_jobnum},
643 $dbh->rollback if $oldAutoCommit;
648 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
655 Checks all fields to make sure this is a valid billing item. If there is an
656 error, returns the error, otherwise returns false. Called by the insert and
664 if ( !$self->locationnum or $self->locationnum == -1 ) {
665 $self->set('locationnum', $self->cust_main->ship_locationnum);
669 $self->ut_numbern('pkgnum')
670 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum')
671 || $self->ut_numbern('pkgpart')
672 || $self->ut_foreign_keyn('contactnum', 'contact', 'contactnum' )
673 || $self->ut_foreign_keyn('locationnum', 'cust_location', 'locationnum')
674 || $self->ut_foreign_keyn('salesnum', 'sales', 'salesnum')
675 || $self->ut_numbern('quantity')
676 || $self->ut_numbern('start_date')
677 || $self->ut_numbern('setup')
678 || $self->ut_numbern('bill')
679 || $self->ut_numbern('susp')
680 || $self->ut_numbern('cancel')
681 || $self->ut_numbern('adjourn')
682 || $self->ut_numbern('resume')
683 || $self->ut_numbern('expire')
684 || $self->ut_numbern('dundate')
685 || $self->ut_flag('no_auto', [ '', 'Y' ])
686 || $self->ut_flag('waive_setup', [ '', 'Y' ])
687 || $self->ut_flag('separate_bill')
688 || $self->ut_textn('agent_pkgid')
689 || $self->ut_enum('recur_show_zero', [ '', 'Y', 'N', ])
690 || $self->ut_enum('setup_show_zero', [ '', 'Y', 'N', ])
691 || $self->ut_foreign_keyn('main_pkgnum', 'cust_pkg', 'pkgnum')
692 || $self->ut_foreign_keyn('pkglinknum', 'part_pkg_link', 'pkglinknum')
693 || $self->ut_foreign_keyn('change_to_pkgnum', 'cust_pkg', 'pkgnum')
695 return $error if $error;
697 return "A package with both start date (future start) and setup date (already started) will never bill"
698 if $self->start_date && $self->setup && ! $upgrade;
700 return "A future unsuspend date can only be set for a package with a suspend date"
701 if $self->resume and !$self->susp and !$self->adjourn;
703 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
705 if ( $self->dbdef_table->column('manual_flag') ) {
706 $self->manual_flag('') if $self->manual_flag eq ' ';
707 $self->manual_flag =~ /^([01]?)$/
708 or return "Illegal manual_flag ". $self->manual_flag;
709 $self->manual_flag($1);
717 Check the pkgpart to make sure it's allowed with the reg_code and/or
718 promo_code of the package (if present) and with the customer's agent.
719 Called from C<insert>, unless we are doing a package change that doesn't
727 # my $error = $self->ut_numbern('pkgpart'); # already done
730 if ( $self->reg_code ) {
732 unless ( grep { $self->pkgpart == $_->pkgpart }
733 map { $_->reg_code_pkg }
734 qsearchs( 'reg_code', { 'code' => $self->reg_code,
735 'agentnum' => $self->cust_main->agentnum })
737 return "Unknown registration code";
740 } elsif ( $self->promo_code ) {
743 qsearchs('part_pkg', {
744 'pkgpart' => $self->pkgpart,
745 'promo_code' => { op=>'ILIKE', value=>$self->promo_code },
747 return 'Unknown promotional code' unless $promo_part_pkg;
751 unless ( $disable_agentcheck ) {
753 qsearchs( 'agent', { 'agentnum' => $self->cust_main->agentnum } );
754 return "agent ". $agent->agentnum. ':'. $agent->agent.
755 " can't purchase pkgpart ". $self->pkgpart
756 unless $agent->pkgpart_hashref->{ $self->pkgpart }
757 || $agent->agentnum == $self->part_pkg->agentnum;
760 $error = $self->ut_foreign_key('pkgpart', 'part_pkg', 'pkgpart' );
761 return $error if $error;
769 =item cancel [ OPTION => VALUE ... ]
771 Cancels and removes all services (see L<FS::cust_svc> and L<FS::part_svc>)
772 in this package, then cancels the package itself (sets the cancel field to
775 Available options are:
779 =item quiet - can be set true to supress email cancellation notices.
781 =item time - can be set to cancel the package based on a specific future or
782 historical date. Using time ensures that the remaining amount is calculated
783 correctly. Note however that this is an immediate cancel and just changes
784 the date. You are PROBABLY looking to expire the account instead of using
787 =item reason - can be set to a cancellation reason (see L<FS:reason>),
788 either a reasonnum of an existing reason, or passing a hashref will create
789 a new reason. The hashref should have the following keys: typenum - Reason
790 type (see L<FS::reason_type>, reason - Text of the new reason.
792 =item date - can be set to a unix style timestamp to specify when to
795 =item nobill - can be set true to skip billing if it might otherwise be done.
797 =item unused_credit - can be set to 1 to credit the remaining time, or 0 to
798 not credit it. This must be set (by change()) when changing the package
799 to a different pkgpart or location, and probably shouldn't be in any other
800 case. If it's not set, the 'unused_credit_cancel' part_pkg option will
803 =item no_delay_cancel - prevents delay_cancel behavior
804 no matter what other options say, for use when changing packages (or any
805 other time you're really sure you want an immediate cancel)
809 If there is an error, returns the error, otherwise returns false.
813 #NOT DOCUMENTING - this should only be used when calling recursively
814 #=item delay_cancel - for internal use, to allow proper handling of
815 #supplemental packages when the main package is flagged to suspend
816 #before cancelling, probably shouldn't be used otherwise (set the
817 #corresponding package option instead)
820 my( $self, %options ) = @_;
823 # pass all suspend/cancel actions to the main package
824 # (unless the pkglinknum has been removed, then the link is defunct and
825 # this package can be canceled on its own)
826 if ( $self->main_pkgnum and $self->pkglinknum and !$options{'from_main'} ) {
827 return $self->main_pkg->cancel(%options);
830 my $conf = new FS::Conf;
832 warn "cust_pkg::cancel called with options".
833 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
836 local $SIG{HUP} = 'IGNORE';
837 local $SIG{INT} = 'IGNORE';
838 local $SIG{QUIT} = 'IGNORE';
839 local $SIG{TERM} = 'IGNORE';
840 local $SIG{TSTP} = 'IGNORE';
841 local $SIG{PIPE} = 'IGNORE';
843 my $oldAutoCommit = $FS::UID::AutoCommit;
844 local $FS::UID::AutoCommit = 0;
847 my $old = $self->select_for_update;
849 if ( $old->get('cancel') || $self->get('cancel') ) {
850 dbh->rollback if $oldAutoCommit;
851 return ""; # no error
854 # XXX possibly set cancel_time to the expire date?
855 my $cancel_time = $options{'time'} || time;
856 my $date = $options{'date'} if $options{'date'}; # expire/cancel later
857 $date = '' if ($date && $date <= $cancel_time); # complain instead?
859 my $delay_cancel = $options{'no_delay_cancel'} ? 0 : $options{'delay_cancel'};
860 if ( !$date && $self->part_pkg->option('delay_cancel',1)
861 && (($self->status eq 'active') || ($self->status eq 'suspended'))
862 && !$options{'no_delay_cancel'}
864 my $expdays = $conf->config('part_pkg-delay_cancel-days') || 1;
865 my $expsecs = 60*60*24*$expdays;
866 my $suspfor = $self->susp ? $cancel_time - $self->susp : 0;
867 $expsecs = $expsecs - $suspfor if $suspfor;
868 unless ($expsecs <= 0) { #if it's already been suspended long enough, don't re-suspend
870 $date = $cancel_time + $expsecs;
874 #race condition: usage could be ongoing until unprovisioned
875 #resolved by performing a change package instead (which unprovisions) and
877 if ( !$options{nobill} && !$date ) {
878 # && $conf->exists('bill_usage_on_cancel') ) { #calc_cancel checks this
879 my $copy = $self->new({$self->hash});
881 $copy->cust_main->bill( 'pkg_list' => [ $copy ],
883 'time' => $cancel_time );
884 warn "Error billing during cancel, custnum ".
885 #$self->cust_main->custnum. ": $error"
890 if ( $options{'reason'} ) {
891 $error = $self->insert_reason( 'reason' => $options{'reason'},
892 'action' => $date ? 'expire' : 'cancel',
893 'date' => $date ? $date : $cancel_time,
894 'reason_otaker' => $options{'reason_otaker'},
897 dbh->rollback if $oldAutoCommit;
898 return "Error inserting cust_pkg_reason: $error";
902 my %svc_cancel_opt = ();
903 $svc_cancel_opt{'date'} = $date if $date;
904 foreach my $cust_svc (
907 sort { $a->[1] <=> $b->[1] }
908 map { [ $_, $_->svc_x ? $_->svc_x->table_info->{'cancel_weight'} : -1 ]; }
909 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
911 my $part_svc = $cust_svc->part_svc;
912 next if ( defined($part_svc) and $part_svc->preserve );
913 my $error = $cust_svc->cancel( %svc_cancel_opt );
916 $dbh->rollback if $oldAutoCommit;
917 return 'Error '. ($svc_cancel_opt{'date'} ? 'expiring' : 'canceling' ).
923 # credit remaining time if appropriate
925 if ( exists($options{'unused_credit'}) ) {
926 $do_credit = $options{'unused_credit'};
929 $do_credit = $self->part_pkg->option('unused_credit_cancel', 1);
932 my $error = $self->credit_remaining('cancel', $cancel_time);
934 $dbh->rollback if $oldAutoCommit;
940 my %hash = $self->hash;
942 $hash{'expire'} = $date;
944 # just to be sure these are clear
945 $hash{'adjourn'} = undef;
946 $hash{'resume'} = undef;
949 $hash{'cancel'} = $cancel_time;
951 $hash{'change_custnum'} = $options{'change_custnum'};
953 # if this is a supplemental package that's lost its part_pkg_link, and it's
954 # being canceled for real, unlink it completely
955 if ( !$date and ! $self->pkglinknum ) {
956 $hash{main_pkgnum} = '';
959 my $new = new FS::cust_pkg ( \%hash );
960 $error = $new->replace( $self, options => { $self->options } );
961 if ( $self->change_to_pkgnum ) {
962 my $change_to = FS::cust_pkg->by_key($self->change_to_pkgnum);
963 $error ||= $change_to->cancel('no_delay_cancel' => 1) || $change_to->delete;
966 $dbh->rollback if $oldAutoCommit;
970 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
971 $error = $supp_pkg->cancel(%options,
973 'date' => $date, #in case it got changed by delay_cancel
974 'delay_cancel' => $delay_cancel,
977 $dbh->rollback if $oldAutoCommit;
978 return "canceling supplemental pkg#".$supp_pkg->pkgnum.": $error";
982 if ($delay_cancel && !$options{'from_main'}) {
983 $error = $new->suspend(
985 'time' => $cancel_time
990 foreach my $usage ( $self->cust_pkg_usage ) {
991 $error = $usage->delete;
993 $dbh->rollback if $oldAutoCommit;
994 return "deleting usage pools: $error";
999 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1000 return '' if $date; #no errors
1002 my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ } $self->cust_main->invoicing_list;
1003 if ( !$options{'quiet'} &&
1004 $conf->exists('emailcancel', $self->cust_main->agentnum) &&
1006 my $msgnum = $conf->config('cancel_msgnum', $self->cust_main->agentnum);
1009 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum });
1010 $error = $msg_template->send( 'cust_main' => $self->cust_main,
1011 'object' => $self );
1014 $error = send_email(
1015 'from' => $conf->invoice_from_full( $self->cust_main->agentnum ),
1016 'to' => \@invoicing_list,
1017 'subject' => ( $conf->config('cancelsubject') || 'Cancellation Notice' ),
1018 'body' => [ map "$_\n", $conf->config('cancelmessage') ],
1019 'custnum' => $self->custnum,
1020 'msgtype' => '', #admin?
1023 #should this do something on errors?
1030 =item cancel_if_expired [ NOW_TIMESTAMP ]
1032 Cancels this package if its expire date has been reached.
1036 sub cancel_if_expired {
1038 my $time = shift || time;
1039 return '' unless $self->expire && $self->expire <= $time;
1040 my $error = $self->cancel;
1042 return "Error cancelling expired pkg ". $self->pkgnum. " for custnum ".
1043 $self->custnum. ": $error";
1050 "Un-cancels" this package: Orders a new package with the same custnum, pkgpart,
1051 locationnum, (other fields?). Attempts to re-provision cancelled services
1052 using history information (errors at this stage are not fatal).
1054 cust_pkg: pass a scalar reference, will be filled in with the new cust_pkg object
1056 svc_fatal: service provisioning errors are fatal
1058 svc_errors: pass an array reference, will be filled in with any provisioning errors
1060 main_pkgnum: link the package as a supplemental package of this one. For
1066 my( $self, %options ) = @_;
1068 #in case you try do do $uncancel-date = $cust_pkg->uncacel
1069 return '' unless $self->get('cancel');
1071 if ( $self->main_pkgnum and !$options{'main_pkgnum'} ) {
1072 return $self->main_pkg->uncancel(%options);
1079 local $SIG{HUP} = 'IGNORE';
1080 local $SIG{INT} = 'IGNORE';
1081 local $SIG{QUIT} = 'IGNORE';
1082 local $SIG{TERM} = 'IGNORE';
1083 local $SIG{TSTP} = 'IGNORE';
1084 local $SIG{PIPE} = 'IGNORE';
1086 my $oldAutoCommit = $FS::UID::AutoCommit;
1087 local $FS::UID::AutoCommit = 0;
1091 # insert the new package
1094 my $cust_pkg = new FS::cust_pkg {
1095 last_bill => ( $options{'last_bill'} || $self->get('last_bill') ),
1096 bill => ( $options{'bill'} || $self->get('bill') ),
1098 uncancel_pkgnum => $self->pkgnum,
1099 main_pkgnum => ($options{'main_pkgnum'} || ''),
1100 map { $_ => $self->get($_) } qw(
1101 custnum pkgpart locationnum
1103 susp adjourn resume expire start_date contract_end dundate
1104 change_date change_pkgpart change_locationnum
1105 manual_flag no_auto separate_bill quantity agent_pkgid
1106 recur_show_zero setup_show_zero
1110 my $error = $cust_pkg->insert(
1111 'change' => 1, #supresses any referral credit to a referring customer
1112 'allow_pkgpart' => 1, # allow this even if the package def is disabled
1115 $dbh->rollback if $oldAutoCommit;
1123 #find historical services within this timeframe before the package cancel
1124 # (incompatible with "time" option to cust_pkg->cancel?)
1125 my $fuzz = 2 * 60; #2 minutes? too much? (might catch separate unprovision)
1126 # too little? (unprovisioing export delay?)
1127 my($end, $start) = ( $self->get('cancel'), $self->get('cancel') - $fuzz );
1128 my @h_cust_svc = $self->h_cust_svc( $end, $start );
1131 foreach my $h_cust_svc (@h_cust_svc) {
1132 my $h_svc_x = $h_cust_svc->h_svc_x( $end, $start );
1133 #next unless $h_svc_x; #should this happen?
1134 (my $table = $h_svc_x->table) =~ s/^h_//;
1135 require "FS/$table.pm";
1136 my $class = "FS::$table";
1137 my $svc_x = $class->new( {
1138 'pkgnum' => $cust_pkg->pkgnum,
1139 'svcpart' => $h_cust_svc->svcpart,
1140 map { $_ => $h_svc_x->get($_) } fields($table)
1144 if ( $h_svc_x->isa('FS::h_svc_Radius_Mixin') ) {
1145 $svc_x->usergroup( [ $h_svc_x->h_usergroup($end, $start) ] );
1148 my $svc_error = $svc_x->insert;
1150 if ( $options{svc_fatal} ) {
1151 $dbh->rollback if $oldAutoCommit;
1154 # if we've failed to insert the svc_x object, svc_Common->insert
1155 # will have removed the cust_svc already. if not, then both records
1156 # were inserted but we failed for some other reason (export, most
1157 # likely). in that case, report the error and delete the records.
1158 push @svc_errors, $svc_error;
1159 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svc_x->svcnum });
1161 # except if export_insert failed, export_delete probably won't be
1163 local $FS::svc_Common::noexport_hack = 1;
1164 my $cleanup_error = $svc_x->delete; # also deletes cust_svc
1165 if ( $cleanup_error ) { # and if THAT fails, then run away
1166 $dbh->rollback if $oldAutoCommit;
1167 return $cleanup_error;
1172 } #foreach $h_cust_svc
1174 #these are pretty rare, but should handle them
1175 # - dsl_device (mac addresses)
1176 # - phone_device (mac addresses)
1177 # - dsl_note (ikano notes)
1178 # - domain_record (i.e. restore DNS information w/domains)
1179 # - inventory_item(?) (inventory w/un-cancelling service?)
1180 # - nas (svc_broaband nas stuff)
1181 #this stuff is unused in the wild afaik
1182 # - mailinglistmember
1184 # - svc_domain.parent_svcnum?
1185 # - acct_snarf (ancient mail fetching config)
1186 # - cgp_rule (communigate)
1187 # - cust_svc_option (used by our Tron stuff)
1188 # - acct_rt_transaction (used by our time worked stuff)
1191 # also move over any services that didn't unprovision at cancellation
1194 foreach my $cust_svc ( qsearch('cust_svc', { pkgnum => $self->pkgnum } ) ) {
1195 $cust_svc->pkgnum( $cust_pkg->pkgnum );
1196 my $error = $cust_svc->replace;
1198 $dbh->rollback if $oldAutoCommit;
1204 # Uncancel any supplemental packages, and make them supplemental to the
1208 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1210 $error = $supp_pkg->uncancel(%options, 'main_pkgnum' => $cust_pkg->pkgnum);
1212 $dbh->rollback if $oldAutoCommit;
1213 return "canceling supplemental pkg#".$supp_pkg->pkgnum.": $error";
1221 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1223 ${ $options{cust_pkg} } = $cust_pkg if ref($options{cust_pkg});
1224 @{ $options{svc_errors} } = @svc_errors if ref($options{svc_errors});
1231 Cancels any pending expiration (sets the expire field to null).
1233 If there is an error, returns the error, otherwise returns false.
1238 my( $self, %options ) = @_;
1241 local $SIG{HUP} = 'IGNORE';
1242 local $SIG{INT} = 'IGNORE';
1243 local $SIG{QUIT} = 'IGNORE';
1244 local $SIG{TERM} = 'IGNORE';
1245 local $SIG{TSTP} = 'IGNORE';
1246 local $SIG{PIPE} = 'IGNORE';
1248 my $oldAutoCommit = $FS::UID::AutoCommit;
1249 local $FS::UID::AutoCommit = 0;
1252 my $old = $self->select_for_update;
1254 my $pkgnum = $old->pkgnum;
1255 if ( $old->get('cancel') || $self->get('cancel') ) {
1256 dbh->rollback if $oldAutoCommit;
1257 return "Can't unexpire cancelled package $pkgnum";
1258 # or at least it's pointless
1261 unless ( $old->get('expire') && $self->get('expire') ) {
1262 dbh->rollback if $oldAutoCommit;
1263 return ""; # no error
1266 my %hash = $self->hash;
1267 $hash{'expire'} = '';
1268 my $new = new FS::cust_pkg ( \%hash );
1269 $error = $new->replace( $self, options => { $self->options } );
1271 $dbh->rollback if $oldAutoCommit;
1275 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1281 =item suspend [ OPTION => VALUE ... ]
1283 Suspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
1284 package, then suspends the package itself (sets the susp field to now).
1286 Available options are:
1290 =item reason - can be set to a cancellation reason (see L<FS:reason>),
1291 either a reasonnum of an existing reason, or passing a hashref will create
1292 a new reason. The hashref should have the following keys:
1293 - typenum - Reason type (see L<FS::reason_type>
1294 - reason - Text of the new reason.
1296 =item date - can be set to a unix style timestamp to specify when to
1299 =item time - can be set to override the current time, for calculation
1300 of final invoices or unused-time credits
1302 =item resume_date - can be set to a time when the package should be
1303 unsuspended. This may be more convenient than calling C<unsuspend()>
1306 =item from_main - allows a supplemental package to be suspended, rather
1307 than redirecting the method call to its main package. For internal use.
1309 =item from_cancel - used when suspending from the cancel method, forces
1310 this to skip everything besides basic suspension. For internal use.
1314 If there is an error, returns the error, otherwise returns false.
1319 my( $self, %options ) = @_;
1322 # pass all suspend/cancel actions to the main package
1323 if ( $self->main_pkgnum and !$options{'from_main'} ) {
1324 return $self->main_pkg->suspend(%options);
1327 local $SIG{HUP} = 'IGNORE';
1328 local $SIG{INT} = 'IGNORE';
1329 local $SIG{QUIT} = 'IGNORE';
1330 local $SIG{TERM} = 'IGNORE';
1331 local $SIG{TSTP} = 'IGNORE';
1332 local $SIG{PIPE} = 'IGNORE';
1334 my $oldAutoCommit = $FS::UID::AutoCommit;
1335 local $FS::UID::AutoCommit = 0;
1338 my $old = $self->select_for_update;
1340 my $pkgnum = $old->pkgnum;
1341 if ( $old->get('cancel') || $self->get('cancel') ) {
1342 dbh->rollback if $oldAutoCommit;
1343 return "Can't suspend cancelled package $pkgnum";
1346 if ( $old->get('susp') || $self->get('susp') ) {
1347 dbh->rollback if $oldAutoCommit;
1348 return ""; # no error # complain on adjourn?
1351 my $suspend_time = $options{'time'} || time;
1352 my $date = $options{date} if $options{date}; # adjourn/suspend later
1353 $date = '' if ($date && $date <= $suspend_time); # complain instead?
1355 if ( $date && $old->get('expire') && $old->get('expire') < $date ) {
1356 dbh->rollback if $oldAutoCommit;
1357 return "Package $pkgnum expires before it would be suspended.";
1360 # some false laziness with sub cancel
1361 if ( !$options{nobill} && !$date && !$options{'from_cancel'} &&
1362 $self->part_pkg->option('bill_suspend_as_cancel',1) ) {
1363 # kind of a kludge--'bill_suspend_as_cancel' to avoid having to
1364 # make the entire cust_main->bill path recognize 'suspend' and
1365 # 'cancel' separately.
1366 warn "Billing $pkgnum on suspension (at $suspend_time)\n" if $DEBUG;
1367 my $copy = $self->new({$self->hash});
1369 $copy->cust_main->bill( 'pkg_list' => [ $copy ],
1371 'time' => $suspend_time );
1372 warn "Error billing during suspend, custnum ".
1373 #$self->cust_main->custnum. ": $error"
1378 my $cust_pkg_reason;
1379 if ( $options{'reason'} ) {
1380 $error = $self->insert_reason( 'reason' => $options{'reason'},
1381 'action' => $date ? 'adjourn' : 'suspend',
1382 'date' => $date ? $date : $suspend_time,
1383 'reason_otaker' => $options{'reason_otaker'},
1386 dbh->rollback if $oldAutoCommit;
1387 return "Error inserting cust_pkg_reason: $error";
1389 $cust_pkg_reason = qsearchs('cust_pkg_reason', {
1390 'date' => $date ? $date : $suspend_time,
1391 'action' => $date ? 'A' : 'S',
1392 'pkgnum' => $self->pkgnum,
1396 # if a reasonnum was passed, get the actual reason object so we can check
1398 # (passing a reason hashref is still allowed, but it can't be used with
1399 # the fancy behavioral options.)
1402 if ($options{'reason'} =~ /^\d+$/) {
1403 $reason = FS::reason->by_key($options{'reason'});
1406 my %hash = $self->hash;
1408 $hash{'adjourn'} = $date;
1410 $hash{'susp'} = $suspend_time;
1413 my $resume_date = $options{'resume_date'} || 0;
1414 if ( $resume_date > ($date || $suspend_time) ) {
1415 $hash{'resume'} = $resume_date;
1418 $options{options} ||= {};
1420 my $new = new FS::cust_pkg ( \%hash );
1421 $error = $new->replace( $self, options => { $self->options,
1422 %{ $options{options} },
1426 $dbh->rollback if $oldAutoCommit;
1430 unless ( $date ) { # then we are suspending now
1432 unless ($options{'from_cancel'}) {
1433 # credit remaining time if appropriate
1434 # (if required by the package def, or the suspend reason)
1435 my $unused_credit = $self->part_pkg->option('unused_credit_suspend',1)
1436 || ( defined($reason) && $reason->unused_credit );
1438 if ( $unused_credit ) {
1439 warn "crediting unused time on pkg#".$self->pkgnum."\n" if $DEBUG;
1440 my $error = $self->credit_remaining('suspend', $suspend_time);
1442 $dbh->rollback if $oldAutoCommit;
1450 foreach my $cust_svc (
1451 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
1453 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
1455 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
1456 $dbh->rollback if $oldAutoCommit;
1457 return "Illegal svcdb value in part_svc!";
1460 require "FS/$svcdb.pm";
1462 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
1464 $error = $svc->suspend;
1466 $dbh->rollback if $oldAutoCommit;
1469 my( $label, $value ) = $cust_svc->label;
1470 push @labels, "$label: $value";
1474 # suspension fees: if there is a feepart, and it's not an unsuspend fee,
1475 # and this is not a suspend-before-cancel
1476 if ( $cust_pkg_reason ) {
1477 my $reason_obj = $cust_pkg_reason->reason;
1478 if ( $reason_obj->feepart and
1479 ! $reason_obj->fee_on_unsuspend and
1480 ! $options{'from_cancel'} ) {
1482 # register the need to charge a fee, cust_main->bill will do the rest
1483 warn "registering suspend fee: pkgnum ".$self->pkgnum.", feepart ".$reason->feepart."\n"
1485 my $cust_pkg_reason_fee = FS::cust_pkg_reason_fee->new({
1486 'pkgreasonnum' => $cust_pkg_reason->num,
1487 'pkgnum' => $self->pkgnum,
1488 'feepart' => $reason->feepart,
1489 'nextbill' => $reason->fee_hold,
1491 $error ||= $cust_pkg_reason_fee->insert;
1495 my $conf = new FS::Conf;
1496 if ( $conf->config('suspend_email_admin') && !$options{'from_cancel'} ) {
1498 my $error = send_email(
1499 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
1500 #invoice_from ??? well as good as any
1501 'to' => $conf->config('suspend_email_admin'),
1502 'subject' => 'FREESIDE NOTIFICATION: Customer package suspended',
1504 "This is an automatic message from your Freeside installation\n",
1505 "informing you that the following customer package has been suspended:\n",
1507 'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
1508 'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
1509 ( map { "Service : $_\n" } @labels ),
1511 'custnum' => $self->custnum,
1512 'msgtype' => 'admin'
1516 warn "WARNING: can't send suspension admin email (suspending anyway): ".
1524 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1525 $error = $supp_pkg->suspend(%options, 'from_main' => 1);
1527 $dbh->rollback if $oldAutoCommit;
1528 return "suspending supplemental pkg#".$supp_pkg->pkgnum.": $error";
1532 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1537 =item credit_remaining MODE TIME
1539 Generate a credit for this package for the time remaining in the current
1540 billing period. MODE is either "suspend" or "cancel" (determines the
1541 credit type). TIME is the time of suspension/cancellation. Both arguments
1546 # Implementation note:
1548 # If you pkgpart-change a package that has been billed, and it's set to give
1549 # credit on package change, then this method gets called and then the new
1550 # package will have no last_bill date. Therefore the customer will be credited
1551 # only once (per billing period) even if there are multiple package changes.
1553 # If you location-change a package that has been billed, this method will NOT
1554 # be called and the new package WILL have the last bill date of the old
1557 # If the new package is then canceled within the same billing cycle,
1558 # credit_remaining needs to run calc_remain on the OLD package to determine
1559 # the amount of unused time to credit.
1561 sub credit_remaining {
1562 # Add a credit for remaining service
1563 my ($self, $mode, $time) = @_;
1564 die 'credit_remaining requires suspend or cancel'
1565 unless $mode eq 'suspend' or $mode eq 'cancel';
1566 die 'no suspend/cancel time' unless $time > 0;
1568 my $conf = FS::Conf->new;
1569 my $reason_type = $conf->config($mode.'_credit_type');
1571 my $last_bill = $self->getfield('last_bill') || 0;
1572 my $next_bill = $self->getfield('bill') || 0;
1573 if ( $last_bill > 0 # the package has been billed
1574 and $next_bill > 0 # the package has a next bill date
1575 and $next_bill >= $time # which is in the future
1577 my $remaining_value = 0;
1579 my $remain_pkg = $self;
1580 $remaining_value = $remain_pkg->calc_remain('time' => $time);
1582 # we may have to walk back past some package changes to get to the
1583 # one that actually has unused time
1584 while ( $remaining_value == 0 ) {
1585 if ( $remain_pkg->change_pkgnum ) {
1586 $remain_pkg = FS::cust_pkg->by_key($remain_pkg->change_pkgnum);
1588 # the package has really never been billed
1591 $remaining_value = $remain_pkg->calc_remain('time' => $time);
1594 if ( $remaining_value > 0 ) {
1595 warn "Crediting for $remaining_value on package ".$self->pkgnum."\n"
1597 my $error = $self->cust_main->credit(
1599 'Credit for unused time on '. $self->part_pkg->pkg,
1600 'reason_type' => $reason_type,
1602 return "Error crediting customer \$$remaining_value for unused time".
1603 " on ". $self->part_pkg->pkg. ": $error"
1605 } #if $remaining_value
1606 } #if $last_bill, etc.
1610 =item unsuspend [ OPTION => VALUE ... ]
1612 Unsuspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
1613 package, then unsuspends the package itself (clears the susp field and the
1614 adjourn field if it is in the past). If the suspend reason includes an
1615 unsuspension package, that package will be ordered.
1617 Available options are:
1623 Can be set to a date to unsuspend the package in the future (the 'resume'
1626 =item adjust_next_bill
1628 Can be set true to adjust the next bill date forward by
1629 the amount of time the account was inactive. This was set true by default
1630 in the past (from 1.4.2 and 1.5.0pre6 through 1.7.0), but now needs to be
1631 explicitly requested with this option or in the price plan.
1635 If there is an error, returns the error, otherwise returns false.
1640 my( $self, %opt ) = @_;
1643 # pass all suspend/cancel actions to the main package
1644 if ( $self->main_pkgnum and !$opt{'from_main'} ) {
1645 return $self->main_pkg->unsuspend(%opt);
1648 local $SIG{HUP} = 'IGNORE';
1649 local $SIG{INT} = 'IGNORE';
1650 local $SIG{QUIT} = 'IGNORE';
1651 local $SIG{TERM} = 'IGNORE';
1652 local $SIG{TSTP} = 'IGNORE';
1653 local $SIG{PIPE} = 'IGNORE';
1655 my $oldAutoCommit = $FS::UID::AutoCommit;
1656 local $FS::UID::AutoCommit = 0;
1659 my $old = $self->select_for_update;
1661 my $pkgnum = $old->pkgnum;
1662 if ( $old->get('cancel') || $self->get('cancel') ) {
1663 $dbh->rollback if $oldAutoCommit;
1664 return "Can't unsuspend cancelled package $pkgnum";
1667 unless ( $old->get('susp') && $self->get('susp') ) {
1668 $dbh->rollback if $oldAutoCommit;
1669 return ""; # no error # complain instead?
1672 # handle the case of setting a future unsuspend (resume) date
1673 # and do not continue to actually unsuspend the package
1674 my $date = $opt{'date'};
1675 if ( $date and $date > time ) { # return an error if $date <= time?
1677 if ( $old->get('expire') && $old->get('expire') < $date ) {
1678 $dbh->rollback if $oldAutoCommit;
1679 return "Package $pkgnum expires before it would be unsuspended.";
1682 my $new = new FS::cust_pkg { $self->hash };
1683 $new->set('resume', $date);
1684 $error = $new->replace($self, options => $self->options);
1687 $dbh->rollback if $oldAutoCommit;
1691 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1697 if (!$self->setup) {
1698 # then this package is being released from on-hold status
1699 $self->set_initial_timers;
1704 foreach my $cust_svc (
1705 qsearch('cust_svc',{'pkgnum'=> $self->pkgnum } )
1707 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
1709 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
1710 $dbh->rollback if $oldAutoCommit;
1711 return "Illegal svcdb value in part_svc!";
1714 require "FS/$svcdb.pm";
1716 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
1718 $error = $svc->unsuspend;
1720 $dbh->rollback if $oldAutoCommit;
1723 my( $label, $value ) = $cust_svc->label;
1724 push @labels, "$label: $value";
1729 my $cust_pkg_reason = $self->last_cust_pkg_reason('susp');
1730 my $reason = $cust_pkg_reason ? $cust_pkg_reason->reason : '';
1732 my %hash = $self->hash;
1733 my $inactive = time - $hash{'susp'};
1735 my $conf = new FS::Conf;
1737 # increment next bill date if certain conditions are met:
1738 # - it was due to be billed at some point
1739 # - either the global or local config says to do this
1740 my $adjust_bill = 0;
1743 && ( $hash{'bill'} || $hash{'setup'} )
1744 && ( $opt{'adjust_next_bill'}
1745 || $conf->exists('unsuspend-always_adjust_next_bill_date')
1746 || $self->part_pkg->option('unsuspend_adjust_bill', 1)
1753 # - the package billed during suspension
1754 # - or it was ordered on hold
1755 # - or the customer was credited for the unused time
1757 if ( $self->option('suspend_bill',1)
1758 or ( $self->part_pkg->option('suspend_bill',1)
1759 and ! $self->option('no_suspend_bill',1)
1761 or $hash{'order_date'} == $hash{'susp'}
1766 if ( $adjust_bill ) {
1767 if ( $self->part_pkg->option('unused_credit_suspend')
1768 or ( $reason and $reason->unused_credit ) ) {
1769 # then the customer was credited for the unused time before suspending,
1770 # so their next bill should be immediate.
1771 $hash{'bill'} = time;
1773 # add the length of time suspended to the bill date
1774 $hash{'bill'} = ( $hash{'bill'} || $hash{'setup'} ) + $inactive;
1779 $hash{'adjourn'} = '' if $hash{'adjourn'} and $hash{'adjourn'} < time;
1780 $hash{'resume'} = '' if !$hash{'adjourn'};
1781 my $new = new FS::cust_pkg ( \%hash );
1782 $error = $new->replace( $self, options => { $self->options } );
1784 $dbh->rollback if $oldAutoCommit;
1791 if ( $reason->unsuspend_pkgpart ) {
1792 #warn "Suspend reason '".$reason->reason."' uses deprecated unsuspend_pkgpart feature.\n"; # in 4.x
1793 my $part_pkg = FS::part_pkg->by_key($reason->unsuspend_pkgpart)
1794 or $error = "Unsuspend package definition ".$reason->unsuspend_pkgpart.
1796 my $start_date = $self->cust_main->next_bill_date
1797 if $reason->unsuspend_hold;
1800 $unsusp_pkg = FS::cust_pkg->new({
1801 'custnum' => $self->custnum,
1802 'pkgpart' => $reason->unsuspend_pkgpart,
1803 'start_date' => $start_date,
1804 'locationnum' => $self->locationnum,
1805 # discount? probably not...
1808 $error ||= $self->cust_main->order_pkg( 'cust_pkg' => $unsusp_pkg );
1811 # new way, using fees
1812 if ( $reason->feepart and $reason->fee_on_unsuspend ) {
1813 # register the need to charge a fee, cust_main->bill will do the rest
1814 warn "registering unsuspend fee: pkgnum ".$self->pkgnum.", feepart ".$reason->feepart."\n"
1816 my $cust_pkg_reason_fee = FS::cust_pkg_reason_fee->new({
1817 'pkgreasonnum' => $cust_pkg_reason->num,
1818 'pkgnum' => $self->pkgnum,
1819 'feepart' => $reason->feepart,
1820 'nextbill' => $reason->fee_hold,
1822 $error ||= $cust_pkg_reason_fee->insert;
1826 $dbh->rollback if $oldAutoCommit;
1831 if ( $conf->config('unsuspend_email_admin') ) {
1833 my $error = send_email(
1834 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
1835 #invoice_from ??? well as good as any
1836 'to' => $conf->config('unsuspend_email_admin'),
1837 'subject' => 'FREESIDE NOTIFICATION: Customer package unsuspended', 'body' => [
1838 "This is an automatic message from your Freeside installation\n",
1839 "informing you that the following customer package has been unsuspended:\n",
1841 'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
1842 'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
1843 ( map { "Service : $_\n" } @labels ),
1845 "An unsuspension fee was charged: ".
1846 $unsusp_pkg->part_pkg->pkg_comment."\n"
1850 'custnum' => $self->custnum,
1851 'msgtype' => 'admin',
1855 warn "WARNING: can't send unsuspension admin email (unsuspending anyway): ".
1861 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1862 $error = $supp_pkg->unsuspend(%opt, 'from_main' => 1);
1864 $dbh->rollback if $oldAutoCommit;
1865 return "unsuspending supplemental pkg#".$supp_pkg->pkgnum.": $error";
1869 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1876 Cancels any pending suspension (sets the adjourn field to null).
1878 If there is an error, returns the error, otherwise returns false.
1883 my( $self, %options ) = @_;
1886 local $SIG{HUP} = 'IGNORE';
1887 local $SIG{INT} = 'IGNORE';
1888 local $SIG{QUIT} = 'IGNORE';
1889 local $SIG{TERM} = 'IGNORE';
1890 local $SIG{TSTP} = 'IGNORE';
1891 local $SIG{PIPE} = 'IGNORE';
1893 my $oldAutoCommit = $FS::UID::AutoCommit;
1894 local $FS::UID::AutoCommit = 0;
1897 my $old = $self->select_for_update;
1899 my $pkgnum = $old->pkgnum;
1900 if ( $old->get('cancel') || $self->get('cancel') ) {
1901 dbh->rollback if $oldAutoCommit;
1902 return "Can't unadjourn cancelled package $pkgnum";
1903 # or at least it's pointless
1906 if ( $old->get('susp') || $self->get('susp') ) {
1907 dbh->rollback if $oldAutoCommit;
1908 return "Can't unadjourn suspended package $pkgnum";
1909 # perhaps this is arbitrary
1912 unless ( $old->get('adjourn') && $self->get('adjourn') ) {
1913 dbh->rollback if $oldAutoCommit;
1914 return ""; # no error
1917 my %hash = $self->hash;
1918 $hash{'adjourn'} = '';
1919 $hash{'resume'} = '';
1920 my $new = new FS::cust_pkg ( \%hash );
1921 $error = $new->replace( $self, options => { $self->options } );
1923 $dbh->rollback if $oldAutoCommit;
1927 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1934 =item change HASHREF | OPTION => VALUE ...
1936 Changes this package: cancels it and creates a new one, with a different
1937 pkgpart or locationnum or both. All services are transferred to the new
1938 package (no change will be made if this is not possible).
1940 Options may be passed as a list of key/value pairs or as a hash reference.
1947 New locationnum, to change the location for this package.
1951 New FS::cust_location object, to create a new location and assign it
1956 New FS::cust_main object, to create a new customer and assign the new package
1961 New pkgpart (see L<FS::part_pkg>).
1965 New refnum (see L<FS::part_referral>).
1969 New quantity; if unspecified, the new package will have the same quantity
1974 "New" (existing) FS::cust_pkg object. The package's services and other
1975 attributes will be transferred to this package.
1979 Set to true to transfer billing dates (start_date, setup, last_bill, bill,
1980 susp, adjourn, cancel, expire, and contract_end) to the new package.
1982 =item unprotect_svcs
1984 Normally, change() will rollback and return an error if some services
1985 can't be transferred (also see the I<cust_pkg-change_svcpart> config option).
1986 If unprotect_svcs is true, this method will transfer as many services as
1987 it can and then unconditionally cancel the old package.
1991 If specified, sets this value for the contract_end date on the new package
1992 (without regard for keep_dates or the usual date-preservation behavior.)
1993 Will throw an error if defined but false; the UI doesn't allow editing
1994 this unless it already exists, making removal impossible to undo.
1998 At least one of locationnum, cust_location, pkgpart, refnum, cust_main, or
1999 cust_pkg must be specified (otherwise, what's the point?)
2001 Returns either the new FS::cust_pkg object or a scalar error.
2005 my $err_or_new_cust_pkg = $old_cust_pkg->change
2009 #used by change and change_later
2010 #didn't put with documented check methods because it depends on change-specific opts
2011 #and it also possibly edits the value of opts
2015 if ( defined($opt->{'contract_end'}) ) {
2016 my $current_contract_end = $self->get('contract_end');
2017 unless ($opt->{'contract_end'}) {
2018 if ($current_contract_end) {
2019 return "Cannot remove contract end date when changing packages";
2021 #shouldn't even pass this option if there's not a current value
2022 #but can be handled gracefully if the option is empty
2023 warn "Contract end date passed unexpectedly";
2024 delete $opt->{'contract_end'};
2028 unless ($current_contract_end) {
2029 #option shouldn't be passed, throw error if it's non-empty
2030 return "Cannot add contract end date when changing packages " . $self->pkgnum;
2036 #some false laziness w/order
2039 my $opt = ref($_[0]) ? shift : { @_ };
2041 my $conf = new FS::Conf;
2043 # handle contract_end on cust_pkg same as passed option
2044 if ( $opt->{'cust_pkg'} ) {
2045 $opt->{'contract_end'} = $opt->{'cust_pkg'}->contract_end;
2046 delete $opt->{'contract_end'} unless $opt->{'contract_end'};
2049 # check contract_end, prevent adding/removing
2050 my $error = $self->_check_change($opt);
2051 return $error if $error;
2053 # Transactionize this whole mess
2054 local $SIG{HUP} = 'IGNORE';
2055 local $SIG{INT} = 'IGNORE';
2056 local $SIG{QUIT} = 'IGNORE';
2057 local $SIG{TERM} = 'IGNORE';
2058 local $SIG{TSTP} = 'IGNORE';
2059 local $SIG{PIPE} = 'IGNORE';
2061 my $oldAutoCommit = $FS::UID::AutoCommit;
2062 local $FS::UID::AutoCommit = 0;
2065 if ( $opt->{'cust_location'} ) {
2066 $error = $opt->{'cust_location'}->find_or_insert;
2068 $dbh->rollback if $oldAutoCommit;
2069 return "creating location record: $error";
2071 $opt->{'locationnum'} = $opt->{'cust_location'}->locationnum;
2074 # Before going any further here: if the package is still in the pre-setup
2075 # state, it's safe to modify it in place. No need to charge/credit for
2076 # partial period, transfer services, transfer usage pools, copy invoice
2077 # details, or change any dates.
2078 if ( ! $self->setup and ! $opt->{cust_pkg} and ! $opt->{cust_main} ) {
2079 foreach ( qw( locationnum pkgpart quantity refnum salesnum ) ) {
2080 if ( length($opt->{$_}) ) {
2081 $self->set($_, $opt->{$_});
2084 # almost. if the new pkgpart specifies start/adjourn/expire timers,
2086 if ( $opt->{'pkgpart'} and $opt->{'pkgpart'} != $self->pkgpart ) {
2087 $self->set_initial_timers;
2089 # but if contract_end was explicitly specified, that overrides all else
2090 $self->set('contract_end', $opt->{'contract_end'})
2091 if $opt->{'contract_end'};
2092 $error = $self->replace;
2094 $dbh->rollback if $oldAutoCommit;
2095 return "modifying package: $error";
2097 $dbh->commit if $oldAutoCommit;
2106 $hash{'setup'} = $time if $self->setup;
2108 $hash{'change_date'} = $time;
2109 $hash{"change_$_"} = $self->$_()
2110 foreach qw( pkgnum pkgpart locationnum );
2112 if ( $opt->{'cust_pkg'} ) {
2113 # treat changing to a package with a different pkgpart as a
2114 # pkgpart change (because it is)
2115 $opt->{'pkgpart'} = $opt->{'cust_pkg'}->pkgpart;
2118 # whether to override pkgpart checking on the new package
2119 my $same_pkgpart = 1;
2120 if ( $opt->{'pkgpart'} and ( $opt->{'pkgpart'} != $self->pkgpart ) ) {
2124 my $unused_credit = 0;
2125 my $keep_dates = $opt->{'keep_dates'};
2127 # Special case. If the pkgpart is changing, and the customer is
2128 # going to be credited for remaining time, don't keep setup, bill,
2129 # or last_bill dates, and DO pass the flag to cancel() to credit
2131 if ( $opt->{'pkgpart'}
2132 and $opt->{'pkgpart'} != $self->pkgpart
2133 and $self->part_pkg->option('unused_credit_change', 1) ) {
2136 $hash{$_} = '' foreach qw(setup bill last_bill);
2139 if ( $keep_dates ) {
2140 foreach my $date ( qw(setup bill last_bill) ) {
2141 $hash{$date} = $self->getfield($date);
2144 # always keep the following dates
2145 foreach my $date (qw(order_date susp adjourn cancel expire resume
2146 start_date contract_end)) {
2147 $hash{$date} = $self->getfield($date);
2149 # but if contract_end was explicitly specified, that overrides all else
2150 $hash{'contract_end'} = $opt->{'contract_end'}
2151 if $opt->{'contract_end'};
2153 # allow $opt->{'locationnum'} = '' to specifically set it to null
2154 # (i.e. customer default location)
2155 $opt->{'locationnum'} = $self->locationnum if !exists($opt->{'locationnum'});
2157 # usually this doesn't matter. the two cases where it does are:
2158 # 1. unused_credit_change + pkgpart change + setup fee on the new package
2160 # 2. (more importantly) changing a package before it's billed
2161 $hash{'waive_setup'} = $self->waive_setup;
2163 # if this package is scheduled for a future package change, preserve that
2164 $hash{'change_to_pkgnum'} = $self->change_to_pkgnum;
2166 my $custnum = $self->custnum;
2167 if ( $opt->{cust_main} ) {
2168 my $cust_main = $opt->{cust_main};
2169 unless ( $cust_main->custnum ) {
2170 my $error = $cust_main->insert( @{ $opt->{cust_main_insert_args}||[] } );
2172 $dbh->rollback if $oldAutoCommit;
2173 return "inserting customer record: $error";
2176 $custnum = $cust_main->custnum;
2179 $hash{'contactnum'} = $opt->{'contactnum'} if $opt->{'contactnum'};
2182 if ( $opt->{'cust_pkg'} ) {
2183 # The target package already exists; update it to show that it was
2184 # changed from this package.
2185 $cust_pkg = $opt->{'cust_pkg'};
2187 # follow all the above rules for date changes, etc.
2188 foreach (keys %hash) {
2189 $cust_pkg->set($_, $hash{$_});
2191 # except those that implement the future package change behavior
2192 foreach (qw(change_to_pkgnum start_date expire)) {
2193 $cust_pkg->set($_, '');
2196 $error = $cust_pkg->replace;
2199 # Create the new package.
2200 $cust_pkg = new FS::cust_pkg {
2201 custnum => $custnum,
2202 locationnum => $opt->{'locationnum'},
2203 ( map { $_ => ( $opt->{$_} || $self->$_() ) }
2204 qw( pkgpart quantity refnum salesnum )
2208 $error = $cust_pkg->insert( 'change' => 1,
2209 'allow_pkgpart' => $same_pkgpart );
2212 $dbh->rollback if $oldAutoCommit;
2213 return "inserting new package: $error";
2216 # Transfer services and cancel old package.
2217 # Enforce service limits only if this is a pkgpart change.
2218 local $FS::cust_svc::ignore_quantity;
2219 $FS::cust_svc::ignore_quantity = 1 if $same_pkgpart;
2220 $error = $self->transfer($cust_pkg);
2221 if ($error and $error == 0) {
2222 # $old_pkg->transfer failed.
2223 $dbh->rollback if $oldAutoCommit;
2224 return "transferring $error";
2227 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
2228 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
2229 $error = $self->transfer($cust_pkg, 'change_svcpart'=>1 );
2230 if ($error and $error == 0) {
2231 # $old_pkg->transfer failed.
2232 $dbh->rollback if $oldAutoCommit;
2233 return "converting $error";
2237 # We set unprotect_svcs when executing a "future package change". It's
2238 # not a user-interactive operation, so returning an error means the
2239 # package change will just fail. Rather than have that happen, we'll
2240 # let leftover services be deleted.
2241 if ($error > 0 and !$opt->{'unprotect_svcs'}) {
2242 # Transfers were successful, but we still had services left on the old
2243 # package. We can't change the package under this circumstances, so abort.
2244 $dbh->rollback if $oldAutoCommit;
2245 return "unable to transfer all services";
2248 #reset usage if changing pkgpart
2249 # AND usage rollover is off (otherwise adds twice, now and at package bill)
2250 if ($self->pkgpart != $cust_pkg->pkgpart) {
2251 my $part_pkg = $cust_pkg->part_pkg;
2252 $error = $part_pkg->reset_usage($cust_pkg, $part_pkg->is_prepaid
2256 if $part_pkg->can('reset_usage') && ! $part_pkg->option('usage_rollover',1);
2259 $dbh->rollback if $oldAutoCommit;
2260 return "setting usage values: $error";
2263 # if NOT changing pkgpart, transfer any usage pools over
2264 foreach my $usage ($self->cust_pkg_usage) {
2265 $usage->set('pkgnum', $cust_pkg->pkgnum);
2266 $error = $usage->replace;
2268 $dbh->rollback if $oldAutoCommit;
2269 return "transferring usage pools: $error";
2274 # transfer discounts, if we're not changing pkgpart
2275 if ( $same_pkgpart ) {
2276 foreach my $old_discount ($self->cust_pkg_discount_active) {
2277 # don't remove the old discount, we may still need to bill that package.
2278 my $new_discount = new FS::cust_pkg_discount {
2279 'pkgnum' => $cust_pkg->pkgnum,
2280 'discountnum' => $old_discount->discountnum,
2281 'months_used' => $old_discount->months_used,
2283 $error = $new_discount->insert;
2285 $dbh->rollback if $oldAutoCommit;
2286 return "transferring discounts: $error";
2291 # transfer (copy) invoice details
2292 foreach my $detail ($self->cust_pkg_detail) {
2293 my $new_detail = FS::cust_pkg_detail->new({ $detail->hash });
2294 $new_detail->set('pkgdetailnum', '');
2295 $new_detail->set('pkgnum', $cust_pkg->pkgnum);
2296 $error = $new_detail->insert;
2298 $dbh->rollback if $oldAutoCommit;
2299 return "transferring package notes: $error";
2305 if ( !$opt->{'cust_pkg'} ) {
2306 # Order any supplemental packages.
2307 my $part_pkg = $cust_pkg->part_pkg;
2308 my @old_supp_pkgs = $self->supplemental_pkgs;
2309 foreach my $link ($part_pkg->supp_part_pkg_link) {
2311 foreach (@old_supp_pkgs) {
2312 if ($_->pkgpart == $link->dst_pkgpart) {
2314 $_->pkgpart(0); # so that it can't match more than once
2318 # false laziness with FS::cust_main::Packages::order_pkg
2319 my $new = FS::cust_pkg->new({
2320 pkgpart => $link->dst_pkgpart,
2321 pkglinknum => $link->pkglinknum,
2322 custnum => $custnum,
2323 main_pkgnum => $cust_pkg->pkgnum,
2324 locationnum => $cust_pkg->locationnum,
2325 start_date => $cust_pkg->start_date,
2326 order_date => $cust_pkg->order_date,
2327 expire => $cust_pkg->expire,
2328 adjourn => $cust_pkg->adjourn,
2329 contract_end => $cust_pkg->contract_end,
2330 refnum => $cust_pkg->refnum,
2331 discountnum => $cust_pkg->discountnum,
2332 waive_setup => $cust_pkg->waive_setup,
2334 if ( $old and $opt->{'keep_dates'} ) {
2335 foreach (qw(setup bill last_bill)) {
2336 $new->set($_, $old->get($_));
2339 $error = $new->insert( allow_pkgpart => $same_pkgpart );
2342 $error ||= $old->transfer($new);
2344 if ( $error and $error > 0 ) {
2345 # no reason why this should ever fail, but still...
2346 $error = "Unable to transfer all services from supplemental package ".
2350 $dbh->rollback if $oldAutoCommit;
2353 push @new_supp_pkgs, $new;
2355 } # if !$opt->{'cust_pkg'}
2356 # because if there is one, then supplemental packages would already
2357 # have been created for it.
2359 #Good to go, cancel old package. Notify 'cancel' of whether to credit
2361 #Don't allow billing the package (preceding period packages and/or
2362 #outstanding usage) if we are keeping dates (i.e. location changing),
2363 #because the new package will be billed for the same date range.
2364 #Supplemental packages are also canceled here.
2366 # during scheduled changes, avoid canceling the package we just
2368 $self->set('change_to_pkgnum' => '');
2370 $error = $self->cancel(
2372 unused_credit => $unused_credit,
2373 nobill => $keep_dates,
2374 change_custnum => ( $self->custnum != $custnum ? $custnum : '' ),
2375 no_delay_cancel => 1,
2378 $dbh->rollback if $oldAutoCommit;
2379 return "canceling old package: $error";
2382 if ( $conf->exists('cust_pkg-change_pkgpart-bill_now') ) {
2384 my $error = $cust_pkg->cust_main->bill(
2385 'pkg_list' => [ $cust_pkg, @new_supp_pkgs ]
2388 $dbh->rollback if $oldAutoCommit;
2389 return "billing new package: $error";
2393 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2399 =item change_later OPTION => VALUE...
2401 Schedule a package change for a later date. This actually orders the new
2402 package immediately, but sets its start date for a future date, and sets
2403 the current package to expire on the same date.
2405 If the package is already scheduled for a change, this can be called with
2406 'start_date' to change the scheduled date, or with pkgpart and/or
2407 locationnum to modify the package change. To cancel the scheduled change
2408 entirely, see C<abort_change>.
2416 The date for the package change. Required, and must be in the future.
2426 The pkgpart, locationnum, quantity and optional contract_end of the new
2427 package, with the same meaning as in C<change>.
2435 my $opt = ref($_[0]) ? shift : { @_ };
2437 # check contract_end, prevent adding/removing
2438 my $error = $self->_check_change($opt);
2439 return $error if $error;
2441 my $oldAutoCommit = $FS::UID::AutoCommit;
2442 local $FS::UID::AutoCommit = 0;
2445 my $cust_main = $self->cust_main;
2447 my $date = delete $opt->{'start_date'} or return 'start_date required';
2449 if ( $date <= time ) {
2450 $dbh->rollback if $oldAutoCommit;
2451 return "start_date $date is in the past";
2454 if ( $self->change_to_pkgnum ) {
2455 my $change_to = FS::cust_pkg->by_key($self->change_to_pkgnum);
2456 my $new_pkgpart = $opt->{'pkgpart'}
2457 if $opt->{'pkgpart'} and $opt->{'pkgpart'} != $change_to->pkgpart;
2458 my $new_locationnum = $opt->{'locationnum'}
2459 if $opt->{'locationnum'} and $opt->{'locationnum'} != $change_to->locationnum;
2460 my $new_quantity = $opt->{'quantity'}
2461 if $opt->{'quantity'} and $opt->{'quantity'} != $change_to->quantity;
2462 my $new_contract_end = $opt->{'contract_end'}
2463 if $opt->{'contract_end'} and $opt->{'contract_end'} != $change_to->contract_end;
2464 if ( $new_pkgpart or $new_locationnum or $new_quantity or $new_contract_end ) {
2465 # it hasn't been billed yet, so in principle we could just edit
2466 # it in place (w/o a package change), but that's bad form.
2467 # So change the package according to the new options...
2468 my $err_or_pkg = $change_to->change(%$opt);
2469 if ( ref $err_or_pkg ) {
2470 # Then set that package up for a future start.
2471 $self->set('change_to_pkgnum', $err_or_pkg->pkgnum);
2472 $self->set('expire', $date); # in case it's different
2473 $err_or_pkg->set('start_date', $date);
2474 $err_or_pkg->set('change_date', '');
2475 $err_or_pkg->set('change_pkgnum', '');
2477 $error = $self->replace ||
2478 $err_or_pkg->replace ||
2479 #because change() might've edited existing scheduled change in place
2480 (($err_or_pkg->pkgnum == $change_to->pkgnum) ? '' :
2481 $change_to->cancel('no_delay_cancel' => 1) ||
2482 $change_to->delete);
2484 $error = $err_or_pkg;
2486 } else { # change the start date only.
2487 $self->set('expire', $date);
2488 $change_to->set('start_date', $date);
2489 $error = $self->replace || $change_to->replace;
2492 $dbh->rollback if $oldAutoCommit;
2495 $dbh->commit if $oldAutoCommit;
2498 } # if $self->change_to_pkgnum
2500 my $new_pkgpart = $opt->{'pkgpart'}
2501 if $opt->{'pkgpart'} and $opt->{'pkgpart'} != $self->pkgpart;
2502 my $new_locationnum = $opt->{'locationnum'}
2503 if $opt->{'locationnum'} and $opt->{'locationnum'} != $self->locationnum;
2504 my $new_quantity = $opt->{'quantity'}
2505 if $opt->{'quantity'} and $opt->{'quantity'} != $self->quantity;
2506 my $new_contract_end = $opt->{'contract_end'}
2507 if $opt->{'contract_end'} and $opt->{'contract_end'} != $self->contract_end;
2509 return '' unless $new_pkgpart or $new_locationnum or $new_quantity or $new_contract_end; # wouldn't do anything
2511 # allow $opt->{'locationnum'} = '' to specifically set it to null
2512 # (i.e. customer default location)
2513 $opt->{'locationnum'} = $self->locationnum if !exists($opt->{'locationnum'});
2515 my $new = FS::cust_pkg->new( {
2516 custnum => $self->custnum,
2517 locationnum => $opt->{'locationnum'},
2518 start_date => $date,
2519 map { $_ => ( $opt->{$_} || $self->$_() ) }
2520 qw( pkgpart quantity refnum salesnum contract_end )
2522 $error = $new->insert('change' => 1,
2523 'allow_pkgpart' => ($new_pkgpart ? 0 : 1));
2525 $self->set('change_to_pkgnum', $new->pkgnum);
2526 $self->set('expire', $date);
2527 $error = $self->replace;
2530 $dbh->rollback if $oldAutoCommit;
2532 $dbh->commit if $oldAutoCommit;
2540 Cancels a future package change scheduled by C<change_later>.
2546 my $pkgnum = $self->change_to_pkgnum;
2547 my $change_to = FS::cust_pkg->by_key($pkgnum) if $pkgnum;
2550 $error = $change_to->cancel || $change_to->delete;
2551 return $error if $error;
2553 $self->set('change_to_pkgnum', '');
2554 $self->set('expire', '');
2558 =item set_quantity QUANTITY
2560 Change the package's quantity field. This is one of the few package properties
2561 that can safely be changed without canceling and reordering the package
2562 (because it doesn't affect tax eligibility). Returns an error or an
2569 $self = $self->replace_old; # just to make sure
2570 $self->quantity(shift);
2574 =item set_salesnum SALESNUM
2576 Change the package's salesnum (sales person) field. This is one of the few
2577 package properties that can safely be changed without canceling and reordering
2578 the package (because it doesn't affect tax eligibility). Returns an error or
2585 $self = $self->replace_old; # just to make sure
2586 $self->salesnum(shift);
2588 # XXX this should probably reassign any credit that's already been given
2591 =item modify_charge OPTIONS
2593 Change the properties of a one-time charge. The following properties can
2594 be changed this way:
2595 - pkg: the package description
2596 - classnum: the package class
2597 - additional: arrayref of additional invoice details to add to this package
2599 and, I<if the charge has not yet been billed>:
2600 - start_date: the date when it will be billed
2601 - amount: the setup fee to be charged
2602 - quantity: the multiplier for the setup fee
2603 - separate_bill: whether to put the charge on a separate invoice
2605 If you pass 'adjust_commission' => 1, and the classnum changes, and there are
2606 commission credits linked to this charge, they will be recalculated.
2613 my $part_pkg = $self->part_pkg;
2614 my $pkgnum = $self->pkgnum;
2617 my $oldAutoCommit = $FS::UID::AutoCommit;
2618 local $FS::UID::AutoCommit = 0;
2620 return "Can't use modify_charge except on one-time charges"
2621 unless $part_pkg->freq eq '0';
2623 if ( length($opt{'pkg'}) and $part_pkg->pkg ne $opt{'pkg'} ) {
2624 $part_pkg->set('pkg', $opt{'pkg'});
2627 my %pkg_opt = $part_pkg->options;
2628 my $pkg_opt_modified = 0;
2630 $opt{'additional'} ||= [];
2633 foreach (grep /^additional/, keys %pkg_opt) {
2634 ($i) = ($_ =~ /^additional_info(\d+)$/);
2635 $old_additional[$i] = $pkg_opt{$_} if $i;
2636 delete $pkg_opt{$_};
2639 for ( $i = 0; exists($opt{'additional'}->[$i]); $i++ ) {
2640 $pkg_opt{ "additional_info$i" } = $opt{'additional'}->[$i];
2641 if (!exists($old_additional[$i])
2642 or $old_additional[$i] ne $opt{'additional'}->[$i])
2644 $pkg_opt_modified = 1;
2647 $pkg_opt_modified = 1 if (scalar(@old_additional) - 1) != $i;
2648 $pkg_opt{'additional_count'} = $i if $i > 0;
2651 if ( exists($opt{'classnum'}) and $part_pkg->classnum ne $opt{'classnum'} )
2654 $old_classnum = $part_pkg->classnum;
2655 $part_pkg->set('classnum', $opt{'classnum'});
2658 if ( !$self->get('setup') ) {
2659 # not yet billed, so allow amount, setup_cost, quantity, start_date,
2662 if ( exists($opt{'amount'})
2663 and $part_pkg->option('setup_fee') != $opt{'amount'}
2664 and $opt{'amount'} > 0 ) {
2666 $pkg_opt{'setup_fee'} = $opt{'amount'};
2667 $pkg_opt_modified = 1;
2670 if ( exists($opt{'setup_cost'})
2671 and $part_pkg->setup_cost != $opt{'setup_cost'}
2672 and $opt{'setup_cost'} > 0 ) {
2674 $part_pkg->set('setup_cost', $opt{'setup_cost'});
2677 if ( exists($opt{'quantity'})
2678 and $opt{'quantity'} != $self->quantity
2679 and $opt{'quantity'} > 0 ) {
2681 $self->set('quantity', $opt{'quantity'});
2684 if ( exists($opt{'start_date'})
2685 and $opt{'start_date'} != $self->start_date ) {
2687 $self->set('start_date', $opt{'start_date'});
2690 if ( exists($opt{'separate_bill'})
2691 and $opt{'separate_bill'} ne $self->separate_bill ) {
2693 $self->set('separate_bill', $opt{'separate_bill'});
2697 } # else simply ignore them; the UI shouldn't allow editing the fields
2699 if ( exists($opt{'taxclass'})
2700 and $part_pkg->taxclass ne $opt{'taxclass'}) {
2702 $part_pkg->set('taxclass', $opt{'taxclass'});
2706 if ( $part_pkg->modified or $pkg_opt_modified ) {
2707 # can we safely modify the package def?
2708 # Yes, if it's not available for purchase, and this is the only instance
2710 if ( $part_pkg->disabled
2711 and FS::cust_pkg->count('pkgpart = '.$part_pkg->pkgpart) == 1
2712 and FS::quotation_pkg->count('pkgpart = '.$part_pkg->pkgpart) == 0
2714 $error = $part_pkg->replace( options => \%pkg_opt );
2717 $part_pkg = $part_pkg->clone;
2718 $part_pkg->set('disabled' => 'Y');
2719 $error = $part_pkg->insert( options => \%pkg_opt );
2720 # and associate this as yet-unbilled package to the new package def
2721 $self->set('pkgpart' => $part_pkg->pkgpart);
2724 $dbh->rollback if $oldAutoCommit;
2729 if ($self->modified) { # for quantity or start_date change, or if we had
2730 # to clone the existing package def
2731 my $error = $self->replace;
2732 return $error if $error;
2734 if (defined $old_classnum) {
2735 # fix invoice grouping records
2736 my $old_catname = $old_classnum
2737 ? FS::pkg_class->by_key($old_classnum)->categoryname
2739 my $new_catname = $opt{'classnum'}
2740 ? $part_pkg->pkg_class->categoryname
2742 if ( $old_catname ne $new_catname ) {
2743 foreach my $cust_bill_pkg ($self->cust_bill_pkg) {
2744 # (there should only be one...)
2745 my @display = qsearch( 'cust_bill_pkg_display', {
2746 'billpkgnum' => $cust_bill_pkg->billpkgnum,
2747 'section' => $old_catname,
2749 foreach (@display) {
2750 $_->set('section', $new_catname);
2751 $error = $_->replace;
2753 $dbh->rollback if $oldAutoCommit;
2757 } # foreach $cust_bill_pkg
2760 if ( $opt{'adjust_commission'} ) {
2761 # fix commission credits...tricky.
2762 foreach my $cust_event ($self->cust_event) {
2763 my $part_event = $cust_event->part_event;
2764 foreach my $table (qw(sales agent)) {
2766 "FS::part_event::Action::Mixin::credit_${table}_pkg_class";
2767 my $credit = qsearchs('cust_credit', {
2768 'eventnum' => $cust_event->eventnum,
2770 if ( $part_event->isa($class) ) {
2771 # Yes, this results in current commission rates being applied
2772 # retroactively to a one-time charge. For accounting purposes
2773 # there ought to be some kind of time limit on doing this.
2774 my $amount = $part_event->_calc_credit($self);
2775 if ( $credit and $credit->amount ne $amount ) {
2776 # Void the old credit.
2777 $error = $credit->void('Package class changed');
2779 $dbh->rollback if $oldAutoCommit;
2780 return "$error (adjusting commission credit)";
2783 # redo the event action to recreate the credit.
2785 eval { $part_event->do_action( $self, $cust_event ) };
2787 $dbh->rollback if $oldAutoCommit;
2790 } # if $part_event->isa($class)
2792 } # foreach $cust_event
2793 } # if $opt{'adjust_commission'}
2794 } # if defined $old_classnum
2796 $dbh->commit if $oldAutoCommit;
2802 use Storable 'thaw';
2805 sub process_bulk_cust_pkg {
2807 my $param = thaw(decode_base64(shift));
2808 warn Dumper($param) if $DEBUG;
2810 my $old_part_pkg = qsearchs('part_pkg',
2811 { pkgpart => $param->{'old_pkgpart'} });
2812 my $new_part_pkg = qsearchs('part_pkg',
2813 { pkgpart => $param->{'new_pkgpart'} });
2814 die "Must select a new package type\n" unless $new_part_pkg;
2815 #my $keep_dates = $param->{'keep_dates'} || 0;
2816 my $keep_dates = 1; # there is no good reason to turn this off
2818 local $SIG{HUP} = 'IGNORE';
2819 local $SIG{INT} = 'IGNORE';
2820 local $SIG{QUIT} = 'IGNORE';
2821 local $SIG{TERM} = 'IGNORE';
2822 local $SIG{TSTP} = 'IGNORE';
2823 local $SIG{PIPE} = 'IGNORE';
2825 my $oldAutoCommit = $FS::UID::AutoCommit;
2826 local $FS::UID::AutoCommit = 0;
2829 my @cust_pkgs = qsearch('cust_pkg', { 'pkgpart' => $param->{'old_pkgpart'} } );
2832 foreach my $old_cust_pkg ( @cust_pkgs ) {
2834 $job->update_statustext(int(100*$i/(scalar @cust_pkgs)));
2835 if ( $old_cust_pkg->getfield('cancel') ) {
2836 warn '[process_bulk_cust_pkg ] skipping canceled pkgnum '.
2837 $old_cust_pkg->pkgnum."\n"
2841 warn '[process_bulk_cust_pkg] changing pkgnum '.$old_cust_pkg->pkgnum."\n"
2843 my $error = $old_cust_pkg->change(
2844 'pkgpart' => $param->{'new_pkgpart'},
2845 'keep_dates' => $keep_dates
2847 if ( !ref($error) ) { # change returns the cust_pkg on success
2849 die "Error changing pkgnum ".$old_cust_pkg->pkgnum.": '$error'\n";
2852 $dbh->commit if $oldAutoCommit;
2858 Returns the last bill date, or if there is no last bill date, the setup date.
2859 Useful for billing metered services.
2865 return $self->setfield('last_bill', $_[0]) if @_;
2866 return $self->getfield('last_bill') if $self->getfield('last_bill');
2867 my $cust_bill_pkg = qsearchs('cust_bill_pkg', { 'pkgnum' => $self->pkgnum,
2868 'edate' => $self->bill, } );
2869 $cust_bill_pkg ? $cust_bill_pkg->sdate : $self->setup || 0;
2872 =item last_cust_pkg_reason ACTION
2874 Returns the most recent ACTION FS::cust_pkg_reason associated with the package.
2875 Returns false if there is no reason or the package is not currenly ACTION'd
2876 ACTION is one of adjourn, susp, cancel, or expire.
2880 sub last_cust_pkg_reason {
2881 my ( $self, $action ) = ( shift, shift );
2882 my $date = $self->get($action);
2884 'table' => 'cust_pkg_reason',
2885 'hashref' => { 'pkgnum' => $self->pkgnum,
2886 'action' => substr(uc($action), 0, 1),
2889 'order_by' => 'ORDER BY num DESC LIMIT 1',
2893 =item last_reason ACTION
2895 Returns the most recent ACTION FS::reason associated with the package.
2896 Returns false if there is no reason or the package is not currenly ACTION'd
2897 ACTION is one of adjourn, susp, cancel, or expire.
2902 my $cust_pkg_reason = shift->last_cust_pkg_reason(@_);
2903 $cust_pkg_reason->reason
2904 if $cust_pkg_reason;
2909 Returns the definition for this billing item, as an FS::part_pkg object (see
2916 return $self->{'_pkgpart'} if $self->{'_pkgpart'};
2917 cluck "cust_pkg->part_pkg called" if $DEBUG > 1;
2918 qsearchs( 'part_pkg', { 'pkgpart' => $self->pkgpart } );
2923 Returns the cancelled package this package was changed from, if any.
2929 return '' unless $self->change_pkgnum;
2930 qsearchs('cust_pkg', { 'pkgnum' => $self->change_pkgnum } );
2933 =item change_cust_main
2935 Returns the customter this package was detached to, if any.
2939 sub change_cust_main {
2941 return '' unless $self->change_custnum;
2942 qsearchs('cust_main', { 'custnum' => $self->change_custnum } );
2947 Calls the I<calc_setup> of the FS::part_pkg object associated with this billing
2954 $self->part_pkg->calc_setup($self, @_);
2959 Calls the I<calc_recur> of the FS::part_pkg object associated with this billing
2966 $self->part_pkg->calc_recur($self, @_);
2971 Returns the base setup fee (per unit) of this package, from the package
2976 # minimal version for 3.x; in 4.x this can invoke currency conversion
2980 $self->part_pkg->unit_setup($self);
2985 Calls the I<base_recur> of the FS::part_pkg object associated with this billing
2992 $self->part_pkg->base_recur($self, @_);
2997 Calls the I<calc_remain> of the FS::part_pkg object associated with this
3004 $self->part_pkg->calc_remain($self, @_);
3009 Calls the I<calc_cancel> of the FS::part_pkg object associated with this
3016 $self->part_pkg->calc_cancel($self, @_);
3021 Returns any invoice line items for this package (see L<FS::cust_bill_pkg>).
3027 qsearch( 'cust_bill_pkg', { 'pkgnum' => $self->pkgnum } );
3030 =item cust_pkg_detail [ DETAILTYPE ]
3032 Returns any customer package details for this package (see
3033 L<FS::cust_pkg_detail>).
3035 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
3039 sub cust_pkg_detail {
3041 my %hash = ( 'pkgnum' => $self->pkgnum );
3042 $hash{detailtype} = shift if @_;
3044 'table' => 'cust_pkg_detail',
3045 'hashref' => \%hash,
3046 'order_by' => 'ORDER BY weight, pkgdetailnum',
3050 =item set_cust_pkg_detail DETAILTYPE [ DETAIL, DETAIL, ... ]
3052 Sets customer package details for this package (see L<FS::cust_pkg_detail>).
3054 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
3056 If there is an error, returns the error, otherwise returns false.
3060 sub set_cust_pkg_detail {
3061 my( $self, $detailtype, @details ) = @_;
3063 local $SIG{HUP} = 'IGNORE';
3064 local $SIG{INT} = 'IGNORE';
3065 local $SIG{QUIT} = 'IGNORE';
3066 local $SIG{TERM} = 'IGNORE';
3067 local $SIG{TSTP} = 'IGNORE';
3068 local $SIG{PIPE} = 'IGNORE';
3070 my $oldAutoCommit = $FS::UID::AutoCommit;
3071 local $FS::UID::AutoCommit = 0;
3074 foreach my $current ( $self->cust_pkg_detail($detailtype) ) {
3075 my $error = $current->delete;
3077 $dbh->rollback if $oldAutoCommit;
3078 return "error removing old detail: $error";
3082 foreach my $detail ( @details ) {
3083 my $cust_pkg_detail = new FS::cust_pkg_detail {
3084 'pkgnum' => $self->pkgnum,
3085 'detailtype' => $detailtype,
3086 'detail' => $detail,
3088 my $error = $cust_pkg_detail->insert;
3090 $dbh->rollback if $oldAutoCommit;
3091 return "error adding new detail: $error";
3096 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3103 Returns the customer billing events (see L<FS::cust_event>) for this invoice.
3107 #false laziness w/cust_bill.pm
3111 'table' => 'cust_event',
3112 'addl_from' => 'JOIN part_event USING ( eventpart )',
3113 'hashref' => { 'tablenum' => $self->pkgnum },
3114 'extra_sql' => " AND eventtable = 'cust_pkg' ",
3118 =item num_cust_event
3120 Returns the number of customer billing events (see L<FS::cust_event>) for this package.
3124 #false laziness w/cust_bill.pm
3125 sub num_cust_event {
3127 my $sql = "SELECT COUNT(*) ". $self->_from_cust_event_where;
3128 $self->_prep_ex($sql, $self->pkgnum)->fetchrow_arrayref->[0];
3131 =item exists_cust_event
3133 Returns true if there are customer billing events (see L<FS::cust_event>) for this package. More efficient than using num_cust_event.
3137 sub exists_cust_event {
3139 my $sql = "SELECT 1 ". $self->_from_cust_event_where. " LIMIT 1";
3140 my $row = $self->_prep_ex($sql, $self->pkgnum)->fetchrow_arrayref;
3141 $row ? $row->[0] : '';
3144 sub _from_cust_event_where {
3146 " FROM cust_event JOIN part_event USING ( eventpart ) ".
3147 " WHERE tablenum = ? AND eventtable = 'cust_pkg' ";
3151 my( $self, $sql, @args ) = @_;
3152 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
3153 $sth->execute(@args) or die $sth->errstr. " executing $sql";
3157 =item cust_svc [ SVCPART ] (old, deprecated usage)
3159 =item cust_svc [ OPTION => VALUE ... ] (current usage)
3161 =item cust_svc_unsorted [ OPTION => VALUE ... ]
3163 Returns the services for this package, as FS::cust_svc objects (see
3164 L<FS::cust_svc>). Available options are svcpart and svcdb. If either is
3165 spcififed, returns only the matching services.
3167 As an optimization, use the cust_svc_unsorted version if you are not displaying
3174 cluck "cust_pkg->cust_svc called" if $DEBUG > 2;
3175 $self->_sort_cust_svc( $self->cust_svc_unsorted_arrayref(@_) );
3178 sub cust_svc_unsorted {
3180 @{ $self->cust_svc_unsorted_arrayref(@_) };
3183 sub cust_svc_unsorted_arrayref {
3186 return [] unless $self->num_cust_svc(@_);
3189 if ( @_ && $_[0] =~ /^\d+/ ) {
3190 $opt{svcpart} = shift;
3191 } elsif ( @_ && ref($_[0]) eq 'HASH' ) {
3198 'table' => 'cust_svc',
3199 'hashref' => { 'pkgnum' => $self->pkgnum },
3201 if ( $opt{svcpart} ) {
3202 $search{hashref}->{svcpart} = $opt{'svcpart'};
3204 if ( $opt{'svcdb'} ) {
3205 $search{addl_from} = ' LEFT JOIN part_svc USING ( svcpart ) ';
3206 $search{extra_sql} = ' AND svcdb = '. dbh->quote( $opt{'svcdb'} );
3209 [ qsearch(\%search) ];
3213 =item overlimit [ SVCPART ]
3215 Returns the services for this package which have exceeded their
3216 usage limit as FS::cust_svc objects (see L<FS::cust_svc>). If a svcpart
3217 is specified, return only the matching services.
3223 return () unless $self->num_cust_svc(@_);
3224 grep { $_->overlimit } $self->cust_svc(@_);
3227 =item h_cust_svc END_TIMESTAMP [ START_TIMESTAMP ] [ MODE ]
3229 Returns historical services for this package created before END TIMESTAMP and
3230 (optionally) not cancelled before START_TIMESTAMP, as FS::h_cust_svc objects
3231 (see L<FS::h_cust_svc>). If MODE is 'I' (for 'invoice'), services with the
3232 I<pkg_svc.hidden> flag will be omitted.
3238 warn "$me _h_cust_svc called on $self\n"
3241 my ($end, $start, $mode) = @_;
3242 my @cust_svc = $self->_sort_cust_svc(
3243 [ qsearch( 'h_cust_svc',
3244 { 'pkgnum' => $self->pkgnum, },
3245 FS::h_cust_svc->sql_h_search(@_),
3248 if ( defined($mode) && $mode eq 'I' ) {
3249 my %hidden_svcpart = map { $_->svcpart => $_->hidden } $self->part_svc;
3250 return grep { !$hidden_svcpart{$_->svcpart} } @cust_svc;
3256 sub _sort_cust_svc {
3257 my( $self, $arrayref ) = @_;
3260 sub ($$) { my ($a, $b) = @_; $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] };
3262 my %pkg_svc = map { $_->svcpart => $_ }
3263 qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
3268 my $pkg_svc = $pkg_svc{ $_->svcpart } || '';
3270 $pkg_svc ? $pkg_svc->primary_svc : '',
3271 $pkg_svc ? $pkg_svc->quantity : 0,
3278 =item num_cust_svc [ SVCPART ] (old, deprecated usage)
3280 =item num_cust_svc [ OPTION => VALUE ... ] (current usage)
3282 Returns the number of services for this package. Available options are svcpart
3283 and svcdb. If either is spcififed, returns only the matching services.
3290 return $self->{'_num_cust_svc'}
3292 && exists($self->{'_num_cust_svc'})
3293 && $self->{'_num_cust_svc'} =~ /\d/;
3295 cluck "cust_pkg->num_cust_svc called, _num_cust_svc:".$self->{'_num_cust_svc'}
3299 if ( @_ && $_[0] =~ /^\d+/ ) {
3300 $opt{svcpart} = shift;
3301 } elsif ( @_ && ref($_[0]) eq 'HASH' ) {
3307 my $select = 'SELECT COUNT(*) FROM cust_svc ';
3308 my $where = ' WHERE pkgnum = ? ';
3309 my @param = ($self->pkgnum);
3311 if ( $opt{'svcpart'} ) {
3312 $where .= ' AND svcpart = ? ';
3313 push @param, $opt{'svcpart'};
3315 if ( $opt{'svcdb'} ) {
3316 $select .= ' LEFT JOIN part_svc USING ( svcpart ) ';
3317 $where .= ' AND svcdb = ? ';
3318 push @param, $opt{'svcdb'};
3321 my $sth = dbh->prepare("$select $where") or die dbh->errstr;
3322 $sth->execute(@param) or die $sth->errstr;
3323 $sth->fetchrow_arrayref->[0];
3326 =item available_part_svc
3328 Returns a list of FS::part_svc objects representing services included in this
3329 package but not yet provisioned. Each FS::part_svc object also has an extra
3330 field, I<num_avail>, which specifies the number of available services.
3332 Accepts option I<provision_hold>; if true, only returns part_svc for which the
3333 associated pkg_svc has the provision_hold flag set.
3337 sub available_part_svc {
3341 my $pkg_quantity = $self->quantity || 1;
3343 grep { $_->num_avail > 0 }
3345 my $part_svc = $_->part_svc;
3346 $part_svc->{'Hash'}{'num_avail'} = #evil encapsulation-breaking
3347 $pkg_quantity * $_->quantity - $self->num_cust_svc($_->svcpart);
3349 # more evil encapsulation breakage
3350 if ($part_svc->{'Hash'}{'num_avail'} > 0) {
3351 my @exports = $part_svc->part_export_did;
3352 $part_svc->{'Hash'}{'can_get_dids'} = scalar(@exports);
3357 grep { $opt{'provision_hold'} ? $_->provision_hold : 1 }
3358 $self->part_pkg->pkg_svc;
3361 =item part_svc [ OPTION => VALUE ... ]
3363 Returns a list of FS::part_svc objects representing provisioned and available
3364 services included in this package. Each FS::part_svc object also has the
3365 following extra fields:
3379 (services) - array reference containing the provisioned services, as cust_svc objects
3383 Accepts two options:
3387 =item summarize_size
3389 If true, will omit the extra cust_pkg_svc option for objects where num_cust_svc
3390 is this size or greater.
3392 =item hide_discontinued
3394 If true, will omit looking for services that are no longer avaialble in the
3402 #label -> ($cust_svc->label)[1]
3408 my $pkg_quantity = $self->quantity || 1;
3410 #XXX some sort of sort order besides numeric by svcpart...
3411 my @part_svc = sort { $a->svcpart <=> $b->svcpart } map {
3413 my $part_svc = $pkg_svc->part_svc;
3414 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
3415 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #more evil
3416 $part_svc->{'Hash'}{'num_avail'} =
3417 max( 0, $pkg_quantity * $pkg_svc->quantity - $num_cust_svc );
3418 $part_svc->{'Hash'}{'cust_pkg_svc'} =
3419 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : []
3420 unless exists($opt{summarize_size}) && $opt{summarize_size} > 0
3421 && $num_cust_svc >= $opt{summarize_size};
3422 $part_svc->{'Hash'}{'hidden'} = $pkg_svc->hidden;
3424 } $self->part_pkg->pkg_svc;
3426 unless ( $opt{hide_discontinued} ) {
3428 push @part_svc, map {
3430 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
3431 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #speak no evail
3432 $part_svc->{'Hash'}{'num_avail'} = 0; #0-$num_cust_svc ?
3433 $part_svc->{'Hash'}{'cust_pkg_svc'} =
3434 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : [];
3436 } $self->extra_part_svc;
3443 =item extra_part_svc
3445 Returns a list of FS::part_svc objects corresponding to services in this
3446 package which are still provisioned but not (any longer) available in the
3451 sub extra_part_svc {
3454 my $pkgnum = $self->pkgnum;
3455 #my $pkgpart = $self->pkgpart;
3458 # 'table' => 'part_svc',
3461 # "WHERE 0 = ( SELECT COUNT(*) FROM pkg_svc
3462 # WHERE pkg_svc.svcpart = part_svc.svcpart
3463 # AND pkg_svc.pkgpart = ?
3466 # AND 0 < ( SELECT COUNT(*) FROM cust_svc
3467 # LEFT JOIN cust_pkg USING ( pkgnum )
3468 # WHERE cust_svc.svcpart = part_svc.svcpart
3471 # 'extra_param' => [ [$self->pkgpart=>'int'], [$self->pkgnum=>'int'] ],
3474 #seems to benchmark slightly faster... (or did?)
3476 my @pkgparts = map $_->pkgpart, $self->part_pkg->self_and_svc_linked;
3477 my $pkgparts = join(',', @pkgparts);
3480 #'select' => 'DISTINCT ON (svcpart) part_svc.*',
3481 #MySQL doesn't grok DISINCT ON
3482 'select' => 'DISTINCT part_svc.*',
3483 'table' => 'part_svc',
3485 "LEFT JOIN pkg_svc ON ( pkg_svc.svcpart = part_svc.svcpart
3486 AND pkg_svc.pkgpart IN ($pkgparts)
3489 LEFT JOIN cust_svc ON ( cust_svc.svcpart = part_svc.svcpart )
3490 LEFT JOIN cust_pkg USING ( pkgnum )
3493 'extra_sql' => "WHERE pkgsvcnum IS NULL AND cust_pkg.pkgnum = ? ",
3494 'extra_param' => [ [$self->pkgnum=>'int'] ],
3500 Returns a short status string for this package, currently:
3506 =item not yet billed
3508 =item one-time charge
3523 my $freq = length($self->freq) ? $self->freq : $self->part_pkg->freq;
3525 return 'cancelled' if $self->get('cancel');
3526 return 'on hold' if $self->susp && ! $self->setup;
3527 return 'suspended' if $self->susp;
3528 return 'not yet billed' unless $self->setup;
3529 return 'one-time charge' if $freq =~ /^(0|$)/;
3533 =item ucfirst_status
3535 Returns the status with the first character capitalized.
3539 sub ucfirst_status {
3540 ucfirst(shift->status);
3545 Class method that returns the list of possible status strings for packages
3546 (see L<the status method|/status>). For example:
3548 @statuses = FS::cust_pkg->statuses();
3552 tie my %statuscolor, 'Tie::IxHash',
3553 'on hold' => 'FF00F5', #brighter purple!
3554 'not yet billed' => '009999', #teal? cyan?
3555 'one-time charge' => '0000CC', #blue #'000000',
3556 'active' => '00CC00',
3557 'suspended' => 'FF9900',
3558 'cancelled' => 'FF0000',
3562 my $self = shift; #could be class...
3563 #grep { $_ !~ /^(not yet billed)$/ } #this is a dumb status anyway
3564 # # mayble split btw one-time vs. recur
3575 Returns a hex triplet color string for this package's status.
3581 $statuscolor{$self->status};
3584 =item is_status_delay_cancel
3586 Returns true if part_pkg has option delay_cancel,
3587 cust_pkg status is 'suspended' and expire is set
3588 to cancel package within the next day (or however
3589 many days are set in global config part_pkg-delay_cancel-days.
3591 Accepts option I<part_pkg-delay_cancel-days> which should be
3592 the value of the config setting, to avoid looking it up again.
3594 This is not a real status, this only meant for hacking display
3595 values, because otherwise treating the package as suspended is
3596 really the whole point of the delay_cancel option.
3600 sub is_status_delay_cancel {
3601 my ($self,%opt) = @_;
3602 if ( $self->main_pkgnum and $self->pkglinknum ) {
3603 return $self->main_pkg->is_status_delay_cancel;
3605 return 0 unless $self->part_pkg->option('delay_cancel',1);
3606 return 0 unless $self->status eq 'suspended';
3607 return 0 unless $self->expire;
3608 my $expdays = $opt{'part_pkg-delay_cancel-days'};
3610 my $conf = new FS::Conf;
3611 $expdays = $conf->config('part_pkg-delay_cancel-days') || 1;
3613 my $expsecs = 60*60*24*$expdays;
3614 return 0 unless $self->expire < time + $expsecs;
3620 Returns a label for this package. (Currently "pkgnum: pkg - comment" or
3621 "pkg - comment" depending on user preference).
3627 my $label = $self->part_pkg->pkg_comment( 'nopkgpart' => 1 );
3628 $label = $self->pkgnum. ": $label"
3629 if $FS::CurrentUser::CurrentUser->option('show_pkgnum');
3633 =item pkg_label_long
3635 Returns a long label for this package, adding the primary service's label to
3640 sub pkg_label_long {
3642 my $label = $self->pkg_label;
3643 my $cust_svc = $self->primary_cust_svc;
3644 $label .= ' ('. ($cust_svc->label)[1]. ')' if $cust_svc;
3650 Returns a customer-localized label for this package.
3656 $self->part_pkg->pkg_locale( $self->cust_main->locale );
3659 =item primary_cust_svc
3661 Returns a primary service (as FS::cust_svc object) if one can be identified.
3665 #for labeling purposes - might not 100% match up with part_pkg->svcpart's idea
3667 sub primary_cust_svc {
3670 my @cust_svc = $self->cust_svc;
3672 return '' unless @cust_svc; #no serivces - irrelevant then
3674 return $cust_svc[0] if scalar(@cust_svc) == 1; #always return a single service
3676 # primary service as specified in the package definition
3677 # or exactly one service definition with quantity one
3678 my $svcpart = $self->part_pkg->svcpart;
3679 @cust_svc = grep { $_->svcpart == $svcpart } @cust_svc;
3680 return $cust_svc[0] if scalar(@cust_svc) == 1;
3682 #couldn't identify one thing..
3688 Returns a list of lists, calling the label method for all services
3689 (see L<FS::cust_svc>) of this billing item.
3695 map { [ $_->label ] } $self->cust_svc;
3698 =item h_labels END_TIMESTAMP [ START_TIMESTAMP ] [ MODE ]
3700 Like the labels method, but returns historical information on services that
3701 were active as of END_TIMESTAMP and (optionally) not cancelled before
3702 START_TIMESTAMP. If MODE is 'I' (for 'invoice'), services with the
3703 I<pkg_svc.hidden> flag will be omitted.
3705 Returns a list of lists, calling the label method for all (historical) services
3706 (see L<FS::h_cust_svc>) of this billing item.
3712 warn "$me _h_labels called on $self\n"
3714 map { [ $_->label(@_) ] } $self->h_cust_svc(@_);
3719 Like labels, except returns a simple flat list, and shortens long
3720 (currently >5 or the cust_bill-max_same_services configuration value) lists of
3721 identical services to one line that lists the service label and the number of
3722 individual services rather than individual items.
3727 shift->_labels_short( 'labels', @_ );
3730 =item h_labels_short END_TIMESTAMP [ START_TIMESTAMP ]
3732 Like h_labels, except returns a simple flat list, and shortens long
3733 (currently >5 or the cust_bill-max_same_services configuration value) lists of
3734 identical services to one line that lists the service label and the number of
3735 individual services rather than individual items.
3739 sub h_labels_short {
3740 shift->_labels_short( 'h_labels', @_ );
3744 my( $self, $method ) = ( shift, shift );
3746 warn "$me _labels_short called on $self with $method method\n"
3749 my $conf = new FS::Conf;
3750 my $max_same_services = $conf->config('cust_bill-max_same_services') || 5;
3752 warn "$me _labels_short populating \%labels\n"
3756 #tie %labels, 'Tie::IxHash';
3757 push @{ $labels{$_->[0]} }, $_->[1]
3758 foreach $self->$method(@_);
3760 warn "$me _labels_short populating \@labels\n"
3764 foreach my $label ( keys %labels ) {
3766 my @values = grep { ! $seen{$_}++ } @{ $labels{$label} };
3767 my $num = scalar(@values);
3768 warn "$me _labels_short $num items for $label\n"
3771 if ( $num > $max_same_services ) {
3772 warn "$me _labels_short more than $max_same_services, so summarizing\n"
3774 push @labels, "$label ($num)";
3776 if ( $conf->exists('cust_bill-consolidate_services') ) {
3777 warn "$me _labels_short consolidating services\n"
3779 # push @labels, "$label: ". join(', ', @values);
3781 my $detail = "$label: ";
3782 $detail .= shift(@values). ', '
3784 && ( length($detail.$values[0]) < 78 || $detail eq "$label: " );
3786 push @labels, $detail;
3788 warn "$me _labels_short done consolidating services\n"
3791 warn "$me _labels_short adding service data\n"
3793 push @labels, map { "$label: $_" } @values;
3804 Returns the parent customer object (see L<FS::cust_main>).
3810 cluck 'cust_pkg->cust_main called' if $DEBUG;
3811 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
3816 Returns the balance for this specific package, when using
3817 experimental package balance.
3823 $self->cust_main->balance_pkgnum( $self->pkgnum );
3826 #these subs are in location_Mixin.pm now... unfortunately the POD doesn't mixin
3830 Returns the location object, if any (see L<FS::cust_location>).
3832 =item cust_location_or_main
3834 If this package is associated with a location, returns the locaiton (see
3835 L<FS::cust_location>), otherwise returns the customer (see L<FS::cust_main>).
3837 =item location_label [ OPTION => VALUE ... ]
3839 Returns the label of the location object (see L<FS::cust_location>).
3843 #end of subs in location_Mixin.pm now... unfortunately the POD doesn't mixin
3845 =item tax_locationnum
3847 Returns the foreign key to a L<FS::cust_location> object for calculating
3848 tax on this package, as determined by the C<tax-pkg_address> and
3849 C<tax-ship_address> configuration flags.
3853 sub tax_locationnum {
3855 my $conf = FS::Conf->new;
3856 if ( $conf->exists('tax-pkg_address') ) {
3857 return $self->locationnum;
3859 elsif ( $conf->exists('tax-ship_address') ) {
3860 return $self->cust_main->ship_locationnum;
3863 return $self->cust_main->bill_locationnum;
3869 Returns the L<FS::cust_location> object for tax_locationnum.
3875 my $conf = FS::Conf->new;
3876 if ( $conf->exists('tax-pkg_address') and $self->locationnum ) {
3877 return FS::cust_location->by_key($self->locationnum);
3879 elsif ( $conf->exists('tax-ship_address') ) {
3880 return $self->cust_main->ship_location;
3883 return $self->cust_main->bill_location;
3887 =item seconds_since TIMESTAMP
3889 Returns the number of seconds all accounts (see L<FS::svc_acct>) in this
3890 package have been online since TIMESTAMP, according to the session monitor.
3892 TIMESTAMP is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
3893 L<Time::Local> and L<Date::Parse> for conversion functions.
3898 my($self, $since) = @_;
3901 foreach my $cust_svc (
3902 grep { $_->part_svc->svcdb eq 'svc_acct' } $self->cust_svc
3904 $seconds += $cust_svc->seconds_since($since);
3911 =item seconds_since_sqlradacct TIMESTAMP_START TIMESTAMP_END
3913 Returns the numbers of seconds all accounts (see L<FS::svc_acct>) in this
3914 package have been online between TIMESTAMP_START (inclusive) and TIMESTAMP_END
3917 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
3918 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
3924 sub seconds_since_sqlradacct {
3925 my($self, $start, $end) = @_;
3929 foreach my $cust_svc (
3931 my $part_svc = $_->part_svc;
3932 $part_svc->svcdb eq 'svc_acct'
3933 && scalar($part_svc->part_export_usage);
3936 $seconds += $cust_svc->seconds_since_sqlradacct($start, $end);
3943 =item attribute_since_sqlradacct TIMESTAMP_START TIMESTAMP_END ATTRIBUTE
3945 Returns the sum of the given attribute for all accounts (see L<FS::svc_acct>)
3946 in this package for sessions ending between TIMESTAMP_START (inclusive) and
3950 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
3951 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
3956 sub attribute_since_sqlradacct {
3957 my($self, $start, $end, $attrib) = @_;
3961 foreach my $cust_svc (
3963 my $part_svc = $_->part_svc;
3964 scalar($part_svc->part_export_usage);
3967 $sum += $cust_svc->attribute_since_sqlradacct($start, $end, $attrib);
3979 my( $self, $value ) = @_;
3980 if ( defined($value) ) {
3981 $self->setfield('quantity', $value);
3983 $self->getfield('quantity') || 1;
3986 =item transfer DEST_PKGNUM | DEST_CUST_PKG, [ OPTION => VALUE ... ]
3988 Transfers as many services as possible from this package to another package.
3990 The destination package can be specified by pkgnum by passing an FS::cust_pkg
3991 object. The destination package must already exist.
3993 Services are moved only if the destination allows services with the correct
3994 I<svcpart> (not svcdb), unless the B<change_svcpart> option is set true. Use
3995 this option with caution! No provision is made for export differences
3996 between the old and new service definitions. Probably only should be used
3997 when your exports for all service definitions of a given svcdb are identical.
3998 (attempt a transfer without it first, to move all possible svcpart-matching
4001 Any services that can't be moved remain in the original package.
4003 Returns an error, if there is one; otherwise, returns the number of services
4004 that couldn't be moved.
4009 my ($self, $dest_pkgnum, %opt) = @_;
4015 if (ref ($dest_pkgnum) eq 'FS::cust_pkg') {
4016 $dest = $dest_pkgnum;
4017 $dest_pkgnum = $dest->pkgnum;
4019 $dest = qsearchs('cust_pkg', { pkgnum => $dest_pkgnum });
4022 return ('Package does not exist: '.$dest_pkgnum) unless $dest;
4024 foreach my $pkg_svc ( $dest->part_pkg->pkg_svc ) {
4025 $target{$pkg_svc->svcpart} = $pkg_svc->quantity * ( $dest->quantity || 1 );
4028 foreach my $cust_svc ($dest->cust_svc) {
4029 $target{$cust_svc->svcpart}--;
4032 my %svcpart2svcparts = ();
4033 if ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
4034 warn "change_svcpart option received, creating alternates list\n" if $DEBUG;
4035 foreach my $svcpart ( map { $_->svcpart } $self->cust_svc ) {
4036 next if exists $svcpart2svcparts{$svcpart};
4037 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
4038 $svcpart2svcparts{$svcpart} = [
4040 sort { $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] }
4042 my $pkg_svc = qsearchs( 'pkg_svc', { 'pkgpart' => $dest->pkgpart,
4043 'svcpart' => $_ } );
4045 $pkg_svc ? $pkg_svc->primary_svc : '',
4046 $pkg_svc ? $pkg_svc->quantity : 0,
4050 grep { $_ != $svcpart }
4052 qsearch('part_svc', { 'svcdb' => $part_svc->svcdb } )
4054 warn "alternates for svcpart $svcpart: ".
4055 join(', ', @{$svcpart2svcparts{$svcpart}}). "\n"
4061 foreach my $cust_svc ($self->cust_svc) {
4062 my $svcnum = $cust_svc->svcnum;
4063 if($target{$cust_svc->svcpart} > 0
4064 or $FS::cust_svc::ignore_quantity) { # maybe should be a 'force' option
4065 $target{$cust_svc->svcpart}--;
4066 my $new = new FS::cust_svc { $cust_svc->hash };
4067 $new->pkgnum($dest_pkgnum);
4068 $error = $new->replace($cust_svc);
4069 } elsif ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
4071 warn "looking for alternates for svcpart ". $cust_svc->svcpart. "\n";
4072 warn "alternates to consider: ".
4073 join(', ', @{$svcpart2svcparts{$cust_svc->svcpart}}). "\n";
4075 my @alternate = grep {
4076 warn "considering alternate svcpart $_: ".
4077 "$target{$_} available in new package\n"
4080 } @{$svcpart2svcparts{$cust_svc->svcpart}};
4082 warn "alternate(s) found\n" if $DEBUG;
4083 my $change_svcpart = $alternate[0];
4084 $target{$change_svcpart}--;
4085 my $new = new FS::cust_svc { $cust_svc->hash };
4086 $new->svcpart($change_svcpart);
4087 $new->pkgnum($dest_pkgnum);
4088 $error = $new->replace($cust_svc);
4096 my @label = $cust_svc->label;
4097 return "service $label[1]: $error";
4103 =item grab_svcnums SVCNUM, SVCNUM ...
4105 Change the pkgnum for the provided services to this packages. If there is an
4106 error, returns the error, otherwise returns false.
4114 local $SIG{HUP} = 'IGNORE';
4115 local $SIG{INT} = 'IGNORE';
4116 local $SIG{QUIT} = 'IGNORE';
4117 local $SIG{TERM} = 'IGNORE';
4118 local $SIG{TSTP} = 'IGNORE';
4119 local $SIG{PIPE} = 'IGNORE';
4121 my $oldAutoCommit = $FS::UID::AutoCommit;
4122 local $FS::UID::AutoCommit = 0;
4125 foreach my $svcnum (@svcnum) {
4126 my $cust_svc = qsearchs('cust_svc', { svcnum=>$svcnum } ) or do {
4127 $dbh->rollback if $oldAutoCommit;
4128 return "unknown svcnum $svcnum";
4130 $cust_svc->pkgnum( $self->pkgnum );
4131 my $error = $cust_svc->replace;
4133 $dbh->rollback if $oldAutoCommit;
4138 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4145 This method is deprecated. See the I<depend_jobnum> option to the insert and
4146 order_pkgs methods in FS::cust_main for a better way to defer provisioning.
4153 local $SIG{HUP} = 'IGNORE';
4154 local $SIG{INT} = 'IGNORE';
4155 local $SIG{QUIT} = 'IGNORE';
4156 local $SIG{TERM} = 'IGNORE';
4157 local $SIG{TSTP} = 'IGNORE';
4158 local $SIG{PIPE} = 'IGNORE';
4160 my $oldAutoCommit = $FS::UID::AutoCommit;
4161 local $FS::UID::AutoCommit = 0;
4164 foreach my $cust_svc ( $self->cust_svc ) {
4165 #false laziness w/svc_Common::insert
4166 my $svc_x = $cust_svc->svc_x;
4167 foreach my $part_export ( $cust_svc->part_svc->part_export ) {
4168 my $error = $part_export->export_insert($svc_x);
4170 $dbh->rollback if $oldAutoCommit;
4176 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4181 =item export_pkg_change OLD_CUST_PKG
4183 Calls the "pkg_change" export action for all services attached to this package.
4187 sub export_pkg_change {
4188 my( $self, $old ) = ( shift, shift );
4190 local $SIG{HUP} = 'IGNORE';
4191 local $SIG{INT} = 'IGNORE';
4192 local $SIG{QUIT} = 'IGNORE';
4193 local $SIG{TERM} = 'IGNORE';
4194 local $SIG{TSTP} = 'IGNORE';
4195 local $SIG{PIPE} = 'IGNORE';
4197 my $oldAutoCommit = $FS::UID::AutoCommit;
4198 local $FS::UID::AutoCommit = 0;
4201 foreach my $svc_x ( map $_->svc_x, $self->cust_svc ) {
4202 my $error = $svc_x->export('pkg_change', $self, $old);
4204 $dbh->rollback if $oldAutoCommit;
4209 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4216 Associates this package with a (suspension or cancellation) reason (see
4217 L<FS::cust_pkg_reason>, possibly inserting a new reason on the fly (see
4220 Available options are:
4226 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.
4230 the access_user (see L<FS::access_user>) providing the reason
4238 the action (cancel, susp, adjourn, expire) associated with the reason
4242 If there is an error, returns the error, otherwise returns false.
4247 my ($self, %options) = @_;
4249 my $otaker = $options{reason_otaker} ||
4250 $FS::CurrentUser::CurrentUser->username;
4253 if ( $options{'reason'} =~ /^(\d+)$/ ) {
4257 } elsif ( ref($options{'reason'}) ) {
4259 return 'Enter a new reason (or select an existing one)'
4260 unless $options{'reason'}->{'reason'} !~ /^\s*$/;
4262 my $reason = new FS::reason({
4263 'reason_type' => $options{'reason'}->{'typenum'},
4264 'reason' => $options{'reason'}->{'reason'},
4266 my $error = $reason->insert;
4267 return $error if $error;
4269 $reasonnum = $reason->reasonnum;
4272 return "Unparseable reason: ". $options{'reason'};
4275 my $cust_pkg_reason =
4276 new FS::cust_pkg_reason({ 'pkgnum' => $self->pkgnum,
4277 'reasonnum' => $reasonnum,
4278 'otaker' => $otaker,
4279 'action' => substr(uc($options{'action'}),0,1),
4280 'date' => $options{'date'}
4285 $cust_pkg_reason->insert;
4288 =item insert_discount
4290 Associates this package with a discount (see L<FS::cust_pkg_discount>, possibly
4291 inserting a new discount on the fly (see L<FS::discount>).
4293 Available options are:
4301 If there is an error, returns the error, otherwise returns false.
4305 sub insert_discount {
4306 #my ($self, %options) = @_;
4309 my $cust_pkg_discount = new FS::cust_pkg_discount {
4310 'pkgnum' => $self->pkgnum,
4311 'discountnum' => $self->discountnum,
4313 'end_date' => '', #XXX
4314 #for the create a new discount case
4315 '_type' => $self->discountnum__type,
4316 'amount' => $self->discountnum_amount,
4317 'percent' => $self->discountnum_percent,
4318 'months' => $self->discountnum_months,
4319 'setup' => $self->discountnum_setup,
4320 #'disabled' => $self->discountnum_disabled,
4323 $cust_pkg_discount->insert;
4326 =item set_usage USAGE_VALUE_HASHREF
4328 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
4329 to which they should be set (see L<FS::svc_acct>). Currently seconds,
4330 upbytes, downbytes, and totalbytes are appropriate keys.
4332 All svc_accts which are part of this package have their values reset.
4337 my ($self, $valueref, %opt) = @_;
4339 #only svc_acct can set_usage for now
4340 foreach my $cust_svc ( $self->cust_svc( 'svcdb'=>'svc_acct' ) ) {
4341 my $svc_x = $cust_svc->svc_x;
4342 $svc_x->set_usage($valueref, %opt)
4343 if $svc_x->can("set_usage");
4347 =item recharge USAGE_VALUE_HASHREF
4349 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
4350 to which they should be set (see L<FS::svc_acct>). Currently seconds,
4351 upbytes, downbytes, and totalbytes are appropriate keys.
4353 All svc_accts which are part of this package have their values incremented.
4358 my ($self, $valueref) = @_;
4360 #only svc_acct can set_usage for now
4361 foreach my $cust_svc ( $self->cust_svc( 'svcdb'=>'svc_acct' ) ) {
4362 my $svc_x = $cust_svc->svc_x;
4363 $svc_x->recharge($valueref)
4364 if $svc_x->can("recharge");
4368 =item cust_pkg_discount
4372 sub cust_pkg_discount {
4374 qsearch('cust_pkg_discount', { 'pkgnum' => $self->pkgnum } );
4377 =item cust_pkg_discount_active
4381 sub cust_pkg_discount_active {
4383 grep { $_->status eq 'active' } $self->cust_pkg_discount;
4386 =item cust_pkg_usage
4388 Returns a list of all voice usage counters attached to this package.
4392 sub cust_pkg_usage {
4394 qsearch('cust_pkg_usage', { pkgnum => $self->pkgnum });
4397 =item apply_usage OPTIONS
4399 Takes the following options:
4400 - cdr: a call detail record (L<FS::cdr>)
4401 - rate_detail: the rate determined for this call (L<FS::rate_detail>)
4402 - minutes: the maximum number of minutes to be charged
4404 Finds available usage minutes for a call of this class, and subtracts
4405 up to that many minutes from the usage pool. If the usage pool is empty,
4406 and the C<cdr-minutes_priority> global config option is set, minutes may
4407 be taken from other calls as well. Either way, an allocation record will
4408 be created (L<FS::cdr_cust_pkg_usage>) and this method will return the
4409 number of minutes of usage applied to the call.
4414 my ($self, %opt) = @_;
4415 my $cdr = $opt{cdr};
4416 my $rate_detail = $opt{rate_detail};
4417 my $minutes = $opt{minutes};
4418 my $classnum = $rate_detail->classnum;
4419 my $pkgnum = $self->pkgnum;
4420 my $custnum = $self->custnum;
4422 local $SIG{HUP} = 'IGNORE';
4423 local $SIG{INT} = 'IGNORE';
4424 local $SIG{QUIT} = 'IGNORE';
4425 local $SIG{TERM} = 'IGNORE';
4426 local $SIG{TSTP} = 'IGNORE';
4427 local $SIG{PIPE} = 'IGNORE';
4429 my $oldAutoCommit = $FS::UID::AutoCommit;
4430 local $FS::UID::AutoCommit = 0;
4432 my $order = FS::Conf->new->config('cdr-minutes_priority');
4436 $is_classnum = ' part_pkg_usage_class.classnum = '.$classnum;
4438 $is_classnum = ' part_pkg_usage_class.classnum IS NULL';
4440 my @usage_recs = qsearch({
4441 'table' => 'cust_pkg_usage',
4442 'addl_from' => ' JOIN part_pkg_usage USING (pkgusagepart)'.
4443 ' JOIN cust_pkg USING (pkgnum)'.
4444 ' JOIN part_pkg_usage_class USING (pkgusagepart)',
4445 'select' => 'cust_pkg_usage.*',
4446 'extra_sql' => " WHERE ( cust_pkg.pkgnum = $pkgnum OR ".
4447 " ( cust_pkg.custnum = $custnum AND ".
4448 " part_pkg_usage.shared IS NOT NULL ) ) AND ".
4449 $is_classnum . ' AND '.
4450 " cust_pkg_usage.minutes > 0",
4451 'order_by' => " ORDER BY priority ASC",
4454 my $orig_minutes = $minutes;
4456 while (!$error and $minutes > 0 and @usage_recs) {
4457 my $cust_pkg_usage = shift @usage_recs;
4458 $cust_pkg_usage->select_for_update;
4459 my $cdr_cust_pkg_usage = FS::cdr_cust_pkg_usage->new({
4460 pkgusagenum => $cust_pkg_usage->pkgusagenum,
4461 acctid => $cdr->acctid,
4462 minutes => min($cust_pkg_usage->minutes, $minutes),
4464 $cust_pkg_usage->set('minutes',
4465 $cust_pkg_usage->minutes - $cdr_cust_pkg_usage->minutes
4467 $error = $cust_pkg_usage->replace || $cdr_cust_pkg_usage->insert;
4468 $minutes -= $cdr_cust_pkg_usage->minutes;
4470 if ( $order and $minutes > 0 and !$error ) {
4471 # then try to steal minutes from another call
4473 'table' => 'cdr_cust_pkg_usage',
4474 'addl_from' => ' JOIN cust_pkg_usage USING (pkgusagenum)'.
4475 ' JOIN part_pkg_usage USING (pkgusagepart)'.
4476 ' JOIN cust_pkg USING (pkgnum)'.
4477 ' JOIN part_pkg_usage_class USING (pkgusagepart)'.
4478 ' JOIN cdr USING (acctid)',
4479 'select' => 'cdr_cust_pkg_usage.*',
4480 'extra_sql' => " WHERE cdr.freesidestatus = 'rated' AND ".
4481 " ( cust_pkg.pkgnum = $pkgnum OR ".
4482 " ( cust_pkg.custnum = $custnum AND ".
4483 " part_pkg_usage.shared IS NOT NULL ) ) AND ".
4484 " part_pkg_usage_class.classnum = $classnum",
4485 'order_by' => ' ORDER BY part_pkg_usage.priority ASC',
4487 if ( $order eq 'time' ) {
4488 # find CDRs that are using minutes, but have a later startdate
4490 my $startdate = $cdr->startdate;
4491 if ($startdate !~ /^\d+$/) {
4492 die "bad cdr startdate '$startdate'";
4494 $search{'extra_sql'} .= " AND cdr.startdate > $startdate";
4495 # minimize needless reshuffling
4496 $search{'order_by'} .= ', cdr.startdate DESC';
4498 # XXX may not work correctly with rate_time schedules. Could
4499 # fix this by storing ratedetailnum in cdr_cust_pkg_usage, I
4501 $search{'addl_from'} .=
4502 ' JOIN rate_detail'.
4503 ' ON (cdr.rated_ratedetailnum = rate_detail.ratedetailnum)';
4504 if ( $order eq 'rate_high' ) {
4505 $search{'extra_sql'} .= ' AND rate_detail.min_charge < '.
4506 $rate_detail->min_charge;
4507 $search{'order_by'} .= ', rate_detail.min_charge ASC';
4508 } elsif ( $order eq 'rate_low' ) {
4509 $search{'extra_sql'} .= ' AND rate_detail.min_charge > '.
4510 $rate_detail->min_charge;
4511 $search{'order_by'} .= ', rate_detail.min_charge DESC';
4513 # this should really never happen
4514 die "invalid cdr-minutes_priority value '$order'\n";
4517 my @cdr_usage_recs = qsearch(\%search);
4519 while (!$error and @cdr_usage_recs and $minutes > 0) {
4520 my $cdr_cust_pkg_usage = shift @cdr_usage_recs;
4521 my $cust_pkg_usage = $cdr_cust_pkg_usage->cust_pkg_usage;
4522 my $old_cdr = $cdr_cust_pkg_usage->cdr;
4523 $reproc_cdrs{$old_cdr->acctid} = $old_cdr;
4524 $cdr_cust_pkg_usage->select_for_update;
4525 $old_cdr->select_for_update;
4526 $cust_pkg_usage->select_for_update;
4527 # in case someone else stole the usage from this CDR
4528 # while waiting for the lock...
4529 next if $old_cdr->acctid != $cdr_cust_pkg_usage->acctid;
4530 # steal the usage allocation and flag the old CDR for reprocessing
4531 $cdr_cust_pkg_usage->set('acctid', $cdr->acctid);
4532 # if the allocation is more minutes than we need, adjust it...
4533 my $delta = $cdr_cust_pkg_usage->minutes - $minutes;
4535 $cdr_cust_pkg_usage->set('minutes', $minutes);
4536 $cust_pkg_usage->set('minutes', $cust_pkg_usage->minutes + $delta);
4537 $error = $cust_pkg_usage->replace;
4539 #warn 'CDR '.$cdr->acctid . ' stealing allocation '.$cdr_cust_pkg_usage->cdrusagenum.' from CDR '.$old_cdr->acctid."\n";
4540 $error ||= $cdr_cust_pkg_usage->replace;
4541 # deduct the stolen minutes
4542 $minutes -= $cdr_cust_pkg_usage->minutes;
4544 # after all minute-stealing is done, reset the affected CDRs
4545 foreach (values %reproc_cdrs) {
4546 $error ||= $_->set_status('');
4547 # XXX or should we just call $cdr->rate right here?
4548 # it's not like we can create a loop this way, since the min_charge
4549 # or call time has to go monotonically in one direction.
4550 # we COULD get some very deep recursions going, though...
4552 } # if $order and $minutes
4555 die "error applying included minutes\npkgnum ".$self->pkgnum.", class $classnum, acctid ".$cdr->acctid."\n$error\n"
4557 $dbh->commit if $oldAutoCommit;
4558 return $orig_minutes - $minutes;
4562 =item supplemental_pkgs
4564 Returns a list of all packages supplemental to this one.
4568 sub supplemental_pkgs {
4570 qsearch('cust_pkg', { 'main_pkgnum' => $self->pkgnum });
4575 Returns the package that this one is supplemental to, if any.
4581 if ( $self->main_pkgnum ) {
4582 return FS::cust_pkg->by_key($self->main_pkgnum);
4589 =head1 CLASS METHODS
4595 Returns an SQL expression identifying recurring packages.
4599 sub recurring_sql { "
4600 '0' != ( select freq from part_pkg
4601 where cust_pkg.pkgpart = part_pkg.pkgpart )
4606 Returns an SQL expression identifying one-time packages.
4611 '0' = ( select freq from part_pkg
4612 where cust_pkg.pkgpart = part_pkg.pkgpart )
4617 Returns an SQL expression identifying ordered packages (recurring packages not
4623 $_[0]->recurring_sql. " AND ". $_[0]->not_yet_billed_sql;
4628 Returns an SQL expression identifying active packages.
4633 $_[0]->recurring_sql. "
4634 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
4635 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4636 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
4639 =item not_yet_billed_sql
4641 Returns an SQL expression identifying packages which have not yet been billed.
4645 sub not_yet_billed_sql { "
4646 ( cust_pkg.setup IS NULL OR cust_pkg.setup = 0 )
4647 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4648 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
4653 Returns an SQL expression identifying inactive packages (one-time packages
4654 that are otherwise unsuspended/uncancelled).
4658 sub inactive_sql { "
4659 ". $_[0]->onetime_sql(). "
4660 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
4661 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4662 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
4667 Returns an SQL expression identifying on-hold packages.
4672 #$_[0]->recurring_sql(). ' AND '.
4674 ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4675 AND cust_pkg.susp IS NOT NULL AND cust_pkg.susp != 0
4676 AND ( cust_pkg.setup IS NULL OR cust_pkg.setup = 0 )
4683 Returns an SQL expression identifying suspended packages.
4687 sub suspended_sql { susp_sql(@_); }
4689 #$_[0]->recurring_sql(). ' AND '.
4691 ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4692 AND cust_pkg.susp IS NOT NULL AND cust_pkg.susp != 0
4693 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
4700 Returns an SQL exprression identifying cancelled packages.
4704 sub cancelled_sql { cancel_sql(@_); }
4706 #$_[0]->recurring_sql(). ' AND '.
4707 "cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0";
4712 Returns an SQL expression to give the package status as a string.
4718 WHEN cust_pkg.cancel IS NOT NULL THEN 'cancelled'
4719 WHEN ( cust_pkg.susp IS NOT NULL AND cust_pkg.setup IS NULL ) THEN 'on hold'
4720 WHEN cust_pkg.susp IS NOT NULL THEN 'suspended'
4721 WHEN cust_pkg.setup IS NULL THEN 'not yet billed'
4722 WHEN ".onetime_sql()." THEN 'one-time charge'
4727 =item search HASHREF
4731 Returns a qsearch hash expression to search for parameters specified in HASHREF.
4732 Valid parameters are
4740 on hold, active, inactive (or one-time charge), suspended, canceled (or cancelled)
4744 Equivalent to "status", except that "canceled"/"cancelled" will exclude
4745 packages that were changed into a new package with the same pkgpart (i.e.
4746 location or quantity changes).
4750 boolean selects custom packages
4756 pkgpart or arrayref or hashref of pkgparts
4760 arrayref of beginning and ending epoch date
4764 arrayref of beginning and ending epoch date
4768 arrayref of beginning and ending epoch date
4772 arrayref of beginning and ending epoch date
4776 arrayref of beginning and ending epoch date
4780 arrayref of beginning and ending epoch date
4784 arrayref of beginning and ending epoch date
4788 pkgnum or APKG_pkgnum
4792 a value suited to passing to FS::UI::Web::cust_header
4796 specifies the user for agent virtualization
4800 boolean; if true, returns only packages with more than 0 FCC phone lines.
4802 =item state, country
4804 Limit to packages with a service location in the specified state and country.
4805 For FCC 477 reporting, mostly.
4809 Limit to packages whose service locations are the same as the customer's
4810 default service location.
4812 =item location_nocust
4814 Limit to packages whose service locations are not the customer's default
4817 =item location_census
4819 Limit to packages whose service locations have census tracts.
4821 =item location_nocensus
4823 Limit to packages whose service locations do not have a census tract.
4825 =item location_geocode
4827 Limit to packages whose locations have geocodes.
4829 =item location_geocode
4831 Limit to packages whose locations do not have geocodes.
4835 Limit to packages associated with a svc_broadband, associated with a sector,
4836 associated with this towernum (or any of these, if it's an arrayref) (or NO
4837 towernum, if it's zero). This is an extreme niche case.
4839 =item 477part, 477rownum, date
4841 Limit to packages included in a specific row of one of the FCC 477 reports.
4842 '477part' is the section name (see L<FS::Report::FCC_477> methods), 'date'
4843 is the report as-of date (completely unrelated to the package setup/bill/
4844 other date fields), and '477rownum' is the row number of the report starting
4845 with zero. Row numbers have no inherent meaning, so this is useful only
4846 for explaining a 477 report you've already run.
4853 my ($class, $params) = @_;
4860 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
4862 "cust_main.agentnum = $1";
4869 if ( $params->{'cust_status'} =~ /^([a-z]+)$/ ) {
4870 push @where, FS::cust_main->cust_status_sql . " = '$1' ";
4874 # parse customer sales person
4877 if ( $params->{'cust_main_salesnum'} =~ /^(\d+)$/ ) {
4878 push @where, ($1 > 0) ? "cust_main.salesnum = $1"
4879 : 'cust_main.salesnum IS NULL';
4884 # parse sales person
4887 if ( $params->{'salesnum'} =~ /^(\d+)$/ ) {
4888 push @where, ($1 > 0) ? "cust_pkg.salesnum = $1"
4889 : 'cust_pkg.salesnum IS NULL';
4896 if ( $params->{'custnum'} =~ /^(\d+)$/ and $1 ) {
4898 "cust_pkg.custnum = $1";
4905 if ( $params->{'pkgbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
4907 "cust_pkg.pkgbatch = '$1'";
4914 if ( $params->{'magic'} eq 'active'
4915 || $params->{'status'} eq 'active' ) {
4917 push @where, FS::cust_pkg->active_sql();
4919 } elsif ( $params->{'magic'} =~ /^not[ _]yet[ _]billed$/
4920 || $params->{'status'} =~ /^not[ _]yet[ _]billed$/ ) {
4922 push @where, FS::cust_pkg->not_yet_billed_sql();
4924 } elsif ( $params->{'magic'} =~ /^(one-time charge|inactive)/
4925 || $params->{'status'} =~ /^(one-time charge|inactive)/ ) {
4927 push @where, FS::cust_pkg->inactive_sql();
4929 } elsif ( $params->{'magic'} =~ /^on[ _]hold$/
4930 || $params->{'status'} =~ /^on[ _]hold$/ ) {
4932 push @where, FS::cust_pkg->on_hold_sql();
4935 } elsif ( $params->{'magic'} eq 'suspended'
4936 || $params->{'status'} eq 'suspended' ) {
4938 push @where, FS::cust_pkg->suspended_sql();
4940 } elsif ( $params->{'magic'} =~ /^cancell?ed$/
4941 || $params->{'status'} =~ /^cancell?ed$/ ) {
4943 push @where, FS::cust_pkg->cancelled_sql();
4947 ### special case: "magic" is used in detail links from browse/part_pkg,
4948 # where "cancelled" has the restriction "and not replaced with a package
4949 # of the same pkgpart". Be consistent with that.
4952 if ( $params->{'magic'} =~ /^cancell?ed$/ ) {
4953 my $new_pkgpart = "SELECT pkgpart FROM cust_pkg AS cust_pkg_next ".
4954 "WHERE cust_pkg_next.change_pkgnum = cust_pkg.pkgnum";
4955 # ...may not exist, if this was just canceled and not changed; in that
4956 # case give it a "new pkgpart" that never equals the old pkgpart
4957 push @where, "COALESCE(($new_pkgpart), 0) != cust_pkg.pkgpart";
4961 # parse package class
4964 if ( exists($params->{'classnum'}) ) {
4967 if ( ref($params->{'classnum'}) ) {
4969 if ( ref($params->{'classnum'}) eq 'HASH' ) {
4970 @classnum = grep $params->{'classnum'}{$_}, keys %{ $params->{'classnum'} };
4971 } elsif ( ref($params->{'classnum'}) eq 'ARRAY' ) {
4972 @classnum = @{ $params->{'classnum'} };
4974 die 'unhandled classnum ref '. $params->{'classnum'};
4978 } elsif ( $params->{'classnum'} =~ /^(\d*)$/ && $1 ne '0' ) {
4985 my @nums = grep $_, @classnum;
4986 push @c_where, 'part_pkg.classnum IN ('. join(',',@nums). ')' if @nums;
4987 my $null = scalar( grep { $_ eq '' } @classnum );
4988 push @c_where, 'part_pkg.classnum IS NULL' if $null;
4990 if ( scalar(@c_where) == 1 ) {
4991 push @where, @c_where;
4992 } elsif ( @c_where ) {
4993 push @where, ' ( '. join(' OR ', @c_where). ' ) ';
5002 # parse refnum (advertising source)
5005 if ( exists($params->{'refnum'}) ) {
5007 if (ref $params->{'refnum'}) {
5008 @refnum = @{ $params->{'refnum'} };
5010 @refnum = ( $params->{'refnum'} );
5012 my $in = join(',', grep /^\d+$/, @refnum);
5013 push @where, "refnum IN($in)" if length $in;
5017 # parse package report options
5020 my @report_option = ();
5021 if ( exists($params->{'report_option'}) ) {
5022 if ( ref($params->{'report_option'}) eq 'ARRAY' ) {
5023 @report_option = @{ $params->{'report_option'} };
5024 } elsif ( $params->{'report_option'} =~ /^([,\d]*)$/ ) {
5025 @report_option = split(',', $1);
5030 if (@report_option) {
5031 # this will result in the empty set for the dangling comma case as it should
5033 map{ "0 < ( SELECT count(*) FROM part_pkg_option
5034 WHERE part_pkg_option.pkgpart = part_pkg.pkgpart
5035 AND optionname = 'report_option_$_'
5036 AND optionvalue = '1' )"
5040 foreach my $any ( grep /^report_option_any/, keys %$params ) {
5042 my @report_option_any = ();
5043 if ( ref($params->{$any}) eq 'ARRAY' ) {
5044 @report_option_any = @{ $params->{$any} };
5045 } elsif ( $params->{$any} =~ /^([,\d]*)$/ ) {
5046 @report_option_any = split(',', $1);
5049 if (@report_option_any) {
5050 # this will result in the empty set for the dangling comma case as it should
5051 push @where, ' ( '. join(' OR ',
5052 map{ "0 < ( SELECT count(*) FROM part_pkg_option
5053 WHERE part_pkg_option.pkgpart = part_pkg.pkgpart
5054 AND optionname = 'report_option_$_'
5055 AND optionvalue = '1' )"
5056 } @report_option_any
5066 push @where, "part_pkg.custom = 'Y'" if $params->{custom};
5072 push @where, "(part_pkg.fcc_ds0s > 0 OR pkg_class.fcc_ds0s > 0)"
5073 if $params->{fcc_line};
5079 if ( exists($params->{'censustract'}) ) {
5080 $params->{'censustract'} =~ /^([.\d]*)$/;
5081 my $censustract = "cust_location.censustract = '$1'";
5082 $censustract .= ' OR cust_location.censustract is NULL' unless $1;
5083 push @where, "( $censustract )";
5087 # parse censustract2
5089 if ( exists($params->{'censustract2'})
5090 && $params->{'censustract2'} =~ /^(\d*)$/
5094 push @where, "cust_location.censustract LIKE '$1%'";
5097 "( cust_location.censustract = '' OR cust_location.censustract IS NULL )";
5102 # parse country/state/zip
5104 for (qw(state country)) { # parsing rules are the same for these
5105 if ( exists($params->{$_})
5106 && uc($params->{$_}) =~ /^([A-Z]{2})$/ )
5108 # XXX post-2.3 only--before that, state/country may be in cust_main
5109 push @where, "cust_location.$_ = '$1'";
5112 if ( exists($params->{zip}) ) {
5113 push @where, "cust_location.zip = " . dbh->quote($params->{zip});
5119 if ( $params->{location_cust} xor $params->{location_nocust} ) {
5120 my $op = $params->{location_cust} ? '=' : '!=';
5121 push @where, "cust_location.locationnum $op cust_main.ship_locationnum";
5123 if ( $params->{location_census} xor $params->{location_nocensus} ) {
5124 my $op = $params->{location_census} ? "IS NOT NULL" : "IS NULL";
5125 push @where, "cust_location.censustract $op";
5127 if ( $params->{location_geocode} xor $params->{location_nogeocode} ) {
5128 my $op = $params->{location_geocode} ? "IS NOT NULL" : "IS NULL";
5129 push @where, "cust_location.geocode $op";
5136 if ( ref($params->{'pkgpart'}) ) {
5139 if ( ref($params->{'pkgpart'}) eq 'HASH' ) {
5140 @pkgpart = grep $params->{'pkgpart'}{$_}, keys %{ $params->{'pkgpart'} };
5141 } elsif ( ref($params->{'pkgpart'}) eq 'ARRAY' ) {
5142 @pkgpart = @{ $params->{'pkgpart'} };
5144 die 'unhandled pkgpart ref '. $params->{'pkgpart'};
5147 @pkgpart = grep /^(\d+)$/, @pkgpart;
5149 push @where, 'pkgpart IN ('. join(',', @pkgpart). ')' if scalar(@pkgpart);
5151 } elsif ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
5152 push @where, "pkgpart = $1";
5161 #false laziness w/report_cust_pkg.html
5164 'one-time charge' => { 'last_bill'=>1, 'bill'=>1, 'adjourn'=>1, 'susp'=>1, 'expire'=>1, 'cancel'=>1, },
5165 'active' => { 'susp'=>1, 'cancel'=>1 },
5166 'suspended' => { 'cancel' => 1 },
5171 if( exists($params->{'active'} ) ) {
5172 # This overrides all the other date-related fields, and includes packages
5173 # that were active at some time during the interval. It excludes:
5174 # - packages that were set up after the end of the interval
5175 # - packages that were canceled before the start of the interval
5176 # - packages that were suspended before the start of the interval
5177 # and are still suspended now
5178 my($beginning, $ending) = @{$params->{'active'}};
5180 "cust_pkg.setup IS NOT NULL",
5181 "cust_pkg.setup <= $ending",
5182 "(cust_pkg.cancel IS NULL OR cust_pkg.cancel >= $beginning )",
5183 "(cust_pkg.susp IS NULL OR cust_pkg.susp >= $beginning )",
5184 "NOT (".FS::cust_pkg->onetime_sql . ")";
5187 my $exclude_change_from = 0;
5188 my $exclude_change_to = 0;
5190 foreach my $field (qw( setup last_bill bill adjourn susp expire contract_end change_date cancel )) {
5192 next unless exists($params->{$field});
5194 my($beginning, $ending) = @{$params->{$field}};
5196 next if $beginning == 0 && $ending == 4294967295;
5199 "cust_pkg.$field IS NOT NULL",
5200 "cust_pkg.$field >= $beginning",
5201 "cust_pkg.$field <= $ending";
5203 $orderby ||= "ORDER BY cust_pkg.$field";
5205 if ( $field eq 'setup' ) {
5206 $exclude_change_from = 1;
5207 } elsif ( $field eq 'cancel' ) {
5208 $exclude_change_to = 1;
5209 } elsif ( $field eq 'change_date' ) {
5210 # if we are given setup and change_date ranges, and the setup date
5211 # falls in _both_ ranges, then include the package whether it was
5213 $exclude_change_from = 0;
5217 if ($exclude_change_from) {
5218 push @where, "change_pkgnum IS NULL";
5220 if ($exclude_change_to) {
5221 # a join might be more efficient here
5222 push @where, "NOT EXISTS(
5223 SELECT 1 FROM cust_pkg AS changed_to_pkg
5224 WHERE cust_pkg.pkgnum = changed_to_pkg.change_pkgnum
5229 $orderby ||= 'ORDER BY bill';
5232 # parse magic, legacy, etc.
5235 if ( $params->{'magic'} &&
5236 $params->{'magic'} =~ /^(active|inactive|suspended|cancell?ed)$/
5239 $orderby = 'ORDER BY pkgnum';
5241 if ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
5242 push @where, "pkgpart = $1";
5245 } elsif ( $params->{'query'} eq 'pkgnum' ) {
5247 $orderby = 'ORDER BY pkgnum';
5249 } elsif ( $params->{'query'} eq 'APKG_pkgnum' ) {
5251 $orderby = 'ORDER BY pkgnum';
5254 SELECT count(*) FROM pkg_svc
5255 WHERE pkg_svc.pkgpart = cust_pkg.pkgpart
5256 AND pkg_svc.quantity > ( SELECT count(*) FROM cust_svc
5257 WHERE cust_svc.pkgnum = cust_pkg.pkgnum
5258 AND cust_svc.svcpart = pkg_svc.svcpart
5265 # parse the extremely weird 'towernum' param
5268 if ($params->{towernum}) {
5269 my $towernum = $params->{towernum};
5270 $towernum = [ $towernum ] if !ref($towernum);
5271 my $in = join(',', grep /^\d+$/, @$towernum);
5273 # inefficient, but this is an obscure feature
5274 eval "use FS::Report::Table";
5275 FS::Report::Table->_init_tower_pkg_cache; # probably does nothing
5276 push @where, "EXISTS(
5277 SELECT 1 FROM tower_pkg_cache
5278 WHERE tower_pkg_cache.pkgnum = cust_pkg.pkgnum
5279 AND tower_pkg_cache.towernum IN ($in)
5285 # parse the 477 report drill-down options
5288 if ($params->{'477part'} =~ /^([a-z]+)$/) {
5290 my ($date, $rownum, $agentnum);
5291 if ($params->{'date'} =~ /^(\d+)$/) {
5294 if ($params->{'477rownum'} =~ /^(\d+)$/) {
5297 if ($params->{'agentnum'} =~ /^(\d+)$/) {
5300 if ($date and defined($rownum)) {
5301 my $report = FS::Report::FCC_477->report($section,
5303 'agentnum' => $agentnum,
5306 my $pkgnums = $report->{detail}->[$rownum]
5307 or die "row $rownum is past the end of the report";
5308 # '0' so that if there are no pkgnums (empty string) it will create
5309 # a valid query that returns nothing
5310 warn "PKGNUMS:\n$pkgnums\n\n"; # XXX debug
5312 # and this overrides everything
5313 @where = ( "cust_pkg.pkgnum IN($pkgnums)" );
5314 } # else we're missing some params, ignore the whole business
5318 # setup queries, links, subs, etc. for the search
5321 # here is the agent virtualization
5322 if ($params->{CurrentUser}) {
5324 qsearchs('access_user', { username => $params->{CurrentUser} });
5327 push @where, $access_user->agentnums_sql('table'=>'cust_main');
5332 push @where, $FS::CurrentUser::CurrentUser->agentnums_sql('table'=>'cust_main');
5335 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
5337 my $addl_from = 'LEFT JOIN part_pkg USING ( pkgpart ) '.
5338 'LEFT JOIN pkg_class ON ( part_pkg.classnum = pkg_class.classnum ) '.
5339 'LEFT JOIN cust_location USING ( locationnum ) '.
5340 FS::UI::Web::join_cust_main('cust_pkg', 'cust_pkg');
5344 if ( $params->{'select_zip5'} ) {
5345 my $zip = 'cust_location.zip';
5347 $select = "DISTINCT substr($zip,1,5) as zip";
5348 $orderby = "ORDER BY substr($zip,1,5)";
5349 $count_query = "SELECT COUNT( DISTINCT substr($zip,1,5) )";
5351 $select = join(', ',
5353 ( map "part_pkg.$_", qw( pkg freq ) ),
5354 'pkg_class.classname',
5355 'cust_main.custnum AS cust_main_custnum',
5356 FS::UI::Web::cust_sql_fields(
5357 $params->{'cust_fields'}
5360 $count_query = 'SELECT COUNT(*)';
5363 $count_query .= " FROM cust_pkg $addl_from $extra_sql";
5366 'table' => 'cust_pkg',
5368 'select' => $select,
5369 'extra_sql' => $extra_sql,
5370 'order_by' => $orderby,
5371 'addl_from' => $addl_from,
5372 'count_query' => $count_query,
5379 Returns a list of two package counts. The first is a count of packages
5380 based on the supplied criteria and the second is the count of residential
5381 packages with those same criteria. Criteria are specified as in the search
5387 my ($class, $params) = @_;
5389 my $sql_query = $class->search( $params );
5391 my $count_sql = delete($sql_query->{'count_query'});
5392 $count_sql =~ s/ FROM/,count(CASE WHEN cust_main.company IS NULL OR cust_main.company = '' THEN 1 END) FROM/
5393 or die "couldn't parse count_sql";
5395 my $count_sth = dbh->prepare($count_sql)
5396 or die "Error preparing $count_sql: ". dbh->errstr;
5398 or die "Error executing $count_sql: ". $count_sth->errstr;
5399 my $count_arrayref = $count_sth->fetchrow_arrayref;
5401 return ( @$count_arrayref );
5405 =item tax_locationnum_sql
5407 Returns an SQL expression for the tax location for a package, based
5408 on the settings of 'tax-pkg_address' and 'tax-ship_address'.
5412 sub tax_locationnum_sql {
5413 my $conf = FS::Conf->new;
5414 if ( $conf->exists('tax-pkg_address') ) {
5415 'cust_pkg.locationnum';
5417 elsif ( $conf->exists('tax-ship_address') ) {
5418 'cust_main.ship_locationnum';
5421 'cust_main.bill_locationnum';
5427 Returns a list: the first item is an SQL fragment identifying matching
5428 packages/customers via location (taking into account shipping and package
5429 address taxation, if enabled), and subsequent items are the parameters to
5430 substitute for the placeholders in that fragment.
5435 my($class, %opt) = @_;
5436 my $ornull = $opt{'ornull'};
5438 my $conf = new FS::Conf;
5440 # '?' placeholders in _location_sql_where
5441 my $x = $ornull ? 3 : 2;
5452 if ( $conf->exists('tax-ship_address') ) {
5455 ( ( ship_last IS NULL OR ship_last = '' )
5456 AND ". _location_sql_where('cust_main', '', $ornull ). "
5458 OR ( ship_last IS NOT NULL AND ship_last != ''
5459 AND ". _location_sql_where('cust_main', 'ship_', $ornull ). "
5462 # AND payby != 'COMP'
5464 @main_param = ( @bill_param, @bill_param );
5468 $main_where = _location_sql_where('cust_main'); # AND payby != 'COMP'
5469 @main_param = @bill_param;
5475 if ( $conf->exists('tax-pkg_address') ) {
5477 my $loc_where = _location_sql_where( 'cust_location', '', $ornull );
5480 ( cust_pkg.locationnum IS NULL AND $main_where )
5481 OR ( cust_pkg.locationnum IS NOT NULL AND $loc_where )
5484 @param = ( @main_param, @bill_param );
5488 $where = $main_where;
5489 @param = @main_param;
5497 #subroutine, helper for location_sql
5498 sub _location_sql_where {
5500 my $prefix = @_ ? shift : '';
5501 my $ornull = @_ ? shift : '';
5503 # $ornull = $ornull ? " OR ( ? IS NULL AND $table.${prefix}county IS NULL ) " : '';
5505 $ornull = $ornull ? ' OR ? IS NULL ' : '';
5507 my $or_empty_city = " OR ( ? = '' AND $table.${prefix}city IS NULL )";
5508 my $or_empty_county = " OR ( ? = '' AND $table.${prefix}county IS NULL )";
5509 my $or_empty_state = " OR ( ? = '' AND $table.${prefix}state IS NULL )";
5511 my $text = (driver_name =~ /^mysql/i) ? 'char' : 'text';
5513 # ( $table.${prefix}city = ? $or_empty_city $ornull )
5515 ( $table.district = ? OR ? = '' OR CAST(? AS $text) IS NULL )
5516 AND ( $table.${prefix}city = ? OR ? = '' OR CAST(? AS $text) IS NULL )
5517 AND ( $table.${prefix}county = ? $or_empty_county $ornull )
5518 AND ( $table.${prefix}state = ? $or_empty_state $ornull )
5519 AND $table.${prefix}country = ?
5524 my( $self, $what ) = @_;
5526 my $what_show_zero = $what. '_show_zero';
5527 length($self->$what_show_zero())
5528 ? ($self->$what_show_zero() eq 'Y')
5529 : $self->part_pkg->$what_show_zero();
5536 =item order CUSTNUM, PKGPARTS_ARYREF, [ REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF [ REFNUM ] ] ]
5538 Bulk cancel + order subroutine. Perhaps slightly deprecated, only used by the
5539 bulk cancel+order in the web UI and nowhere else (edit/process/cust_pkg.cgi)
5541 CUSTNUM is a customer (see L<FS::cust_main>)
5543 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
5544 L<FS::part_pkg>) to order for this customer. Duplicates are of course
5547 REMOVE_PKGNUMS is an optional list of pkgnums specifying the billing items to
5548 remove for this customer. The services (see L<FS::cust_svc>) are moved to the
5549 new billing items. An error is returned if this is not possible (see
5550 L<FS::pkg_svc>). An empty arrayref is equivalent to not specifying this
5553 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
5554 newly-created cust_pkg objects.
5556 REFNUM, if specified, will specify the FS::pkg_referral record to be created
5557 and inserted. Multiple FS::pkg_referral records can be created by
5558 setting I<refnum> to an array reference of refnums or a hash reference with
5559 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
5560 record will be created corresponding to cust_main.refnum.
5565 my ($custnum, $pkgparts, $remove_pkgnum, $return_cust_pkg, $refnum) = @_;
5567 my $conf = new FS::Conf;
5569 # Transactionize this whole mess
5570 local $SIG{HUP} = 'IGNORE';
5571 local $SIG{INT} = 'IGNORE';
5572 local $SIG{QUIT} = 'IGNORE';
5573 local $SIG{TERM} = 'IGNORE';
5574 local $SIG{TSTP} = 'IGNORE';
5575 local $SIG{PIPE} = 'IGNORE';
5577 my $oldAutoCommit = $FS::UID::AutoCommit;
5578 local $FS::UID::AutoCommit = 0;
5582 # my $cust_main = qsearchs('cust_main', { custnum => $custnum });
5583 # return "Customer not found: $custnum" unless $cust_main;
5585 warn "$me order: pkgnums to remove: ". join(',', @$remove_pkgnum). "\n"
5588 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
5591 my $change = scalar(@old_cust_pkg) != 0;
5594 if ( scalar(@old_cust_pkg) == 1 && scalar(@$pkgparts) == 1 ) {
5596 warn "$me order: changing pkgnum ". $old_cust_pkg[0]->pkgnum.
5597 " to pkgpart ". $pkgparts->[0]. "\n"
5600 my $err_or_cust_pkg =
5601 $old_cust_pkg[0]->change( 'pkgpart' => $pkgparts->[0],
5602 'refnum' => $refnum,
5605 unless (ref($err_or_cust_pkg)) {
5606 $dbh->rollback if $oldAutoCommit;
5607 return $err_or_cust_pkg;
5610 push @$return_cust_pkg, $err_or_cust_pkg;
5611 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5616 # Create the new packages.
5617 foreach my $pkgpart (@$pkgparts) {
5619 warn "$me order: inserting pkgpart $pkgpart\n" if $DEBUG;
5621 my $cust_pkg = new FS::cust_pkg { custnum => $custnum,
5622 pkgpart => $pkgpart,
5626 $error = $cust_pkg->insert( 'change' => $change );
5627 push @$return_cust_pkg, $cust_pkg;
5629 foreach my $link ($cust_pkg->part_pkg->supp_part_pkg_link) {
5630 my $supp_pkg = FS::cust_pkg->new({
5631 custnum => $custnum,
5632 pkgpart => $link->dst_pkgpart,
5634 main_pkgnum => $cust_pkg->pkgnum,
5637 $error ||= $supp_pkg->insert( 'change' => $change );
5638 push @$return_cust_pkg, $supp_pkg;
5642 $dbh->rollback if $oldAutoCommit;
5647 # $return_cust_pkg now contains refs to all of the newly
5650 # Transfer services and cancel old packages.
5651 foreach my $old_pkg (@old_cust_pkg) {
5653 warn "$me order: transferring services from pkgnum ". $old_pkg->pkgnum. "\n"
5656 foreach my $new_pkg (@$return_cust_pkg) {
5657 $error = $old_pkg->transfer($new_pkg);
5658 if ($error and $error == 0) {
5659 # $old_pkg->transfer failed.
5660 $dbh->rollback if $oldAutoCommit;
5665 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
5666 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
5667 foreach my $new_pkg (@$return_cust_pkg) {
5668 $error = $old_pkg->transfer($new_pkg, 'change_svcpart'=>1 );
5669 if ($error and $error == 0) {
5670 # $old_pkg->transfer failed.
5671 $dbh->rollback if $oldAutoCommit;
5678 # Transfers were successful, but we went through all of the
5679 # new packages and still had services left on the old package.
5680 # We can't cancel the package under the circumstances, so abort.
5681 $dbh->rollback if $oldAutoCommit;
5682 return "Unable to transfer all services from package ".$old_pkg->pkgnum;
5684 $error = $old_pkg->cancel( quiet=>1, 'no_delay_cancel'=>1 );
5690 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5694 =item bulk_change PKGPARTS_ARYREF, REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF ]
5696 A bulk change method to change packages for multiple customers.
5698 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
5699 L<FS::part_pkg>) to order for each customer. Duplicates are of course
5702 REMOVE_PKGNUMS is an list of pkgnums specifying the billing items to
5703 replace. The services (see L<FS::cust_svc>) are moved to the
5704 new billing items. An error is returned if this is not possible (see
5707 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
5708 newly-created cust_pkg objects.
5713 my ($pkgparts, $remove_pkgnum, $return_cust_pkg) = @_;
5715 # Transactionize this whole mess
5716 local $SIG{HUP} = 'IGNORE';
5717 local $SIG{INT} = 'IGNORE';
5718 local $SIG{QUIT} = 'IGNORE';
5719 local $SIG{TERM} = 'IGNORE';
5720 local $SIG{TSTP} = 'IGNORE';
5721 local $SIG{PIPE} = 'IGNORE';
5723 my $oldAutoCommit = $FS::UID::AutoCommit;
5724 local $FS::UID::AutoCommit = 0;
5728 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
5731 while(scalar(@old_cust_pkg)) {
5733 my $custnum = $old_cust_pkg[0]->custnum;
5734 my (@remove) = map { $_->pkgnum }
5735 grep { $_->custnum == $custnum } @old_cust_pkg;
5736 @old_cust_pkg = grep { $_->custnum != $custnum } @old_cust_pkg;
5738 my $error = order $custnum, $pkgparts, \@remove, \@return;
5740 push @errors, $error
5742 push @$return_cust_pkg, @return;
5745 if (scalar(@errors)) {
5746 $dbh->rollback if $oldAutoCommit;
5747 return join(' / ', @errors);
5750 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5754 =item forward_emails
5756 Returns a hash of svcnums and corresponding email addresses
5757 for svc_acct services that can be used as source or dest
5758 for svc_forward services provisioned in this package.
5760 Accepts options I<svc_forward> OR I<svcnum> for a svc_forward
5761 service; if included, will ensure the current values of the
5762 specified service are included in the list, even if for some
5763 other reason they wouldn't be. If called as a class method
5764 with a specified service, returns only these current values.
5766 Caution: does not actually check if svc_forward services are
5767 available to be provisioned on this package.
5771 sub forward_emails {
5775 #load optional service, thoroughly validated
5776 die "Use svcnum or svc_forward, not both"
5777 if $opt{'svcnum'} && $opt{'svc_forward'};
5778 my $svc_forward = $opt{'svc_forward'};
5779 $svc_forward ||= qsearchs('svc_forward',{ 'svcnum' => $opt{'svcnum'} })
5781 die "Specified service is not a forward service"
5782 if $svc_forward && (ref($svc_forward) ne 'FS::svc_forward');
5783 die "Specified service not found"
5784 if ($opt{'svcnum'} || $opt{'svc_forward'}) && !$svc_forward;
5788 ## everything below was basically copied from httemplate/edit/svc_forward.cgi
5789 ## with minimal refactoring, not sure why we can't just load all svc_accts for this custnum
5791 #add current values from specified service, if there was one
5793 foreach my $method (qw( srcsvc_acct dstsvc_acct )) {
5794 my $svc_acct = $svc_forward->$method();
5795 $email{$svc_acct->svcnum} = $svc_acct->email if $svc_acct;
5799 if (ref($self) eq 'FS::cust_pkg') {
5801 #and including the rest for this customer
5802 my($u_part_svc,@u_acct_svcparts);
5803 foreach $u_part_svc ( qsearch('part_svc',{'svcdb'=>'svc_acct'}) ) {
5804 push @u_acct_svcparts,$u_part_svc->getfield('svcpart');
5807 my $custnum = $self->getfield('custnum');
5808 foreach my $i_cust_pkg ( qsearch('cust_pkg',{'custnum'=>$custnum}) ) {
5809 my $cust_pkgnum = $i_cust_pkg->getfield('pkgnum');
5810 #now find the corresponding record(s) in cust_svc (for this pkgnum!)
5811 foreach my $acct_svcpart (@u_acct_svcparts) {
5812 foreach my $i_cust_svc (
5813 qsearch( 'cust_svc', { 'pkgnum' => $cust_pkgnum,
5814 'svcpart' => $acct_svcpart } )
5816 my $svc_acct = qsearchs( 'svc_acct', { 'svcnum' => $i_cust_svc->svcnum } );
5817 $email{$svc_acct->svcnum} = $svc_acct->email;
5826 # Used by FS::Upgrade to migrate to a new database.
5827 sub _upgrade_data { # class method
5828 my ($class, %opts) = @_;
5829 $class->_upgrade_otaker(%opts);
5831 # RT#10139, bug resulting in contract_end being set when it shouldn't
5832 'UPDATE cust_pkg SET contract_end = NULL WHERE contract_end = -1',
5833 # RT#10830, bad calculation of prorate date near end of year
5834 # the date range for bill is December 2009, and we move it forward
5835 # one year if it's before the previous bill date (which it should
5837 'UPDATE cust_pkg SET bill = bill + (365*24*60*60) WHERE bill < last_bill
5838 AND bill > 1259654400 AND bill < 1262332800 AND (SELECT plan FROM part_pkg
5839 WHERE part_pkg.pkgpart = cust_pkg.pkgpart) = \'prorate\'',
5840 # RT6628, add order_date to cust_pkg
5841 'update cust_pkg set order_date = (select history_date from h_cust_pkg
5842 where h_cust_pkg.pkgnum = cust_pkg.pkgnum and
5843 history_action = \'insert\') where order_date is null',
5845 foreach my $sql (@statements) {
5846 my $sth = dbh->prepare($sql);
5847 $sth->execute or die $sth->errstr;
5850 # RT31194: supplemental package links that are deleted don't clean up
5852 my @pkglinknums = qsearch({
5853 'select' => 'DISTINCT cust_pkg.pkglinknum',
5854 'table' => 'cust_pkg',
5855 'addl_from' => ' LEFT JOIN part_pkg_link USING (pkglinknum) ',
5856 'extra_sql' => ' WHERE cust_pkg.pkglinknum IS NOT NULL
5857 AND part_pkg_link.pkglinknum IS NULL',
5859 foreach (@pkglinknums) {
5860 my $pkglinknum = $_->pkglinknum;
5861 warn "cleaning part_pkg_link #$pkglinknum\n";
5862 my $part_pkg_link = FS::part_pkg_link->new({pkglinknum => $pkglinknum});
5863 my $error = $part_pkg_link->remove_linked;
5864 die $error if $error;
5872 sub order is not OO. Perhaps it should be moved to FS::cust_main and made so?
5874 In sub order, the @pkgparts array (passed by reference) is clobbered.
5876 Also in sub order, no money is adjusted. Once FS::part_pkg defines a standard
5877 method to pass dates to the recur_prog expression, it should do so.
5879 FS::svc_acct, FS::svc_domain, FS::svc_www, FS::svc_ip and FS::svc_forward are
5880 loaded via 'use' at compile time, rather than via 'require' in sub { setup,
5881 suspend, unsuspend, cancel } because they use %FS::UID::callback to load
5882 configuration values. Probably need a subroutine which decides what to do
5883 based on whether or not we've fetched the user yet, rather than a hash. See
5884 FS::UID and the TODO.
5886 Now that things are transactional should the check in the insert method be
5891 L<FS::Record>, L<FS::cust_main>, L<FS::part_pkg>, L<FS::cust_svc>,
5892 L<FS::pkg_svc>, schema.html from the base documentation