2 use base qw( FS::cust_pkg::Search FS::cust_pkg::API
3 FS::otaker_Mixin FS::cust_main_Mixin FS::Sales_Mixin
4 FS::contact_Mixin FS::location_Mixin
5 FS::m2m_Common FS::option_Common
10 use Scalar::Util qw( blessed );
11 use List::Util qw(min max);
13 use Time::Local qw( timelocal timelocal_nocheck );
15 use FS::UID qw( dbh driver_name );
16 use FS::Misc qw( send_email );
17 use FS::Record qw( qsearch qsearchs fields );
23 use FS::cust_location;
25 use FS::cust_bill_pkg;
26 use FS::cust_pkg_detail;
27 use FS::cust_pkg_usage;
28 use FS::cdr_cust_pkg_usage;
33 use FS::cust_pkg_reason;
35 use FS::cust_pkg_usageprice;
36 use FS::cust_pkg_discount;
42 # need to 'use' these instead of 'require' in sub { cancel, suspend, unsuspend,
44 # because they load configuration by setting FS::UID::callback (see TODO)
50 # for sending cancel emails in sub cancel
53 our ($disable_agentcheck, $DEBUG, $me, $import) = (0, 0, '[FS::cust_pkg]', 0);
55 our $upgrade = 0; #go away after setup+start dates cleaned up for old customers
59 my ( $hashref, $cache ) = @_;
60 #if ( $hashref->{'pkgpart'} ) {
61 if ( $hashref->{'pkg'} ) {
62 # #@{ $self->{'_pkgnum'} } = ();
63 # my $subcache = $cache->subcache('pkgpart', 'part_pkg');
64 # $self->{'_pkgpart'} = $subcache;
65 # #push @{ $self->{'_pkgnum'} },
66 # FS::part_pkg->new_or_cached($hashref, $subcache);
67 $self->{'_pkgpart'} = FS::part_pkg->new($hashref);
69 if ( exists $hashref->{'svcnum'} ) {
70 #@{ $self->{'_pkgnum'} } = ();
71 my $subcache = $cache->subcache('svcnum', 'cust_svc', $hashref->{pkgnum});
72 $self->{'_svcnum'} = $subcache;
73 #push @{ $self->{'_pkgnum'} },
74 FS::cust_svc->new_or_cached($hashref, $subcache) if $hashref->{svcnum};
80 FS::cust_pkg - Object methods for cust_pkg objects
86 $record = new FS::cust_pkg \%hash;
87 $record = new FS::cust_pkg { 'column' => 'value' };
89 $error = $record->insert;
91 $error = $new_record->replace($old_record);
93 $error = $record->delete;
95 $error = $record->check;
97 $error = $record->cancel;
99 $error = $record->suspend;
101 $error = $record->unsuspend;
103 $part_pkg = $record->part_pkg;
105 @labels = $record->labels;
107 $seconds = $record->seconds_since($timestamp);
109 #bulk cancel+order... perhaps slightly deprecated, only used by the bulk
110 # cancel+order in the web UI and nowhere else (edit/process/cust_pkg.cgi)
111 $error = FS::cust_pkg::order( $custnum, \@pkgparts );
112 $error = FS::cust_pkg::order( $custnum, \@pkgparts, \@remove_pkgnums ] );
116 An FS::cust_pkg object represents a customer billing item. FS::cust_pkg
117 inherits from FS::Record. The following fields are currently supported:
123 Primary key (assigned automatically for new billing items)
127 Customer (see L<FS::cust_main>)
131 Billing item definition (see L<FS::part_pkg>)
135 Optional link to package location (see L<FS::location>)
139 date package was ordered (also remains same on changes)
151 date (next bill date)
179 order taker (see L<FS::access_user>)
183 If this field is set to 1, disables the automatic
184 unsuspension of this package when using the B<unsuspendauto> config option.
188 If not set, defaults to 1
192 Date of change from previous package
202 =item change_locationnum
210 The pkgnum of the package that this package is supplemental to, if any.
214 The package link (L<FS::part_pkg_link>) that defines this supplemental
215 package, if it is one.
217 =item change_to_pkgnum
219 The pkgnum of the package this one will be "changed to" in the future
220 (on its expiration date).
224 Note: setup, last_bill, bill, adjourn, susp, expire, cancel and change_date
225 are specified as UNIX timestamps; see L<perlfunc/"time">. Also see
226 L<Time::Local> and L<Date::Parse> for conversion functions.
234 Create a new billing item. To add the item to the database, see L<"insert">.
238 sub table { 'cust_pkg'; }
239 sub cust_linked { $_[0]->cust_main_custnum || $_[0]->custnum }
240 sub cust_unlinked_msg {
242 "WARNING: can't find cust_main.custnum ". $self->custnum.
243 ' (cust_pkg.pkgnum '. $self->pkgnum. ')';
246 =item set_initial_timers
248 If required by the package definition, sets any automatic expire, adjourn,
249 or contract_end timers to some number of months after the start date
250 (or setup date, if the package has already been setup). If the package has
251 a delayed setup fee after a period of "free days", will also set the
252 start date to the end of that period.
256 sub set_initial_timers {
258 my $part_pkg = $self->part_pkg;
259 foreach my $action ( qw(expire adjourn contract_end) ) {
260 my $months = $part_pkg->option("${action}_months",1);
261 if($months and !$self->get($action)) {
262 my $start = $self->start_date || $self->setup || time;
263 $self->set($action, $part_pkg->add_freq($start, $months) );
267 # if this package has "free days" and delayed setup fee, then
268 # set start date that many days in the future.
269 # (this should have been set in the UI, but enforce it here)
270 if ( $part_pkg->option('free_days',1)
271 && $part_pkg->option('delay_setup',1)
274 $self->start_date( $part_pkg->default_start_date );
279 =item insert [ OPTION => VALUE ... ]
281 Adds this billing item to the database ("Orders" the item). If there is an
282 error, returns the error, otherwise returns false.
284 If the additional field I<promo_code> is defined instead of I<pkgpart>, it
285 will be used to look up the package definition and agent restrictions will be
288 If the additional field I<refnum> is defined, an FS::pkg_referral record will
289 be created and inserted. Multiple FS::pkg_referral records can be created by
290 setting I<refnum> to an array reference of refnums or a hash reference with
291 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
292 record will be created corresponding to cust_main.refnum.
294 If the additional field I<cust_pkg_usageprice> is defined, it will be treated
295 as an arrayref of FS::cust_pkg_usageprice objects, which will be inserted.
296 (Note that this field cannot be set with a usual ->cust_pkg_usageprice method.
297 It can be set as part of the hash when creating the object, or with the B<set>
300 The following options are available:
306 If set true, supresses actions that should only be taken for new package
307 orders. (Currently this includes: intro periods when delay_setup is on,
308 auto-adding a 1st start date, auto-adding expiration/adjourn/contract_end dates)
312 cust_pkg_option records will be created
316 a ticket will be added to this customer with this subject
320 an optional queue name for ticket additions
324 Don't check the legality of the package definition. This should be used
325 when performing a package change that doesn't change the pkgpart (i.e.
333 my( $self, %options ) = @_;
336 $error = $self->check_pkgpart unless $options{'allow_pkgpart'};
337 return $error if $error;
339 my $part_pkg = $self->part_pkg;
341 if ( ! $import && ! $options{'change'} ) {
343 # set order date to now
344 $self->order_date(time) unless ($import && $self->order_date);
346 # if the package def says to start only on the first of the month:
347 if ( $part_pkg->option('start_1st', 1) && !$self->start_date ) {
348 my ($sec,$min,$hour,$mday,$mon,$year) = (localtime(time) )[0,1,2,3,4,5];
349 $mon += 1 unless $mday == 1;
350 until ( $mon < 12 ) { $mon -= 12; $year++; }
351 $self->start_date( timelocal_nocheck(0,0,0,1,$mon,$year) );
354 if ($self->susp eq 'now' or $part_pkg->start_on_hold) {
355 # if the package was ordered on hold:
357 # - don't set the start date (it will be started manually)
358 $self->set('susp', $self->order_date);
359 $self->set('start_date', '');
361 # set expire/adjourn/contract_end timers, and free days, if appropriate
362 $self->set_initial_timers;
364 } # else this is a package change, and shouldn't have "new package" behavior
366 my $oldAutoCommit = $FS::UID::AutoCommit;
367 local $FS::UID::AutoCommit = 0;
370 $error = $self->SUPER::insert($options{options} ? %{$options{options}} : ());
372 $dbh->rollback if $oldAutoCommit;
376 $self->refnum($self->cust_main->refnum) unless $self->refnum;
377 $self->refnum( [ $self->refnum ] ) unless ref($self->refnum);
378 $self->process_m2m( 'link_table' => 'pkg_referral',
379 'target_table' => 'part_referral',
380 'params' => $self->refnum,
383 if ( $self->hashref->{cust_pkg_usageprice} ) {
384 for my $cust_pkg_usageprice ( @{ $self->hashref->{cust_pkg_usageprice} } ) {
385 $cust_pkg_usageprice->pkgnum( $self->pkgnum );
386 my $error = $cust_pkg_usageprice->insert;
388 $dbh->rollback if $oldAutoCommit;
394 if ( $self->discountnum ) {
395 my $error = $self->insert_discount();
397 $dbh->rollback if $oldAutoCommit;
402 my $conf = new FS::Conf;
404 if ( ! $import && $conf->config('ticket_system') && $options{ticket_subject} ) {
406 #this init stuff is still inefficient, but at least its limited to
407 # the small number (any?) folks using ticket emailing on pkg order
410 # use lib ( "/opt/rt3/local/lib", "/opt/rt3/lib" );
417 use FS::TicketSystem;
418 FS::TicketSystem->init();
420 my $q = new RT::Queue($RT::SystemUser);
421 $q->Load($options{ticket_queue}) if $options{ticket_queue};
422 my $t = new RT::Ticket($RT::SystemUser);
423 my $mime = new MIME::Entity;
424 $mime->build( Type => 'text/plain', Data => $options{ticket_subject} );
425 $t->Create( $options{ticket_queue} ? (Queue => $q) : (),
426 Subject => $options{ticket_subject},
429 $t->AddLink( Type => 'MemberOf',
430 Target => 'freeside://freeside/cust_main/'. $self->custnum,
434 if (! $import && $conf->config('welcome_letter') && $self->cust_main->num_pkgs == 1) {
435 my $queue = new FS::queue {
436 'job' => 'FS::cust_main::queueable_print',
438 $error = $queue->insert(
439 'custnum' => $self->custnum,
440 'template' => 'welcome_letter',
444 warn "can't send welcome letter: $error";
449 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
456 This method now works but you probably shouldn't use it.
458 You don't want to delete packages, because there would then be no record
459 the customer ever purchased the package. Instead, see the cancel method and
460 hide cancelled packages.
467 my $oldAutoCommit = $FS::UID::AutoCommit;
468 local $FS::UID::AutoCommit = 0;
471 foreach my $cust_pkg_discount ($self->cust_pkg_discount) {
472 my $error = $cust_pkg_discount->delete;
474 $dbh->rollback if $oldAutoCommit;
478 #cust_bill_pkg_discount?
480 foreach my $cust_pkg_detail ($self->cust_pkg_detail) {
481 my $error = $cust_pkg_detail->delete;
483 $dbh->rollback if $oldAutoCommit;
488 foreach my $cust_pkg_reason (
490 'table' => 'cust_pkg_reason',
491 'hashref' => { 'pkgnum' => $self->pkgnum },
495 my $error = $cust_pkg_reason->delete;
497 $dbh->rollback if $oldAutoCommit;
504 my $error = $self->SUPER::delete(@_);
506 $dbh->rollback if $oldAutoCommit;
510 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
516 =item replace [ OLD_RECORD ] [ HASHREF | OPTION => VALUE ... ]
518 Replaces the OLD_RECORD with this one in the database. If there is an error,
519 returns the error, otherwise returns false.
521 Currently, custnum, setup, bill, adjourn, susp, expire, and cancel may be changed.
523 Changing pkgpart may have disasterous effects. See the order subroutine.
525 setup and bill are normally updated by calling the bill method of a customer
526 object (see L<FS::cust_main>).
528 suspend is normally updated by the suspend and unsuspend methods.
530 cancel is normally updated by the cancel method (and also the order subroutine
533 Available options are:
539 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.
543 the access_user (see L<FS::access_user>) providing the reason
547 hashref of keys and values - cust_pkg_option records will be created, updated or removed as appopriate
556 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
561 ( ref($_[0]) eq 'HASH' )
565 #return "Can't (yet?) change pkgpart!" if $old->pkgpart != $new->pkgpart;
566 #return "Can't change otaker!" if $old->otaker ne $new->otaker;
569 #return "Can't change setup once it exists!"
570 # if $old->getfield('setup') &&
571 # $old->getfield('setup') != $new->getfield('setup');
573 #some logic for bill, susp, cancel?
575 local($disable_agentcheck) = 1 if $old->pkgpart == $new->pkgpart;
577 my $oldAutoCommit = $FS::UID::AutoCommit;
578 local $FS::UID::AutoCommit = 0;
581 foreach my $method ( qw(adjourn expire) ) { # How many reasons?
582 if ($options->{'reason'} && $new->$method && $old->$method ne $new->$method) {
583 my $error = $new->insert_reason(
584 'reason' => $options->{'reason'},
585 'date' => $new->$method,
587 'reason_otaker' => $options->{'reason_otaker'},
590 dbh->rollback if $oldAutoCommit;
591 return "Error inserting cust_pkg_reason: $error";
596 #save off and freeze RADIUS attributes for any associated svc_acct records
598 if ( $old->part_pkg->is_prepaid || $new->part_pkg->is_prepaid ) {
600 #also check for specific exports?
601 # to avoid spurious modify export events
602 @svc_acct = map { $_->svc_x }
603 grep { $_->part_svc->svcdb eq 'svc_acct' }
606 $_->snapshot foreach @svc_acct;
610 my $error = $new->export_pkg_change($old)
611 || $new->SUPER::replace( $old,
613 ? $options->{options}
617 $dbh->rollback if $oldAutoCommit;
621 #for prepaid packages,
622 #trigger export of new RADIUS Expiration attribute when cust_pkg.bill changes
623 foreach my $old_svc_acct ( @svc_acct ) {
624 my $new_svc_acct = new FS::svc_acct { $old_svc_acct->hash };
626 $new_svc_acct->replace( $old_svc_acct,
627 'depend_jobnum' => $options->{depend_jobnum},
630 $dbh->rollback if $oldAutoCommit;
635 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
642 Checks all fields to make sure this is a valid billing item. If there is an
643 error, returns the error, otherwise returns false. Called by the insert and
651 if ( !$self->locationnum or $self->locationnum == -1 ) {
652 $self->set('locationnum', $self->cust_main->ship_locationnum);
656 $self->ut_numbern('pkgnum')
657 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum')
658 || $self->ut_numbern('pkgpart')
659 || $self->ut_foreign_keyn('contactnum', 'contact', 'contactnum' )
660 || $self->ut_foreign_keyn('locationnum', 'cust_location', 'locationnum')
661 || $self->ut_foreign_keyn('salesnum', 'sales', 'salesnum')
662 || $self->ut_numbern('quantity')
663 || $self->ut_numbern('start_date')
664 || $self->ut_numbern('setup')
665 || $self->ut_numbern('bill')
666 || $self->ut_numbern('susp')
667 || $self->ut_numbern('cancel')
668 || $self->ut_numbern('adjourn')
669 || $self->ut_numbern('resume')
670 || $self->ut_numbern('expire')
671 || $self->ut_numbern('dundate')
672 || $self->ut_flag('no_auto', [ '', 'Y' ])
673 || $self->ut_flag('waive_setup', [ '', 'Y' ])
674 || $self->ut_flag('separate_bill')
675 || $self->ut_textn('agent_pkgid')
676 || $self->ut_enum('recur_show_zero', [ '', 'Y', 'N', ])
677 || $self->ut_enum('setup_show_zero', [ '', 'Y', 'N', ])
678 || $self->ut_foreign_keyn('main_pkgnum', 'cust_pkg', 'pkgnum')
679 || $self->ut_foreign_keyn('pkglinknum', 'part_pkg_link', 'pkglinknum')
680 || $self->ut_foreign_keyn('change_to_pkgnum', 'cust_pkg', 'pkgnum')
682 return $error if $error;
684 return "A package with both start date (future start) and setup date (already started) will never bill"
685 if $self->start_date && $self->setup && ! $upgrade;
687 return "A future unsuspend date can only be set for a package with a suspend date"
688 if $self->resume and !$self->susp and !$self->adjourn;
690 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
692 if ( $self->dbdef_table->column('manual_flag') ) {
693 $self->manual_flag('') if $self->manual_flag eq ' ';
694 $self->manual_flag =~ /^([01]?)$/
695 or return "Illegal manual_flag ". $self->manual_flag;
696 $self->manual_flag($1);
704 Check the pkgpart to make sure it's allowed with the reg_code and/or
705 promo_code of the package (if present) and with the customer's agent.
706 Called from C<insert>, unless we are doing a package change that doesn't
714 # my $error = $self->ut_numbern('pkgpart'); # already done
717 if ( $self->reg_code ) {
719 unless ( grep { $self->pkgpart == $_->pkgpart }
720 map { $_->reg_code_pkg }
721 qsearchs( 'reg_code', { 'code' => $self->reg_code,
722 'agentnum' => $self->cust_main->agentnum })
724 return "Unknown registration code";
727 } elsif ( $self->promo_code ) {
730 qsearchs('part_pkg', {
731 'pkgpart' => $self->pkgpart,
732 'promo_code' => { op=>'ILIKE', value=>$self->promo_code },
734 return 'Unknown promotional code' unless $promo_part_pkg;
738 unless ( $disable_agentcheck ) {
740 qsearchs( 'agent', { 'agentnum' => $self->cust_main->agentnum } );
741 return "agent ". $agent->agentnum. ':'. $agent->agent.
742 " can't purchase pkgpart ". $self->pkgpart
743 unless $agent->pkgpart_hashref->{ $self->pkgpart }
744 || $agent->agentnum == $self->part_pkg->agentnum;
747 $error = $self->ut_foreign_key('pkgpart', 'part_pkg', 'pkgpart' );
748 return $error if $error;
756 =item cancel [ OPTION => VALUE ... ]
758 Cancels and removes all services (see L<FS::cust_svc> and L<FS::part_svc>)
759 in this package, then cancels the package itself (sets the cancel field to
762 Available options are:
766 =item quiet - can be set true to supress email cancellation notices.
768 =item time - can be set to cancel the package based on a specific future or
769 historical date. Using time ensures that the remaining amount is calculated
770 correctly. Note however that this is an immediate cancel and just changes
771 the date. You are PROBABLY looking to expire the account instead of using
774 =item reason - can be set to a cancellation reason (see L<FS:reason>),
775 either a reasonnum of an existing reason, or passing a hashref will create
776 a new reason. The hashref should have the following keys: typenum - Reason
777 type (see L<FS::reason_type>, reason - Text of the new reason.
779 =item date - can be set to a unix style timestamp to specify when to
782 =item nobill - can be set true to skip billing if it might otherwise be done.
784 =item unused_credit - can be set to 1 to credit the remaining time, or 0 to
785 not credit it. This must be set (by change()) when changing the package
786 to a different pkgpart or location, and probably shouldn't be in any other
787 case. If it's not set, the 'unused_credit_cancel' part_pkg option will
790 =item no_delay_cancel - prevents delay_cancel behavior
791 no matter what other options say, for use when changing packages (or any
792 other time you're really sure you want an immediate cancel)
796 If there is an error, returns the error, otherwise returns false.
800 #NOT DOCUMENTING - this should only be used when calling recursively
801 #=item delay_cancel - for internal use, to allow proper handling of
802 #supplemental packages when the main package is flagged to suspend
803 #before cancelling, probably shouldn't be used otherwise (set the
804 #corresponding package option instead)
807 my( $self, %options ) = @_;
810 # pass all suspend/cancel actions to the main package
811 # (unless the pkglinknum has been removed, then the link is defunct and
812 # this package can be canceled on its own)
813 if ( $self->main_pkgnum and $self->pkglinknum and !$options{'from_main'} ) {
814 return $self->main_pkg->cancel(%options);
817 my $conf = new FS::Conf;
819 warn "cust_pkg::cancel called with options".
820 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
823 my $oldAutoCommit = $FS::UID::AutoCommit;
824 local $FS::UID::AutoCommit = 0;
827 my $old = $self->select_for_update;
829 if ( $old->get('cancel') || $self->get('cancel') ) {
830 dbh->rollback if $oldAutoCommit;
831 return ""; # no error
834 # XXX possibly set cancel_time to the expire date?
835 my $cancel_time = $options{'time'} || time;
836 my $date = $options{'date'} if $options{'date'}; # expire/cancel later
837 $date = '' if ($date && $date <= $cancel_time); # complain instead?
839 my $delay_cancel = $options{'no_delay_cancel'} ? 0 : $options{'delay_cancel'};
840 if ( !$date && $self->part_pkg->option('delay_cancel',1)
841 && (($self->status eq 'active') || ($self->status eq 'suspended'))
842 && !$options{'no_delay_cancel'}
844 my $expdays = $conf->config('part_pkg-delay_cancel-days') || 1;
845 my $expsecs = 60*60*24*$expdays;
846 my $suspfor = $self->susp ? $cancel_time - $self->susp : 0;
847 $expsecs = $expsecs - $suspfor if $suspfor;
848 unless ($expsecs <= 0) { #if it's already been suspended long enough, don't re-suspend
850 $date = $cancel_time + $expsecs;
854 #race condition: usage could be ongoing until unprovisioned
855 #resolved by performing a change package instead (which unprovisions) and
857 if ( !$options{nobill} && !$date ) {
858 # && $conf->exists('bill_usage_on_cancel') ) { #calc_cancel checks this
859 my $copy = $self->new({$self->hash});
861 $copy->cust_main->bill( 'pkg_list' => [ $copy ],
863 'time' => $cancel_time );
864 warn "Error billing during cancel, custnum ".
865 #$self->cust_main->custnum. ": $error"
870 if ( $options{'reason'} ) {
871 $error = $self->insert_reason( 'reason' => $options{'reason'},
872 'action' => $date ? 'expire' : 'cancel',
873 'date' => $date ? $date : $cancel_time,
874 'reason_otaker' => $options{'reason_otaker'},
877 dbh->rollback if $oldAutoCommit;
878 return "Error inserting cust_pkg_reason: $error";
882 my %svc_cancel_opt = ();
883 $svc_cancel_opt{'date'} = $date if $date;
884 foreach my $cust_svc (
887 sort { $a->[1] <=> $b->[1] }
888 map { [ $_, $_->svc_x ? $_->svc_x->table_info->{'cancel_weight'} : -1 ]; }
889 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
891 my $part_svc = $cust_svc->part_svc;
892 next if ( defined($part_svc) and $part_svc->preserve );
893 my $error = $cust_svc->cancel( %svc_cancel_opt );
896 $dbh->rollback if $oldAutoCommit;
897 return 'Error '. ($svc_cancel_opt{'date'} ? 'expiring' : 'canceling' ).
903 # credit remaining time if appropriate
905 if ( exists($options{'unused_credit'}) ) {
906 $do_credit = $options{'unused_credit'};
909 $do_credit = $self->part_pkg->option('unused_credit_cancel', 1);
912 my $error = $self->credit_remaining('cancel', $cancel_time);
914 $dbh->rollback if $oldAutoCommit;
920 my %hash = $self->hash;
922 $hash{'expire'} = $date;
924 # just to be sure these are clear
925 $hash{'adjourn'} = undef;
926 $hash{'resume'} = undef;
929 $hash{'cancel'} = $cancel_time;
931 $hash{'change_custnum'} = $options{'change_custnum'};
933 # if this is a supplemental package that's lost its part_pkg_link, and it's
934 # being canceled for real, unlink it completely
935 if ( !$date and ! $self->pkglinknum ) {
936 $hash{main_pkgnum} = '';
939 my $new = new FS::cust_pkg ( \%hash );
940 $error = $new->replace( $self, options => { $self->options } );
941 if ( $self->change_to_pkgnum ) {
942 my $change_to = FS::cust_pkg->by_key($self->change_to_pkgnum);
943 $error ||= $change_to->cancel('no_delay_cancel' => 1) || $change_to->delete;
946 $dbh->rollback if $oldAutoCommit;
950 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
951 $error = $supp_pkg->cancel(%options,
953 'date' => $date, #in case it got changed by delay_cancel
954 'delay_cancel' => $delay_cancel,
957 $dbh->rollback if $oldAutoCommit;
958 return "canceling supplemental pkg#".$supp_pkg->pkgnum.": $error";
962 if ($delay_cancel && !$options{'from_main'}) {
963 $error = $new->suspend(
965 'time' => $cancel_time
970 foreach my $usage ( $self->cust_pkg_usage ) {
971 $error = $usage->delete;
973 $dbh->rollback if $oldAutoCommit;
974 return "deleting usage pools: $error";
979 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
980 return '' if $date; #no errors
982 my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ } $self->cust_main->invoicing_list;
983 if ( !$options{'quiet'} &&
984 $conf->exists('emailcancel', $self->cust_main->agentnum) &&
986 my $msgnum = $conf->config('cancel_msgnum', $self->cust_main->agentnum);
989 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum });
990 $error = $msg_template->send( 'cust_main' => $self->cust_main,
995 'from' => $conf->invoice_from_full( $self->cust_main->agentnum ),
996 'to' => \@invoicing_list,
997 'subject' => ( $conf->config('cancelsubject') || 'Cancellation Notice' ),
998 'body' => [ map "$_\n", $conf->config('cancelmessage') ],
999 'custnum' => $self->custnum,
1000 'msgtype' => '', #admin?
1003 #should this do something on errors?
1010 =item cancel_if_expired [ NOW_TIMESTAMP ]
1012 Cancels this package if its expire date has been reached.
1016 sub cancel_if_expired {
1018 my $time = shift || time;
1019 return '' unless $self->expire && $self->expire <= $time;
1020 my $error = $self->cancel;
1022 return "Error cancelling expired pkg ". $self->pkgnum. " for custnum ".
1023 $self->custnum. ": $error";
1030 "Un-cancels" this package: Orders a new package with the same custnum, pkgpart,
1031 locationnum, (other fields?). Attempts to re-provision cancelled services
1032 using history information (errors at this stage are not fatal).
1034 cust_pkg: pass a scalar reference, will be filled in with the new cust_pkg object
1036 svc_fatal: service provisioning errors are fatal
1038 svc_errors: pass an array reference, will be filled in with any provisioning errors
1040 main_pkgnum: link the package as a supplemental package of this one. For
1046 my( $self, %options ) = @_;
1048 #in case you try do do $uncancel-date = $cust_pkg->uncacel
1049 return '' unless $self->get('cancel');
1051 if ( $self->main_pkgnum and !$options{'main_pkgnum'} ) {
1052 return $self->main_pkg->uncancel(%options);
1059 my $oldAutoCommit = $FS::UID::AutoCommit;
1060 local $FS::UID::AutoCommit = 0;
1064 # insert the new package
1067 my $cust_pkg = new FS::cust_pkg {
1068 last_bill => ( $options{'last_bill'} || $self->get('last_bill') ),
1069 bill => ( $options{'bill'} || $self->get('bill') ),
1071 uncancel_pkgnum => $self->pkgnum,
1072 main_pkgnum => ($options{'main_pkgnum'} || ''),
1073 map { $_ => $self->get($_) } qw(
1074 custnum pkgpart locationnum
1076 susp adjourn resume expire start_date contract_end dundate
1077 change_date change_pkgpart change_locationnum
1078 manual_flag no_auto separate_bill quantity agent_pkgid
1079 recur_show_zero setup_show_zero
1083 my $error = $cust_pkg->insert(
1084 'change' => 1, #supresses any referral credit to a referring customer
1085 'allow_pkgpart' => 1, # allow this even if the package def is disabled
1088 $dbh->rollback if $oldAutoCommit;
1096 #find historical services within this timeframe before the package cancel
1097 # (incompatible with "time" option to cust_pkg->cancel?)
1098 my $fuzz = 2 * 60; #2 minutes? too much? (might catch separate unprovision)
1099 # too little? (unprovisioing export delay?)
1100 my($end, $start) = ( $self->get('cancel'), $self->get('cancel') - $fuzz );
1101 my @h_cust_svc = $self->h_cust_svc( $end, $start );
1104 foreach my $h_cust_svc (@h_cust_svc) {
1105 my $h_svc_x = $h_cust_svc->h_svc_x( $end, $start );
1106 #next unless $h_svc_x; #should this happen?
1107 (my $table = $h_svc_x->table) =~ s/^h_//;
1108 require "FS/$table.pm";
1109 my $class = "FS::$table";
1110 my $svc_x = $class->new( {
1111 'pkgnum' => $cust_pkg->pkgnum,
1112 'svcpart' => $h_cust_svc->svcpart,
1113 map { $_ => $h_svc_x->get($_) } fields($table)
1117 if ( $h_svc_x->isa('FS::h_svc_Radius_Mixin') ) {
1118 $svc_x->usergroup( [ $h_svc_x->h_usergroup($end, $start) ] );
1121 my $svc_error = $svc_x->insert;
1123 if ( $options{svc_fatal} ) {
1124 $dbh->rollback if $oldAutoCommit;
1127 # if we've failed to insert the svc_x object, svc_Common->insert
1128 # will have removed the cust_svc already. if not, then both records
1129 # were inserted but we failed for some other reason (export, most
1130 # likely). in that case, report the error and delete the records.
1131 push @svc_errors, $svc_error;
1132 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svc_x->svcnum });
1134 # except if export_insert failed, export_delete probably won't be
1136 local $FS::svc_Common::noexport_hack = 1;
1137 my $cleanup_error = $svc_x->delete; # also deletes cust_svc
1138 if ( $cleanup_error ) { # and if THAT fails, then run away
1139 $dbh->rollback if $oldAutoCommit;
1140 return $cleanup_error;
1145 } #foreach $h_cust_svc
1147 #these are pretty rare, but should handle them
1148 # - dsl_device (mac addresses)
1149 # - phone_device (mac addresses)
1150 # - dsl_note (ikano notes)
1151 # - domain_record (i.e. restore DNS information w/domains)
1152 # - inventory_item(?) (inventory w/un-cancelling service?)
1153 # - nas (svc_broaband nas stuff)
1154 #this stuff is unused in the wild afaik
1155 # - mailinglistmember
1157 # - svc_domain.parent_svcnum?
1158 # - acct_snarf (ancient mail fetching config)
1159 # - cgp_rule (communigate)
1160 # - cust_svc_option (used by our Tron stuff)
1161 # - acct_rt_transaction (used by our time worked stuff)
1164 # also move over any services that didn't unprovision at cancellation
1167 foreach my $cust_svc ( qsearch('cust_svc', { pkgnum => $self->pkgnum } ) ) {
1168 $cust_svc->pkgnum( $cust_pkg->pkgnum );
1169 my $error = $cust_svc->replace;
1171 $dbh->rollback if $oldAutoCommit;
1177 # Uncancel any supplemental packages, and make them supplemental to the
1181 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1183 $error = $supp_pkg->uncancel(%options, 'main_pkgnum' => $cust_pkg->pkgnum);
1185 $dbh->rollback if $oldAutoCommit;
1186 return "canceling supplemental pkg#".$supp_pkg->pkgnum.": $error";
1194 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1196 ${ $options{cust_pkg} } = $cust_pkg if ref($options{cust_pkg});
1197 @{ $options{svc_errors} } = @svc_errors if ref($options{svc_errors});
1204 Cancels any pending expiration (sets the expire field to null).
1206 If there is an error, returns the error, otherwise returns false.
1211 my( $self, %options ) = @_;
1214 my $oldAutoCommit = $FS::UID::AutoCommit;
1215 local $FS::UID::AutoCommit = 0;
1218 my $old = $self->select_for_update;
1220 my $pkgnum = $old->pkgnum;
1221 if ( $old->get('cancel') || $self->get('cancel') ) {
1222 dbh->rollback if $oldAutoCommit;
1223 return "Can't unexpire cancelled package $pkgnum";
1224 # or at least it's pointless
1227 unless ( $old->get('expire') && $self->get('expire') ) {
1228 dbh->rollback if $oldAutoCommit;
1229 return ""; # no error
1232 my %hash = $self->hash;
1233 $hash{'expire'} = '';
1234 my $new = new FS::cust_pkg ( \%hash );
1235 $error = $new->replace( $self, options => { $self->options } );
1237 $dbh->rollback if $oldAutoCommit;
1241 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1247 =item suspend [ OPTION => VALUE ... ]
1249 Suspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
1250 package, then suspends the package itself (sets the susp field to now).
1252 Available options are:
1256 =item reason - can be set to a cancellation reason (see L<FS:reason>),
1257 either a reasonnum of an existing reason, or passing a hashref will create
1258 a new reason. The hashref should have the following keys:
1259 - typenum - Reason type (see L<FS::reason_type>
1260 - reason - Text of the new reason.
1262 =item date - can be set to a unix style timestamp to specify when to
1265 =item time - can be set to override the current time, for calculation
1266 of final invoices or unused-time credits
1268 =item resume_date - can be set to a time when the package should be
1269 unsuspended. This may be more convenient than calling C<unsuspend()>
1272 =item from_main - allows a supplemental package to be suspended, rather
1273 than redirecting the method call to its main package. For internal use.
1275 =item from_cancel - used when suspending from the cancel method, forces
1276 this to skip everything besides basic suspension. For internal use.
1280 If there is an error, returns the error, otherwise returns false.
1285 my( $self, %options ) = @_;
1288 # pass all suspend/cancel actions to the main package
1289 if ( $self->main_pkgnum and !$options{'from_main'} ) {
1290 return $self->main_pkg->suspend(%options);
1293 my $oldAutoCommit = $FS::UID::AutoCommit;
1294 local $FS::UID::AutoCommit = 0;
1297 my $old = $self->select_for_update;
1299 my $pkgnum = $old->pkgnum;
1300 if ( $old->get('cancel') || $self->get('cancel') ) {
1301 dbh->rollback if $oldAutoCommit;
1302 return "Can't suspend cancelled package $pkgnum";
1305 if ( $old->get('susp') || $self->get('susp') ) {
1306 dbh->rollback if $oldAutoCommit;
1307 return ""; # no error # complain on adjourn?
1310 my $suspend_time = $options{'time'} || time;
1311 my $date = $options{date} if $options{date}; # adjourn/suspend later
1312 $date = '' if ($date && $date <= $suspend_time); # complain instead?
1314 if ( $date && $old->get('expire') && $old->get('expire') < $date ) {
1315 dbh->rollback if $oldAutoCommit;
1316 return "Package $pkgnum expires before it would be suspended.";
1319 # some false laziness with sub cancel
1320 if ( !$options{nobill} && !$date && !$options{'from_cancel'} &&
1321 $self->part_pkg->option('bill_suspend_as_cancel',1) ) {
1322 # kind of a kludge--'bill_suspend_as_cancel' to avoid having to
1323 # make the entire cust_main->bill path recognize 'suspend' and
1324 # 'cancel' separately.
1325 warn "Billing $pkgnum on suspension (at $suspend_time)\n" if $DEBUG;
1326 my $copy = $self->new({$self->hash});
1328 $copy->cust_main->bill( 'pkg_list' => [ $copy ],
1330 'time' => $suspend_time );
1331 warn "Error billing during suspend, custnum ".
1332 #$self->cust_main->custnum. ": $error"
1337 my $cust_pkg_reason;
1338 if ( $options{'reason'} ) {
1339 $error = $self->insert_reason( 'reason' => $options{'reason'},
1340 'action' => $date ? 'adjourn' : 'suspend',
1341 'date' => $date ? $date : $suspend_time,
1342 'reason_otaker' => $options{'reason_otaker'},
1345 dbh->rollback if $oldAutoCommit;
1346 return "Error inserting cust_pkg_reason: $error";
1348 $cust_pkg_reason = qsearchs('cust_pkg_reason', {
1349 'date' => $date ? $date : $suspend_time,
1350 'action' => $date ? 'A' : 'S',
1351 'pkgnum' => $self->pkgnum,
1355 # if a reasonnum was passed, get the actual reason object so we can check
1357 # (passing a reason hashref is still allowed, but it can't be used with
1358 # the fancy behavioral options.)
1361 if ($options{'reason'} =~ /^\d+$/) {
1362 $reason = FS::reason->by_key($options{'reason'});
1365 my %hash = $self->hash;
1367 $hash{'adjourn'} = $date;
1369 $hash{'susp'} = $suspend_time;
1372 my $resume_date = $options{'resume_date'} || 0;
1373 if ( $resume_date > ($date || $suspend_time) ) {
1374 $hash{'resume'} = $resume_date;
1377 $options{options} ||= {};
1379 my $new = new FS::cust_pkg ( \%hash );
1380 $error = $new->replace( $self, options => { $self->options,
1381 %{ $options{options} },
1385 $dbh->rollback if $oldAutoCommit;
1389 unless ( $date ) { # then we are suspending now
1391 unless ($options{'from_cancel'}) {
1392 # credit remaining time if appropriate
1393 # (if required by the package def, or the suspend reason)
1394 my $unused_credit = $self->part_pkg->option('unused_credit_suspend',1)
1395 || ( defined($reason) && $reason->unused_credit );
1397 if ( $unused_credit ) {
1398 warn "crediting unused time on pkg#".$self->pkgnum."\n" if $DEBUG;
1399 my $error = $self->credit_remaining('suspend', $suspend_time);
1401 $dbh->rollback if $oldAutoCommit;
1409 foreach my $cust_svc (
1410 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
1412 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
1414 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
1415 $dbh->rollback if $oldAutoCommit;
1416 return "Illegal svcdb value in part_svc!";
1419 require "FS/$svcdb.pm";
1421 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
1423 $error = $svc->suspend;
1425 $dbh->rollback if $oldAutoCommit;
1428 my( $label, $value ) = $cust_svc->label;
1429 push @labels, "$label: $value";
1433 # suspension fees: if there is a feepart, and it's not an unsuspend fee,
1434 # and this is not a suspend-before-cancel
1435 if ( $cust_pkg_reason ) {
1436 my $reason_obj = $cust_pkg_reason->reason;
1437 if ( $reason_obj->feepart and
1438 ! $reason_obj->fee_on_unsuspend and
1439 ! $options{'from_cancel'} ) {
1441 # register the need to charge a fee, cust_main->bill will do the rest
1442 warn "registering suspend fee: pkgnum ".$self->pkgnum.", feepart ".$reason->feepart."\n"
1444 my $cust_pkg_reason_fee = FS::cust_pkg_reason_fee->new({
1445 'pkgreasonnum' => $cust_pkg_reason->num,
1446 'pkgnum' => $self->pkgnum,
1447 'feepart' => $reason->feepart,
1448 'nextbill' => $reason->fee_hold,
1450 $error ||= $cust_pkg_reason_fee->insert;
1454 my $conf = new FS::Conf;
1455 if ( $conf->config('suspend_email_admin') && !$options{'from_cancel'} ) {
1457 my $error = send_email(
1458 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
1459 #invoice_from ??? well as good as any
1460 'to' => $conf->config('suspend_email_admin'),
1461 'subject' => 'FREESIDE NOTIFICATION: Customer package suspended',
1463 "This is an automatic message from your Freeside installation\n",
1464 "informing you that the following customer package has been suspended:\n",
1466 'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
1467 'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
1468 ( map { "Service : $_\n" } @labels ),
1470 'custnum' => $self->custnum,
1471 'msgtype' => 'admin'
1475 warn "WARNING: can't send suspension admin email (suspending anyway): ".
1483 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1484 $error = $supp_pkg->suspend(%options, 'from_main' => 1);
1486 $dbh->rollback if $oldAutoCommit;
1487 return "suspending supplemental pkg#".$supp_pkg->pkgnum.": $error";
1491 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1496 =item credit_remaining MODE TIME
1498 Generate a credit for this package for the time remaining in the current
1499 billing period. MODE is either "suspend" or "cancel" (determines the
1500 credit type). TIME is the time of suspension/cancellation. Both arguments
1505 # Implementation note:
1507 # If you pkgpart-change a package that has been billed, and it's set to give
1508 # credit on package change, then this method gets called and then the new
1509 # package will have no last_bill date. Therefore the customer will be credited
1510 # only once (per billing period) even if there are multiple package changes.
1512 # If you location-change a package that has been billed, this method will NOT
1513 # be called and the new package WILL have the last bill date of the old
1516 # If the new package is then canceled within the same billing cycle,
1517 # credit_remaining needs to run calc_remain on the OLD package to determine
1518 # the amount of unused time to credit.
1520 sub credit_remaining {
1521 # Add a credit for remaining service
1522 my ($self, $mode, $time) = @_;
1523 die 'credit_remaining requires suspend or cancel'
1524 unless $mode eq 'suspend' or $mode eq 'cancel';
1525 die 'no suspend/cancel time' unless $time > 0;
1527 my $conf = FS::Conf->new;
1528 my $reason_type = $conf->config($mode.'_credit_type');
1530 my $last_bill = $self->getfield('last_bill') || 0;
1531 my $next_bill = $self->getfield('bill') || 0;
1532 if ( $last_bill > 0 # the package has been billed
1533 and $next_bill > 0 # the package has a next bill date
1534 and $next_bill >= $time # which is in the future
1536 my @cust_credit_source_bill_pkg = ();
1537 my $remaining_value = 0;
1539 my $remain_pkg = $self;
1540 $remaining_value = $remain_pkg->calc_remain(
1542 'cust_credit_source_bill_pkg' => \@cust_credit_source_bill_pkg,
1545 # we may have to walk back past some package changes to get to the
1546 # one that actually has unused time
1547 while ( $remaining_value == 0 ) {
1548 if ( $remain_pkg->change_pkgnum ) {
1549 $remain_pkg = FS::cust_pkg->by_key($remain_pkg->change_pkgnum);
1551 # the package has really never been billed
1554 $remaining_value = $remain_pkg->calc_remain(
1556 'cust_credit_source_bill_pkg' => \@cust_credit_source_bill_pkg,
1560 if ( $remaining_value > 0 ) {
1561 warn "Crediting for $remaining_value on package ".$self->pkgnum."\n"
1563 my $error = $self->cust_main->credit(
1565 'Credit for unused time on '. $self->part_pkg->pkg,
1566 'reason_type' => $reason_type,
1567 'cust_credit_source_bill_pkg' => \@cust_credit_source_bill_pkg,
1569 return "Error crediting customer \$$remaining_value for unused time".
1570 " on ". $self->part_pkg->pkg. ": $error"
1572 } #if $remaining_value
1573 } #if $last_bill, etc.
1577 =item unsuspend [ OPTION => VALUE ... ]
1579 Unsuspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
1580 package, then unsuspends the package itself (clears the susp field and the
1581 adjourn field if it is in the past). If the suspend reason includes an
1582 unsuspension package, that package will be ordered.
1584 Available options are:
1590 Can be set to a date to unsuspend the package in the future (the 'resume'
1593 =item adjust_next_bill
1595 Can be set true to adjust the next bill date forward by
1596 the amount of time the account was inactive. This was set true by default
1597 in the past (from 1.4.2 and 1.5.0pre6 through 1.7.0), but now needs to be
1598 explicitly requested with this option or in the price plan.
1602 If there is an error, returns the error, otherwise returns false.
1607 my( $self, %opt ) = @_;
1610 # pass all suspend/cancel actions to the main package
1611 if ( $self->main_pkgnum and !$opt{'from_main'} ) {
1612 return $self->main_pkg->unsuspend(%opt);
1615 my $oldAutoCommit = $FS::UID::AutoCommit;
1616 local $FS::UID::AutoCommit = 0;
1619 my $old = $self->select_for_update;
1621 my $pkgnum = $old->pkgnum;
1622 if ( $old->get('cancel') || $self->get('cancel') ) {
1623 $dbh->rollback if $oldAutoCommit;
1624 return "Can't unsuspend cancelled package $pkgnum";
1627 unless ( $old->get('susp') && $self->get('susp') ) {
1628 $dbh->rollback if $oldAutoCommit;
1629 return ""; # no error # complain instead?
1632 # handle the case of setting a future unsuspend (resume) date
1633 # and do not continue to actually unsuspend the package
1634 my $date = $opt{'date'};
1635 if ( $date and $date > time ) { # return an error if $date <= time?
1637 if ( $old->get('expire') && $old->get('expire') < $date ) {
1638 $dbh->rollback if $oldAutoCommit;
1639 return "Package $pkgnum expires before it would be unsuspended.";
1642 my $new = new FS::cust_pkg { $self->hash };
1643 $new->set('resume', $date);
1644 $error = $new->replace($self, options => $self->options);
1647 $dbh->rollback if $oldAutoCommit;
1651 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1657 if (!$self->setup) {
1658 # then this package is being released from on-hold status
1659 $self->set_initial_timers;
1664 foreach my $cust_svc (
1665 qsearch('cust_svc',{'pkgnum'=> $self->pkgnum } )
1667 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
1669 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
1670 $dbh->rollback if $oldAutoCommit;
1671 return "Illegal svcdb value in part_svc!";
1674 require "FS/$svcdb.pm";
1676 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
1678 $error = $svc->unsuspend;
1680 $dbh->rollback if $oldAutoCommit;
1683 my( $label, $value ) = $cust_svc->label;
1684 push @labels, "$label: $value";
1689 my $cust_pkg_reason = $self->last_cust_pkg_reason('susp');
1690 my $reason = $cust_pkg_reason ? $cust_pkg_reason->reason : '';
1692 my %hash = $self->hash;
1693 my $inactive = time - $hash{'susp'};
1695 my $conf = new FS::Conf;
1697 #adjust the next bill date forward
1698 # increment next bill date if certain conditions are met:
1699 # - it was due to be billed at some point
1700 # - either the global or local config says to do this
1701 my $adjust_bill = 0;
1704 && ( $hash{'bill'} || $hash{'setup'} )
1705 && ( $opt{'adjust_next_bill'}
1706 || $conf->exists('unsuspend-always_adjust_next_bill_date')
1707 || $self->part_pkg->option('unsuspend_adjust_bill', 1)
1714 # - the package billed during suspension
1715 # - or it was ordered on hold
1716 # - or the customer was credited for the unused time
1718 if ( $self->option('suspend_bill',1)
1719 or ( $self->part_pkg->option('suspend_bill',1)
1720 and ! $self->option('no_suspend_bill',1)
1722 or $hash{'order_date'} == $hash{'susp'}
1727 if ( $adjust_bill ) {
1728 if ( $self->part_pkg->option('unused_credit_suspend')
1729 or ( ref($reason) and $reason->unused_credit ) ) {
1730 # then the customer was credited for the unused time before suspending,
1731 # so their next bill should be immediate
1732 $hash{'bill'} = time;
1734 # add the length of time suspended to the bill date
1735 $hash{'bill'} = ( $hash{'bill'} || $hash{'setup'} ) + $inactive;
1740 $hash{'adjourn'} = '' if $hash{'adjourn'} and $hash{'adjourn'} < time;
1741 $hash{'resume'} = '' if !$hash{'adjourn'};
1742 my $new = new FS::cust_pkg ( \%hash );
1743 $error = $new->replace( $self, options => { $self->options } );
1745 $dbh->rollback if $oldAutoCommit;
1752 if ( $reason->unsuspend_pkgpart ) {
1753 #warn "Suspend reason '".$reason->reason."' uses deprecated unsuspend_pkgpart feature.\n"; # in 4.x
1754 my $part_pkg = FS::part_pkg->by_key($reason->unsuspend_pkgpart)
1755 or $error = "Unsuspend package definition ".$reason->unsuspend_pkgpart.
1757 my $start_date = $self->cust_main->next_bill_date
1758 if $reason->unsuspend_hold;
1761 $unsusp_pkg = FS::cust_pkg->new({
1762 'custnum' => $self->custnum,
1763 'pkgpart' => $reason->unsuspend_pkgpart,
1764 'start_date' => $start_date,
1765 'locationnum' => $self->locationnum,
1766 # discount? probably not...
1769 $error ||= $self->cust_main->order_pkg( 'cust_pkg' => $unsusp_pkg );
1772 # new way, using fees
1773 if ( $reason->feepart and $reason->fee_on_unsuspend ) {
1774 # register the need to charge a fee, cust_main->bill will do the rest
1775 warn "registering unsuspend fee: pkgnum ".$self->pkgnum.", feepart ".$reason->feepart."\n"
1777 my $cust_pkg_reason_fee = FS::cust_pkg_reason_fee->new({
1778 'pkgreasonnum' => $cust_pkg_reason->num,
1779 'pkgnum' => $self->pkgnum,
1780 'feepart' => $reason->feepart,
1781 'nextbill' => $reason->fee_hold,
1783 $error ||= $cust_pkg_reason_fee->insert;
1787 $dbh->rollback if $oldAutoCommit;
1792 if ( $conf->config('unsuspend_email_admin') ) {
1794 my $error = send_email(
1795 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
1796 #invoice_from ??? well as good as any
1797 'to' => $conf->config('unsuspend_email_admin'),
1798 'subject' => 'FREESIDE NOTIFICATION: Customer package unsuspended', 'body' => [
1799 "This is an automatic message from your Freeside installation\n",
1800 "informing you that the following customer package has been unsuspended:\n",
1802 'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
1803 'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
1804 ( map { "Service : $_\n" } @labels ),
1806 "An unsuspension fee was charged: ".
1807 $unsusp_pkg->part_pkg->pkg_comment."\n"
1811 'custnum' => $self->custnum,
1812 'msgtype' => 'admin',
1816 warn "WARNING: can't send unsuspension admin email (unsuspending anyway): ".
1822 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1823 $error = $supp_pkg->unsuspend(%opt, 'from_main' => 1);
1825 $dbh->rollback if $oldAutoCommit;
1826 return "unsuspending supplemental pkg#".$supp_pkg->pkgnum.": $error";
1830 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1837 Cancels any pending suspension (sets the adjourn field to null).
1839 If there is an error, returns the error, otherwise returns false.
1844 my( $self, %options ) = @_;
1847 my $oldAutoCommit = $FS::UID::AutoCommit;
1848 local $FS::UID::AutoCommit = 0;
1851 my $old = $self->select_for_update;
1853 my $pkgnum = $old->pkgnum;
1854 if ( $old->get('cancel') || $self->get('cancel') ) {
1855 dbh->rollback if $oldAutoCommit;
1856 return "Can't unadjourn cancelled package $pkgnum";
1857 # or at least it's pointless
1860 if ( $old->get('susp') || $self->get('susp') ) {
1861 dbh->rollback if $oldAutoCommit;
1862 return "Can't unadjourn suspended package $pkgnum";
1863 # perhaps this is arbitrary
1866 unless ( $old->get('adjourn') && $self->get('adjourn') ) {
1867 dbh->rollback if $oldAutoCommit;
1868 return ""; # no error
1871 my %hash = $self->hash;
1872 $hash{'adjourn'} = '';
1873 $hash{'resume'} = '';
1874 my $new = new FS::cust_pkg ( \%hash );
1875 $error = $new->replace( $self, options => { $self->options } );
1877 $dbh->rollback if $oldAutoCommit;
1881 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1888 =item change HASHREF | OPTION => VALUE ...
1890 Changes this package: cancels it and creates a new one, with a different
1891 pkgpart or locationnum or both. All services are transferred to the new
1892 package (no change will be made if this is not possible).
1894 Options may be passed as a list of key/value pairs or as a hash reference.
1901 New locationnum, to change the location for this package.
1905 New FS::cust_location object, to create a new location and assign it
1910 New FS::cust_main object, to create a new customer and assign the new package
1915 New pkgpart (see L<FS::part_pkg>).
1919 New refnum (see L<FS::part_referral>).
1923 New quantity; if unspecified, the new package will have the same quantity
1928 "New" (existing) FS::cust_pkg object. The package's services and other
1929 attributes will be transferred to this package.
1933 Set to true to transfer billing dates (start_date, setup, last_bill, bill,
1934 susp, adjourn, cancel, expire, and contract_end) to the new package.
1936 =item unprotect_svcs
1938 Normally, change() will rollback and return an error if some services
1939 can't be transferred (also see the I<cust_pkg-change_svcpart> config option).
1940 If unprotect_svcs is true, this method will transfer as many services as
1941 it can and then unconditionally cancel the old package.
1945 At least one of locationnum, cust_location, pkgpart, refnum, cust_main, or
1946 cust_pkg must be specified (otherwise, what's the point?)
1948 Returns either the new FS::cust_pkg object or a scalar error.
1952 my $err_or_new_cust_pkg = $old_cust_pkg->change
1956 #some false laziness w/order
1959 my $opt = ref($_[0]) ? shift : { @_ };
1961 my $conf = new FS::Conf;
1963 # Transactionize this whole mess
1964 my $oldAutoCommit = $FS::UID::AutoCommit;
1965 local $FS::UID::AutoCommit = 0;
1974 $hash{'setup'} = $time if $self->setup;
1976 $hash{'change_date'} = $time;
1977 $hash{"change_$_"} = $self->$_()
1978 foreach qw( pkgnum pkgpart locationnum );
1980 if ( $opt->{'cust_location'} ) {
1981 $error = $opt->{'cust_location'}->find_or_insert;
1983 $dbh->rollback if $oldAutoCommit;
1984 return "creating location record: $error";
1986 $opt->{'locationnum'} = $opt->{'cust_location'}->locationnum;
1989 if ( $opt->{'cust_pkg'} ) {
1990 # treat changing to a package with a different pkgpart as a
1991 # pkgpart change (because it is)
1992 $opt->{'pkgpart'} = $opt->{'cust_pkg'}->pkgpart;
1995 # whether to override pkgpart checking on the new package
1996 my $same_pkgpart = 1;
1997 if ( $opt->{'pkgpart'} and ( $opt->{'pkgpart'} != $self->pkgpart ) ) {
2001 my $unused_credit = 0;
2002 my $keep_dates = $opt->{'keep_dates'};
2003 # Special case. If the pkgpart is changing, and the customer is
2004 # going to be credited for remaining time, don't keep setup, bill,
2005 # or last_bill dates, and DO pass the flag to cancel() to credit
2007 if ( $opt->{'pkgpart'}
2008 and $opt->{'pkgpart'} != $self->pkgpart
2009 and $self->part_pkg->option('unused_credit_change', 1) ) {
2012 $hash{$_} = '' foreach qw(setup bill last_bill);
2015 if ( $keep_dates ) {
2016 foreach my $date ( qw(setup bill last_bill susp adjourn cancel expire
2017 resume start_date contract_end ) ) {
2018 $hash{$date} = $self->getfield($date);
2021 # always keep this date, regardless of anything
2022 # (the date of the package change is in a different field)
2023 $hash{'order_date'} = $self->getfield('order_date');
2025 # allow $opt->{'locationnum'} = '' to specifically set it to null
2026 # (i.e. customer default location)
2027 $opt->{'locationnum'} = $self->locationnum if !exists($opt->{'locationnum'});
2029 # usually this doesn't matter. the two cases where it does are:
2030 # 1. unused_credit_change + pkgpart change + setup fee on the new package
2032 # 2. (more importantly) changing a package before it's billed
2033 $hash{'waive_setup'} = $self->waive_setup;
2035 my $custnum = $self->custnum;
2036 if ( $opt->{cust_main} ) {
2037 my $cust_main = $opt->{cust_main};
2038 unless ( $cust_main->custnum ) {
2039 my $error = $cust_main->insert( @{ $opt->{cust_main_insert_args}||[] } );
2041 $dbh->rollback if $oldAutoCommit;
2042 return "inserting customer record: $error";
2045 $custnum = $cust_main->custnum;
2048 $hash{'contactnum'} = $opt->{'contactnum'} if $opt->{'contactnum'};
2051 if ( $opt->{'cust_pkg'} ) {
2052 # The target package already exists; update it to show that it was
2053 # changed from this package.
2054 $cust_pkg = $opt->{'cust_pkg'};
2056 foreach ( qw( pkgnum pkgpart locationnum ) ) {
2057 $cust_pkg->set("change_$_", $self->get($_));
2059 $cust_pkg->set('change_date', $time);
2060 $error = $cust_pkg->replace;
2063 # Create the new package.
2064 $cust_pkg = new FS::cust_pkg {
2065 custnum => $custnum,
2066 locationnum => $opt->{'locationnum'},
2067 ( map { $_ => ( $opt->{$_} || $self->$_() ) }
2068 qw( pkgpart quantity refnum salesnum )
2072 $error = $cust_pkg->insert( 'change' => 1,
2073 'allow_pkgpart' => $same_pkgpart );
2076 $dbh->rollback if $oldAutoCommit;
2077 return "inserting new package: $error";
2080 # Transfer services and cancel old package.
2081 # Enforce service limits only if this is a pkgpart change.
2082 local $FS::cust_svc::ignore_quantity;
2083 $FS::cust_svc::ignore_quantity = 1 if $same_pkgpart;
2084 $error = $self->transfer($cust_pkg);
2085 if ($error and $error == 0) {
2086 # $old_pkg->transfer failed.
2087 $dbh->rollback if $oldAutoCommit;
2088 return "transferring $error";
2091 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
2092 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
2093 $error = $self->transfer($cust_pkg, 'change_svcpart'=>1 );
2094 if ($error and $error == 0) {
2095 # $old_pkg->transfer failed.
2096 $dbh->rollback if $oldAutoCommit;
2097 return "converting $error";
2101 # We set unprotect_svcs when executing a "future package change". It's
2102 # not a user-interactive operation, so returning an error means the
2103 # package change will just fail. Rather than have that happen, we'll
2104 # let leftover services be deleted.
2105 if ($error > 0 and !$opt->{'unprotect_svcs'}) {
2106 # Transfers were successful, but we still had services left on the old
2107 # package. We can't change the package under this circumstances, so abort.
2108 $dbh->rollback if $oldAutoCommit;
2109 return "unable to transfer all services";
2112 #reset usage if changing pkgpart
2113 # AND usage rollover is off (otherwise adds twice, now and at package bill)
2114 if ($self->pkgpart != $cust_pkg->pkgpart) {
2115 my $part_pkg = $cust_pkg->part_pkg;
2116 $error = $part_pkg->reset_usage($cust_pkg, $part_pkg->is_prepaid
2120 if $part_pkg->can('reset_usage') && ! $part_pkg->option('usage_rollover',1);
2123 $dbh->rollback if $oldAutoCommit;
2124 return "setting usage values: $error";
2127 # if NOT changing pkgpart, transfer any usage pools over
2128 foreach my $usage ($self->cust_pkg_usage) {
2129 $usage->set('pkgnum', $cust_pkg->pkgnum);
2130 $error = $usage->replace;
2132 $dbh->rollback if $oldAutoCommit;
2133 return "transferring usage pools: $error";
2138 # transfer usage pricing add-ons, if we're not changing pkgpart
2139 if ( $same_pkgpart ) {
2140 foreach my $old_cust_pkg_usageprice ($self->cust_pkg_usageprice) {
2141 my $new_cust_pkg_usageprice = new FS::cust_pkg_usageprice {
2142 'pkgnum' => $cust_pkg->pkgnum,
2143 'usagepricepart' => $old_cust_pkg_usageprice->usagepricepart,
2144 'quantity' => $old_cust_pkg_usageprice->quantity,
2146 $error = $new_cust_pkg_usageprice->insert;
2148 $dbh->rollback if $oldAutoCommit;
2149 return "Error transferring usage pricing add-on: $error";
2154 # transfer discounts, if we're not changing pkgpart
2155 if ( $same_pkgpart ) {
2156 foreach my $old_discount ($self->cust_pkg_discount_active) {
2157 # don't remove the old discount, we may still need to bill that package.
2158 my $new_discount = new FS::cust_pkg_discount {
2159 'pkgnum' => $cust_pkg->pkgnum,
2160 'discountnum' => $old_discount->discountnum,
2161 'months_used' => $old_discount->months_used,
2163 $error = $new_discount->insert;
2165 $dbh->rollback if $oldAutoCommit;
2166 return "transferring discounts: $error";
2171 # transfer (copy) invoice details
2172 foreach my $detail ($self->cust_pkg_detail) {
2173 my $new_detail = FS::cust_pkg_detail->new({ $detail->hash });
2174 $new_detail->set('pkgdetailnum', '');
2175 $new_detail->set('pkgnum', $cust_pkg->pkgnum);
2176 $error = $new_detail->insert;
2178 $dbh->rollback if $oldAutoCommit;
2179 return "transferring package notes: $error";
2185 if ( !$opt->{'cust_pkg'} ) {
2186 # Order any supplemental packages.
2187 my $part_pkg = $cust_pkg->part_pkg;
2188 my @old_supp_pkgs = $self->supplemental_pkgs;
2189 foreach my $link ($part_pkg->supp_part_pkg_link) {
2191 foreach (@old_supp_pkgs) {
2192 if ($_->pkgpart == $link->dst_pkgpart) {
2194 $_->pkgpart(0); # so that it can't match more than once
2198 # false laziness with FS::cust_main::Packages::order_pkg
2199 my $new = FS::cust_pkg->new({
2200 pkgpart => $link->dst_pkgpart,
2201 pkglinknum => $link->pkglinknum,
2202 custnum => $custnum,
2203 main_pkgnum => $cust_pkg->pkgnum,
2204 locationnum => $cust_pkg->locationnum,
2205 start_date => $cust_pkg->start_date,
2206 order_date => $cust_pkg->order_date,
2207 expire => $cust_pkg->expire,
2208 adjourn => $cust_pkg->adjourn,
2209 contract_end => $cust_pkg->contract_end,
2210 refnum => $cust_pkg->refnum,
2211 discountnum => $cust_pkg->discountnum,
2212 waive_setup => $cust_pkg->waive_setup,
2214 if ( $old and $opt->{'keep_dates'} ) {
2215 foreach (qw(setup bill last_bill)) {
2216 $new->set($_, $old->get($_));
2219 $error = $new->insert( allow_pkgpart => $same_pkgpart );
2222 $error ||= $old->transfer($new);
2224 if ( $error and $error > 0 ) {
2225 # no reason why this should ever fail, but still...
2226 $error = "Unable to transfer all services from supplemental package ".
2230 $dbh->rollback if $oldAutoCommit;
2233 push @new_supp_pkgs, $new;
2235 } # if !$opt->{'cust_pkg'}
2236 # because if there is one, then supplemental packages would already
2237 # have been created for it.
2239 #Good to go, cancel old package. Notify 'cancel' of whether to credit
2241 #Don't allow billing the package (preceding period packages and/or
2242 #outstanding usage) if we are keeping dates (i.e. location changing),
2243 #because the new package will be billed for the same date range.
2244 #Supplemental packages are also canceled here.
2246 # during scheduled changes, avoid canceling the package we just
2248 $self->set('change_to_pkgnum' => '');
2250 $error = $self->cancel(
2252 unused_credit => $unused_credit,
2253 nobill => $keep_dates,
2254 change_custnum => ( $self->custnum != $custnum ? $custnum : '' ),
2255 no_delay_cancel => 1,
2258 $dbh->rollback if $oldAutoCommit;
2259 return "canceling old package: $error";
2262 if ( $conf->exists('cust_pkg-change_pkgpart-bill_now') ) {
2264 my $error = $cust_pkg->cust_main->bill(
2265 'pkg_list' => [ $cust_pkg, @new_supp_pkgs ]
2268 $dbh->rollback if $oldAutoCommit;
2269 return "billing new package: $error";
2273 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2279 =item change_later OPTION => VALUE...
2281 Schedule a package change for a later date. This actually orders the new
2282 package immediately, but sets its start date for a future date, and sets
2283 the current package to expire on the same date.
2285 If the package is already scheduled for a change, this can be called with
2286 'start_date' to change the scheduled date, or with pkgpart and/or
2287 locationnum to modify the package change. To cancel the scheduled change
2288 entirely, see C<abort_change>.
2296 The date for the package change. Required, and must be in the future.
2304 The pkgpart. locationnum, and quantity of the new package, with the same
2305 meaning as in C<change>.
2313 my $opt = ref($_[0]) ? shift : { @_ };
2315 my $oldAutoCommit = $FS::UID::AutoCommit;
2316 local $FS::UID::AutoCommit = 0;
2319 my $cust_main = $self->cust_main;
2321 my $date = delete $opt->{'start_date'} or return 'start_date required';
2323 if ( $date <= time ) {
2324 $dbh->rollback if $oldAutoCommit;
2325 return "start_date $date is in the past";
2330 if ( $self->change_to_pkgnum ) {
2331 my $change_to = FS::cust_pkg->by_key($self->change_to_pkgnum);
2332 my $new_pkgpart = $opt->{'pkgpart'}
2333 if $opt->{'pkgpart'} and $opt->{'pkgpart'} != $change_to->pkgpart;
2334 my $new_locationnum = $opt->{'locationnum'}
2335 if $opt->{'locationnum'} and $opt->{'locationnum'} != $change_to->locationnum;
2336 my $new_quantity = $opt->{'quantity'}
2337 if $opt->{'quantity'} and $opt->{'quantity'} != $change_to->quantity;
2338 if ( $new_pkgpart or $new_locationnum or $new_quantity ) {
2339 # it hasn't been billed yet, so in principle we could just edit
2340 # it in place (w/o a package change), but that's bad form.
2341 # So change the package according to the new options...
2342 my $err_or_pkg = $change_to->change(%$opt);
2343 if ( ref $err_or_pkg ) {
2344 # Then set that package up for a future start.
2345 $self->set('change_to_pkgnum', $err_or_pkg->pkgnum);
2346 $self->set('expire', $date); # in case it's different
2347 $err_or_pkg->set('start_date', $date);
2348 $err_or_pkg->set('change_date', '');
2349 $err_or_pkg->set('change_pkgnum', '');
2351 $error = $self->replace ||
2352 $err_or_pkg->replace ||
2353 $change_to->cancel('no_delay_cancel' => 1) ||
2356 $error = $err_or_pkg;
2358 } else { # change the start date only.
2359 $self->set('expire', $date);
2360 $change_to->set('start_date', $date);
2361 $error = $self->replace || $change_to->replace;
2364 $dbh->rollback if $oldAutoCommit;
2367 $dbh->commit if $oldAutoCommit;
2370 } # if $self->change_to_pkgnum
2372 my $new_pkgpart = $opt->{'pkgpart'}
2373 if $opt->{'pkgpart'} and $opt->{'pkgpart'} != $self->pkgpart;
2374 my $new_locationnum = $opt->{'locationnum'}
2375 if $opt->{'locationnum'} and $opt->{'locationnum'} != $self->locationnum;
2376 my $new_quantity = $opt->{'quantity'}
2377 if $opt->{'quantity'} and $opt->{'quantity'} != $self->quantity;
2379 return '' unless $new_pkgpart or $new_locationnum or $new_quantity; # wouldn't do anything
2381 # allow $opt->{'locationnum'} = '' to specifically set it to null
2382 # (i.e. customer default location)
2383 $opt->{'locationnum'} = $self->locationnum if !exists($opt->{'locationnum'});
2385 my $new = FS::cust_pkg->new( {
2386 custnum => $self->custnum,
2387 locationnum => $opt->{'locationnum'},
2388 start_date => $date,
2389 map { $_ => ( $opt->{$_} || $self->$_() ) }
2390 qw( pkgpart quantity refnum salesnum )
2392 $error = $new->insert('change' => 1,
2393 'allow_pkgpart' => ($new_pkgpart ? 0 : 1));
2395 $self->set('change_to_pkgnum', $new->pkgnum);
2396 $self->set('expire', $date);
2397 $error = $self->replace;
2400 $dbh->rollback if $oldAutoCommit;
2402 $dbh->commit if $oldAutoCommit;
2410 Cancels a future package change scheduled by C<change_later>.
2416 my $pkgnum = $self->change_to_pkgnum;
2417 my $change_to = FS::cust_pkg->by_key($pkgnum) if $pkgnum;
2420 $error = $change_to->cancel || $change_to->delete;
2421 return $error if $error;
2423 $self->set('change_to_pkgnum', '');
2424 $self->set('expire', '');
2428 =item set_quantity QUANTITY
2430 Change the package's quantity field. This is one of the few package properties
2431 that can safely be changed without canceling and reordering the package
2432 (because it doesn't affect tax eligibility). Returns an error or an
2439 $self = $self->replace_old; # just to make sure
2440 $self->quantity(shift);
2444 =item set_salesnum SALESNUM
2446 Change the package's salesnum (sales person) field. This is one of the few
2447 package properties that can safely be changed without canceling and reordering
2448 the package (because it doesn't affect tax eligibility). Returns an error or
2455 $self = $self->replace_old; # just to make sure
2456 $self->salesnum(shift);
2458 # XXX this should probably reassign any credit that's already been given
2461 =item modify_charge OPTIONS
2463 Change the properties of a one-time charge. The following properties can
2464 be changed this way:
2465 - pkg: the package description
2466 - classnum: the package class
2467 - additional: arrayref of additional invoice details to add to this package
2469 and, I<if the charge has not yet been billed>:
2470 - start_date: the date when it will be billed
2471 - amount: the setup fee to be charged
2472 - quantity: the multiplier for the setup fee
2473 - separate_bill: whether to put the charge on a separate invoice
2475 If you pass 'adjust_commission' => 1, and the classnum changes, and there are
2476 commission credits linked to this charge, they will be recalculated.
2483 my $part_pkg = $self->part_pkg;
2484 my $pkgnum = $self->pkgnum;
2487 my $oldAutoCommit = $FS::UID::AutoCommit;
2488 local $FS::UID::AutoCommit = 0;
2490 return "Can't use modify_charge except on one-time charges"
2491 unless $part_pkg->freq eq '0';
2493 if ( length($opt{'pkg'}) and $part_pkg->pkg ne $opt{'pkg'} ) {
2494 $part_pkg->set('pkg', $opt{'pkg'});
2497 my %pkg_opt = $part_pkg->options;
2498 my $pkg_opt_modified = 0;
2500 $opt{'additional'} ||= [];
2503 foreach (grep /^additional/, keys %pkg_opt) {
2504 ($i) = ($_ =~ /^additional_info(\d+)$/);
2505 $old_additional[$i] = $pkg_opt{$_} if $i;
2506 delete $pkg_opt{$_};
2509 for ( $i = 0; exists($opt{'additional'}->[$i]); $i++ ) {
2510 $pkg_opt{ "additional_info$i" } = $opt{'additional'}->[$i];
2511 if (!exists($old_additional[$i])
2512 or $old_additional[$i] ne $opt{'additional'}->[$i])
2514 $pkg_opt_modified = 1;
2517 $pkg_opt_modified = 1 if (scalar(@old_additional) - 1) != $i;
2518 $pkg_opt{'additional_count'} = $i if $i > 0;
2521 if ( exists($opt{'classnum'}) and $part_pkg->classnum ne $opt{'classnum'} )
2524 $old_classnum = $part_pkg->classnum;
2525 $part_pkg->set('classnum', $opt{'classnum'});
2528 if ( !$self->get('setup') ) {
2529 # not yet billed, so allow amount, setup_cost, quantity, start_date,
2532 if ( exists($opt{'amount'})
2533 and $part_pkg->option('setup_fee') != $opt{'amount'}
2534 and $opt{'amount'} > 0 ) {
2536 $pkg_opt{'setup_fee'} = $opt{'amount'};
2537 $pkg_opt_modified = 1;
2540 if ( exists($opt{'setup_cost'})
2541 and $part_pkg->setup_cost != $opt{'setup_cost'}
2542 and $opt{'setup_cost'} > 0 ) {
2544 $part_pkg->set('setup_cost', $opt{'setup_cost'});
2547 if ( exists($opt{'quantity'})
2548 and $opt{'quantity'} != $self->quantity
2549 and $opt{'quantity'} > 0 ) {
2551 $self->set('quantity', $opt{'quantity'});
2554 if ( exists($opt{'start_date'})
2555 and $opt{'start_date'} != $self->start_date ) {
2557 $self->set('start_date', $opt{'start_date'});
2560 if ( exists($opt{'separate_bill'})
2561 and $opt{'separate_bill'} ne $self->separate_bill ) {
2563 $self->set('separate_bill', $opt{'separate_bill'});
2567 } # else simply ignore them; the UI shouldn't allow editing the fields
2570 if ( exists($opt{'taxclass'})
2571 and $part_pkg->taxclass ne $opt{'taxclass'}) {
2573 $part_pkg->set('taxclass', $opt{'taxclass'});
2577 if ( $part_pkg->modified or $pkg_opt_modified ) {
2578 # can we safely modify the package def?
2579 # Yes, if it's not available for purchase, and this is the only instance
2581 if ( $part_pkg->disabled
2582 and FS::cust_pkg->count('pkgpart = '.$part_pkg->pkgpart) == 1
2583 and FS::quotation_pkg->count('pkgpart = '.$part_pkg->pkgpart) == 0
2585 $error = $part_pkg->replace( options => \%pkg_opt );
2588 $part_pkg = $part_pkg->clone;
2589 $part_pkg->set('disabled' => 'Y');
2590 $error = $part_pkg->insert( options => \%pkg_opt );
2591 # and associate this as yet-unbilled package to the new package def
2592 $self->set('pkgpart' => $part_pkg->pkgpart);
2595 $dbh->rollback if $oldAutoCommit;
2600 if ($self->modified) { # for quantity or start_date change, or if we had
2601 # to clone the existing package def
2602 my $error = $self->replace;
2603 return $error if $error;
2605 if (defined $old_classnum) {
2606 # fix invoice grouping records
2607 my $old_catname = $old_classnum
2608 ? FS::pkg_class->by_key($old_classnum)->categoryname
2610 my $new_catname = $opt{'classnum'}
2611 ? $part_pkg->pkg_class->categoryname
2613 if ( $old_catname ne $new_catname ) {
2614 foreach my $cust_bill_pkg ($self->cust_bill_pkg) {
2615 # (there should only be one...)
2616 my @display = qsearch( 'cust_bill_pkg_display', {
2617 'billpkgnum' => $cust_bill_pkg->billpkgnum,
2618 'section' => $old_catname,
2620 foreach (@display) {
2621 $_->set('section', $new_catname);
2622 $error = $_->replace;
2624 $dbh->rollback if $oldAutoCommit;
2628 } # foreach $cust_bill_pkg
2631 if ( $opt{'adjust_commission'} ) {
2632 # fix commission credits...tricky.
2633 foreach my $cust_event ($self->cust_event) {
2634 my $part_event = $cust_event->part_event;
2635 foreach my $table (qw(sales agent)) {
2637 "FS::part_event::Action::Mixin::credit_${table}_pkg_class";
2638 my $credit = qsearchs('cust_credit', {
2639 'eventnum' => $cust_event->eventnum,
2641 if ( $part_event->isa($class) ) {
2642 # Yes, this results in current commission rates being applied
2643 # retroactively to a one-time charge. For accounting purposes
2644 # there ought to be some kind of time limit on doing this.
2645 my $amount = $part_event->_calc_credit($self);
2646 if ( $credit and $credit->amount ne $amount ) {
2647 # Void the old credit.
2648 $error = $credit->void('Package class changed');
2650 $dbh->rollback if $oldAutoCommit;
2651 return "$error (adjusting commission credit)";
2654 # redo the event action to recreate the credit.
2656 eval { $part_event->do_action( $self, $cust_event ) };
2658 $dbh->rollback if $oldAutoCommit;
2661 } # if $part_event->isa($class)
2663 } # foreach $cust_event
2664 } # if $opt{'adjust_commission'}
2665 } # if defined $old_classnum
2667 $dbh->commit if $oldAutoCommit;
2674 sub process_bulk_cust_pkg {
2677 warn Dumper($param) if $DEBUG;
2679 my $old_part_pkg = qsearchs('part_pkg',
2680 { pkgpart => $param->{'old_pkgpart'} });
2681 my $new_part_pkg = qsearchs('part_pkg',
2682 { pkgpart => $param->{'new_pkgpart'} });
2683 die "Must select a new package type\n" unless $new_part_pkg;
2684 #my $keep_dates = $param->{'keep_dates'} || 0;
2685 my $keep_dates = 1; # there is no good reason to turn this off
2687 my $oldAutoCommit = $FS::UID::AutoCommit;
2688 local $FS::UID::AutoCommit = 0;
2691 my @cust_pkgs = qsearch('cust_pkg', { 'pkgpart' => $param->{'old_pkgpart'} } );
2694 foreach my $old_cust_pkg ( @cust_pkgs ) {
2696 $job->update_statustext(int(100*$i/(scalar @cust_pkgs)));
2697 if ( $old_cust_pkg->getfield('cancel') ) {
2698 warn '[process_bulk_cust_pkg ] skipping canceled pkgnum '.
2699 $old_cust_pkg->pkgnum."\n"
2703 warn '[process_bulk_cust_pkg] changing pkgnum '.$old_cust_pkg->pkgnum."\n"
2705 my $error = $old_cust_pkg->change(
2706 'pkgpart' => $param->{'new_pkgpart'},
2707 'keep_dates' => $keep_dates
2709 if ( !ref($error) ) { # change returns the cust_pkg on success
2711 die "Error changing pkgnum ".$old_cust_pkg->pkgnum.": '$error'\n";
2714 $dbh->commit if $oldAutoCommit;
2720 Returns the last bill date, or if there is no last bill date, the setup date.
2721 Useful for billing metered services.
2727 return $self->setfield('last_bill', $_[0]) if @_;
2728 return $self->getfield('last_bill') if $self->getfield('last_bill');
2729 my $cust_bill_pkg = qsearchs('cust_bill_pkg', { 'pkgnum' => $self->pkgnum,
2730 'edate' => $self->bill, } );
2731 $cust_bill_pkg ? $cust_bill_pkg->sdate : $self->setup || 0;
2734 =item last_cust_pkg_reason ACTION
2736 Returns the most recent ACTION FS::cust_pkg_reason associated with the package.
2737 Returns false if there is no reason or the package is not currenly ACTION'd
2738 ACTION is one of adjourn, susp, cancel, or expire.
2742 sub last_cust_pkg_reason {
2743 my ( $self, $action ) = ( shift, shift );
2744 my $date = $self->get($action);
2746 'table' => 'cust_pkg_reason',
2747 'hashref' => { 'pkgnum' => $self->pkgnum,
2748 'action' => substr(uc($action), 0, 1),
2751 'order_by' => 'ORDER BY num DESC LIMIT 1',
2755 =item last_reason ACTION
2757 Returns the most recent ACTION FS::reason associated with the package.
2758 Returns false if there is no reason or the package is not currenly ACTION'd
2759 ACTION is one of adjourn, susp, cancel, or expire.
2764 my $cust_pkg_reason = shift->last_cust_pkg_reason(@_);
2765 $cust_pkg_reason->reason
2766 if $cust_pkg_reason;
2771 Returns the definition for this billing item, as an FS::part_pkg object (see
2778 return $self->{'_pkgpart'} if $self->{'_pkgpart'};
2779 cluck "cust_pkg->part_pkg called" if $DEBUG > 1;
2780 qsearchs( 'part_pkg', { 'pkgpart' => $self->pkgpart } );
2785 Returns the cancelled package this package was changed from, if any.
2791 return '' unless $self->change_pkgnum;
2792 qsearchs('cust_pkg', { 'pkgnum' => $self->change_pkgnum } );
2795 =item change_cust_main
2797 Returns the customter this package was detached to, if any.
2801 sub change_cust_main {
2803 return '' unless $self->change_custnum;
2804 qsearchs('cust_main', { 'custnum' => $self->change_custnum } );
2809 Calls the I<calc_setup> of the FS::part_pkg object associated with this billing
2816 $self->part_pkg->calc_setup($self, @_);
2821 Calls the I<calc_recur> of the FS::part_pkg object associated with this billing
2828 $self->part_pkg->calc_recur($self, @_);
2833 Calls the I<base_setup> of the FS::part_pkg object associated with this billing
2840 $self->part_pkg->base_setup($self, @_);
2845 Calls the I<base_recur> of the FS::part_pkg object associated with this billing
2852 $self->part_pkg->base_recur($self, @_);
2857 Calls the I<calc_remain> of the FS::part_pkg object associated with this
2864 $self->part_pkg->calc_remain($self, @_);
2869 Calls the I<calc_cancel> of the FS::part_pkg object associated with this
2876 $self->part_pkg->calc_cancel($self, @_);
2881 Returns any invoice line items for this package (see L<FS::cust_bill_pkg>).
2887 qsearch( 'cust_bill_pkg', { 'pkgnum' => $self->pkgnum } );
2890 =item cust_pkg_detail [ DETAILTYPE ]
2892 Returns any customer package details for this package (see
2893 L<FS::cust_pkg_detail>).
2895 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
2899 sub cust_pkg_detail {
2901 my %hash = ( 'pkgnum' => $self->pkgnum );
2902 $hash{detailtype} = shift if @_;
2904 'table' => 'cust_pkg_detail',
2905 'hashref' => \%hash,
2906 'order_by' => 'ORDER BY weight, pkgdetailnum',
2910 =item set_cust_pkg_detail DETAILTYPE [ DETAIL, DETAIL, ... ]
2912 Sets customer package details for this package (see L<FS::cust_pkg_detail>).
2914 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
2916 If there is an error, returns the error, otherwise returns false.
2920 sub set_cust_pkg_detail {
2921 my( $self, $detailtype, @details ) = @_;
2923 my $oldAutoCommit = $FS::UID::AutoCommit;
2924 local $FS::UID::AutoCommit = 0;
2927 foreach my $current ( $self->cust_pkg_detail($detailtype) ) {
2928 my $error = $current->delete;
2930 $dbh->rollback if $oldAutoCommit;
2931 return "error removing old detail: $error";
2935 foreach my $detail ( @details ) {
2936 my $cust_pkg_detail = new FS::cust_pkg_detail {
2937 'pkgnum' => $self->pkgnum,
2938 'detailtype' => $detailtype,
2939 'detail' => $detail,
2941 my $error = $cust_pkg_detail->insert;
2943 $dbh->rollback if $oldAutoCommit;
2944 return "error adding new detail: $error";
2949 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2956 Returns the customer billing events (see L<FS::cust_event>) for this invoice.
2960 #false laziness w/cust_bill.pm
2964 'table' => 'cust_event',
2965 'addl_from' => 'JOIN part_event USING ( eventpart )',
2966 'hashref' => { 'tablenum' => $self->pkgnum },
2967 'extra_sql' => " AND eventtable = 'cust_pkg' ",
2971 =item num_cust_event
2973 Returns the number of customer billing events (see L<FS::cust_event>) for this package.
2977 #false laziness w/cust_bill.pm
2978 sub num_cust_event {
2980 my $sql = "SELECT COUNT(*) ". $self->_from_cust_event_where;
2981 $self->_prep_ex($sql, $self->pkgnum)->fetchrow_arrayref->[0];
2984 =item exists_cust_event
2986 Returns true if there are customer billing events (see L<FS::cust_event>) for this package. More efficient than using num_cust_event.
2990 sub exists_cust_event {
2992 my $sql = "SELECT 1 ". $self->_from_cust_event_where. " LIMIT 1";
2993 my $row = $self->_prep_ex($sql, $self->pkgnum)->fetchrow_arrayref;
2994 $row ? $row->[0] : '';
2997 sub _from_cust_event_where {
2999 " FROM cust_event JOIN part_event USING ( eventpart ) ".
3000 " WHERE tablenum = ? AND eventtable = 'cust_pkg' ";
3004 my( $self, $sql, @args ) = @_;
3005 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
3006 $sth->execute(@args) or die $sth->errstr. " executing $sql";
3010 =item part_pkg_currency_option OPTIONNAME
3012 Returns a two item list consisting of the currency of this customer, if any,
3013 and a value for the provided option. If the customer has a currency, the value
3014 is the option value the given name and the currency (see
3015 L<FS::part_pkg_currency>). Otherwise, if the customer has no currency, is the
3016 regular option value for the given name (see L<FS::part_pkg_option>).
3020 sub part_pkg_currency_option {
3021 my( $self, $optionname ) = @_;
3022 my $part_pkg = $self->part_pkg;
3023 if ( my $currency = $self->cust_main->currency ) {
3024 ($currency, $part_pkg->part_pkg_currency_option($currency, $optionname) );
3026 ('', $part_pkg->option($optionname) );
3030 =item cust_svc [ SVCPART ] (old, deprecated usage)
3032 =item cust_svc [ OPTION => VALUE ... ] (current usage)
3034 =item cust_svc_unsorted [ OPTION => VALUE ... ]
3036 Returns the services for this package, as FS::cust_svc objects (see
3037 L<FS::cust_svc>). Available options are svcpart and svcdb. If either is
3038 spcififed, returns only the matching services.
3040 As an optimization, use the cust_svc_unsorted version if you are not displaying
3047 cluck "cust_pkg->cust_svc called" if $DEBUG > 2;
3048 $self->_sort_cust_svc( $self->cust_svc_unsorted_arrayref(@_) );
3051 sub cust_svc_unsorted {
3053 @{ $self->cust_svc_unsorted_arrayref(@_) };
3056 sub cust_svc_unsorted_arrayref {
3059 return [] unless $self->num_cust_svc(@_);
3062 if ( @_ && $_[0] =~ /^\d+/ ) {
3063 $opt{svcpart} = shift;
3064 } elsif ( @_ && ref($_[0]) eq 'HASH' ) {
3071 'table' => 'cust_svc',
3072 'hashref' => { 'pkgnum' => $self->pkgnum },
3074 if ( $opt{svcpart} ) {
3075 $search{hashref}->{svcpart} = $opt{'svcpart'};
3077 if ( $opt{'svcdb'} ) {
3078 $search{addl_from} = ' LEFT JOIN part_svc USING ( svcpart ) ';
3079 $search{extra_sql} = ' AND svcdb = '. dbh->quote( $opt{'svcdb'} );
3082 [ qsearch(\%search) ];
3086 =item overlimit [ SVCPART ]
3088 Returns the services for this package which have exceeded their
3089 usage limit as FS::cust_svc objects (see L<FS::cust_svc>). If a svcpart
3090 is specified, return only the matching services.
3096 return () unless $self->num_cust_svc(@_);
3097 grep { $_->overlimit } $self->cust_svc(@_);
3100 =item h_cust_svc END_TIMESTAMP [ START_TIMESTAMP ] [ MODE ]
3102 Returns historical services for this package created before END TIMESTAMP and
3103 (optionally) not cancelled before START_TIMESTAMP, as FS::h_cust_svc objects
3104 (see L<FS::h_cust_svc>). If MODE is 'I' (for 'invoice'), services with the
3105 I<pkg_svc.hidden> flag will be omitted.
3111 warn "$me _h_cust_svc called on $self\n"
3114 my ($end, $start, $mode) = @_;
3116 local($FS::Record::qsearch_qualify_columns) = 0;
3118 my @cust_svc = $self->_sort_cust_svc(
3119 [ qsearch( 'h_cust_svc',
3120 { 'pkgnum' => $self->pkgnum, },
3121 FS::h_cust_svc->sql_h_search(@_),
3125 if ( defined($mode) && $mode eq 'I' ) {
3126 my %hidden_svcpart = map { $_->svcpart => $_->hidden } $self->part_svc;
3127 return grep { !$hidden_svcpart{$_->svcpart} } @cust_svc;
3133 sub _sort_cust_svc {
3134 my( $self, $arrayref ) = @_;
3137 sub ($$) { my ($a, $b) = @_; $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] };
3139 my %pkg_svc = map { $_->svcpart => $_ }
3140 qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
3145 my $pkg_svc = $pkg_svc{ $_->svcpart } || '';
3147 $pkg_svc ? $pkg_svc->primary_svc : '',
3148 $pkg_svc ? $pkg_svc->quantity : 0,
3155 =item num_cust_svc [ SVCPART ] (old, deprecated usage)
3157 =item num_cust_svc [ OPTION => VALUE ... ] (current usage)
3159 Returns the number of services for this package. Available options are svcpart
3160 and svcdb. If either is spcififed, returns only the matching services.
3167 return $self->{'_num_cust_svc'}
3169 && exists($self->{'_num_cust_svc'})
3170 && $self->{'_num_cust_svc'} =~ /\d/;
3172 cluck "cust_pkg->num_cust_svc called, _num_cust_svc:".$self->{'_num_cust_svc'}
3176 if ( @_ && $_[0] =~ /^\d+/ ) {
3177 $opt{svcpart} = shift;
3178 } elsif ( @_ && ref($_[0]) eq 'HASH' ) {
3184 my $select = 'SELECT COUNT(*) FROM cust_svc ';
3185 my $where = ' WHERE pkgnum = ? ';
3186 my @param = ($self->pkgnum);
3188 if ( $opt{'svcpart'} ) {
3189 $where .= ' AND svcpart = ? ';
3190 push @param, $opt{'svcpart'};
3192 if ( $opt{'svcdb'} ) {
3193 $select .= ' LEFT JOIN part_svc USING ( svcpart ) ';
3194 $where .= ' AND svcdb = ? ';
3195 push @param, $opt{'svcdb'};
3198 my $sth = dbh->prepare("$select $where") or die dbh->errstr;
3199 $sth->execute(@param) or die $sth->errstr;
3200 $sth->fetchrow_arrayref->[0];
3203 =item available_part_svc
3205 Returns a list of FS::part_svc objects representing services included in this
3206 package but not yet provisioned. Each FS::part_svc object also has an extra
3207 field, I<num_avail>, which specifies the number of available services.
3211 sub available_part_svc {
3214 my $pkg_quantity = $self->quantity || 1;
3216 grep { $_->num_avail > 0 }
3218 my $part_svc = $_->part_svc;
3219 $part_svc->{'Hash'}{'num_avail'} = #evil encapsulation-breaking
3220 $pkg_quantity * $_->quantity - $self->num_cust_svc($_->svcpart);
3222 # more evil encapsulation breakage
3223 if($part_svc->{'Hash'}{'num_avail'} > 0) {
3224 my @exports = $part_svc->part_export_did;
3225 $part_svc->{'Hash'}{'can_get_dids'} = scalar(@exports);
3230 $self->part_pkg->pkg_svc;
3233 =item part_svc [ OPTION => VALUE ... ]
3235 Returns a list of FS::part_svc objects representing provisioned and available
3236 services included in this package. Each FS::part_svc object also has the
3237 following extra fields:
3251 (services) - array reference containing the provisioned services, as cust_svc objects
3255 Accepts two options:
3259 =item summarize_size
3261 If true, will omit the extra cust_pkg_svc option for objects where num_cust_svc
3262 is this size or greater.
3264 =item hide_discontinued
3266 If true, will omit looking for services that are no longer avaialble in the
3274 #label -> ($cust_svc->label)[1]
3280 my $pkg_quantity = $self->quantity || 1;
3282 #XXX some sort of sort order besides numeric by svcpart...
3283 my @part_svc = sort { $a->svcpart <=> $b->svcpart } map {
3285 my $part_svc = $pkg_svc->part_svc;
3286 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
3287 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #more evil
3288 $part_svc->{'Hash'}{'num_avail'} =
3289 max( 0, $pkg_quantity * $pkg_svc->quantity - $num_cust_svc );
3290 $part_svc->{'Hash'}{'cust_pkg_svc'} =
3291 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : []
3292 unless exists($opt{summarize_size}) && $opt{summarize_size} > 0
3293 && $num_cust_svc >= $opt{summarize_size};
3294 $part_svc->{'Hash'}{'hidden'} = $pkg_svc->hidden;
3296 } $self->part_pkg->pkg_svc;
3298 unless ( $opt{hide_discontinued} ) {
3300 push @part_svc, map {
3302 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
3303 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #speak no evail
3304 $part_svc->{'Hash'}{'num_avail'} = 0; #0-$num_cust_svc ?
3305 $part_svc->{'Hash'}{'cust_pkg_svc'} =
3306 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : [];
3308 } $self->extra_part_svc;
3315 =item extra_part_svc
3317 Returns a list of FS::part_svc objects corresponding to services in this
3318 package which are still provisioned but not (any longer) available in the
3323 sub extra_part_svc {
3326 my $pkgnum = $self->pkgnum;
3327 #my $pkgpart = $self->pkgpart;
3330 # 'table' => 'part_svc',
3333 # "WHERE 0 = ( SELECT COUNT(*) FROM pkg_svc
3334 # WHERE pkg_svc.svcpart = part_svc.svcpart
3335 # AND pkg_svc.pkgpart = ?
3338 # AND 0 < ( SELECT COUNT(*) FROM cust_svc
3339 # LEFT JOIN cust_pkg USING ( pkgnum )
3340 # WHERE cust_svc.svcpart = part_svc.svcpart
3343 # 'extra_param' => [ [$self->pkgpart=>'int'], [$self->pkgnum=>'int'] ],
3346 #seems to benchmark slightly faster... (or did?)
3348 my @pkgparts = map $_->pkgpart, $self->part_pkg->self_and_svc_linked;
3349 my $pkgparts = join(',', @pkgparts);
3352 #'select' => 'DISTINCT ON (svcpart) part_svc.*',
3353 #MySQL doesn't grok DISINCT ON
3354 'select' => 'DISTINCT part_svc.*',
3355 'table' => 'part_svc',
3357 "LEFT JOIN pkg_svc ON ( pkg_svc.svcpart = part_svc.svcpart
3358 AND pkg_svc.pkgpart IN ($pkgparts)
3361 LEFT JOIN cust_svc ON ( cust_svc.svcpart = part_svc.svcpart )
3362 LEFT JOIN cust_pkg USING ( pkgnum )
3365 'extra_sql' => "WHERE pkgsvcnum IS NULL AND cust_pkg.pkgnum = ? ",
3366 'extra_param' => [ [$self->pkgnum=>'int'] ],
3372 Returns a short status string for this package, currently:
3378 =item not yet billed
3380 =item one-time charge
3395 my $freq = length($self->freq) ? $self->freq : $self->part_pkg->freq;
3397 return 'cancelled' if $self->get('cancel');
3398 return 'on hold' if $self->susp && ! $self->setup;
3399 return 'suspended' if $self->susp;
3400 return 'not yet billed' unless $self->setup;
3401 return 'one-time charge' if $freq =~ /^(0|$)/;
3405 =item ucfirst_status
3407 Returns the status with the first character capitalized.
3411 sub ucfirst_status {
3412 ucfirst(shift->status);
3417 Class method that returns the list of possible status strings for packages
3418 (see L<the status method|/status>). For example:
3420 @statuses = FS::cust_pkg->statuses();
3424 tie my %statuscolor, 'Tie::IxHash',
3425 'on hold' => 'FF00F5', #brighter purple!
3426 'not yet billed' => '009999', #teal? cyan?
3427 'one-time charge' => '0000CC', #blue #'000000',
3428 'active' => '00CC00',
3429 'suspended' => 'FF9900',
3430 'cancelled' => 'FF0000',
3434 my $self = shift; #could be class...
3435 #grep { $_ !~ /^(not yet billed)$/ } #this is a dumb status anyway
3436 # # mayble split btw one-time vs. recur
3447 Returns a hex triplet color string for this package's status.
3453 $statuscolor{$self->status};
3456 =item is_status_delay_cancel
3458 Returns true if part_pkg has option delay_cancel,
3459 cust_pkg status is 'suspended' and expire is set
3460 to cancel package within the next day (or however
3461 many days are set in global config part_pkg-delay_cancel-days.
3463 This is not a real status, this only meant for hacking display
3464 values, because otherwise treating the package as suspended is
3465 really the whole point of the delay_cancel option.
3469 sub is_status_delay_cancel {
3471 if ( $self->main_pkgnum and $self->pkglinknum ) {
3472 return $self->main_pkg->is_status_delay_cancel;
3474 return 0 unless $self->part_pkg->option('delay_cancel',1);
3475 return 0 unless $self->status eq 'suspended';
3476 return 0 unless $self->expire;
3477 my $conf = new FS::Conf;
3478 my $expdays = $conf->config('part_pkg-delay_cancel-days') || 1;
3479 my $expsecs = 60*60*24*$expdays;
3480 return 0 unless $self->expire < time + $expsecs;
3486 Returns a label for this package. (Currently "pkgnum: pkg - comment" or
3487 "pkg - comment" depending on user preference).
3493 my $label = $self->part_pkg->pkg_comment( cust_pkg=>$self, nopkgpart=>1 );
3494 $label = $self->pkgnum. ": $label"
3495 if $FS::CurrentUser::CurrentUser->option('show_pkgnum');
3499 =item pkg_label_long
3501 Returns a long label for this package, adding the primary service's label to
3506 sub pkg_label_long {
3508 my $label = $self->pkg_label;
3509 my $cust_svc = $self->primary_cust_svc;
3510 $label .= ' ('. ($cust_svc->label)[1]. ')' if $cust_svc;
3516 Returns a customer-localized label for this package.
3522 $self->part_pkg->pkg_locale( $self->cust_main->locale );
3525 =item primary_cust_svc
3527 Returns a primary service (as FS::cust_svc object) if one can be identified.
3531 #for labeling purposes - might not 100% match up with part_pkg->svcpart's idea
3533 sub primary_cust_svc {
3536 my @cust_svc = $self->cust_svc;
3538 return '' unless @cust_svc; #no serivces - irrelevant then
3540 return $cust_svc[0] if scalar(@cust_svc) == 1; #always return a single service
3542 # primary service as specified in the package definition
3543 # or exactly one service definition with quantity one
3544 my $svcpart = $self->part_pkg->svcpart;
3545 @cust_svc = grep { $_->svcpart == $svcpart } @cust_svc;
3546 return $cust_svc[0] if scalar(@cust_svc) == 1;
3548 #couldn't identify one thing..
3554 Returns a list of lists, calling the label method for all services
3555 (see L<FS::cust_svc>) of this billing item.
3561 map { [ $_->label ] } $self->cust_svc;
3564 =item h_labels END_TIMESTAMP [ START_TIMESTAMP ] [ MODE ]
3566 Like the labels method, but returns historical information on services that
3567 were active as of END_TIMESTAMP and (optionally) not cancelled before
3568 START_TIMESTAMP. If MODE is 'I' (for 'invoice'), services with the
3569 I<pkg_svc.hidden> flag will be omitted.
3571 Returns a list of lists, calling the label method for all (historical) services
3572 (see L<FS::h_cust_svc>) of this billing item.
3578 warn "$me _h_labels called on $self\n"
3580 map { [ $_->label(@_) ] } $self->h_cust_svc(@_);
3585 Like labels, except returns a simple flat list, and shortens long
3586 (currently >5 or the cust_bill-max_same_services configuration value) lists of
3587 identical services to one line that lists the service label and the number of
3588 individual services rather than individual items.
3593 shift->_labels_short( 'labels', @_ );
3596 =item h_labels_short END_TIMESTAMP [ START_TIMESTAMP ]
3598 Like h_labels, except returns a simple flat list, and shortens long
3599 (currently >5 or the cust_bill-max_same_services configuration value) lists of
3600 identical services to one line that lists the service label and the number of
3601 individual services rather than individual items.
3605 sub h_labels_short {
3606 shift->_labels_short( 'h_labels', @_ );
3610 my( $self, $method ) = ( shift, shift );
3612 warn "$me _labels_short called on $self with $method method\n"
3615 my $conf = new FS::Conf;
3616 my $max_same_services = $conf->config('cust_bill-max_same_services') || 5;
3618 warn "$me _labels_short populating \%labels\n"
3622 #tie %labels, 'Tie::IxHash';
3623 push @{ $labels{$_->[0]} }, $_->[1]
3624 foreach $self->$method(@_);
3626 warn "$me _labels_short populating \@labels\n"
3630 foreach my $label ( keys %labels ) {
3632 my @values = grep { ! $seen{$_}++ } @{ $labels{$label} };
3633 my $num = scalar(@values);
3634 warn "$me _labels_short $num items for $label\n"
3637 if ( $num > $max_same_services ) {
3638 warn "$me _labels_short more than $max_same_services, so summarizing\n"
3640 push @labels, "$label ($num)";
3642 if ( $conf->exists('cust_bill-consolidate_services') ) {
3643 warn "$me _labels_short consolidating services\n"
3645 # push @labels, "$label: ". join(', ', @values);
3647 my $detail = "$label: ";
3648 $detail .= shift(@values). ', '
3650 && ( length($detail.$values[0]) < 78 || $detail eq "$label: " );
3652 push @labels, $detail;
3654 warn "$me _labels_short done consolidating services\n"
3657 warn "$me _labels_short adding service data\n"
3659 push @labels, map { "$label: $_" } @values;
3670 Returns the parent customer object (see L<FS::cust_main>).
3674 Returns the balance for this specific package, when using
3675 experimental package balance.
3681 $self->cust_main->balance_pkgnum( $self->pkgnum );
3684 #these subs are in location_Mixin.pm now... unfortunately the POD doesn't mixin
3688 Returns the location object, if any (see L<FS::cust_location>).
3690 =item cust_location_or_main
3692 If this package is associated with a location, returns the locaiton (see
3693 L<FS::cust_location>), otherwise returns the customer (see L<FS::cust_main>).
3695 =item location_label [ OPTION => VALUE ... ]
3697 Returns the label of the location object (see L<FS::cust_location>).
3701 #end of subs in location_Mixin.pm now... unfortunately the POD doesn't mixin
3703 =item tax_locationnum
3705 Returns the foreign key to a L<FS::cust_location> object for calculating
3706 tax on this package, as determined by the C<tax-pkg_address> and
3707 C<tax-ship_address> configuration flags.
3711 sub tax_locationnum {
3713 my $conf = FS::Conf->new;
3714 if ( $conf->exists('tax-pkg_address') ) {
3715 return $self->locationnum;
3717 elsif ( $conf->exists('tax-ship_address') ) {
3718 return $self->cust_main->ship_locationnum;
3721 return $self->cust_main->bill_locationnum;
3727 Returns the L<FS::cust_location> object for tax_locationnum.
3733 my $conf = FS::Conf->new;
3734 if ( $conf->exists('tax-pkg_address') and $self->locationnum ) {
3735 return FS::cust_location->by_key($self->locationnum);
3737 elsif ( $conf->exists('tax-ship_address') ) {
3738 return $self->cust_main->ship_location;
3741 return $self->cust_main->bill_location;
3745 =item seconds_since TIMESTAMP
3747 Returns the number of seconds all accounts (see L<FS::svc_acct>) in this
3748 package have been online since TIMESTAMP, according to the session monitor.
3750 TIMESTAMP is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
3751 L<Time::Local> and L<Date::Parse> for conversion functions.
3756 my($self, $since) = @_;
3759 foreach my $cust_svc (
3760 grep { $_->part_svc->svcdb eq 'svc_acct' } $self->cust_svc
3762 $seconds += $cust_svc->seconds_since($since);
3769 =item seconds_since_sqlradacct TIMESTAMP_START TIMESTAMP_END
3771 Returns the numbers of seconds all accounts (see L<FS::svc_acct>) in this
3772 package have been online between TIMESTAMP_START (inclusive) and TIMESTAMP_END
3775 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
3776 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
3782 sub seconds_since_sqlradacct {
3783 my($self, $start, $end) = @_;
3787 foreach my $cust_svc (
3789 my $part_svc = $_->part_svc;
3790 $part_svc->svcdb eq 'svc_acct'
3791 && scalar($part_svc->part_export_usage);
3794 $seconds += $cust_svc->seconds_since_sqlradacct($start, $end);
3801 =item attribute_since_sqlradacct TIMESTAMP_START TIMESTAMP_END ATTRIBUTE
3803 Returns the sum of the given attribute for all accounts (see L<FS::svc_acct>)
3804 in this package for sessions ending between TIMESTAMP_START (inclusive) and
3808 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
3809 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
3814 sub attribute_since_sqlradacct {
3815 my($self, $start, $end, $attrib) = @_;
3819 foreach my $cust_svc (
3821 my $part_svc = $_->part_svc;
3822 scalar($part_svc->part_export_usage);
3825 $sum += $cust_svc->attribute_since_sqlradacct($start, $end, $attrib);
3837 my( $self, $value ) = @_;
3838 if ( defined($value) ) {
3839 $self->setfield('quantity', $value);
3841 $self->getfield('quantity') || 1;
3844 =item transfer DEST_PKGNUM | DEST_CUST_PKG, [ OPTION => VALUE ... ]
3846 Transfers as many services as possible from this package to another package.
3848 The destination package can be specified by pkgnum by passing an FS::cust_pkg
3849 object. The destination package must already exist.
3851 Services are moved only if the destination allows services with the correct
3852 I<svcpart> (not svcdb), unless the B<change_svcpart> option is set true. Use
3853 this option with caution! No provision is made for export differences
3854 between the old and new service definitions. Probably only should be used
3855 when your exports for all service definitions of a given svcdb are identical.
3856 (attempt a transfer without it first, to move all possible svcpart-matching
3859 Any services that can't be moved remain in the original package.
3861 Returns an error, if there is one; otherwise, returns the number of services
3862 that couldn't be moved.
3867 my ($self, $dest_pkgnum, %opt) = @_;
3873 if (ref ($dest_pkgnum) eq 'FS::cust_pkg') {
3874 $dest = $dest_pkgnum;
3875 $dest_pkgnum = $dest->pkgnum;
3877 $dest = qsearchs('cust_pkg', { pkgnum => $dest_pkgnum });
3880 return ('Package does not exist: '.$dest_pkgnum) unless $dest;
3882 foreach my $pkg_svc ( $dest->part_pkg->pkg_svc ) {
3883 $target{$pkg_svc->svcpart} = $pkg_svc->quantity * ( $dest->quantity || 1 );
3886 foreach my $cust_svc ($dest->cust_svc) {
3887 $target{$cust_svc->svcpart}--;
3890 my %svcpart2svcparts = ();
3891 if ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
3892 warn "change_svcpart option received, creating alternates list\n" if $DEBUG;
3893 foreach my $svcpart ( map { $_->svcpart } $self->cust_svc ) {
3894 next if exists $svcpart2svcparts{$svcpart};
3895 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
3896 $svcpart2svcparts{$svcpart} = [
3898 sort { $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] }
3900 my $pkg_svc = qsearchs( 'pkg_svc', { 'pkgpart' => $dest->pkgpart,
3901 'svcpart' => $_ } );
3903 $pkg_svc ? $pkg_svc->primary_svc : '',
3904 $pkg_svc ? $pkg_svc->quantity : 0,
3908 grep { $_ != $svcpart }
3910 qsearch('part_svc', { 'svcdb' => $part_svc->svcdb } )
3912 warn "alternates for svcpart $svcpart: ".
3913 join(', ', @{$svcpart2svcparts{$svcpart}}). "\n"
3919 foreach my $cust_svc ($self->cust_svc) {
3920 my $svcnum = $cust_svc->svcnum;
3921 if($target{$cust_svc->svcpart} > 0
3922 or $FS::cust_svc::ignore_quantity) { # maybe should be a 'force' option
3923 $target{$cust_svc->svcpart}--;
3924 my $new = new FS::cust_svc { $cust_svc->hash };
3925 $new->pkgnum($dest_pkgnum);
3926 $error = $new->replace($cust_svc);
3927 } elsif ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
3929 warn "looking for alternates for svcpart ". $cust_svc->svcpart. "\n";
3930 warn "alternates to consider: ".
3931 join(', ', @{$svcpart2svcparts{$cust_svc->svcpart}}). "\n";
3933 my @alternate = grep {
3934 warn "considering alternate svcpart $_: ".
3935 "$target{$_} available in new package\n"
3938 } @{$svcpart2svcparts{$cust_svc->svcpart}};
3940 warn "alternate(s) found\n" if $DEBUG;
3941 my $change_svcpart = $alternate[0];
3942 $target{$change_svcpart}--;
3943 my $new = new FS::cust_svc { $cust_svc->hash };
3944 $new->svcpart($change_svcpart);
3945 $new->pkgnum($dest_pkgnum);
3946 $error = $new->replace($cust_svc);
3954 my @label = $cust_svc->label;
3955 return "$label[0] $label[1]: $error";
3961 =item grab_svcnums SVCNUM, SVCNUM ...
3963 Change the pkgnum for the provided services to this packages. If there is an
3964 error, returns the error, otherwise returns false.
3972 my $oldAutoCommit = $FS::UID::AutoCommit;
3973 local $FS::UID::AutoCommit = 0;
3976 foreach my $svcnum (@svcnum) {
3977 my $cust_svc = qsearchs('cust_svc', { svcnum=>$svcnum } ) or do {
3978 $dbh->rollback if $oldAutoCommit;
3979 return "unknown svcnum $svcnum";
3981 $cust_svc->pkgnum( $self->pkgnum );
3982 my $error = $cust_svc->replace;
3984 $dbh->rollback if $oldAutoCommit;
3989 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3996 This method is deprecated. See the I<depend_jobnum> option to the insert and
3997 order_pkgs methods in FS::cust_main for a better way to defer provisioning.
4001 #looks like this is still used by the order_pkg and change_pkg methods in
4002 # ClientAPI/MyAccount, need to look into those before removing
4006 my $oldAutoCommit = $FS::UID::AutoCommit;
4007 local $FS::UID::AutoCommit = 0;
4010 foreach my $cust_svc ( $self->cust_svc ) {
4011 #false laziness w/svc_Common::insert
4012 my $svc_x = $cust_svc->svc_x;
4013 foreach my $part_export ( $cust_svc->part_svc->part_export ) {
4014 my $error = $part_export->export_insert($svc_x);
4016 $dbh->rollback if $oldAutoCommit;
4022 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4027 =item export_pkg_change OLD_CUST_PKG
4029 Calls the "pkg_change" export action for all services attached to this package.
4033 sub export_pkg_change {
4034 my( $self, $old ) = ( shift, shift );
4036 my $oldAutoCommit = $FS::UID::AutoCommit;
4037 local $FS::UID::AutoCommit = 0;
4040 foreach my $svc_x ( map $_->svc_x, $self->cust_svc ) {
4041 my $error = $svc_x->export('pkg_change', $self, $old);
4043 $dbh->rollback if $oldAutoCommit;
4048 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4055 Associates this package with a (suspension or cancellation) reason (see
4056 L<FS::cust_pkg_reason>, possibly inserting a new reason on the fly (see
4059 Available options are:
4065 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.
4069 the access_user (see L<FS::access_user>) providing the reason
4077 the action (cancel, susp, adjourn, expire) associated with the reason
4081 If there is an error, returns the error, otherwise returns false.
4086 my ($self, %options) = @_;
4088 my $otaker = $options{reason_otaker} ||
4089 $FS::CurrentUser::CurrentUser->username;
4092 if ( $options{'reason'} =~ /^(\d+)$/ ) {
4096 } elsif ( ref($options{'reason'}) ) {
4098 return 'Enter a new reason (or select an existing one)'
4099 unless $options{'reason'}->{'reason'} !~ /^\s*$/;
4101 my $reason = new FS::reason({
4102 'reason_type' => $options{'reason'}->{'typenum'},
4103 'reason' => $options{'reason'}->{'reason'},
4105 my $error = $reason->insert;
4106 return $error if $error;
4108 $reasonnum = $reason->reasonnum;
4111 return "Unparseable reason: ". $options{'reason'};
4114 my $cust_pkg_reason =
4115 new FS::cust_pkg_reason({ 'pkgnum' => $self->pkgnum,
4116 'reasonnum' => $reasonnum,
4117 'otaker' => $otaker,
4118 'action' => substr(uc($options{'action'}),0,1),
4119 'date' => $options{'date'}
4124 $cust_pkg_reason->insert;
4127 =item insert_discount
4129 Associates this package with a discount (see L<FS::cust_pkg_discount>, possibly
4130 inserting a new discount on the fly (see L<FS::discount>).
4132 Available options are:
4140 If there is an error, returns the error, otherwise returns false.
4144 sub insert_discount {
4145 #my ($self, %options) = @_;
4148 my $cust_pkg_discount = new FS::cust_pkg_discount {
4149 'pkgnum' => $self->pkgnum,
4150 'discountnum' => $self->discountnum,
4152 'end_date' => '', #XXX
4153 #for the create a new discount case
4154 '_type' => $self->discountnum__type,
4155 'amount' => $self->discountnum_amount,
4156 'percent' => $self->discountnum_percent,
4157 'months' => $self->discountnum_months,
4158 'setup' => $self->discountnum_setup,
4159 #'disabled' => $self->discountnum_disabled,
4162 $cust_pkg_discount->insert;
4165 =item set_usage USAGE_VALUE_HASHREF
4167 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
4168 to which they should be set (see L<FS::svc_acct>). Currently seconds,
4169 upbytes, downbytes, and totalbytes are appropriate keys.
4171 All svc_accts which are part of this package have their values reset.
4176 my ($self, $valueref, %opt) = @_;
4178 #only svc_acct can set_usage for now
4179 foreach my $cust_svc ( $self->cust_svc( 'svcdb'=>'svc_acct' ) ) {
4180 my $svc_x = $cust_svc->svc_x;
4181 $svc_x->set_usage($valueref, %opt)
4182 if $svc_x->can("set_usage");
4186 =item recharge USAGE_VALUE_HASHREF
4188 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
4189 to which they should be set (see L<FS::svc_acct>). Currently seconds,
4190 upbytes, downbytes, and totalbytes are appropriate keys.
4192 All svc_accts which are part of this package have their values incremented.
4197 my ($self, $valueref) = @_;
4199 #only svc_acct can set_usage for now
4200 foreach my $cust_svc ( $self->cust_svc( 'svcdb'=>'svc_acct' ) ) {
4201 my $svc_x = $cust_svc->svc_x;
4202 $svc_x->recharge($valueref)
4203 if $svc_x->can("recharge");
4207 =item apply_usageprice
4211 sub apply_usageprice {
4214 my $oldAutoCommit = $FS::UID::AutoCommit;
4215 local $FS::UID::AutoCommit = 0;
4220 foreach my $cust_pkg_usageprice ( $self->cust_pkg_usageprice ) {
4221 $error ||= $cust_pkg_usageprice->apply;
4225 $dbh->rollback if $oldAutoCommit;
4226 die "error applying part_pkg_usageprice add-ons, pkgnum ". $self->pkgnum.
4229 $dbh->commit if $oldAutoCommit;
4235 =item cust_pkg_discount
4237 =item cust_pkg_discount_active
4241 sub cust_pkg_discount_active {
4243 grep { $_->status eq 'active' } $self->cust_pkg_discount;
4246 =item cust_pkg_usage
4248 Returns a list of all voice usage counters attached to this package.
4250 =item apply_usage OPTIONS
4252 Takes the following options:
4253 - cdr: a call detail record (L<FS::cdr>)
4254 - rate_detail: the rate determined for this call (L<FS::rate_detail>)
4255 - minutes: the maximum number of minutes to be charged
4257 Finds available usage minutes for a call of this class, and subtracts
4258 up to that many minutes from the usage pool. If the usage pool is empty,
4259 and the C<cdr-minutes_priority> global config option is set, minutes may
4260 be taken from other calls as well. Either way, an allocation record will
4261 be created (L<FS::cdr_cust_pkg_usage>) and this method will return the
4262 number of minutes of usage applied to the call.
4267 my ($self, %opt) = @_;
4268 my $cdr = $opt{cdr};
4269 my $rate_detail = $opt{rate_detail};
4270 my $minutes = $opt{minutes};
4271 my $classnum = $rate_detail->classnum;
4272 my $pkgnum = $self->pkgnum;
4273 my $custnum = $self->custnum;
4275 my $oldAutoCommit = $FS::UID::AutoCommit;
4276 local $FS::UID::AutoCommit = 0;
4279 my $order = FS::Conf->new->config('cdr-minutes_priority');
4283 $is_classnum = ' part_pkg_usage_class.classnum = '.$classnum;
4285 $is_classnum = ' part_pkg_usage_class.classnum IS NULL';
4287 my @usage_recs = qsearch({
4288 'table' => 'cust_pkg_usage',
4289 'addl_from' => ' JOIN part_pkg_usage USING (pkgusagepart)'.
4290 ' JOIN cust_pkg USING (pkgnum)'.
4291 ' JOIN part_pkg_usage_class USING (pkgusagepart)',
4292 'select' => 'cust_pkg_usage.*',
4293 'extra_sql' => " WHERE ( cust_pkg.pkgnum = $pkgnum OR ".
4294 " ( cust_pkg.custnum = $custnum AND ".
4295 " part_pkg_usage.shared IS NOT NULL ) ) AND ".
4296 $is_classnum . ' AND '.
4297 " cust_pkg_usage.minutes > 0",
4298 'order_by' => " ORDER BY priority ASC",
4301 my $orig_minutes = $minutes;
4303 while (!$error and $minutes > 0 and @usage_recs) {
4304 my $cust_pkg_usage = shift @usage_recs;
4305 $cust_pkg_usage->select_for_update;
4306 my $cdr_cust_pkg_usage = FS::cdr_cust_pkg_usage->new({
4307 pkgusagenum => $cust_pkg_usage->pkgusagenum,
4308 acctid => $cdr->acctid,
4309 minutes => min($cust_pkg_usage->minutes, $minutes),
4311 $cust_pkg_usage->set('minutes',
4312 $cust_pkg_usage->minutes - $cdr_cust_pkg_usage->minutes
4314 $error = $cust_pkg_usage->replace || $cdr_cust_pkg_usage->insert;
4315 $minutes -= $cdr_cust_pkg_usage->minutes;
4317 if ( $order and $minutes > 0 and !$error ) {
4318 # then try to steal minutes from another call
4320 'table' => 'cdr_cust_pkg_usage',
4321 'addl_from' => ' JOIN cust_pkg_usage USING (pkgusagenum)'.
4322 ' JOIN part_pkg_usage USING (pkgusagepart)'.
4323 ' JOIN cust_pkg USING (pkgnum)'.
4324 ' JOIN part_pkg_usage_class USING (pkgusagepart)'.
4325 ' JOIN cdr USING (acctid)',
4326 'select' => 'cdr_cust_pkg_usage.*',
4327 'extra_sql' => " WHERE cdr.freesidestatus = 'rated' AND ".
4328 " ( cust_pkg.pkgnum = $pkgnum OR ".
4329 " ( cust_pkg.custnum = $custnum AND ".
4330 " part_pkg_usage.shared IS NOT NULL ) ) AND ".
4331 " part_pkg_usage_class.classnum = $classnum",
4332 'order_by' => ' ORDER BY part_pkg_usage.priority ASC',
4334 if ( $order eq 'time' ) {
4335 # find CDRs that are using minutes, but have a later startdate
4337 my $startdate = $cdr->startdate;
4338 if ($startdate !~ /^\d+$/) {
4339 die "bad cdr startdate '$startdate'";
4341 $search{'extra_sql'} .= " AND cdr.startdate > $startdate";
4342 # minimize needless reshuffling
4343 $search{'order_by'} .= ', cdr.startdate DESC';
4345 # XXX may not work correctly with rate_time schedules. Could
4346 # fix this by storing ratedetailnum in cdr_cust_pkg_usage, I
4348 $search{'addl_from'} .=
4349 ' JOIN rate_detail'.
4350 ' ON (cdr.rated_ratedetailnum = rate_detail.ratedetailnum)';
4351 if ( $order eq 'rate_high' ) {
4352 $search{'extra_sql'} .= ' AND rate_detail.min_charge < '.
4353 $rate_detail->min_charge;
4354 $search{'order_by'} .= ', rate_detail.min_charge ASC';
4355 } elsif ( $order eq 'rate_low' ) {
4356 $search{'extra_sql'} .= ' AND rate_detail.min_charge > '.
4357 $rate_detail->min_charge;
4358 $search{'order_by'} .= ', rate_detail.min_charge DESC';
4360 # this should really never happen
4361 die "invalid cdr-minutes_priority value '$order'\n";
4364 my @cdr_usage_recs = qsearch(\%search);
4366 while (!$error and @cdr_usage_recs and $minutes > 0) {
4367 my $cdr_cust_pkg_usage = shift @cdr_usage_recs;
4368 my $cust_pkg_usage = $cdr_cust_pkg_usage->cust_pkg_usage;
4369 my $old_cdr = $cdr_cust_pkg_usage->cdr;
4370 $reproc_cdrs{$old_cdr->acctid} = $old_cdr;
4371 $cdr_cust_pkg_usage->select_for_update;
4372 $old_cdr->select_for_update;
4373 $cust_pkg_usage->select_for_update;
4374 # in case someone else stole the usage from this CDR
4375 # while waiting for the lock...
4376 next if $old_cdr->acctid != $cdr_cust_pkg_usage->acctid;
4377 # steal the usage allocation and flag the old CDR for reprocessing
4378 $cdr_cust_pkg_usage->set('acctid', $cdr->acctid);
4379 # if the allocation is more minutes than we need, adjust it...
4380 my $delta = $cdr_cust_pkg_usage->minutes - $minutes;
4382 $cdr_cust_pkg_usage->set('minutes', $minutes);
4383 $cust_pkg_usage->set('minutes', $cust_pkg_usage->minutes + $delta);
4384 $error = $cust_pkg_usage->replace;
4386 #warn 'CDR '.$cdr->acctid . ' stealing allocation '.$cdr_cust_pkg_usage->cdrusagenum.' from CDR '.$old_cdr->acctid."\n";
4387 $error ||= $cdr_cust_pkg_usage->replace;
4388 # deduct the stolen minutes
4389 $minutes -= $cdr_cust_pkg_usage->minutes;
4391 # after all minute-stealing is done, reset the affected CDRs
4392 foreach (values %reproc_cdrs) {
4393 $error ||= $_->set_status('');
4394 # XXX or should we just call $cdr->rate right here?
4395 # it's not like we can create a loop this way, since the min_charge
4396 # or call time has to go monotonically in one direction.
4397 # we COULD get some very deep recursions going, though...
4399 } # if $order and $minutes
4402 die "error applying included minutes\npkgnum ".$self->pkgnum.", class $classnum, acctid ".$cdr->acctid."\n$error\n"
4404 $dbh->commit if $oldAutoCommit;
4405 return $orig_minutes - $minutes;
4409 =item supplemental_pkgs
4411 Returns a list of all packages supplemental to this one.
4415 sub supplemental_pkgs {
4417 qsearch('cust_pkg', { 'main_pkgnum' => $self->pkgnum });
4422 Returns the package that this one is supplemental to, if any.
4428 if ( $self->main_pkgnum ) {
4429 return FS::cust_pkg->by_key($self->main_pkgnum);
4436 =head1 CLASS METHODS
4442 Returns an SQL expression identifying recurring packages.
4446 sub recurring_sql { "
4447 '0' != ( select freq from part_pkg
4448 where cust_pkg.pkgpart = part_pkg.pkgpart )
4453 Returns an SQL expression identifying one-time packages.
4458 '0' = ( select freq from part_pkg
4459 where cust_pkg.pkgpart = part_pkg.pkgpart )
4464 Returns an SQL expression identifying ordered packages (recurring packages not
4470 $_[0]->recurring_sql. " AND ". $_[0]->not_yet_billed_sql;
4475 Returns an SQL expression identifying active packages.
4480 $_[0]->recurring_sql. "
4481 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
4482 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4483 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
4486 =item not_yet_billed_sql
4488 Returns an SQL expression identifying packages which have not yet been billed.
4492 sub not_yet_billed_sql { "
4493 ( cust_pkg.setup IS NULL OR cust_pkg.setup = 0 )
4494 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4495 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
4500 Returns an SQL expression identifying inactive packages (one-time packages
4501 that are otherwise unsuspended/uncancelled).
4505 sub inactive_sql { "
4506 ". $_[0]->onetime_sql(). "
4507 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
4508 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4509 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
4514 Returns an SQL expression identifying on-hold packages.
4519 #$_[0]->recurring_sql(). ' AND '.
4521 ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4522 AND cust_pkg.susp IS NOT NULL AND cust_pkg.susp != 0
4523 AND ( cust_pkg.setup IS NULL OR cust_pkg.setup = 0 )
4530 Returns an SQL expression identifying suspended packages.
4534 sub suspended_sql { susp_sql(@_); }
4536 #$_[0]->recurring_sql(). ' AND '.
4538 ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4539 AND cust_pkg.susp IS NOT NULL AND cust_pkg.susp != 0
4540 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
4547 Returns an SQL exprression identifying cancelled packages.
4551 sub cancelled_sql { cancel_sql(@_); }
4553 #$_[0]->recurring_sql(). ' AND '.
4554 "cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0";
4559 Returns an SQL expression to give the package status as a string.
4565 WHEN cust_pkg.cancel IS NOT NULL THEN 'cancelled'
4566 WHEN ( cust_pkg.susp IS NOT NULL AND cust_pkg.setup IS NULL ) THEN 'on hold'
4567 WHEN cust_pkg.susp IS NOT NULL THEN 'suspended'
4568 WHEN cust_pkg.setup IS NULL THEN 'not yet billed'
4569 WHEN ".onetime_sql()." THEN 'one-time charge'
4576 Returns a list of two package counts. The first is a count of packages
4577 based on the supplied criteria and the second is the count of residential
4578 packages with those same criteria. Criteria are specified as in the search
4584 my ($class, $params) = @_;
4586 my $sql_query = $class->search( $params );
4588 my $count_sql = delete($sql_query->{'count_query'});
4589 $count_sql =~ s/ FROM/,count(CASE WHEN cust_main.company IS NULL OR cust_main.company = '' THEN 1 END) FROM/
4590 or die "couldn't parse count_sql";
4592 my $count_sth = dbh->prepare($count_sql)
4593 or die "Error preparing $count_sql: ". dbh->errstr;
4595 or die "Error executing $count_sql: ". $count_sth->errstr;
4596 my $count_arrayref = $count_sth->fetchrow_arrayref;
4598 return ( @$count_arrayref );
4602 =item tax_locationnum_sql
4604 Returns an SQL expression for the tax location for a package, based
4605 on the settings of 'tax-pkg_address' and 'tax-ship_address'.
4609 sub tax_locationnum_sql {
4610 my $conf = FS::Conf->new;
4611 if ( $conf->exists('tax-pkg_address') ) {
4612 'cust_pkg.locationnum';
4614 elsif ( $conf->exists('tax-ship_address') ) {
4615 'cust_main.ship_locationnum';
4618 'cust_main.bill_locationnum';
4624 Returns a list: the first item is an SQL fragment identifying matching
4625 packages/customers via location (taking into account shipping and package
4626 address taxation, if enabled), and subsequent items are the parameters to
4627 substitute for the placeholders in that fragment.
4632 my($class, %opt) = @_;
4633 my $ornull = $opt{'ornull'};
4635 my $conf = new FS::Conf;
4637 # '?' placeholders in _location_sql_where
4638 my $x = $ornull ? 3 : 2;
4649 if ( $conf->exists('tax-ship_address') ) {
4652 ( ( ship_last IS NULL OR ship_last = '' )
4653 AND ". _location_sql_where('cust_main', '', $ornull ). "
4655 OR ( ship_last IS NOT NULL AND ship_last != ''
4656 AND ". _location_sql_where('cust_main', 'ship_', $ornull ). "
4659 # AND payby != 'COMP'
4661 @main_param = ( @bill_param, @bill_param );
4665 $main_where = _location_sql_where('cust_main'); # AND payby != 'COMP'
4666 @main_param = @bill_param;
4672 if ( $conf->exists('tax-pkg_address') ) {
4674 my $loc_where = _location_sql_where( 'cust_location', '', $ornull );
4677 ( cust_pkg.locationnum IS NULL AND $main_where )
4678 OR ( cust_pkg.locationnum IS NOT NULL AND $loc_where )
4681 @param = ( @main_param, @bill_param );
4685 $where = $main_where;
4686 @param = @main_param;
4694 #subroutine, helper for location_sql
4695 sub _location_sql_where {
4697 my $prefix = @_ ? shift : '';
4698 my $ornull = @_ ? shift : '';
4700 # $ornull = $ornull ? " OR ( ? IS NULL AND $table.${prefix}county IS NULL ) " : '';
4702 $ornull = $ornull ? ' OR ? IS NULL ' : '';
4704 my $or_empty_city = " OR ( ? = '' AND $table.${prefix}city IS NULL )";
4705 my $or_empty_county = " OR ( ? = '' AND $table.${prefix}county IS NULL )";
4706 my $or_empty_state = " OR ( ? = '' AND $table.${prefix}state IS NULL )";
4708 my $text = (driver_name =~ /^mysql/i) ? 'char' : 'text';
4710 # ( $table.${prefix}city = ? $or_empty_city $ornull )
4712 ( $table.district = ? OR ? = '' OR CAST(? AS $text) IS NULL )
4713 AND ( $table.${prefix}city = ? OR ? = '' OR CAST(? AS $text) IS NULL )
4714 AND ( $table.${prefix}county = ? $or_empty_county $ornull )
4715 AND ( $table.${prefix}state = ? $or_empty_state $ornull )
4716 AND $table.${prefix}country = ?
4721 my( $self, $what ) = @_;
4723 my $what_show_zero = $what. '_show_zero';
4724 length($self->$what_show_zero())
4725 ? ($self->$what_show_zero() eq 'Y')
4726 : $self->part_pkg->$what_show_zero();
4733 =item order CUSTNUM, PKGPARTS_ARYREF, [ REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF [ REFNUM ] ] ]
4735 Bulk cancel + order subroutine. Perhaps slightly deprecated, only used by the
4736 bulk cancel+order in the web UI and nowhere else (edit/process/cust_pkg.cgi)
4738 CUSTNUM is a customer (see L<FS::cust_main>)
4740 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
4741 L<FS::part_pkg>) to order for this customer. Duplicates are of course
4744 REMOVE_PKGNUMS is an optional list of pkgnums specifying the billing items to
4745 remove for this customer. The services (see L<FS::cust_svc>) are moved to the
4746 new billing items. An error is returned if this is not possible (see
4747 L<FS::pkg_svc>). An empty arrayref is equivalent to not specifying this
4750 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
4751 newly-created cust_pkg objects.
4753 REFNUM, if specified, will specify the FS::pkg_referral record to be created
4754 and inserted. Multiple FS::pkg_referral records can be created by
4755 setting I<refnum> to an array reference of refnums or a hash reference with
4756 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
4757 record will be created corresponding to cust_main.refnum.
4762 my ($custnum, $pkgparts, $remove_pkgnum, $return_cust_pkg, $refnum) = @_;
4764 my $conf = new FS::Conf;
4766 # Transactionize this whole mess
4767 my $oldAutoCommit = $FS::UID::AutoCommit;
4768 local $FS::UID::AutoCommit = 0;
4772 # my $cust_main = qsearchs('cust_main', { custnum => $custnum });
4773 # return "Customer not found: $custnum" unless $cust_main;
4775 warn "$me order: pkgnums to remove: ". join(',', @$remove_pkgnum). "\n"
4778 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
4781 my $change = scalar(@old_cust_pkg) != 0;
4784 if ( scalar(@old_cust_pkg) == 1 && scalar(@$pkgparts) == 1 ) {
4786 warn "$me order: changing pkgnum ". $old_cust_pkg[0]->pkgnum.
4787 " to pkgpart ". $pkgparts->[0]. "\n"
4790 my $err_or_cust_pkg =
4791 $old_cust_pkg[0]->change( 'pkgpart' => $pkgparts->[0],
4792 'refnum' => $refnum,
4795 unless (ref($err_or_cust_pkg)) {
4796 $dbh->rollback if $oldAutoCommit;
4797 return $err_or_cust_pkg;
4800 push @$return_cust_pkg, $err_or_cust_pkg;
4801 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4806 # Create the new packages.
4807 foreach my $pkgpart (@$pkgparts) {
4809 warn "$me order: inserting pkgpart $pkgpart\n" if $DEBUG;
4811 my $cust_pkg = new FS::cust_pkg { custnum => $custnum,
4812 pkgpart => $pkgpart,
4816 $error = $cust_pkg->insert( 'change' => $change );
4817 push @$return_cust_pkg, $cust_pkg;
4819 foreach my $link ($cust_pkg->part_pkg->supp_part_pkg_link) {
4820 my $supp_pkg = FS::cust_pkg->new({
4821 custnum => $custnum,
4822 pkgpart => $link->dst_pkgpart,
4824 main_pkgnum => $cust_pkg->pkgnum,
4827 $error ||= $supp_pkg->insert( 'change' => $change );
4828 push @$return_cust_pkg, $supp_pkg;
4832 $dbh->rollback if $oldAutoCommit;
4837 # $return_cust_pkg now contains refs to all of the newly
4840 # Transfer services and cancel old packages.
4841 foreach my $old_pkg (@old_cust_pkg) {
4843 warn "$me order: transferring services from pkgnum ". $old_pkg->pkgnum. "\n"
4846 foreach my $new_pkg (@$return_cust_pkg) {
4847 $error = $old_pkg->transfer($new_pkg);
4848 if ($error and $error == 0) {
4849 # $old_pkg->transfer failed.
4850 $dbh->rollback if $oldAutoCommit;
4855 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
4856 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
4857 foreach my $new_pkg (@$return_cust_pkg) {
4858 $error = $old_pkg->transfer($new_pkg, 'change_svcpart'=>1 );
4859 if ($error and $error == 0) {
4860 # $old_pkg->transfer failed.
4861 $dbh->rollback if $oldAutoCommit;
4868 # Transfers were successful, but we went through all of the
4869 # new packages and still had services left on the old package.
4870 # We can't cancel the package under the circumstances, so abort.
4871 $dbh->rollback if $oldAutoCommit;
4872 return "Unable to transfer all services from package ".$old_pkg->pkgnum;
4874 $error = $old_pkg->cancel( quiet=>1, 'no_delay_cancel'=>1 );
4880 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4884 =item bulk_change PKGPARTS_ARYREF, REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF ]
4886 A bulk change method to change packages for multiple customers.
4888 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
4889 L<FS::part_pkg>) to order for each customer. Duplicates are of course
4892 REMOVE_PKGNUMS is an list of pkgnums specifying the billing items to
4893 replace. The services (see L<FS::cust_svc>) are moved to the
4894 new billing items. An error is returned if this is not possible (see
4897 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
4898 newly-created cust_pkg objects.
4903 my ($pkgparts, $remove_pkgnum, $return_cust_pkg) = @_;
4905 # Transactionize this whole mess
4906 my $oldAutoCommit = $FS::UID::AutoCommit;
4907 local $FS::UID::AutoCommit = 0;
4911 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
4914 while(scalar(@old_cust_pkg)) {
4916 my $custnum = $old_cust_pkg[0]->custnum;
4917 my (@remove) = map { $_->pkgnum }
4918 grep { $_->custnum == $custnum } @old_cust_pkg;
4919 @old_cust_pkg = grep { $_->custnum != $custnum } @old_cust_pkg;
4921 my $error = order $custnum, $pkgparts, \@remove, \@return;
4923 push @errors, $error
4925 push @$return_cust_pkg, @return;
4928 if (scalar(@errors)) {
4929 $dbh->rollback if $oldAutoCommit;
4930 return join(' / ', @errors);
4933 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4937 # Used by FS::Upgrade to migrate to a new database.
4938 sub _upgrade_data { # class method
4939 my ($class, %opts) = @_;
4940 $class->_upgrade_otaker(%opts);
4942 # RT#10139, bug resulting in contract_end being set when it shouldn't
4943 'UPDATE cust_pkg SET contract_end = NULL WHERE contract_end = -1',
4944 # RT#10830, bad calculation of prorate date near end of year
4945 # the date range for bill is December 2009, and we move it forward
4946 # one year if it's before the previous bill date (which it should
4948 'UPDATE cust_pkg SET bill = bill + (365*24*60*60) WHERE bill < last_bill
4949 AND bill > 1259654400 AND bill < 1262332800 AND (SELECT plan FROM part_pkg
4950 WHERE part_pkg.pkgpart = cust_pkg.pkgpart) = \'prorate\'',
4951 # RT6628, add order_date to cust_pkg
4952 'update cust_pkg set order_date = (select history_date from h_cust_pkg
4953 where h_cust_pkg.pkgnum = cust_pkg.pkgnum and
4954 history_action = \'insert\') where order_date is null',
4956 foreach my $sql (@statements) {
4957 my $sth = dbh->prepare($sql);
4958 $sth->execute or die $sth->errstr;
4961 # RT31194: supplemental package links that are deleted don't clean up
4963 my @pkglinknums = qsearch({
4964 'select' => 'DISTINCT cust_pkg.pkglinknum',
4965 'table' => 'cust_pkg',
4966 'addl_from' => ' LEFT JOIN part_pkg_link USING (pkglinknum) ',
4967 'extra_sql' => ' WHERE cust_pkg.pkglinknum IS NOT NULL
4968 AND part_pkg_link.pkglinknum IS NULL',
4970 foreach (@pkglinknums) {
4971 my $pkglinknum = $_->pkglinknum;
4972 warn "cleaning part_pkg_link #$pkglinknum\n";
4973 my $part_pkg_link = FS::part_pkg_link->new({pkglinknum => $pkglinknum});
4974 my $error = $part_pkg_link->remove_linked;
4975 die $error if $error;
4983 sub order is not OO. Perhaps it should be moved to FS::cust_main and made so?
4985 In sub order, the @pkgparts array (passed by reference) is clobbered.
4987 Also in sub order, no money is adjusted. Once FS::part_pkg defines a standard
4988 method to pass dates to the recur_prog expression, it should do so.
4990 FS::svc_acct, FS::svc_domain, FS::svc_www, FS::svc_ip and FS::svc_forward are
4991 loaded via 'use' at compile time, rather than via 'require' in sub { setup,
4992 suspend, unsuspend, cancel } because they use %FS::UID::callback to load
4993 configuration values. Probably need a subroutine which decides what to do
4994 based on whether or not we've fetched the user yet, rather than a hash. See
4995 FS::UID and the TODO.
4997 Now that things are transactional should the check in the insert method be
5002 L<FS::Record>, L<FS::cust_main>, L<FS::part_pkg>, L<FS::cust_svc>,
5003 L<FS::pkg_svc>, schema.html from the base documentation