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 sum);
13 use Time::Local qw( timelocal timelocal_nocheck );
15 use FS::UID qw( dbh driver_name );
16 use FS::Record qw( qsearch qsearchs fields );
22 use FS::cust_location;
24 use FS::cust_bill_pkg;
25 use FS::cust_pkg_detail;
26 use FS::cust_pkg_usage;
27 use FS::cdr_cust_pkg_usage;
32 use FS::cust_pkg_reason;
34 use FS::cust_pkg_usageprice;
35 use FS::cust_pkg_discount;
43 # temporary fix; remove this once (un)suspend admin notices are cleaned up
44 use FS::Misc qw(send_email);
46 # need to 'use' these instead of 'require' in sub { cancel, suspend, unsuspend,
48 # because they load configuration by setting FS::UID::callback (see TODO)
54 # for sending cancel emails in sub cancel
57 our ($disable_agentcheck, $DEBUG, $me, $import) = (0, 0, '[FS::cust_pkg]', 0);
59 our $upgrade = 0; #go away after setup+start dates cleaned up for old customers
61 our $cache_enabled = 0;
64 my( $self, $hashref ) = @_;
65 if ( $cache_enabled && $hashref->{'pkg'} && $hashref->{'plan'} ) {
66 $self->{'_pkgpart'} = FS::part_pkg->new($hashref);
72 my ( $hashref, $cache ) = @_;
73 # #if ( $hashref->{'pkgpart'} ) {
74 # if ( $hashref->{'pkg'} ) {
75 # # #@{ $self->{'_pkgnum'} } = ();
76 # # my $subcache = $cache->subcache('pkgpart', 'part_pkg');
77 # # $self->{'_pkgpart'} = $subcache;
78 # # #push @{ $self->{'_pkgnum'} },
79 # # FS::part_pkg->new_or_cached($hashref, $subcache);
80 # $self->{'_pkgpart'} = FS::part_pkg->new($hashref);
82 if ( exists $hashref->{'svcnum'} ) {
83 #@{ $self->{'_pkgnum'} } = ();
84 my $subcache = $cache->subcache('svcnum', 'cust_svc', $hashref->{pkgnum});
85 $self->{'_svcnum'} = $subcache;
86 #push @{ $self->{'_pkgnum'} },
87 FS::cust_svc->new_or_cached($hashref, $subcache) if $hashref->{svcnum};
93 FS::cust_pkg - Object methods for cust_pkg objects
99 $record = new FS::cust_pkg \%hash;
100 $record = new FS::cust_pkg { 'column' => 'value' };
102 $error = $record->insert;
104 $error = $new_record->replace($old_record);
106 $error = $record->delete;
108 $error = $record->check;
110 $error = $record->cancel;
112 $error = $record->suspend;
114 $error = $record->unsuspend;
116 $part_pkg = $record->part_pkg;
118 @labels = $record->labels;
120 $seconds = $record->seconds_since($timestamp);
122 #bulk cancel+order... perhaps slightly deprecated, only used by the bulk
123 # cancel+order in the web UI and nowhere else (edit/process/cust_pkg.cgi)
124 $error = FS::cust_pkg::order( $custnum, \@pkgparts );
125 $error = FS::cust_pkg::order( $custnum, \@pkgparts, \@remove_pkgnums ] );
129 An FS::cust_pkg object represents a customer billing item. FS::cust_pkg
130 inherits from FS::Record. The following fields are currently supported:
136 Primary key (assigned automatically for new billing items)
140 Customer (see L<FS::cust_main>)
144 Billing item definition (see L<FS::part_pkg>)
148 Optional link to package location (see L<FS::location>)
152 date package was ordered (also remains same on changes)
164 date (next bill date)
192 order taker (see L<FS::access_user>)
196 If not set, defaults to 1
200 Date of change from previous package
210 =item change_locationnum
218 The pkgnum of the package that this package is supplemental to, if any.
222 The package link (L<FS::part_pkg_link>) that defines this supplemental
223 package, if it is one.
225 =item change_to_pkgnum
227 The pkgnum of the package this one will be "changed to" in the future
228 (on its expiration date).
232 Note: setup, last_bill, bill, adjourn, susp, expire, cancel and change_date
233 are specified as UNIX timestamps; see L<perlfunc/"time">. Also see
234 L<Time::Local> and L<Date::Parse> for conversion functions.
242 Create a new billing item. To add the item to the database, see L<"insert">.
246 sub table { 'cust_pkg'; }
247 sub cust_linked { $_[0]->cust_main_custnum || $_[0]->custnum }
248 sub cust_unlinked_msg {
250 "WARNING: can't find cust_main.custnum ". $self->custnum.
251 ' (cust_pkg.pkgnum '. $self->pkgnum. ')';
254 =item set_initial_timers
256 If required by the package definition, sets any automatic expire, adjourn,
257 or contract_end timers to some number of months after the start date
258 (or setup date, if the package has already been setup). If the package has
259 a delayed setup fee after a period of "free days", will also set the
260 start date to the end of that period.
262 If the package has an automatic transfer rule (C<change_to_pkgnum>), then
263 this will also order the package and set its start date.
267 sub set_initial_timers {
269 my $part_pkg = $self->part_pkg;
270 my $start = $self->start_date || $self->setup || time;
272 foreach my $action ( qw(expire adjourn contract_end) ) {
273 my $months = $part_pkg->get("${action}_months");
274 if($months and !$self->get($action)) {
275 $self->set($action, $part_pkg->add_freq($start, $months) );
279 # if this package has an expire date and a change_to_pkgpart, set automatic
281 # (but don't call change_later, as that would call $self->replace, and we're
282 # probably in the middle of $self->insert right now)
283 if ( $part_pkg->expire_months and $part_pkg->change_to_pkgpart ) {
284 if ( $self->change_to_pkgnum ) {
285 # this can happen if a package is ordered on hold, scheduled for a
286 # future change _while on hold_, and then released from hold, causing
287 # the automatic transfer to schedule.
289 # what's correct behavior in that case? I think it's to disallow
290 # future-changing an on-hold package that has an automatic transfer.
291 # but if we DO get into this situation, let the manual package change
293 warn "pkgnum ".$self->pkgnum.": manual future package change blocks ".
294 "automatic transfer.\n";
296 my $change_to = FS::cust_pkg->new( {
297 start_date => $self->get('expire'),
298 pkgpart => $part_pkg->change_to_pkgpart,
299 map { $_ => $self->get($_) }
300 qw( custnum locationnum quantity refnum salesnum contract_end )
302 my $error = $change_to->insert;
304 return $error if $error;
305 $self->set('change_to_pkgnum', $change_to->pkgnum);
309 # if this package has "free days" and delayed setup fee, then
310 # set start date that many days in the future.
311 # (this should have been set in the UI, but enforce it here)
312 if ( $part_pkg->option('free_days',1)
313 && $part_pkg->option('delay_setup',1)
316 $self->start_date( $part_pkg->default_start_date );
322 =item insert [ OPTION => VALUE ... ]
324 Adds this billing item to the database ("Orders" the item). If there is an
325 error, returns the error, otherwise returns false.
327 If the additional field I<promo_code> is defined instead of I<pkgpart>, it
328 will be used to look up the package definition and agent restrictions will be
331 If the additional field I<refnum> is defined, an FS::pkg_referral record will
332 be created and inserted. Multiple FS::pkg_referral records can be created by
333 setting I<refnum> to an array reference of refnums or a hash reference with
334 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
335 record will be created corresponding to cust_main.refnum.
337 If the additional field I<cust_pkg_usageprice> is defined, it will be treated
338 as an arrayref of FS::cust_pkg_usageprice objects, which will be inserted.
339 (Note that this field cannot be set with a usual ->cust_pkg_usageprice method.
340 It can be set as part of the hash when creating the object, or with the B<set>
343 The following options are available:
349 If set true, supresses actions that should only be taken for new package
350 orders. (Currently this includes: intro periods when delay_setup is on,
351 auto-adding a 1st start date, auto-adding expiration/adjourn/contract_end dates)
355 cust_pkg_option records will be created
359 a ticket will be added to this customer with this subject
363 an optional queue name for ticket additions
367 Don't check the legality of the package definition. This should be used
368 when performing a package change that doesn't change the pkgpart (i.e.
376 my( $self, %options ) = @_;
378 my $oldAutoCommit = $FS::UID::AutoCommit;
379 local $FS::UID::AutoCommit = 0;
383 $error = $self->check_pkgpart unless $options{'allow_pkgpart'};
385 my $part_pkg = $self->part_pkg;
387 if ( ! $import && ! $options{'change'} ) {
389 # set order date to now
390 $self->order_date(time) unless ($import && $self->order_date);
392 # if the package def says to start only on the first of the month:
393 if ( $part_pkg->option('start_1st', 1) && !$self->start_date ) {
394 my ($sec,$min,$hour,$mday,$mon,$year) = (localtime(time) )[0,1,2,3,4,5];
395 $mon += 1 unless $mday == 1;
396 until ( $mon < 12 ) { $mon -= 12; $year++; }
397 $self->start_date( timelocal_nocheck(0,0,0,1,$mon,$year) );
400 if ($self->susp eq 'now' or $part_pkg->start_on_hold) {
401 # if the package was ordered on hold:
403 # - don't set the start date (it will be started manually)
404 $self->set('susp', $self->order_date);
405 $self->set('start_date', '');
407 # set expire/adjourn/contract_end timers, and free days, if appropriate
408 # and automatic package transfer, which can fail, so capture the result
409 $error = $self->set_initial_timers;
411 } # else this is a package change, and shouldn't have "new package" behavior
413 $error ||= $self->SUPER::insert($options{options} ? %{$options{options}} : ());
415 $dbh->rollback if $oldAutoCommit;
419 $self->refnum($self->cust_main->refnum) unless $self->refnum;
420 $self->refnum( [ $self->refnum ] ) unless ref($self->refnum);
421 $self->process_m2m( 'link_table' => 'pkg_referral',
422 'target_table' => 'part_referral',
423 'params' => $self->refnum,
426 if ( $self->hashref->{cust_pkg_usageprice} ) {
427 for my $cust_pkg_usageprice ( @{ $self->hashref->{cust_pkg_usageprice} } ) {
428 $cust_pkg_usageprice->pkgnum( $self->pkgnum );
429 my $error = $cust_pkg_usageprice->insert;
431 $dbh->rollback if $oldAutoCommit;
437 if ( $self->setup_discountnum || $self->recur_discountnum ) {
438 my $error = $self->insert_discount();
440 $dbh->rollback if $oldAutoCommit;
445 my $conf = new FS::Conf;
447 if ($self->locationnum) {
449 map qsearch( 'part_export', {exportnum=>$_} ),
450 $conf->config('cust_location-exports'); #, $agentnum
452 foreach my $part_export ( @part_export ) {
453 my $error = $part_export->export_pkg_location($self); #, @$export_args);
455 $dbh->rollback if $oldAutoCommit;
456 return "exporting to ". $part_export->exporttype.
457 " (transaction rolled back): $error";
462 if ( ! $import && $conf->config('ticket_system') && $options{ticket_subject} ) {
464 #this init stuff is still inefficient, but at least its limited to
465 # the small number (any?) folks using ticket emailing on pkg order
468 # use lib ( "/opt/rt3/local/lib", "/opt/rt3/lib" );
475 use FS::TicketSystem;
476 FS::TicketSystem->init();
478 my $q = new RT::Queue($RT::SystemUser);
479 $q->Load($options{ticket_queue}) if $options{ticket_queue};
480 my $t = new RT::Ticket($RT::SystemUser);
481 my $mime = new MIME::Entity;
482 $mime->build( Type => 'text/plain', Data => $options{ticket_subject} );
483 $t->Create( $options{ticket_queue} ? (Queue => $q) : (),
484 Subject => $options{ticket_subject},
487 $t->AddLink( Type => 'MemberOf',
488 Target => 'freeside://freeside/cust_main/'. $self->custnum,
492 if (! $import && $conf->config('welcome_letter') && $self->cust_main->num_pkgs == 1) {
493 my $queue = new FS::queue {
494 'job' => 'FS::cust_main::queueable_print',
496 $error = $queue->insert(
497 'custnum' => $self->custnum,
498 'template' => 'welcome_letter',
502 warn "can't send welcome letter: $error";
507 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
514 This method now works but you probably shouldn't use it.
516 You don't want to delete packages, because there would then be no record
517 the customer ever purchased the package. Instead, see the cancel method and
518 hide cancelled packages.
522 # this is still used internally to abort future package changes, so it
528 # The following foreign keys to cust_pkg are not cleaned up here, and will
529 # cause package deletion to fail:
531 # cust_credit.pkgnum and commission_pkgnum (and cust_credit_void)
532 # cust_credit_bill.pkgnum
533 # cust_pay_pending.pkgnum
534 # cust_pay.pkgnum (and cust_pay_void)
535 # cust_bill_pay.pkgnum (wtf, shouldn't reference pkgnum)
536 # cust_pkg_usage.pkgnum
537 # cust_pkg.uncancel_pkgnum, change_pkgnum, main_pkgnum, and change_to_pkgnum
538 # rt_field_charge.pkgnum
540 # cust_svc is handled by canceling the package before deleting it
541 # cust_pkg_option is handled via option_Common
543 my $oldAutoCommit = $FS::UID::AutoCommit;
544 local $FS::UID::AutoCommit = 0;
547 foreach my $cust_pkg_discount ($self->cust_pkg_discount) {
548 my $error = $cust_pkg_discount->delete;
550 $dbh->rollback if $oldAutoCommit;
554 #cust_bill_pkg_discount?
556 foreach my $cust_pkg_detail ($self->cust_pkg_detail) {
557 my $error = $cust_pkg_detail->delete;
559 $dbh->rollback if $oldAutoCommit;
564 foreach my $cust_pkg_reason (
566 'table' => 'cust_pkg_reason',
567 'hashref' => { 'pkgnum' => $self->pkgnum },
571 my $error = $cust_pkg_reason->delete;
573 $dbh->rollback if $oldAutoCommit;
578 foreach my $pkg_referral ( $self->pkg_referral ) {
579 my $error = $pkg_referral->delete;
581 $dbh->rollback if $oldAutoCommit;
586 my $error = $self->SUPER::delete(@_);
588 $dbh->rollback if $oldAutoCommit;
592 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
598 =item replace [ OLD_RECORD ] [ HASHREF | OPTION => VALUE ... ]
600 Replaces the OLD_RECORD with this one in the database. If there is an error,
601 returns the error, otherwise returns false.
603 Currently, custnum, setup, bill, adjourn, susp, expire, and cancel may be changed.
605 Changing pkgpart may have disasterous effects. See the order subroutine.
607 setup and bill are normally updated by calling the bill method of a customer
608 object (see L<FS::cust_main>).
610 suspend is normally updated by the suspend and unsuspend methods.
612 cancel is normally updated by the cancel method (and also the order subroutine
615 Available options are:
621 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.
625 the access_user (see L<FS::access_user>) providing the reason
629 hashref of keys and values - cust_pkg_option records will be created, updated or removed as appopriate
638 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
643 ( ref($_[0]) eq 'HASH' )
647 #return "Can't (yet?) change pkgpart!" if $old->pkgpart != $new->pkgpart;
648 #return "Can't change otaker!" if $old->otaker ne $new->otaker;
651 #return "Can't change setup once it exists!"
652 # if $old->getfield('setup') &&
653 # $old->getfield('setup') != $new->getfield('setup');
655 #some logic for bill, susp, cancel?
657 local($disable_agentcheck) = 1 if $old->pkgpart == $new->pkgpart;
659 my $oldAutoCommit = $FS::UID::AutoCommit;
660 local $FS::UID::AutoCommit = 0;
663 foreach my $method ( qw(adjourn expire) ) { # How many reasons?
664 if ($options->{'reason'} && $new->$method && $old->$method ne $new->$method) {
665 my $error = $new->insert_reason(
666 'reason' => $options->{'reason'},
667 'date' => $new->$method,
669 'reason_otaker' => $options->{'reason_otaker'},
672 dbh->rollback if $oldAutoCommit;
673 return "Error inserting cust_pkg_reason: $error";
678 #save off and freeze RADIUS attributes for any associated svc_acct records
680 if ( $old->part_pkg->is_prepaid || $new->part_pkg->is_prepaid ) {
682 #also check for specific exports?
683 # to avoid spurious modify export events
684 @svc_acct = map { $_->svc_x }
685 grep { $_->part_svc->svcdb eq 'svc_acct' }
688 $_->snapshot foreach @svc_acct;
692 my $error = $new->export_pkg_change($old)
693 || $new->SUPER::replace( $old,
695 ? $options->{options}
699 $dbh->rollback if $oldAutoCommit;
703 #for prepaid packages,
704 #trigger export of new RADIUS Expiration attribute when cust_pkg.bill changes
705 foreach my $old_svc_acct ( @svc_acct ) {
706 my $new_svc_acct = new FS::svc_acct { $old_svc_acct->hash };
708 $new_svc_acct->replace( $old_svc_acct,
709 'depend_jobnum' => $options->{depend_jobnum},
712 $dbh->rollback if $oldAutoCommit;
717 # also run exports if removing locationnum?
718 # doesn't seem to happen, and we don't export blank locationnum on insert...
719 if ($new->locationnum and ($new->locationnum != $old->locationnum)) {
720 my $conf = new FS::Conf;
722 map qsearch( 'part_export', {exportnum=>$_} ),
723 $conf->config('cust_location-exports'); #, $agentnum
725 foreach my $part_export ( @part_export ) {
726 my $error = $part_export->export_pkg_location($new); #, @$export_args);
728 $dbh->rollback if $oldAutoCommit;
729 return "exporting to ". $part_export->exporttype.
730 " (transaction rolled back): $error";
735 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
742 Checks all fields to make sure this is a valid billing item. If there is an
743 error, returns the error, otherwise returns false. Called by the insert and
751 if ( !$self->locationnum or $self->locationnum == -1 ) {
752 $self->set('locationnum', $self->cust_main->ship_locationnum);
756 $self->ut_numbern('pkgnum')
757 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum')
758 || $self->ut_numbern('pkgpart')
759 || $self->ut_foreign_keyn('contactnum', 'contact', 'contactnum' )
760 || $self->ut_foreign_keyn('locationnum', 'cust_location', 'locationnum')
761 || $self->ut_foreign_keyn('salesnum', 'sales', 'salesnum')
762 || $self->ut_numbern('quantity')
763 || $self->ut_numbern('start_date')
764 || $self->ut_numbern('setup')
765 || $self->ut_numbern('bill')
766 || $self->ut_numbern('susp')
767 || $self->ut_numbern('cancel')
768 || $self->ut_numbern('adjourn')
769 || $self->ut_numbern('resume')
770 || $self->ut_numbern('expire')
771 || $self->ut_numbern('dundate')
772 || $self->ut_flag('no_auto', [ '', 'Y' ])
773 || $self->ut_flag('waive_setup', [ '', 'Y' ])
774 || $self->ut_flag('separate_bill')
775 || $self->ut_textn('agent_pkgid')
776 || $self->ut_enum('recur_show_zero', [ '', 'Y', 'N', ])
777 || $self->ut_enum('setup_show_zero', [ '', 'Y', 'N', ])
778 || $self->ut_foreign_keyn('main_pkgnum', 'cust_pkg', 'pkgnum')
779 || $self->ut_foreign_keyn('pkglinknum', 'part_pkg_link', 'pkglinknum')
780 || $self->ut_foreign_keyn('change_to_pkgnum', 'cust_pkg', 'pkgnum')
782 return $error if $error;
784 return "A package with both start date (future start) and setup date (already started) will never bill"
785 if $self->start_date && $self->setup && ! $upgrade;
787 return "A future unsuspend date can only be set for a package with a suspend date"
788 if $self->resume and !$self->susp and !$self->adjourn;
790 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
797 Check the pkgpart to make sure it's allowed with the reg_code and/or
798 promo_code of the package (if present) and with the customer's agent.
799 Called from C<insert>, unless we are doing a package change that doesn't
807 # my $error = $self->ut_numbern('pkgpart'); # already done
810 if ( $self->reg_code ) {
812 unless ( grep { $self->pkgpart == $_->pkgpart }
813 map { $_->reg_code_pkg }
814 qsearchs( 'reg_code', { 'code' => $self->reg_code,
815 'agentnum' => $self->cust_main->agentnum })
817 return "Unknown registration code";
820 } elsif ( $self->promo_code ) {
823 qsearchs('part_pkg', {
824 'pkgpart' => $self->pkgpart,
825 'promo_code' => { op=>'ILIKE', value=>$self->promo_code },
827 return 'Unknown promotional code' unless $promo_part_pkg;
831 unless ( $disable_agentcheck ) {
833 qsearchs( 'agent', { 'agentnum' => $self->cust_main->agentnum } );
834 return "agent ". $agent->agentnum. ':'. $agent->agent.
835 " can't purchase pkgpart ". $self->pkgpart
836 unless $agent->pkgpart_hashref->{ $self->pkgpart }
837 || $agent->agentnum == $self->part_pkg->agentnum;
840 $error = $self->ut_foreign_key('pkgpart', 'part_pkg', 'pkgpart' );
841 return $error if $error;
849 =item cancel [ OPTION => VALUE ... ]
851 Cancels and removes all services (see L<FS::cust_svc> and L<FS::part_svc>)
852 in this package, then cancels the package itself (sets the cancel field to
855 Available options are:
859 =item quiet - can be set true to supress email cancellation notices.
861 =item time - can be set to cancel the package based on a specific future or
862 historical date. Using time ensures that the remaining amount is calculated
863 correctly. Note however that this is an immediate cancel and just changes
864 the date. You are PROBABLY looking to expire the account instead of using
867 =item reason - can be set to a cancellation reason (see L<FS:reason>),
868 either a reasonnum of an existing reason, or passing a hashref will create
869 a new reason. The hashref should have the following keys: typenum - Reason
870 type (see L<FS::reason_type>, reason - Text of the new reason.
872 =item date - can be set to a unix style timestamp to specify when to
875 =item nobill - can be set true to skip billing if it might otherwise be done.
877 =item unused_credit - can be set to 1 to credit the remaining time, or 0 to
878 not credit it. This must be set (by change()) when changing the package
879 to a different pkgpart or location, and probably shouldn't be in any other
880 case. If it's not set, the 'unused_credit_cancel' part_pkg option will
883 =item no_delay_cancel - prevents delay_cancel behavior
884 no matter what other options say, for use when changing packages (or any
885 other time you're really sure you want an immediate cancel)
889 If there is an error, returns the error, otherwise returns false.
893 #NOT DOCUMENTING - this should only be used when calling recursively
894 #=item delay_cancel - for internal use, to allow proper handling of
895 #supplemental packages when the main package is flagged to suspend
896 #before cancelling, probably shouldn't be used otherwise (set the
897 #corresponding package option instead)
900 my( $self, %options ) = @_;
903 # supplemental packages can now be separately canceled, though the UI
904 # shouldn't permit it
906 ## pass all suspend/cancel actions to the main package
907 ## (unless the pkglinknum has been removed, then the link is defunct and
908 ## this package can be canceled on its own)
909 #if ( $self->main_pkgnum and $self->pkglinknum and !$options{'from_main'} ) {
910 # return $self->main_pkg->cancel(%options);
913 my $conf = new FS::Conf;
915 warn "cust_pkg::cancel called with options".
916 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
919 my $oldAutoCommit = $FS::UID::AutoCommit;
920 local $FS::UID::AutoCommit = 0;
923 my $old = $self->select_for_update;
925 if ( $old->get('cancel') || $self->get('cancel') ) {
926 dbh->rollback if $oldAutoCommit;
927 return ""; # no error
930 # XXX possibly set cancel_time to the expire date?
931 my $cancel_time = $options{'time'} || time;
932 my $date = $options{'date'} if $options{'date'}; # expire/cancel later
933 $date = '' if ($date && $date <= $cancel_time); # complain instead?
935 my $delay_cancel = $options{'no_delay_cancel'} ? 0 : $options{'delay_cancel'};
936 if ( !$date && $self->part_pkg->option('delay_cancel',1)
937 && (($self->status eq 'active') || ($self->status eq 'suspended'))
938 && !$options{'no_delay_cancel'}
940 my $expdays = $conf->config('part_pkg-delay_cancel-days') || 1;
941 my $expsecs = 60*60*24*$expdays;
942 my $suspfor = $self->susp ? $cancel_time - $self->susp : 0;
943 $expsecs = $expsecs - $suspfor if $suspfor;
944 unless ($expsecs <= 0) { #if it's already been suspended long enough, don't re-suspend
946 $date = $cancel_time + $expsecs;
950 #race condition: usage could be ongoing until unprovisioned
951 #resolved by performing a change package instead (which unprovisions) and
953 if ( !$options{nobill} && !$date ) {
954 # && $conf->exists('bill_usage_on_cancel') ) { #calc_cancel checks this
955 my $copy = $self->new({$self->hash});
957 $copy->cust_main->bill( 'pkg_list' => [ $copy ],
959 'time' => $cancel_time );
960 warn "Error billing during cancel, custnum ".
961 #$self->cust_main->custnum. ": $error"
966 if ( $options{'reason'} ) {
967 $error = $self->insert_reason( 'reason' => $options{'reason'},
968 'action' => $date ? 'expire' : 'cancel',
969 'date' => $date ? $date : $cancel_time,
970 'reason_otaker' => $options{'reason_otaker'},
973 dbh->rollback if $oldAutoCommit;
974 return "Error inserting cust_pkg_reason: $error";
978 my %svc_cancel_opt = ();
979 $svc_cancel_opt{'date'} = $date if $date;
980 foreach my $cust_svc (
983 sort { $a->[1] <=> $b->[1] }
984 map { [ $_, $_->svc_x ? $_->svc_x->table_info->{'cancel_weight'} : -1 ]; }
985 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
987 my $part_svc = $cust_svc->part_svc;
988 next if ( defined($part_svc) and $part_svc->preserve );
989 my $error = $cust_svc->cancel( %svc_cancel_opt );
992 $dbh->rollback if $oldAutoCommit;
993 return 'Error '. ($svc_cancel_opt{'date'} ? 'expiring' : 'canceling' ).
998 # if a reasonnum was passed, get the actual reason object so we can check
1002 if ($options{'reason'} =~ /^\d+$/) {
1003 $reason = FS::reason->by_key($options{'reason'});
1007 # credit remaining time if any of these are true:
1008 # - unused_credit => 1 was passed (this happens when canceling a package
1009 # for a package change when unused_credit_change is set)
1010 # - no unused_credit option, and there is a cancel reason, and the cancel
1011 # reason says to credit the package
1012 # - no unused_credit option, and the package definition says to credit the
1013 # package on cancellation
1015 if ( exists($options{'unused_credit'}) ) {
1016 $do_credit = $options{'unused_credit'};
1017 } elsif ( defined($reason) && $reason->unused_credit ) {
1020 $do_credit = $self->part_pkg->option('unused_credit_cancel', 1);
1023 my $error = $self->credit_remaining('cancel', $cancel_time);
1025 $dbh->rollback if $oldAutoCommit;
1031 my %hash = $self->hash;
1033 $hash{'expire'} = $date;
1034 if ($delay_cancel) {
1035 # just to be sure these are clear
1036 $hash{'adjourn'} = undef;
1037 $hash{'resume'} = undef;
1040 $hash{'cancel'} = $cancel_time;
1042 $hash{'change_custnum'} = $options{'change_custnum'};
1044 # if this is a supplemental package that's lost its part_pkg_link, and it's
1045 # being canceled for real, unlink it completely
1046 if ( !$date and ! $self->pkglinknum ) {
1047 $hash{main_pkgnum} = '';
1050 # if there is a future package change scheduled, unlink from it (like
1051 # abort_change) first, then delete it.
1052 $hash{'change_to_pkgnum'} = '';
1054 # save the package state
1055 my $new = new FS::cust_pkg ( \%hash );
1056 $error = $new->replace( $self, options => { $self->options } );
1058 if ( $self->change_to_pkgnum ) {
1059 my $change_to = FS::cust_pkg->by_key($self->change_to_pkgnum);
1060 $error ||= $change_to->cancel('no_delay_cancel' => 1) || $change_to->delete;
1063 $dbh->rollback if $oldAutoCommit;
1067 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1068 $error = $supp_pkg->cancel(%options,
1070 'date' => $date, #in case it got changed by delay_cancel
1071 'delay_cancel' => $delay_cancel,
1074 $dbh->rollback if $oldAutoCommit;
1075 return "canceling supplemental pkg#".$supp_pkg->pkgnum.": $error";
1079 if ($delay_cancel && !$options{'from_main'}) {
1080 $error = $new->suspend(
1082 'time' => $cancel_time
1087 foreach my $usage ( $self->cust_pkg_usage ) {
1088 $error = $usage->delete;
1090 $dbh->rollback if $oldAutoCommit;
1091 return "deleting usage pools: $error";
1096 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1097 return '' if $date; #no errors
1099 my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ } $self->cust_main->invoicing_list;
1100 if ( !$options{'quiet'} &&
1101 $conf->exists('emailcancel', $self->cust_main->agentnum) &&
1103 my $msgnum = $conf->config('cancel_msgnum', $self->cust_main->agentnum);
1106 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum });
1107 $error = $msg_template->send( 'cust_main' => $self->cust_main,
1108 'object' => $self );
1110 #should this do something on errors?
1117 =item cancel_if_expired [ NOW_TIMESTAMP ]
1119 Cancels this package if its expire date has been reached.
1123 sub cancel_if_expired {
1125 my $time = shift || time;
1126 return '' unless $self->expire && $self->expire <= $time;
1127 my $error = $self->cancel;
1129 return "Error cancelling expired pkg ". $self->pkgnum. " for custnum ".
1130 $self->custnum. ": $error";
1135 =item uncancel_svc_x
1137 For cancelled cust_pkg, returns a list of new, uninserted FS::svc_X records
1138 for services that would be inserted by L</uncancel>. Returned objects also
1139 include the field _h_svc_x, which contains the service history object.
1141 Set pkgnum before inserting.
1143 Accepts the following options:
1145 only_svcnum - arrayref of svcnum, only returns objects for these svcnum
1146 (and only if they would otherwise be returned by this)
1150 sub uncancel_svc_x {
1151 my ($self, %opt) = @_;
1153 die 'uncancel_svc_x called on a non-cancelled cust_pkg' unless $self->get('cancel');
1155 #find historical services within this timeframe before the package cancel
1156 # (incompatible with "time" option to cust_pkg->cancel?)
1157 my $fuzz = 2 * 60; #2 minutes? too much? (might catch separate unprovision)
1158 # too little? (unprovisioing export delay?)
1159 my($end, $start) = ( $self->get('cancel'), $self->get('cancel') - $fuzz );
1160 my @h_cust_svc = $self->h_cust_svc( $end, $start );
1163 foreach my $h_cust_svc (@h_cust_svc) {
1164 next if $opt{'only_svcnum'} && !(grep { $_ == $h_cust_svc->svcnum } @{$opt{'only_svcnum'}});
1165 # filter out services that still exist on this package (ie preserved svcs)
1166 # but keep services that have since been provisioned on another package (for informational purposes)
1167 next if qsearchs('cust_svc',{ 'svcnum' => $h_cust_svc->svcnum, 'pkgnum' => $self->pkgnum });
1168 my $h_svc_x = $h_cust_svc->h_svc_x( $end, $start );
1169 next unless $h_svc_x; # this probably doesn't happen, but just in case
1170 (my $table = $h_svc_x->table) =~ s/^h_//;
1171 require "FS/$table.pm";
1172 my $class = "FS::$table";
1173 my $svc_x = $class->new( {
1174 'svcpart' => $h_cust_svc->svcpart,
1175 '_h_svc_x' => $h_svc_x,
1176 map { $_ => $h_svc_x->get($_) } fields($table)
1180 if ( $h_svc_x->isa('FS::h_svc_Radius_Mixin') ) {
1181 $svc_x->usergroup( [ $h_svc_x->h_usergroup($end, $start) ] );
1184 #these are pretty rare, but should handle them
1185 # - dsl_device (mac addresses)
1186 # - phone_device (mac addresses)
1187 # - dsl_note (ikano notes)
1188 # - domain_record (i.e. restore DNS information w/domains)
1189 # - inventory_item(?) (inventory w/un-cancelling service?)
1190 # - nas (svc_broaband nas stuff)
1191 #this stuff is unused in the wild afaik
1192 # - mailinglistmember
1194 # - svc_domain.parent_svcnum?
1195 # - acct_snarf (ancient mail fetching config)
1196 # - cgp_rule (communigate)
1197 # - cust_svc_option (used by our Tron stuff)
1198 # - acct_rt_transaction (used by our time worked stuff)
1200 push @svc_x, $svc_x;
1205 =item uncancel_svc_summary
1207 Returns an array of hashrefs, one for each service that could
1208 potentially be reprovisioned by L</uncancel>, with the following keys:
1216 label - from history table if not currently calculable, undefined if it can't be loaded
1218 reprovisionable - 1 if test reprovision succeeded, otherwise 0
1220 num_cust_svc - number of svcs for this svcpart, only if summarizing (see below)
1222 Cannot be run from within a transaction. Performs inserts
1223 to test the results, and then rolls back the transaction.
1224 Does not perform exports, so does not catch if export would fail.
1226 Also accepts the following options:
1228 no_test_reprovision - skip the test inserts (reprovisionable field will not exist)
1230 summarize_size - if true, returns a single summary record for svcparts with at
1231 least this many svcs, will have key num_cust_svc but not uncancel_svcnum, label or reprovisionable
1235 sub uncancel_svc_summary {
1236 my ($self, %opt) = @_;
1238 die 'uncancel_svc_summary called on a non-cancelled cust_pkg' unless $self->get('cancel');
1239 die 'uncancel_svc_summary called from within a transaction' unless $FS::UID::AutoCommit;
1241 local $FS::svc_Common::noexport_hack = 1; # very important not to run exports!!!
1242 local $FS::UID::AutoCommit = 0;
1244 # sort by svcpart, to check summarize_size
1245 my $uncancel_svc_x = {};
1246 foreach my $svc_x (sort { $a->{'svcpart'} <=> $b->{'svcpart'} } $self->uncancel_svc_x) {
1247 $uncancel_svc_x->{$svc_x->svcpart} = [] unless $uncancel_svc_x->{$svc_x->svcpart};
1248 push @{$uncancel_svc_x->{$svc_x->svcpart}}, $svc_x;
1252 foreach my $svcpart (keys %$uncancel_svc_x) {
1253 my @svcpart_svc_x = @{$uncancel_svc_x->{$svcpart}};
1254 if ($opt{'summarize_size'} && (@svcpart_svc_x >= $opt{'summarize_size'})) {
1255 my $svc_x = $svcpart_svc_x[0]; #grab first one for access to $part_svc
1256 my $part_svc = $svc_x->part_svc;
1258 'svcpart' => $part_svc->svcpart,
1259 'svc' => $part_svc->svc,
1260 'num_cust_svc' => scalar(@svcpart_svc_x),
1263 foreach my $svc_x (@svcpart_svc_x) {
1264 my $part_svc = $svc_x->part_svc;
1266 'svcpart' => $part_svc->svcpart,
1267 'svc' => $part_svc->svc,
1268 'uncancel_svcnum' => $svc_x->get('_h_svc_x')->svcnum,
1270 $svc_x->pkgnum($self->pkgnum); # provisioning services on a canceled package, will be rolled back
1272 unless ($opt{'no_test_reprovision'}) {
1273 # avoid possibly fatal errors from missing linked records
1274 eval { $insert_error = $svc_x->insert };
1275 $insert_error ||= $@;
1277 if ($opt{'no_test_reprovision'} or $insert_error) {
1278 # avoid possibly fatal errors from missing linked records
1279 eval { $out->{'label'} = $svc_x->label };
1280 eval { $out->{'label'} = $svc_x->get('_h_svc_x')->label } unless defined($out->{'label'});
1281 $out->{'reprovisionable'} = 0 unless $opt{'no_test_reprovision'};
1283 $out->{'label'} = $svc_x->label;
1284 $out->{'reprovisionable'} = 1;
1297 "Un-cancels" this package: Orders a new package with the same custnum, pkgpart,
1298 locationnum, (other fields?). Attempts to re-provision cancelled services
1299 using history information (errors at this stage are not fatal).
1301 cust_pkg: pass a scalar reference, will be filled in with the new cust_pkg object
1303 svc_fatal: service provisioning errors are fatal
1305 svc_errors: pass an array reference, will be filled in with any provisioning errors
1307 only_svcnum: arrayref, only attempt to re-provision these cancelled services
1309 main_pkgnum: link the package as a supplemental package of this one. For
1315 my( $self, %options ) = @_;
1317 #in case you try do do $uncancel-date = $cust_pkg->uncacel
1318 return '' unless $self->get('cancel');
1320 if ( $self->main_pkgnum and !$options{'main_pkgnum'} ) {
1321 return $self->main_pkg->uncancel(%options);
1328 my $oldAutoCommit = $FS::UID::AutoCommit;
1329 local $FS::UID::AutoCommit = 0;
1333 # insert the new package
1336 my $cust_pkg = new FS::cust_pkg {
1337 last_bill => ( $options{'last_bill'} || $self->get('last_bill') ),
1338 bill => ( $options{'bill'} || $self->get('bill') ),
1340 uncancel_pkgnum => $self->pkgnum,
1341 main_pkgnum => ($options{'main_pkgnum'} || ''),
1342 map { $_ => $self->get($_) } qw(
1343 custnum pkgpart locationnum
1345 susp adjourn resume expire start_date contract_end dundate
1346 change_date change_pkgpart change_locationnum
1347 no_auto separate_bill quantity agent_pkgid
1348 recur_show_zero setup_show_zero
1352 my $error = $cust_pkg->insert(
1353 'change' => 1, #supresses any referral credit to a referring customer
1354 'allow_pkgpart' => 1, # allow this even if the package def is disabled
1357 $dbh->rollback if $oldAutoCommit;
1366 foreach my $svc_x ($self->uncancel_svc_x('only_svcnum' => $options{'only_svcnum'})) {
1368 $svc_x->pkgnum($cust_pkg->pkgnum);
1369 my $svc_error = $svc_x->insert;
1372 if ( $options{svc_fatal} ) {
1373 $dbh->rollback if $oldAutoCommit;
1376 # if we've failed to insert the svc_x object, svc_Common->insert
1377 # will have removed the cust_svc already. if not, then both records
1378 # were inserted but we failed for some other reason (export, most
1379 # likely). in that case, report the error and delete the records.
1380 push @svc_errors, $svc_error;
1381 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svc_x->svcnum });
1383 # except if export_insert failed, export_delete probably won't be
1385 local $FS::svc_Common::noexport_hack = 1;
1386 my $cleanup_error = $svc_x->delete; # also deletes cust_svc
1387 if ( $cleanup_error ) { # and if THAT fails, then run away
1388 $dbh->rollback if $oldAutoCommit;
1389 return $cleanup_error;
1394 } #foreach uncancel_svc_x
1397 # also move over any services that didn't unprovision at cancellation
1400 foreach my $cust_svc ( qsearch('cust_svc', { pkgnum => $self->pkgnum } ) ) {
1401 $cust_svc->pkgnum( $cust_pkg->pkgnum );
1402 my $error = $cust_svc->replace;
1404 $dbh->rollback if $oldAutoCommit;
1410 # Uncancel any supplemental packages, and make them supplemental to the
1414 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1416 $error = $supp_pkg->uncancel(%options, 'main_pkgnum' => $cust_pkg->pkgnum);
1418 $dbh->rollback if $oldAutoCommit;
1419 return "canceling supplemental pkg#".$supp_pkg->pkgnum.": $error";
1427 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1429 ${ $options{cust_pkg} } = $cust_pkg if ref($options{cust_pkg});
1430 @{ $options{svc_errors} } = @svc_errors if ref($options{svc_errors});
1437 Cancels any pending expiration (sets the expire field to null)
1438 for this package and any supplemental packages.
1440 If there is an error, returns the error, otherwise returns false.
1448 my $oldAutoCommit = $FS::UID::AutoCommit;
1449 local $FS::UID::AutoCommit = 0;
1452 my $old = $self->select_for_update;
1454 my $pkgnum = $old->pkgnum;
1455 if ( $old->get('cancel') || $self->get('cancel') ) {
1456 dbh->rollback if $oldAutoCommit;
1457 return "Can't unexpire cancelled package $pkgnum";
1458 # or at least it's pointless
1461 unless ( $old->get('expire') && $self->get('expire') ) {
1462 dbh->rollback if $oldAutoCommit;
1463 return ""; # no error
1466 my %hash = $self->hash;
1467 $hash{'expire'} = '';
1468 my $new = new FS::cust_pkg ( \%hash );
1469 $error = $new->replace( $self, options => { $self->options } );
1471 $dbh->rollback if $oldAutoCommit;
1475 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1476 $error = $supp_pkg->unexpire;
1478 $dbh->rollback if $oldAutoCommit;
1479 return "unexpiring supplemental pkg#".$supp_pkg->pkgnum.": $error";
1483 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1489 =item suspend [ OPTION => VALUE ... ]
1491 Suspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
1492 package, then suspends the package itself (sets the susp field to now).
1494 Available options are:
1498 =item reason - can be set to a cancellation reason (see L<FS:reason>),
1499 either a reasonnum of an existing reason, or passing a hashref will create
1500 a new reason. The hashref should have the following keys:
1501 - typenum - Reason type (see L<FS::reason_type>
1502 - reason - Text of the new reason.
1504 =item date - can be set to a unix style timestamp to specify when to
1507 =item time - can be set to override the current time, for calculation
1508 of final invoices or unused-time credits
1510 =item resume_date - can be set to a time when the package should be
1511 unsuspended. This may be more convenient than calling C<unsuspend()>
1514 =item from_main - allows a supplemental package to be suspended, rather
1515 than redirecting the method call to its main package. For internal use.
1517 =item from_cancel - used when suspending from the cancel method, forces
1518 this to skip everything besides basic suspension. For internal use.
1522 If there is an error, returns the error, otherwise returns false.
1527 my( $self, %options ) = @_;
1530 # supplemental packages still can't be separately suspended, but silently
1531 # exit instead of failing or passing the action to the main package (so
1532 # that the "Suspend customer" action doesn't trip over the supplemental
1535 if ( $self->main_pkgnum and !$options{'from_main'} ) {
1539 my $oldAutoCommit = $FS::UID::AutoCommit;
1540 local $FS::UID::AutoCommit = 0;
1543 my $old = $self->select_for_update;
1545 my $pkgnum = $old->pkgnum;
1546 if ( $old->get('cancel') || $self->get('cancel') ) {
1547 dbh->rollback if $oldAutoCommit;
1548 return "Can't suspend cancelled package $pkgnum";
1551 if ( $old->get('susp') || $self->get('susp') ) {
1552 dbh->rollback if $oldAutoCommit;
1553 return ""; # no error # complain on adjourn?
1556 my $suspend_time = $options{'time'} || time;
1557 my $date = $options{date} if $options{date}; # adjourn/suspend later
1558 $date = '' if ($date && $date <= $suspend_time); # complain instead?
1560 if ( $date && $old->get('expire') && $old->get('expire') < $date ) {
1561 dbh->rollback if $oldAutoCommit;
1562 return "Package $pkgnum expires before it would be suspended.";
1565 # some false laziness with sub cancel
1566 if ( !$options{nobill} && !$date && !$options{'from_cancel'} &&
1567 $self->part_pkg->option('bill_suspend_as_cancel',1) ) {
1568 # kind of a kludge--'bill_suspend_as_cancel' to avoid having to
1569 # make the entire cust_main->bill path recognize 'suspend' and
1570 # 'cancel' separately.
1571 warn "Billing $pkgnum on suspension (at $suspend_time)\n" if $DEBUG;
1572 my $copy = $self->new({$self->hash});
1574 $copy->cust_main->bill( 'pkg_list' => [ $copy ],
1576 'time' => $suspend_time );
1577 warn "Error billing during suspend, custnum ".
1578 #$self->cust_main->custnum. ": $error"
1583 my $cust_pkg_reason;
1584 if ( $options{'reason'} ) {
1585 $error = $self->insert_reason( 'reason' => $options{'reason'},
1586 'action' => $date ? 'adjourn' : 'suspend',
1587 'date' => $date ? $date : $suspend_time,
1588 'reason_otaker' => $options{'reason_otaker'},
1591 dbh->rollback if $oldAutoCommit;
1592 return "Error inserting cust_pkg_reason: $error";
1594 $cust_pkg_reason = qsearchs('cust_pkg_reason', {
1595 'date' => $date ? $date : $suspend_time,
1596 'action' => $date ? 'A' : 'S',
1597 'pkgnum' => $self->pkgnum,
1601 # if a reasonnum was passed, get the actual reason object so we can check
1603 # (passing a reason hashref is still allowed, but it can't be used with
1604 # the fancy behavioral options.)
1607 if ($options{'reason'} =~ /^\d+$/) {
1608 $reason = FS::reason->by_key($options{'reason'});
1611 my %hash = $self->hash;
1613 $hash{'adjourn'} = $date;
1615 $hash{'susp'} = $suspend_time;
1618 my $resume_date = $options{'resume_date'} || 0;
1619 if ( $resume_date > ($date || $suspend_time) ) {
1620 $hash{'resume'} = $resume_date;
1623 $options{options} ||= {};
1625 my $new = new FS::cust_pkg ( \%hash );
1626 $error = $new->replace( $self, options => { $self->options,
1627 %{ $options{options} },
1631 $dbh->rollback if $oldAutoCommit;
1635 unless ( $date ) { # then we are suspending now
1637 unless ($options{'from_cancel'}) {
1638 # credit remaining time if appropriate
1639 # (if required by the package def, or the suspend reason)
1640 my $unused_credit = $self->part_pkg->option('unused_credit_suspend',1)
1641 || ( defined($reason) && $reason->unused_credit );
1643 if ( $unused_credit ) {
1644 warn "crediting unused time on pkg#".$self->pkgnum."\n" if $DEBUG;
1645 my $error = $self->credit_remaining('suspend', $suspend_time);
1647 $dbh->rollback if $oldAutoCommit;
1653 my @cust_svc = qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } );
1655 #attempt ordering ala cust_svc_suspend_cascade (without infinite-looping
1656 # on the circular dep case)
1657 # (this is too simple for multi-level deps, we need to use something
1658 # to resolve the DAG properly when possible)
1660 $svcpart{$_->svcpart} = 0 foreach @cust_svc;
1661 foreach my $svcpart ( keys %svcpart ) {
1662 foreach my $part_svc_link (
1663 FS::part_svc_link->by_agentnum($self->cust_main->agentnum,
1664 src_svcpart => $svcpart,
1665 link_type => 'cust_svc_suspend_cascade'
1668 $svcpart{$part_svc_link->dst_svcpart} = max(
1669 $svcpart{$part_svc_link->dst_svcpart},
1670 $svcpart{$part_svc_link->src_svcpart} + 1
1674 @cust_svc = sort { $svcpart{ $a->svcpart } <=> $svcpart{ $b->svcpart } }
1678 foreach my $cust_svc ( @cust_svc ) {
1679 $cust_svc->suspend( 'labels_arrayref' => \@labels );
1682 # suspension fees: if there is a feepart, and it's not an unsuspend fee,
1683 # and this is not a suspend-before-cancel
1684 if ( $cust_pkg_reason ) {
1685 my $reason_obj = $cust_pkg_reason->reason;
1686 if ( $reason_obj->feepart and
1687 ! $reason_obj->fee_on_unsuspend and
1688 ! $options{'from_cancel'} ) {
1690 # register the need to charge a fee, cust_main->bill will do the rest
1691 warn "registering suspend fee: pkgnum ".$self->pkgnum.", feepart ".$reason->feepart."\n"
1693 my $cust_pkg_reason_fee = FS::cust_pkg_reason_fee->new({
1694 'pkgreasonnum' => $cust_pkg_reason->num,
1695 'pkgnum' => $self->pkgnum,
1696 'feepart' => $reason->feepart,
1697 'nextbill' => $reason->fee_hold,
1699 $error ||= $cust_pkg_reason_fee->insert;
1703 my $conf = new FS::Conf;
1704 if ( $conf->config('suspend_email_admin') && !$options{'from_cancel'} ) {
1706 my $error = send_email(
1707 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
1708 #invoice_from ??? well as good as any
1709 'to' => $conf->config('suspend_email_admin'),
1710 'subject' => 'FREESIDE NOTIFICATION: Customer package suspended',
1712 "This is an automatic message from your Freeside installation\n",
1713 "informing you that the following customer package has been suspended:\n",
1715 'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
1716 'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
1717 ( map { "Service : $_\n" } @labels ),
1719 'custnum' => $self->custnum,
1720 'msgtype' => 'admin'
1724 warn "WARNING: can't send suspension admin email (suspending anyway): ".
1732 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1733 $error = $supp_pkg->suspend(%options, 'from_main' => 1);
1735 $dbh->rollback if $oldAutoCommit;
1736 return "suspending supplemental pkg#".$supp_pkg->pkgnum.": $error";
1740 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1745 =item credit_remaining MODE TIME
1747 Generate a credit for this package for the time remaining in the current
1748 billing period. MODE is either "suspend" or "cancel" (determines the
1749 credit type). TIME is the time of suspension/cancellation. Both arguments
1754 # Implementation note:
1756 # If you pkgpart-change a package that has been billed, and it's set to give
1757 # credit on package change, then this method gets called and then the new
1758 # package will have no last_bill date. Therefore the customer will be credited
1759 # only once (per billing period) even if there are multiple package changes.
1761 # If you location-change a package that has been billed, this method will NOT
1762 # be called and the new package WILL have the last bill date of the old
1765 # If the new package is then canceled within the same billing cycle,
1766 # credit_remaining needs to run calc_remain on the OLD package to determine
1767 # the amount of unused time to credit.
1769 sub credit_remaining {
1770 # Add a credit for remaining service
1771 my ($self, $mode, $time) = @_;
1772 die 'credit_remaining requires suspend or cancel'
1773 unless $mode eq 'suspend' or $mode eq 'cancel';
1774 die 'no suspend/cancel time' unless $time > 0;
1776 my $conf = FS::Conf->new;
1777 my $reason_type = $conf->config($mode.'_credit_type');
1781 my $remain_pkg = $self;
1782 my (@billpkgnums, @amounts, @setuprecurs);
1784 # we may have to walk back past some package changes to get to the
1785 # one that actually has unused time. loop until that happens, or we
1786 # reach the first package in the chain.
1788 my $last_bill = $remain_pkg->get('last_bill') || 0;
1789 my $next_bill = $remain_pkg->get('bill') || 0;
1790 if ( $last_bill > 0 # the package has been billed
1791 and $next_bill > 0 # the package has a next bill date
1792 and $next_bill >= $time # which is in the future
1795 # Find actual charges for the period ending on or after the cancel
1797 my @charges = qsearch('cust_bill_pkg', {
1798 pkgnum => $remain_pkg->pkgnum,
1799 edate => {op => '>=', value => $time},
1800 recur => {op => '>' , value => 0},
1803 foreach my $cust_bill_pkg (@charges) {
1804 # hack to deal with the weird behavior of edate on package
1806 my $edate = $cust_bill_pkg->edate;
1807 if ( $self->recur_temporality eq 'preceding' ) {
1808 $edate = $self->add_freq($cust_bill_pkg->sdate);
1811 # this will also get any package charges that are _entirely_ after
1812 # the cancellation date (can happen with advance billing). in that
1813 # case, use the entire recurring charge:
1814 my $amount = $cust_bill_pkg->recur - $cust_bill_pkg->usage;
1815 my $max_credit = $amount
1816 - $cust_bill_pkg->credited('', '', setuprecur => 'recur') || 0;
1818 # but if the cancellation happens during the interval, prorate it:
1819 # (XXX obey prorate_round_day here?)
1820 if ( $cust_bill_pkg->sdate < $time ) {
1822 ($edate - $time) / ($edate - $cust_bill_pkg->sdate);
1825 # if there are existing credits, don't let the sum of credits exceed
1826 # the recurring charge
1827 $amount = $max_credit if $amount > $max_credit;
1829 $amount = sprintf('%.2f', $amount);
1831 # if no time has been used and/or there are existing line item
1832 # credits, we may end up not needing to credit anything.
1833 if ( $amount > 0 ) {
1835 push @billpkgnums, $cust_bill_pkg->billpkgnum;
1836 push @amounts, $amount;
1837 push @setuprecurs, 'recur';
1839 warn "Crediting for $amount on package ".$remain_pkg->pkgnum."\n"
1848 if ( my $changed_from_pkgnum = $remain_pkg->change_pkgnum ) {
1849 $remain_pkg = FS::cust_pkg->by_key($changed_from_pkgnum);
1851 # the package has really never been billed
1856 # keep traditional behavior here.
1858 my $reason = FS::reason->new_or_existing(
1859 reason => 'Credit for unused time on '. $self->part_pkg->pkg,
1860 type => $reason_type,
1864 return "failed to set credit reason: $@";
1867 my $error = FS::cust_credit->credit_lineitems(
1868 'billpkgnums' => \@billpkgnums,
1869 'setuprecurs' => \@setuprecurs,
1870 'amounts' => \@amounts,
1871 'custnum' => $self->custnum,
1873 'reasonnum' => $reason->reasonnum,
1881 =item unsuspend [ OPTION => VALUE ... ]
1883 Unsuspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
1884 package, then unsuspends the package itself (clears the susp field and the
1885 adjourn field if it is in the past). If the suspend reason includes an
1886 unsuspension package, that package will be ordered.
1888 Available options are:
1894 Can be set to a date to unsuspend the package in the future (the 'resume'
1897 =item adjust_next_bill
1899 Can be set true to adjust the next bill date forward by
1900 the amount of time the account was inactive. This was set true by default
1901 in the past (from 1.4.2 and 1.5.0pre6 through 1.7.0), but now needs to be
1902 explicitly requested with this option or in the price plan.
1906 If there is an error, returns the error, otherwise returns false.
1911 my( $self, %opt ) = @_;
1914 # pass all suspend/cancel actions to the main package
1915 if ( $self->main_pkgnum and !$opt{'from_main'} ) {
1916 return $self->main_pkg->unsuspend(%opt);
1919 my $oldAutoCommit = $FS::UID::AutoCommit;
1920 local $FS::UID::AutoCommit = 0;
1923 my $old = $self->select_for_update;
1925 my $pkgnum = $old->pkgnum;
1926 if ( $old->get('cancel') || $self->get('cancel') ) {
1927 $dbh->rollback if $oldAutoCommit;
1928 return "Can't unsuspend cancelled package $pkgnum";
1931 unless ( $old->get('susp') && $self->get('susp') ) {
1932 $dbh->rollback if $oldAutoCommit;
1933 return ""; # no error # complain instead?
1936 # handle the case of setting a future unsuspend (resume) date
1937 # and do not continue to actually unsuspend the package
1938 my $date = $opt{'date'};
1939 if ( $date and $date > time ) { # return an error if $date <= time?
1941 if ( $old->get('expire') && $old->get('expire') < $date ) {
1942 $dbh->rollback if $oldAutoCommit;
1943 return "Package $pkgnum expires before it would be unsuspended.";
1946 my $new = new FS::cust_pkg { $self->hash };
1947 $new->set('resume', $date);
1948 $error = $new->replace($self, options => $self->options);
1951 $dbh->rollback if $oldAutoCommit;
1955 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1961 if (!$self->setup) {
1962 # then this package is being released from on-hold status
1963 $error = $self->set_initial_timers;
1965 $dbh->rollback if $oldAutoCommit;
1972 foreach my $cust_svc (
1973 qsearch('cust_svc',{'pkgnum'=> $self->pkgnum } )
1975 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
1977 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
1978 $dbh->rollback if $oldAutoCommit;
1979 return "Illegal svcdb value in part_svc!";
1982 require "FS/$svcdb.pm";
1984 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
1986 $error = $svc->unsuspend;
1988 $dbh->rollback if $oldAutoCommit;
1991 my( $label, $value ) = $cust_svc->label;
1992 push @labels, "$label: $value";
1997 my $cust_pkg_reason = $self->last_cust_pkg_reason('susp');
1998 my $reason = $cust_pkg_reason ? $cust_pkg_reason->reason : '';
2000 my %hash = $self->hash;
2001 my $inactive = time - $hash{'susp'};
2003 my $conf = new FS::Conf;
2005 #adjust the next bill date forward
2006 # increment next bill date if certain conditions are met:
2007 # - it was due to be billed at some point
2008 # - either the global or local config says to do this
2009 my $adjust_bill = 0;
2012 && ( $hash{'bill'} || $hash{'setup'} )
2013 && ( $opt{'adjust_next_bill'}
2014 || $conf->exists('unsuspend-always_adjust_next_bill_date')
2015 || $self->part_pkg->option('unsuspend_adjust_bill', 1)
2022 # - the package billed during suspension
2023 # - or it was ordered on hold
2024 # - or the customer was credited for the unused time
2026 if ( $self->option('suspend_bill',1)
2027 or ( $self->part_pkg->option('suspend_bill',1)
2028 and ! $self->option('no_suspend_bill',1)
2030 or $hash{'order_date'} == $hash{'susp'}
2035 if ( $adjust_bill ) {
2036 if ( $self->part_pkg->option('unused_credit_suspend')
2037 or ( ref($reason) and $reason->unused_credit ) ) {
2038 # then the customer was credited for the unused time before suspending,
2039 # so their next bill should be immediate
2040 $hash{'bill'} = time;
2042 # add the length of time suspended to the bill date
2043 $hash{'bill'} = ( $hash{'bill'} || $hash{'setup'} ) + $inactive;
2048 $hash{'adjourn'} = '' if $hash{'adjourn'} and $hash{'adjourn'} < time;
2049 $hash{'resume'} = '' if !$hash{'adjourn'};
2050 my $new = new FS::cust_pkg ( \%hash );
2051 $error = $new->replace( $self, options => { $self->options } );
2053 $dbh->rollback if $oldAutoCommit;
2060 if ( $reason->unsuspend_pkgpart ) {
2061 warn "Suspend reason '".$reason->reason."' uses deprecated unsuspend_pkgpart feature.\n";
2062 my $part_pkg = FS::part_pkg->by_key($reason->unsuspend_pkgpart)
2063 or $error = "Unsuspend package definition ".$reason->unsuspend_pkgpart.
2065 my $start_date = $self->cust_main->next_bill_date
2066 if $reason->unsuspend_hold;
2069 $unsusp_pkg = FS::cust_pkg->new({
2070 'custnum' => $self->custnum,
2071 'pkgpart' => $reason->unsuspend_pkgpart,
2072 'start_date' => $start_date,
2073 'locationnum' => $self->locationnum,
2074 # discount? probably not...
2077 $error ||= $self->cust_main->order_pkg( 'cust_pkg' => $unsusp_pkg );
2080 # new way, using fees
2081 if ( $reason->feepart and $reason->fee_on_unsuspend ) {
2082 # register the need to charge a fee, cust_main->bill will do the rest
2083 warn "registering unsuspend fee: pkgnum ".$self->pkgnum.", feepart ".$reason->feepart."\n"
2085 my $cust_pkg_reason_fee = FS::cust_pkg_reason_fee->new({
2086 'pkgreasonnum' => $cust_pkg_reason->num,
2087 'pkgnum' => $self->pkgnum,
2088 'feepart' => $reason->feepart,
2089 'nextbill' => $reason->fee_hold,
2091 $error ||= $cust_pkg_reason_fee->insert;
2095 $dbh->rollback if $oldAutoCommit;
2100 if ( $conf->config('unsuspend_email_admin') ) {
2102 my $error = send_email(
2103 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
2104 #invoice_from ??? well as good as any
2105 'to' => $conf->config('unsuspend_email_admin'),
2106 'subject' => 'FREESIDE NOTIFICATION: Customer package unsuspended', 'body' => [
2107 "This is an automatic message from your Freeside installation\n",
2108 "informing you that the following customer package has been unsuspended:\n",
2110 'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
2111 'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
2112 ( map { "Service : $_\n" } @labels ),
2114 "An unsuspension fee was charged: ".
2115 $unsusp_pkg->part_pkg->pkg_comment."\n"
2119 'custnum' => $self->custnum,
2120 'msgtype' => 'admin',
2124 warn "WARNING: can't send unsuspension admin email (unsuspending anyway): ".
2130 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
2131 $error = $supp_pkg->unsuspend(%opt, 'from_main' => 1);
2133 $dbh->rollback if $oldAutoCommit;
2134 return "unsuspending supplemental pkg#".$supp_pkg->pkgnum.": $error";
2138 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2145 Cancels any pending suspension (sets the adjourn field to null)
2146 for this package and any supplemental packages.
2148 If there is an error, returns the error, otherwise returns false.
2156 my $oldAutoCommit = $FS::UID::AutoCommit;
2157 local $FS::UID::AutoCommit = 0;
2160 my $old = $self->select_for_update;
2162 my $pkgnum = $old->pkgnum;
2163 if ( $old->get('cancel') || $self->get('cancel') ) {
2164 dbh->rollback if $oldAutoCommit;
2165 return "Can't unadjourn cancelled package $pkgnum";
2166 # or at least it's pointless
2169 if ( $old->get('susp') || $self->get('susp') ) {
2170 dbh->rollback if $oldAutoCommit;
2171 return "Can't unadjourn suspended package $pkgnum";
2172 # perhaps this is arbitrary
2175 unless ( $old->get('adjourn') && $self->get('adjourn') ) {
2176 dbh->rollback if $oldAutoCommit;
2177 return ""; # no error
2180 my %hash = $self->hash;
2181 $hash{'adjourn'} = '';
2182 $hash{'resume'} = '';
2183 my $new = new FS::cust_pkg ( \%hash );
2184 $error = $new->replace( $self, options => { $self->options } );
2186 $dbh->rollback if $oldAutoCommit;
2190 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
2191 $error = $supp_pkg->unadjourn;
2193 $dbh->rollback if $oldAutoCommit;
2194 return "unadjourning supplemental pkg#".$supp_pkg->pkgnum.": $error";
2198 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2205 =item change HASHREF | OPTION => VALUE ...
2207 Changes this package: cancels it and creates a new one, with a different
2208 pkgpart or locationnum or both. All services are transferred to the new
2209 package (no change will be made if this is not possible).
2211 Options may be passed as a list of key/value pairs or as a hash reference.
2218 New locationnum, to change the location for this package.
2222 New FS::cust_location object, to create a new location and assign it
2227 New FS::cust_main object, to create a new customer and assign the new package
2232 New pkgpart (see L<FS::part_pkg>).
2236 New refnum (see L<FS::part_referral>).
2240 New quantity; if unspecified, the new package will have the same quantity
2245 "New" (existing) FS::cust_pkg object. The package's services and other
2246 attributes will be transferred to this package.
2250 Set to true to transfer billing dates (start_date, setup, last_bill, bill,
2251 susp, adjourn, cancel, expire, and contract_end) to the new package.
2253 =item unprotect_svcs
2255 Normally, change() will rollback and return an error if some services
2256 can't be transferred (also see the I<cust_pkg-change_svcpart> config option).
2257 If unprotect_svcs is true, this method will transfer as many services as
2258 it can and then unconditionally cancel the old package.
2262 If specified, sets this value for the contract_end date on the new package
2263 (without regard for keep_dates or the usual date-preservation behavior.)
2264 Will throw an error if defined but false; the UI doesn't allow editing
2265 this unless it already exists, making removal impossible to undo.
2269 At least one of locationnum, cust_location, pkgpart, refnum, cust_main, or
2270 cust_pkg must be specified (otherwise, what's the point?)
2272 Returns either the new FS::cust_pkg object or a scalar error.
2276 my $err_or_new_cust_pkg = $old_cust_pkg->change
2280 #used by change and change_later
2281 #didn't put with documented check methods because it depends on change-specific opts
2282 #and it also possibly edits the value of opts
2286 if ( defined($opt->{'contract_end'}) ) {
2287 my $current_contract_end = $self->get('contract_end');
2288 unless ($opt->{'contract_end'}) {
2289 if ($current_contract_end) {
2290 return "Cannot remove contract end date when changing packages";
2292 #shouldn't even pass this option if there's not a current value
2293 #but can be handled gracefully if the option is empty
2294 warn "Contract end date passed unexpectedly";
2295 delete $opt->{'contract_end'};
2299 unless ($current_contract_end) {
2300 #option shouldn't be passed, throw error if it's non-empty
2301 return "Cannot add contract end date when changing packages " . $self->pkgnum;
2307 #some false laziness w/order
2310 my $opt = ref($_[0]) ? shift : { @_ };
2312 my $conf = new FS::Conf;
2314 # handle contract_end on cust_pkg same as passed option
2315 if ( $opt->{'cust_pkg'} ) {
2316 $opt->{'contract_end'} = $opt->{'cust_pkg'}->contract_end;
2317 delete $opt->{'contract_end'} unless $opt->{'contract_end'};
2320 # check contract_end, prevent adding/removing
2321 my $error = $self->_check_change($opt);
2322 return $error if $error;
2324 # Transactionize this whole mess
2325 my $oldAutoCommit = $FS::UID::AutoCommit;
2326 local $FS::UID::AutoCommit = 0;
2329 if ( $opt->{'cust_location'} ) {
2330 $error = $opt->{'cust_location'}->find_or_insert;
2332 $dbh->rollback if $oldAutoCommit;
2333 return "creating location record: $error";
2335 $opt->{'locationnum'} = $opt->{'cust_location'}->locationnum;
2338 # figure out if we're changing pkgpart
2339 if ( $opt->{'cust_pkg'} ) {
2340 $opt->{'pkgpart'} = $opt->{'cust_pkg'}->pkgpart;
2343 # whether to override pkgpart checking on the new package
2344 my $same_pkgpart = 1;
2345 if ( $opt->{'pkgpart'} and ( $opt->{'pkgpart'} != $self->pkgpart ) ) {
2349 $self->set('waive_setup', $opt->{'waive_setup'}) if $opt->{'waive_setup'};
2351 # Before going any further here: if the package is still in the pre-setup
2352 # state, it's safe to modify it in place. No need to charge/credit for
2353 # partial period, transfer usage pools, copy invoice details, or change any
2354 # dates. We DO need to "transfer" services (from the package to itself) to
2355 # check their validity on the new pkgpart.
2356 if ( ! $self->setup and ! $opt->{cust_pkg} and ! $opt->{cust_main} ) {
2357 foreach ( qw( locationnum pkgpart quantity refnum salesnum waive_setup ) ) {
2358 if ( length($opt->{$_}) ) {
2359 $self->set($_, $opt->{$_});
2362 # almost. if the new pkgpart specifies start/adjourn/expire timers,
2364 if ( !$same_pkgpart ) {
2365 $error ||= $self->set_initial_timers;
2367 # but if contract_end was explicitly specified, that overrides all else
2368 $self->set('contract_end', $opt->{'contract_end'})
2369 if $opt->{'contract_end'};
2371 $error ||= $self->replace;
2373 $dbh->rollback if $oldAutoCommit;
2374 return "modifying package: $error";
2377 # check/convert services (only on pkgpart change, to avoid surprises
2378 # when editing locations)
2379 # (maybe do this if changing quantity?)
2380 if ( !$same_pkgpart ) {
2382 $error = $self->transfer($self);
2384 if ( $error and $error == 0 ) {
2385 $error = "transferring $error";
2386 } elsif ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
2387 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
2388 $error = $self->transfer($self, 'change_svcpart'=>1 );
2389 if ($error and $error == 0) {
2390 $error = "converting $error";
2395 $error = "unable to transfer all services";
2399 $dbh->rollback if $oldAutoCommit;
2403 } # done transferring services
2405 $dbh->commit if $oldAutoCommit;
2414 $hash{'setup'} = $time if $self->get('setup');
2416 $hash{'change_date'} = $time;
2417 $hash{"change_$_"} = $self->$_()
2418 foreach qw( pkgnum pkgpart locationnum );
2420 my $unused_credit = 0;
2421 my $keep_dates = $opt->{'keep_dates'};
2423 # Special case. If the pkgpart is changing, and the customer is going to be
2424 # credited for remaining time, don't keep setup, bill, or last_bill dates,
2425 # and DO pass the flag to cancel() to credit the customer. If the old
2426 # package had a setup date, set the new package's setup to the package
2427 # change date so that it has the same status as before.
2428 if ( $opt->{'pkgpart'}
2429 and $opt->{'pkgpart'} != $self->pkgpart
2430 and $self->part_pkg->option('unused_credit_change', 1) ) {
2433 $hash{'last_bill'} = '';
2437 if ( $keep_dates ) {
2438 foreach my $date ( qw(setup bill last_bill) ) {
2439 $hash{$date} = $self->getfield($date);
2442 # always keep the following dates
2443 foreach my $date (qw(order_date susp adjourn cancel expire resume
2444 start_date contract_end)) {
2445 $hash{$date} = $self->getfield($date);
2447 # but if contract_end was explicitly specified, that overrides all else
2448 $hash{'contract_end'} = $opt->{'contract_end'}
2449 if $opt->{'contract_end'};
2451 # allow $opt->{'locationnum'} = '' to specifically set it to null
2452 # (i.e. customer default location)
2453 $opt->{'locationnum'} = $self->locationnum if !exists($opt->{'locationnum'});
2455 # usually this doesn't matter. the two cases where it does are:
2456 # 1. unused_credit_change + pkgpart change + setup fee on the new package
2458 # 2. (more importantly) changing a package before it's billed
2459 $hash{'waive_setup'} = $self->waive_setup;
2461 # if this package is scheduled for a future package change, preserve that
2462 $hash{'change_to_pkgnum'} = $self->change_to_pkgnum;
2464 my $custnum = $self->custnum;
2465 if ( $opt->{cust_main} ) {
2466 my $cust_main = $opt->{cust_main};
2467 unless ( $cust_main->custnum ) {
2468 my $error = $cust_main->insert( @{ $opt->{cust_main_insert_args}||[] } );
2470 $dbh->rollback if $oldAutoCommit;
2471 return "inserting customer record: $error";
2474 $custnum = $cust_main->custnum;
2477 $hash{'contactnum'} = $opt->{'contactnum'} if $opt->{'contactnum'};
2480 if ( $opt->{'cust_pkg'} ) {
2481 # The target package already exists; update it to show that it was
2482 # changed from this package.
2483 $cust_pkg = $opt->{'cust_pkg'};
2485 # follow all the above rules for date changes, etc.
2486 foreach (keys %hash) {
2487 $cust_pkg->set($_, $hash{$_});
2489 # except those that implement the future package change behavior
2490 foreach (qw(change_to_pkgnum start_date expire)) {
2491 $cust_pkg->set($_, '');
2494 $error = $cust_pkg->replace;
2497 # Create the new package.
2498 $cust_pkg = new FS::cust_pkg {
2499 custnum => $custnum,
2500 locationnum => $opt->{'locationnum'},
2501 ( map { $_ => ( $opt->{$_} || $self->$_() ) }
2502 qw( pkgpart quantity refnum salesnum )
2506 $error = $cust_pkg->insert( 'change' => 1,
2507 'allow_pkgpart' => $same_pkgpart );
2510 $dbh->rollback if $oldAutoCommit;
2511 return "inserting new package: $error";
2514 # Transfer services and cancel old package.
2515 # Enforce service limits only if this is a pkgpart change.
2516 local $FS::cust_svc::ignore_quantity;
2517 $FS::cust_svc::ignore_quantity = 1 if $same_pkgpart;
2518 $error = $self->transfer($cust_pkg);
2519 if ($error and $error == 0) {
2520 # $old_pkg->transfer failed.
2521 $dbh->rollback if $oldAutoCommit;
2522 return "transferring $error";
2525 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
2526 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
2527 $error = $self->transfer($cust_pkg, 'change_svcpart'=>1 );
2528 if ($error and $error == 0) {
2529 # $old_pkg->transfer failed.
2530 $dbh->rollback if $oldAutoCommit;
2531 return "converting $error";
2535 # We set unprotect_svcs when executing a "future package change". It's
2536 # not a user-interactive operation, so returning an error means the
2537 # package change will just fail. Rather than have that happen, we'll
2538 # let leftover services be deleted.
2539 if ($error > 0 and !$opt->{'unprotect_svcs'}) {
2540 # Transfers were successful, but we still had services left on the old
2541 # package. We can't change the package under this circumstances, so abort.
2542 $dbh->rollback if $oldAutoCommit;
2543 return "unable to transfer all services";
2546 #reset usage if changing pkgpart
2547 # AND usage rollover is off (otherwise adds twice, now and at package bill)
2548 if ($self->pkgpart != $cust_pkg->pkgpart) {
2549 my $part_pkg = $cust_pkg->part_pkg;
2550 $error = $part_pkg->reset_usage($cust_pkg, $part_pkg->is_prepaid
2554 if $part_pkg->can('reset_usage') && ! $part_pkg->option('usage_rollover',1);
2557 $dbh->rollback if $oldAutoCommit;
2558 return "setting usage values: $error";
2561 # if NOT changing pkgpart, transfer any usage pools over
2562 foreach my $usage ($self->cust_pkg_usage) {
2563 $usage->set('pkgnum', $cust_pkg->pkgnum);
2564 $error = $usage->replace;
2566 $dbh->rollback if $oldAutoCommit;
2567 return "transferring usage pools: $error";
2572 # transfer usage pricing add-ons, if we're not changing pkgpart or if they were specified
2573 if ( $same_pkgpart || $opt->{'cust_pkg_usageprice'}) {
2574 my @old_cust_pkg_usageprice;
2575 if ($opt->{'cust_pkg_usageprice'}) {
2576 @old_cust_pkg_usageprice = @{ $opt->{'cust_pkg_usageprice'} };
2578 @old_cust_pkg_usageprice = $self->cust_pkg_usageprice;
2580 foreach my $old_cust_pkg_usageprice (@old_cust_pkg_usageprice) {
2581 my $new_cust_pkg_usageprice = new FS::cust_pkg_usageprice {
2582 'pkgnum' => $cust_pkg->pkgnum,
2583 'usagepricepart' => $old_cust_pkg_usageprice->usagepricepart,
2584 'quantity' => $old_cust_pkg_usageprice->quantity,
2586 $error = $new_cust_pkg_usageprice->insert;
2588 $dbh->rollback if $oldAutoCommit;
2589 return "Error transferring usage pricing add-on: $error";
2594 # transfer discounts, if we're not changing pkgpart
2595 if ( $same_pkgpart ) {
2596 foreach my $old_discount ($self->cust_pkg_discount_active) {
2597 # don't remove the old discount, we may still need to bill that package.
2598 my $new_discount = new FS::cust_pkg_discount {
2599 'pkgnum' => $cust_pkg->pkgnum,
2600 'discountnum' => $old_discount->discountnum,
2601 'months_used' => $old_discount->months_used,
2603 $error = $new_discount->insert;
2605 $dbh->rollback if $oldAutoCommit;
2606 return "transferring discounts: $error";
2611 # transfer (copy) invoice details
2612 foreach my $detail ($self->cust_pkg_detail) {
2613 my $new_detail = FS::cust_pkg_detail->new({ $detail->hash });
2614 $new_detail->set('pkgdetailnum', '');
2615 $new_detail->set('pkgnum', $cust_pkg->pkgnum);
2616 $error = $new_detail->insert;
2618 $dbh->rollback if $oldAutoCommit;
2619 return "transferring package notes: $error";
2623 # transfer scheduled expire/adjourn reasons
2624 foreach my $action ('expire', 'adjourn') {
2625 if ( $cust_pkg->get($action) ) {
2626 my $reason = $self->last_cust_pkg_reason($action);
2628 $reason->set('pkgnum', $cust_pkg->pkgnum);
2629 $error = $reason->replace;
2631 $dbh->rollback if $oldAutoCommit;
2632 return "transferring $action reason: $error";
2640 if ( !$opt->{'cust_pkg'} ) {
2641 # Order any supplemental packages.
2642 my $part_pkg = $cust_pkg->part_pkg;
2643 my @old_supp_pkgs = $self->supplemental_pkgs;
2644 foreach my $link ($part_pkg->supp_part_pkg_link) {
2646 foreach (@old_supp_pkgs) {
2647 if ($_->pkgpart == $link->dst_pkgpart) {
2649 $_->pkgpart(0); # so that it can't match more than once
2653 # false laziness with FS::cust_main::Packages::order_pkg
2654 my $new = FS::cust_pkg->new({
2655 pkgpart => $link->dst_pkgpart,
2656 pkglinknum => $link->pkglinknum,
2657 custnum => $custnum,
2658 main_pkgnum => $cust_pkg->pkgnum,
2659 locationnum => $cust_pkg->locationnum,
2660 start_date => $cust_pkg->start_date,
2661 order_date => $cust_pkg->order_date,
2662 expire => $cust_pkg->expire,
2663 adjourn => $cust_pkg->adjourn,
2664 contract_end => $cust_pkg->contract_end,
2665 refnum => $cust_pkg->refnum,
2666 discountnum => $cust_pkg->discountnum,
2667 waive_setup => $cust_pkg->waive_setup,
2669 if ( $old and $opt->{'keep_dates'} ) {
2670 foreach (qw(setup bill last_bill)) {
2671 $new->set($_, $old->get($_));
2674 $error = $new->insert( allow_pkgpart => $same_pkgpart );
2677 $error ||= $old->transfer($new);
2679 if ( $error and $error > 0 ) {
2680 # no reason why this should ever fail, but still...
2681 $error = "Unable to transfer all services from supplemental package ".
2685 $dbh->rollback if $oldAutoCommit;
2688 push @new_supp_pkgs, $new;
2690 } # if !$opt->{'cust_pkg'}
2691 # because if there is one, then supplemental packages would already
2692 # have been created for it.
2694 #Good to go, cancel old package. Notify 'cancel' of whether to credit
2696 #Don't allow billing the package (preceding period packages and/or
2697 #outstanding usage) if we are keeping dates (i.e. location changing),
2698 #because the new package will be billed for the same date range.
2699 #Supplemental packages are also canceled here.
2701 # during scheduled changes, avoid canceling the package we just
2703 $self->set('change_to_pkgnum' => '');
2705 $error = $self->cancel(
2707 unused_credit => $unused_credit,
2708 nobill => $keep_dates,
2709 change_custnum => ( $self->custnum != $custnum ? $custnum : '' ),
2710 no_delay_cancel => 1,
2713 $dbh->rollback if $oldAutoCommit;
2714 return "canceling old package: $error";
2717 # transfer rt_field_charge, if we're not changing pkgpart
2718 # after billing of old package, before billing of new package
2719 if ( $same_pkgpart ) {
2720 foreach my $rt_field_charge ($self->rt_field_charge) {
2721 $rt_field_charge->set('pkgnum', $cust_pkg->pkgnum);
2722 $error = $rt_field_charge->replace;
2724 $dbh->rollback if $oldAutoCommit;
2725 return "transferring rt_field_charge: $error";
2730 if ( $conf->exists('cust_pkg-change_pkgpart-bill_now') ) {
2732 my $error = $cust_pkg->cust_main->bill(
2733 'pkg_list' => [ $cust_pkg, @new_supp_pkgs ]
2736 $dbh->rollback if $oldAutoCommit;
2737 return "billing new package: $error";
2741 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2747 =item change_later OPTION => VALUE...
2749 Schedule a package change for a later date. This actually orders the new
2750 package immediately, but sets its start date for a future date, and sets
2751 the current package to expire on the same date.
2753 If the package is already scheduled for a change, this can be called with
2754 'start_date' to change the scheduled date, or with pkgpart and/or
2755 locationnum to modify the package change. To cancel the scheduled change
2756 entirely, see C<abort_change>.
2764 The date for the package change. Required, and must be in the future.
2774 The pkgpart, locationnum, quantity and optional contract_end of the new
2775 package, with the same meaning as in C<change>.
2783 my $opt = ref($_[0]) ? shift : { @_ };
2785 # check contract_end, prevent adding/removing
2786 my $error = $self->_check_change($opt);
2787 return $error if $error;
2789 my $oldAutoCommit = $FS::UID::AutoCommit;
2790 local $FS::UID::AutoCommit = 0;
2793 my $cust_main = $self->cust_main;
2795 my $date = delete $opt->{'start_date'} or return 'start_date required';
2797 if ( $date <= time ) {
2798 $dbh->rollback if $oldAutoCommit;
2799 return "start_date $date is in the past";
2802 # If the user entered a new location, set it up now.
2803 if ( $opt->{'cust_location'} ) {
2804 $error = $opt->{'cust_location'}->find_or_insert;
2806 $dbh->rollback if $oldAutoCommit;
2807 return "creating location record: $error";
2809 $opt->{'locationnum'} = $opt->{'cust_location'}->locationnum;
2812 if ( $self->change_to_pkgnum ) {
2813 my $change_to = FS::cust_pkg->by_key($self->change_to_pkgnum);
2814 my $new_pkgpart = $opt->{'pkgpart'}
2815 if $opt->{'pkgpart'} and $opt->{'pkgpart'} != $change_to->pkgpart;
2816 my $new_locationnum = $opt->{'locationnum'}
2817 if $opt->{'locationnum'} and $opt->{'locationnum'} != $change_to->locationnum;
2818 my $new_quantity = $opt->{'quantity'}
2819 if $opt->{'quantity'} and $opt->{'quantity'} != $change_to->quantity;
2820 my $new_contract_end = $opt->{'contract_end'}
2821 if $opt->{'contract_end'} and $opt->{'contract_end'} != $change_to->contract_end;
2822 if ( $new_pkgpart or $new_locationnum or $new_quantity or $new_contract_end ) {
2823 # it hasn't been billed yet, so in principle we could just edit
2824 # it in place (w/o a package change), but that's bad form.
2825 # So change the package according to the new options...
2826 my $err_or_pkg = $change_to->change(%$opt);
2827 if ( ref $err_or_pkg ) {
2828 # Then set that package up for a future start.
2829 $self->set('change_to_pkgnum', $err_or_pkg->pkgnum);
2830 $self->set('expire', $date); # in case it's different
2831 $err_or_pkg->set('start_date', $date);
2832 $err_or_pkg->set('change_date', '');
2833 $err_or_pkg->set('change_pkgnum', '');
2835 $error = $self->replace ||
2836 $err_or_pkg->replace ||
2837 #because change() might've edited existing scheduled change in place
2838 (($err_or_pkg->pkgnum == $change_to->pkgnum) ? '' :
2839 $change_to->cancel('no_delay_cancel' => 1) ||
2840 $change_to->delete);
2842 $error = $err_or_pkg;
2844 } else { # change the start date only.
2845 $self->set('expire', $date);
2846 $change_to->set('start_date', $date);
2847 $error = $self->replace || $change_to->replace;
2850 $dbh->rollback if $oldAutoCommit;
2853 $dbh->commit if $oldAutoCommit;
2856 } # if $self->change_to_pkgnum
2858 my $new_pkgpart = $opt->{'pkgpart'}
2859 if $opt->{'pkgpart'} and $opt->{'pkgpart'} != $self->pkgpart;
2860 my $new_locationnum = $opt->{'locationnum'}
2861 if $opt->{'locationnum'} and $opt->{'locationnum'} != $self->locationnum;
2862 my $new_quantity = $opt->{'quantity'}
2863 if $opt->{'quantity'} and $opt->{'quantity'} != $self->quantity;
2864 my $new_contract_end = $opt->{'contract_end'}
2865 if $opt->{'contract_end'} and $opt->{'contract_end'} != $self->contract_end;
2867 return '' unless $new_pkgpart or $new_locationnum or $new_quantity or $new_contract_end; # wouldn't do anything
2869 # allow $opt->{'locationnum'} = '' to specifically set it to null
2870 # (i.e. customer default location)
2871 $opt->{'locationnum'} = $self->locationnum if !exists($opt->{'locationnum'});
2873 my $new = FS::cust_pkg->new( {
2874 custnum => $self->custnum,
2875 locationnum => $opt->{'locationnum'},
2876 start_date => $date,
2877 map { $_ => ( $opt->{$_} || $self->$_() ) }
2878 qw( pkgpart quantity refnum salesnum contract_end )
2880 $error = $new->insert('change' => 1,
2881 'allow_pkgpart' => ($new_pkgpart ? 0 : 1));
2883 $self->set('change_to_pkgnum', $new->pkgnum);
2884 $self->set('expire', $date);
2885 $error = $self->replace;
2888 $dbh->rollback if $oldAutoCommit;
2890 $dbh->commit if $oldAutoCommit;
2898 Cancels a future package change scheduled by C<change_later>.
2904 my $oldAutoCommit = $FS::UID::AutoCommit;
2905 local $FS::UID::AutoCommit = 0;
2907 my $pkgnum = $self->change_to_pkgnum;
2908 my $change_to = FS::cust_pkg->by_key($pkgnum) if $pkgnum;
2910 $self->set('change_to_pkgnum', '');
2911 $self->set('expire', '');
2912 $error = $self->replace;
2914 $error ||= $change_to->cancel || $change_to->delete;
2917 if ( $oldAutoCommit ) {
2928 =item set_quantity QUANTITY
2930 Change the package's quantity field. This is one of the few package properties
2931 that can safely be changed without canceling and reordering the package
2932 (because it doesn't affect tax eligibility). Returns an error or an
2939 $self = $self->replace_old; # just to make sure
2940 $self->quantity(shift);
2944 =item set_salesnum SALESNUM
2946 Change the package's salesnum (sales person) field. This is one of the few
2947 package properties that can safely be changed without canceling and reordering
2948 the package (because it doesn't affect tax eligibility). Returns an error or
2955 $self = $self->replace_old; # just to make sure
2956 $self->salesnum(shift);
2958 # XXX this should probably reassign any credit that's already been given
2961 =item modify_charge OPTIONS
2963 Change the properties of a one-time charge. The following properties can
2964 be changed this way:
2965 - pkg: the package description
2966 - classnum: the package class
2967 - additional: arrayref of additional invoice details to add to this package
2969 and, I<if the charge has not yet been billed>:
2970 - start_date: the date when it will be billed
2971 - amount: the setup fee to be charged
2972 - quantity: the multiplier for the setup fee
2973 - separate_bill: whether to put the charge on a separate invoice
2975 If you pass 'adjust_commission' => 1, and the classnum changes, and there are
2976 commission credits linked to this charge, they will be recalculated.
2983 my $part_pkg = $self->part_pkg;
2984 my $pkgnum = $self->pkgnum;
2987 my $oldAutoCommit = $FS::UID::AutoCommit;
2988 local $FS::UID::AutoCommit = 0;
2990 return "Can't use modify_charge except on one-time charges"
2991 unless $part_pkg->freq eq '0';
2993 if ( length($opt{'pkg'}) and $part_pkg->pkg ne $opt{'pkg'} ) {
2994 $part_pkg->set('pkg', $opt{'pkg'});
2997 my %pkg_opt = $part_pkg->options;
2998 my $pkg_opt_modified = 0;
3000 $opt{'additional'} ||= [];
3003 foreach (grep /^additional/, keys %pkg_opt) {
3004 ($i) = ($_ =~ /^additional_info(\d+)$/);
3005 $old_additional[$i] = $pkg_opt{$_} if $i;
3006 delete $pkg_opt{$_};
3009 for ( $i = 0; exists($opt{'additional'}->[$i]); $i++ ) {
3010 $pkg_opt{ "additional_info$i" } = $opt{'additional'}->[$i];
3011 if (!exists($old_additional[$i])
3012 or $old_additional[$i] ne $opt{'additional'}->[$i])
3014 $pkg_opt_modified = 1;
3017 $pkg_opt_modified = 1 if scalar(@old_additional) != $i;
3018 $pkg_opt{'additional_count'} = $i if $i > 0;
3021 if ( exists($opt{'classnum'}) and $part_pkg->classnum ne $opt{'classnum'} )
3024 $old_classnum = $part_pkg->classnum;
3025 $part_pkg->set('classnum', $opt{'classnum'});
3028 if ( !$self->get('setup') ) {
3029 # not yet billed, so allow amount, setup_cost, quantity, start_date,
3032 if ( exists($opt{'amount'})
3033 and $part_pkg->option('setup_fee') != $opt{'amount'}
3034 and $opt{'amount'} > 0 ) {
3036 $pkg_opt{'setup_fee'} = $opt{'amount'};
3037 $pkg_opt_modified = 1;
3040 if ( exists($opt{'setup_cost'})
3041 and $part_pkg->setup_cost != $opt{'setup_cost'}
3042 and $opt{'setup_cost'} > 0 ) {
3044 $part_pkg->set('setup_cost', $opt{'setup_cost'});
3047 if ( exists($opt{'quantity'})
3048 and $opt{'quantity'} != $self->quantity
3049 and $opt{'quantity'} > 0 ) {
3051 $self->set('quantity', $opt{'quantity'});
3054 if ( exists($opt{'start_date'})
3055 and $opt{'start_date'} != $self->start_date ) {
3057 $self->set('start_date', $opt{'start_date'});
3060 if ( exists($opt{'separate_bill'})
3061 and $opt{'separate_bill'} ne $self->separate_bill ) {
3063 $self->set('separate_bill', $opt{'separate_bill'});
3067 } # else simply ignore them; the UI shouldn't allow editing the fields
3070 if ( exists($opt{'taxclass'})
3071 and $part_pkg->taxclass ne $opt{'taxclass'}) {
3073 $part_pkg->set('taxclass', $opt{'taxclass'});
3077 if ( $part_pkg->modified or $pkg_opt_modified ) {
3078 # can we safely modify the package def?
3079 # Yes, if it's not available for purchase, and this is the only instance
3081 if ( $part_pkg->disabled
3082 and FS::cust_pkg->count('pkgpart = '.$part_pkg->pkgpart) == 1
3083 and FS::quotation_pkg->count('pkgpart = '.$part_pkg->pkgpart) == 0
3085 $error = $part_pkg->replace( options => \%pkg_opt );
3088 $part_pkg = $part_pkg->clone;
3089 $part_pkg->set('disabled' => 'Y');
3090 $error = $part_pkg->insert( options => \%pkg_opt );
3091 # and associate this as yet-unbilled package to the new package def
3092 $self->set('pkgpart' => $part_pkg->pkgpart);
3095 $dbh->rollback if $oldAutoCommit;
3100 if ($self->modified) { # for quantity or start_date change, or if we had
3101 # to clone the existing package def
3102 my $error = $self->replace;
3103 return $error if $error;
3105 if (defined $old_classnum) {
3106 # fix invoice grouping records
3107 my $old_catname = $old_classnum
3108 ? FS::pkg_class->by_key($old_classnum)->categoryname
3110 my $new_catname = $opt{'classnum'}
3111 ? $part_pkg->pkg_class->categoryname
3113 if ( $old_catname ne $new_catname ) {
3114 foreach my $cust_bill_pkg ($self->cust_bill_pkg) {
3115 # (there should only be one...)
3116 my @display = qsearch( 'cust_bill_pkg_display', {
3117 'billpkgnum' => $cust_bill_pkg->billpkgnum,
3118 'section' => $old_catname,
3120 foreach (@display) {
3121 $_->set('section', $new_catname);
3122 $error = $_->replace;
3124 $dbh->rollback if $oldAutoCommit;
3128 } # foreach $cust_bill_pkg
3131 if ( $opt{'adjust_commission'} ) {
3132 # fix commission credits...tricky.
3133 foreach my $cust_event ($self->cust_event) {
3134 my $part_event = $cust_event->part_event;
3135 foreach my $table (qw(sales agent)) {
3137 "FS::part_event::Action::Mixin::credit_${table}_pkg_class";
3138 my $credit = qsearchs('cust_credit', {
3139 'eventnum' => $cust_event->eventnum,
3141 if ( $part_event->isa($class) ) {
3142 # Yes, this results in current commission rates being applied
3143 # retroactively to a one-time charge. For accounting purposes
3144 # there ought to be some kind of time limit on doing this.
3145 my $amount = $part_event->_calc_credit($self);
3146 if ( $credit and $credit->amount ne $amount ) {
3147 # Void the old credit.
3148 $error = $credit->void('Package class changed');
3150 $dbh->rollback if $oldAutoCommit;
3151 return "$error (adjusting commission credit)";
3154 # redo the event action to recreate the credit.
3156 eval { $part_event->do_action( $self, $cust_event ) };
3158 $dbh->rollback if $oldAutoCommit;
3161 } # if $part_event->isa($class)
3163 } # foreach $cust_event
3164 } # if $opt{'adjust_commission'}
3165 } # if defined $old_classnum
3167 $dbh->commit if $oldAutoCommit;
3171 sub process_bulk_cust_pkg {
3174 warn Dumper($param) if $DEBUG;
3176 my $old_part_pkg = qsearchs('part_pkg',
3177 { pkgpart => $param->{'old_pkgpart'} });
3178 my $new_part_pkg = qsearchs('part_pkg',
3179 { pkgpart => $param->{'new_pkgpart'} });
3180 die "Must select a new package type\n" unless $new_part_pkg;
3181 #my $keep_dates = $param->{'keep_dates'} || 0;
3182 my $keep_dates = 1; # there is no good reason to turn this off
3184 my $oldAutoCommit = $FS::UID::AutoCommit;
3185 local $FS::UID::AutoCommit = 0;
3188 my @cust_pkgs = qsearch('cust_pkg', { 'pkgpart' => $param->{'old_pkgpart'} } );
3191 foreach my $old_cust_pkg ( @cust_pkgs ) {
3193 $job->update_statustext(int(100*$i/(scalar @cust_pkgs)));
3194 if ( $old_cust_pkg->getfield('cancel') ) {
3195 warn '[process_bulk_cust_pkg ] skipping canceled pkgnum '.
3196 $old_cust_pkg->pkgnum."\n"
3200 warn '[process_bulk_cust_pkg] changing pkgnum '.$old_cust_pkg->pkgnum."\n"
3202 my $error = $old_cust_pkg->change(
3203 'pkgpart' => $param->{'new_pkgpart'},
3204 'keep_dates' => $keep_dates
3206 if ( !ref($error) ) { # change returns the cust_pkg on success
3208 die "Error changing pkgnum ".$old_cust_pkg->pkgnum.": '$error'\n";
3211 $dbh->commit if $oldAutoCommit;
3217 Returns the last bill date, or if there is no last bill date, the setup date.
3218 Useful for billing metered services.
3224 return $self->setfield('last_bill', $_[0]) if @_;
3225 return $self->getfield('last_bill') if $self->getfield('last_bill');
3226 my $cust_bill_pkg = qsearchs('cust_bill_pkg', { 'pkgnum' => $self->pkgnum,
3227 'edate' => $self->bill, } );
3228 $cust_bill_pkg ? $cust_bill_pkg->sdate : $self->setup || 0;
3231 =item last_cust_pkg_reason ACTION
3233 Returns the most recent ACTION FS::cust_pkg_reason associated with the package.
3234 Returns false if there is no reason or the package is not currenly ACTION'd
3235 ACTION is one of adjourn, susp, cancel, or expire.
3239 sub last_cust_pkg_reason {
3240 my ( $self, $action ) = ( shift, shift );
3241 my $date = $self->get($action);
3243 'table' => 'cust_pkg_reason',
3244 'hashref' => { 'pkgnum' => $self->pkgnum,
3245 'action' => substr(uc($action), 0, 1),
3248 'order_by' => 'ORDER BY num DESC LIMIT 1',
3252 =item last_reason ACTION
3254 Returns the most recent ACTION FS::reason associated with the package.
3255 Returns false if there is no reason or the package is not currenly ACTION'd
3256 ACTION is one of adjourn, susp, cancel, or expire.
3261 my $cust_pkg_reason = shift->last_cust_pkg_reason(@_);
3262 $cust_pkg_reason->reason
3263 if $cust_pkg_reason;
3268 Returns the definition for this billing item, as an FS::part_pkg object (see
3275 return $self->{'_pkgpart'} if $self->{'_pkgpart'};
3276 cluck "cust_pkg->part_pkg called" if $DEBUG > 1;
3277 qsearchs( 'part_pkg', { 'pkgpart' => $self->pkgpart } );
3282 Returns the cancelled package this package was changed from, if any.
3288 return '' unless $self->change_pkgnum;
3289 qsearchs('cust_pkg', { 'pkgnum' => $self->change_pkgnum } );
3292 =item change_cust_main
3294 Returns the customter this package was detached to, if any.
3298 sub change_cust_main {
3300 return '' unless $self->change_custnum;
3301 qsearchs('cust_main', { 'custnum' => $self->change_custnum } );
3306 Calls the I<calc_setup> of the FS::part_pkg object associated with this billing
3313 $self->part_pkg->calc_setup($self, @_);
3318 Calls the I<calc_recur> of the FS::part_pkg object associated with this billing
3325 $self->part_pkg->calc_recur($self, @_);
3330 Calls the I<base_setup> of the FS::part_pkg object associated with this billing
3337 $self->part_pkg->base_setup($self, @_);
3342 Calls the I<base_recur> of the FS::part_pkg object associated with this billing
3349 $self->part_pkg->base_recur($self, @_);
3354 Calls the I<calc_remain> of the FS::part_pkg object associated with this
3361 $self->part_pkg->calc_remain($self, @_);
3366 Calls the I<calc_cancel> of the FS::part_pkg object associated with this
3373 $self->part_pkg->calc_cancel($self, @_);
3378 Returns any invoice line items for this package (see L<FS::cust_bill_pkg>).
3384 qsearch( 'cust_bill_pkg', { 'pkgnum' => $self->pkgnum } );
3387 =item cust_pkg_detail [ DETAILTYPE ]
3389 Returns any customer package details for this package (see
3390 L<FS::cust_pkg_detail>).
3392 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
3396 sub cust_pkg_detail {
3398 my %hash = ( 'pkgnum' => $self->pkgnum );
3399 $hash{detailtype} = shift if @_;
3401 'table' => 'cust_pkg_detail',
3402 'hashref' => \%hash,
3403 'order_by' => 'ORDER BY weight, pkgdetailnum',
3407 =item set_cust_pkg_detail DETAILTYPE [ DETAIL, DETAIL, ... ]
3409 Sets customer package details for this package (see L<FS::cust_pkg_detail>).
3411 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
3413 If there is an error, returns the error, otherwise returns false.
3417 sub set_cust_pkg_detail {
3418 my( $self, $detailtype, @details ) = @_;
3420 my $oldAutoCommit = $FS::UID::AutoCommit;
3421 local $FS::UID::AutoCommit = 0;
3424 foreach my $current ( $self->cust_pkg_detail($detailtype) ) {
3425 my $error = $current->delete;
3427 $dbh->rollback if $oldAutoCommit;
3428 return "error removing old detail: $error";
3432 foreach my $detail ( @details ) {
3433 my $cust_pkg_detail = new FS::cust_pkg_detail {
3434 'pkgnum' => $self->pkgnum,
3435 'detailtype' => $detailtype,
3436 'detail' => $detail,
3438 my $error = $cust_pkg_detail->insert;
3440 $dbh->rollback if $oldAutoCommit;
3441 return "error adding new detail: $error";
3446 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3453 Returns the customer billing events (see L<FS::cust_event>) for this invoice.
3457 #false laziness w/cust_bill.pm
3461 'table' => 'cust_event',
3462 'addl_from' => 'JOIN part_event USING ( eventpart )',
3463 'hashref' => { 'tablenum' => $self->pkgnum },
3464 'extra_sql' => " AND eventtable = 'cust_pkg' ",
3468 =item num_cust_event
3470 Returns the number of customer billing events (see L<FS::cust_event>) for this package.
3474 #false laziness w/cust_bill.pm
3475 sub num_cust_event {
3477 my $sql = "SELECT COUNT(*) ". $self->_from_cust_event_where;
3478 $self->_prep_ex($sql, $self->pkgnum)->fetchrow_arrayref->[0];
3481 =item exists_cust_event
3483 Returns true if there are customer billing events (see L<FS::cust_event>) for this package. More efficient than using num_cust_event.
3487 sub exists_cust_event {
3489 my $sql = "SELECT 1 ". $self->_from_cust_event_where. " LIMIT 1";
3490 my $row = $self->_prep_ex($sql, $self->pkgnum)->fetchrow_arrayref;
3491 $row ? $row->[0] : '';
3494 sub _from_cust_event_where {
3496 " FROM cust_event JOIN part_event USING ( eventpart ) ".
3497 " WHERE tablenum = ? AND eventtable = 'cust_pkg' ";
3501 my( $self, $sql, @args ) = @_;
3502 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
3503 $sth->execute(@args) or die $sth->errstr. " executing $sql";
3507 =item part_pkg_currency_option OPTIONNAME
3509 Returns a two item list consisting of the currency of this customer, if any,
3510 and a value for the provided option. If the customer has a currency, the value
3511 is the option value the given name and the currency (see
3512 L<FS::part_pkg_currency>). Otherwise, if the customer has no currency, is the
3513 regular option value for the given name (see L<FS::part_pkg_option>).
3517 sub part_pkg_currency_option {
3518 my( $self, $optionname ) = @_;
3519 my $part_pkg = $self->part_pkg;
3520 if ( my $currency = $self->cust_main->currency ) {
3521 ($currency, $part_pkg->part_pkg_currency_option($currency, $optionname) );
3523 ('', $part_pkg->option($optionname) );
3527 =item cust_svc [ SVCPART ] (old, deprecated usage)
3529 =item cust_svc [ OPTION => VALUE ... ] (current usage)
3531 =item cust_svc_unsorted [ OPTION => VALUE ... ]
3533 Returns the services for this package, as FS::cust_svc objects (see
3534 L<FS::cust_svc>). Available options are svcpart and svcdb. If either is
3535 spcififed, returns only the matching services.
3537 As an optimization, use the cust_svc_unsorted version if you are not displaying
3544 cluck "cust_pkg->cust_svc called" if $DEBUG > 2;
3545 $self->_sort_cust_svc( $self->cust_svc_unsorted_arrayref(@_) );
3548 sub cust_svc_unsorted {
3550 @{ $self->cust_svc_unsorted_arrayref(@_) };
3553 sub cust_svc_unsorted_arrayref {
3556 return [] unless $self->num_cust_svc(@_);
3559 if ( @_ && $_[0] =~ /^\d+/ ) {
3560 $opt{svcpart} = shift;
3561 } elsif ( @_ && ref($_[0]) eq 'HASH' ) {
3568 'select' => 'cust_svc.*, part_svc.*',
3569 'table' => 'cust_svc',
3570 'hashref' => { 'pkgnum' => $self->pkgnum },
3571 'addl_from' => 'LEFT JOIN part_svc USING ( svcpart )',
3573 $search{hashref}->{svcpart} = $opt{svcpart}
3575 $search{extra_sql} = ' AND svcdb = '. dbh->quote( $opt{svcdb} )
3578 [ qsearch(\%search) ];
3582 =item overlimit [ SVCPART ]
3584 Returns the services for this package which have exceeded their
3585 usage limit as FS::cust_svc objects (see L<FS::cust_svc>). If a svcpart
3586 is specified, return only the matching services.
3592 return () unless $self->num_cust_svc(@_);
3593 grep { $_->overlimit } $self->cust_svc(@_);
3596 =item h_cust_svc END_TIMESTAMP [ START_TIMESTAMP ] [ MODE ]
3598 Returns historical services for this package created before END TIMESTAMP and
3599 (optionally) not cancelled before START_TIMESTAMP, as FS::h_cust_svc objects
3600 (see L<FS::h_cust_svc>). If MODE is 'I' (for 'invoice'), services with the
3601 I<pkg_svc.hidden> flag will be omitted.
3607 warn "$me _h_cust_svc called on $self\n"
3610 my ($end, $start, $mode) = @_;
3612 local($FS::Record::qsearch_qualify_columns) = 0;
3614 my @cust_svc = $self->_sort_cust_svc(
3615 [ qsearch( 'h_cust_svc',
3616 { 'pkgnum' => $self->pkgnum, },
3617 FS::h_cust_svc->sql_h_search(@_),
3621 if ( defined($mode) && $mode eq 'I' ) {
3622 my %hidden_svcpart = map { $_->svcpart => $_->hidden } $self->part_svc;
3623 return grep { !$hidden_svcpart{$_->svcpart} } @cust_svc;
3629 sub _sort_cust_svc {
3630 my( $self, $arrayref ) = @_;
3633 sub ($$) { my ($a, $b) = @_; $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] };
3635 my %pkg_svc = map { $_->svcpart => $_ }
3636 qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
3641 my $pkg_svc = $pkg_svc{ $_->svcpart } || '';
3643 $pkg_svc ? $pkg_svc->primary_svc : '',
3644 $pkg_svc ? $pkg_svc->quantity : 0,
3651 =item num_cust_svc [ SVCPART ] (old, deprecated usage)
3653 =item num_cust_svc [ OPTION => VALUE ... ] (current usage)
3655 Returns the number of services for this package. Available options are svcpart
3656 and svcdb. If either is spcififed, returns only the matching services.
3663 return $self->{'_num_cust_svc'}
3665 && exists($self->{'_num_cust_svc'})
3666 && $self->{'_num_cust_svc'} =~ /\d/;
3668 cluck "cust_pkg->num_cust_svc called, _num_cust_svc:".$self->{'_num_cust_svc'}
3672 if ( @_ && $_[0] =~ /^\d+/ ) {
3673 $opt{svcpart} = shift;
3674 } elsif ( @_ && ref($_[0]) eq 'HASH' ) {
3680 my $select = 'SELECT COUNT(*) FROM cust_svc ';
3681 my $where = ' WHERE pkgnum = ? ';
3682 my @param = ($self->pkgnum);
3684 if ( $opt{'svcpart'} ) {
3685 $where .= ' AND svcpart = ? ';
3686 push @param, $opt{'svcpart'};
3688 if ( $opt{'svcdb'} ) {
3689 $select .= ' LEFT JOIN part_svc USING ( svcpart ) ';
3690 $where .= ' AND svcdb = ? ';
3691 push @param, $opt{'svcdb'};
3694 my $sth = dbh->prepare("$select $where") or die dbh->errstr;
3695 $sth->execute(@param) or die $sth->errstr;
3696 $sth->fetchrow_arrayref->[0];
3699 =item available_part_svc
3701 Returns a list of FS::part_svc objects representing services included in this
3702 package but not yet provisioned. Each FS::part_svc object also has an extra
3703 field, I<num_avail>, which specifies the number of available services.
3705 Accepts option I<provision_hold>; if true, only returns part_svc for which the
3706 associated pkg_svc has the provision_hold flag set.
3710 sub available_part_svc {
3714 my $pkg_quantity = $self->quantity || 1;
3716 grep { $_->num_avail > 0 }
3718 my $part_svc = $_->part_svc;
3719 $part_svc->{'Hash'}{'num_avail'} = #evil encapsulation-breaking
3720 $pkg_quantity * $_->quantity - $self->num_cust_svc($_->svcpart);
3722 # more evil encapsulation breakage
3723 if ($part_svc->{'Hash'}{'num_avail'} > 0) {
3724 my @exports = $part_svc->part_export_did;
3725 $part_svc->{'Hash'}{'can_get_dids'} = scalar(@exports);
3730 grep { $opt{'provision_hold'} ? $_->provision_hold : 1 }
3731 $self->part_pkg->pkg_svc;
3734 =item part_svc [ OPTION => VALUE ... ]
3736 Returns a list of FS::part_svc objects representing provisioned and available
3737 services included in this package. Each FS::part_svc object also has the
3738 following extra fields:
3752 (services) - array reference containing the provisioned services, as cust_svc objects
3756 Accepts two options:
3760 =item summarize_size
3762 If true, will omit the extra cust_pkg_svc option for objects where num_cust_svc
3763 is this size or greater.
3765 =item hide_discontinued
3767 If true, will omit looking for services that are no longer avaialble in the
3775 #label -> ($cust_svc->label)[1]
3781 my $pkg_quantity = $self->quantity || 1;
3783 #XXX some sort of sort order besides numeric by svcpart...
3784 my @part_svc = sort { $a->svcpart <=> $b->svcpart } map {
3786 my $part_svc = $pkg_svc->part_svc;
3787 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
3788 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #more evil
3789 $part_svc->{'Hash'}{'num_avail'} =
3790 max( 0, $pkg_quantity * $pkg_svc->quantity - $num_cust_svc );
3791 $part_svc->{'Hash'}{'cust_pkg_svc'} =
3792 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : []
3793 unless exists($opt{summarize_size}) && $opt{summarize_size} > 0
3794 && $num_cust_svc >= $opt{summarize_size};
3795 $part_svc->{'Hash'}{'hidden'} = $pkg_svc->hidden;
3797 } $self->part_pkg->pkg_svc;
3799 unless ( $opt{hide_discontinued} ) {
3801 push @part_svc, map {
3803 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
3804 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #speak no evail
3805 $part_svc->{'Hash'}{'num_avail'} = 0; #0-$num_cust_svc ?
3806 $part_svc->{'Hash'}{'cust_pkg_svc'} =
3807 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : [];
3809 } $self->extra_part_svc;
3816 =item extra_part_svc
3818 Returns a list of FS::part_svc objects corresponding to services in this
3819 package which are still provisioned but not (any longer) available in the
3824 sub extra_part_svc {
3827 my $pkgnum = $self->pkgnum;
3828 #my $pkgpart = $self->pkgpart;
3831 # 'table' => 'part_svc',
3834 # "WHERE 0 = ( SELECT COUNT(*) FROM pkg_svc
3835 # WHERE pkg_svc.svcpart = part_svc.svcpart
3836 # AND pkg_svc.pkgpart = ?
3839 # AND 0 < ( SELECT COUNT(*) FROM cust_svc
3840 # LEFT JOIN cust_pkg USING ( pkgnum )
3841 # WHERE cust_svc.svcpart = part_svc.svcpart
3844 # 'extra_param' => [ [$self->pkgpart=>'int'], [$self->pkgnum=>'int'] ],
3847 #seems to benchmark slightly faster... (or did?)
3849 my @pkgparts = map $_->pkgpart, $self->part_pkg->self_and_svc_linked;
3850 my $pkgparts = join(',', @pkgparts);
3853 #'select' => 'DISTINCT ON (svcpart) part_svc.*',
3854 #MySQL doesn't grok DISINCT ON
3855 'select' => 'DISTINCT part_svc.*',
3856 'table' => 'part_svc',
3858 "LEFT JOIN pkg_svc ON ( pkg_svc.svcpart = part_svc.svcpart
3859 AND pkg_svc.pkgpart IN ($pkgparts)
3862 LEFT JOIN cust_svc ON ( cust_svc.svcpart = part_svc.svcpart )
3863 LEFT JOIN cust_pkg USING ( pkgnum )
3866 'extra_sql' => "WHERE pkgsvcnum IS NULL AND cust_pkg.pkgnum = ? ",
3867 'extra_param' => [ [$self->pkgnum=>'int'] ],
3873 Returns a short status string for this package, currently:
3879 =item not yet billed
3881 =item one-time charge
3896 my $freq = length($self->freq) ? $self->freq : $self->part_pkg->freq;
3898 return 'cancelled' if $self->get('cancel');
3899 return 'on hold' if $self->susp && ! $self->setup;
3900 return 'suspended' if $self->susp;
3901 return 'not yet billed' unless $self->setup;
3902 return 'one-time charge' if $freq =~ /^(0|$)/;
3906 =item ucfirst_status
3908 Returns the status with the first character capitalized.
3912 sub ucfirst_status {
3913 ucfirst(shift->status);
3918 Class method that returns the list of possible status strings for packages
3919 (see L<the status method|/status>). For example:
3921 @statuses = FS::cust_pkg->statuses();
3925 tie my %statuscolor, 'Tie::IxHash',
3926 'on hold' => 'FF00F5', #brighter purple!
3927 'not yet billed' => '009999', #teal? cyan?
3928 'one-time charge' => '0000CC', #blue #'000000',
3929 'active' => '00CC00',
3930 'suspended' => 'FF9900',
3931 'cancelled' => 'FF0000',
3935 my $self = shift; #could be class...
3936 #grep { $_ !~ /^(not yet billed)$/ } #this is a dumb status anyway
3937 # # mayble split btw one-time vs. recur
3948 Returns a hex triplet color string for this package's status.
3954 $statuscolor{$self->status};
3957 =item is_status_delay_cancel
3959 Returns true if part_pkg has option delay_cancel,
3960 cust_pkg status is 'suspended' and expire is set
3961 to cancel package within the next day (or however
3962 many days are set in global config part_pkg-delay_cancel-days.
3964 Accepts option I<part_pkg-delay_cancel-days> which should be
3965 the value of the config setting, to avoid looking it up again.
3967 This is not a real status, this only meant for hacking display
3968 values, because otherwise treating the package as suspended is
3969 really the whole point of the delay_cancel option.
3973 sub is_status_delay_cancel {
3974 my ($self,%opt) = @_;
3975 if ( $self->main_pkgnum and $self->pkglinknum ) {
3976 return $self->main_pkg->is_status_delay_cancel;
3978 return 0 unless $self->part_pkg->option('delay_cancel',1);
3979 return 0 unless $self->status eq 'suspended';
3980 return 0 unless $self->expire;
3981 my $expdays = $opt{'part_pkg-delay_cancel-days'};
3983 my $conf = new FS::Conf;
3984 $expdays = $conf->config('part_pkg-delay_cancel-days') || 1;
3986 my $expsecs = 60*60*24*$expdays;
3987 return 0 unless $self->expire < time + $expsecs;
3993 Returns a label for this package. (Currently "pkgnum: pkg - comment" or
3994 "pkg - comment" depending on user preference).
4000 my $label = $self->part_pkg->pkg_comment( cust_pkg=>$self, nopkgpart=>1 );
4001 $label = $self->pkgnum. ": $label"
4002 if $FS::CurrentUser::CurrentUser->option('show_pkgnum');
4006 =item pkg_label_long
4008 Returns a long label for this package, adding the primary service's label to
4013 sub pkg_label_long {
4015 my $label = $self->pkg_label;
4016 my $cust_svc = $self->primary_cust_svc;
4017 $label .= ' ('. ($cust_svc->label)[1]. ')' if $cust_svc;
4023 Returns a customer-localized label for this package.
4029 $self->part_pkg->pkg_locale( $self->cust_main->locale );
4032 =item primary_cust_svc
4034 Returns a primary service (as FS::cust_svc object) if one can be identified.
4038 #for labeling purposes - might not 100% match up with part_pkg->svcpart's idea
4040 sub primary_cust_svc {
4043 my @cust_svc = $self->cust_svc;
4045 return '' unless @cust_svc; #no serivces - irrelevant then
4047 return $cust_svc[0] if scalar(@cust_svc) == 1; #always return a single service
4049 # primary service as specified in the package definition
4050 # or exactly one service definition with quantity one
4051 my $svcpart = $self->part_pkg->svcpart;
4052 @cust_svc = grep { $_->svcpart == $svcpart } @cust_svc;
4053 return $cust_svc[0] if scalar(@cust_svc) == 1;
4055 #couldn't identify one thing..
4061 Returns a list of lists, calling the label method for all services
4062 (see L<FS::cust_svc>) of this billing item.
4068 map { [ $_->label ] } $self->cust_svc;
4071 =item h_labels END_TIMESTAMP [, START_TIMESTAMP [, MODE [, LOCALE ] ] ]
4073 Like the labels method, but returns historical information on services that
4074 were active as of END_TIMESTAMP and (optionally) not cancelled before
4075 START_TIMESTAMP. If MODE is 'I' (for 'invoice'), services with the
4076 I<pkg_svc.hidden> flag will be omitted.
4078 If LOCALE is passed, service definition names will be localized.
4080 Returns a list of lists, calling the label method for all (historical)
4081 services (see L<FS::h_cust_svc>) of this billing item.
4087 my ($end, $start, $mode, $locale) = @_;
4088 warn "$me h_labels\n"
4090 map { [ $_->label($end, $start, $locale) ] }
4091 $self->h_cust_svc($end, $start, $mode);
4096 Like labels, except returns a simple flat list, and shortens long
4097 (currently >5 or the cust_bill-max_same_services configuration value) lists of
4098 identical services to one line that lists the service label and the number of
4099 individual services rather than individual items.
4104 shift->_labels_short( 'labels' ); # 'labels' takes no further arguments
4107 =item h_labels_short END_TIMESTAMP [, START_TIMESTAMP [, MODE [, LOCALE ] ] ]
4109 Like h_labels, except returns a simple flat list, and shortens long
4110 (currently >5 or the cust_bill-max_same_services configuration value) lists
4111 of identical services to one line that lists the service label and the
4112 number of individual services rather than individual items.
4116 sub h_labels_short {
4117 shift->_labels_short( 'h_labels', @_ );
4120 # takes a method name ('labels' or 'h_labels') and all its arguments;
4121 # maybe should be "shorten($self->h_labels( ... ) )"
4124 my( $self, $method ) = ( shift, shift );
4126 warn "$me _labels_short called on $self with $method method\n"
4129 my $conf = new FS::Conf;
4130 my $max_same_services = $conf->config('cust_bill-max_same_services') || 5;
4132 warn "$me _labels_short populating \%labels\n"
4136 #tie %labels, 'Tie::IxHash';
4137 push @{ $labels{$_->[0]} }, $_->[1]
4138 foreach $self->$method(@_);
4140 warn "$me _labels_short populating \@labels\n"
4144 foreach my $label ( keys %labels ) {
4146 my @values = grep { ! $seen{$_}++ } @{ $labels{$label} };
4147 my $num = scalar(@values);
4148 warn "$me _labels_short $num items for $label\n"
4151 if ( $num > $max_same_services ) {
4152 warn "$me _labels_short more than $max_same_services, so summarizing\n"
4154 push @labels, "$label ($num)";
4156 if ( $conf->exists('cust_bill-consolidate_services') ) {
4157 warn "$me _labels_short consolidating services\n"
4159 # push @labels, "$label: ". join(', ', @values);
4161 my $detail = "$label: ";
4162 $detail .= shift(@values). ', '
4164 && ( length($detail.$values[0]) < 78 || $detail eq "$label: " );
4166 push @labels, $detail;
4168 warn "$me _labels_short done consolidating services\n"
4171 warn "$me _labels_short adding service data\n"
4173 push @labels, map { "$label: $_" } @values;
4184 Returns the parent customer object (see L<FS::cust_main>).
4188 Returns the balance for this specific package, when using
4189 experimental package balance.
4195 $self->cust_main->balance_pkgnum( $self->pkgnum );
4198 #these subs are in location_Mixin.pm now... unfortunately the POD doesn't mixin
4202 Returns the location object, if any (see L<FS::cust_location>).
4204 =item cust_location_or_main
4206 If this package is associated with a location, returns the locaiton (see
4207 L<FS::cust_location>), otherwise returns the customer (see L<FS::cust_main>).
4209 =item location_label [ OPTION => VALUE ... ]
4211 Returns the label of the location object (see L<FS::cust_location>).
4215 #end of subs in location_Mixin.pm now... unfortunately the POD doesn't mixin
4217 =item tax_locationnum
4219 Returns the foreign key to a L<FS::cust_location> object for calculating
4220 tax on this package, as determined by the C<tax-pkg_address> and
4221 C<tax-ship_address> configuration flags.
4225 sub tax_locationnum {
4227 my $conf = FS::Conf->new;
4228 if ( $conf->exists('tax-pkg_address') ) {
4229 return $self->locationnum;
4231 elsif ( $conf->exists('tax-ship_address') ) {
4232 return $self->cust_main->ship_locationnum;
4235 return $self->cust_main->bill_locationnum;
4241 Returns the L<FS::cust_location> object for tax_locationnum.
4247 my $conf = FS::Conf->new;
4248 if ( $conf->exists('tax-pkg_address') and $self->locationnum ) {
4249 return FS::cust_location->by_key($self->locationnum);
4251 elsif ( $conf->exists('tax-ship_address') ) {
4252 return $self->cust_main->ship_location;
4255 return $self->cust_main->bill_location;
4259 =item seconds_since TIMESTAMP
4261 Returns the number of seconds all accounts (see L<FS::svc_acct>) in this
4262 package have been online since TIMESTAMP, according to the session monitor.
4264 TIMESTAMP is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
4265 L<Time::Local> and L<Date::Parse> for conversion functions.
4270 my($self, $since) = @_;
4273 foreach my $cust_svc (
4274 grep { $_->part_svc->svcdb eq 'svc_acct' } $self->cust_svc
4276 $seconds += $cust_svc->seconds_since($since);
4283 =item seconds_since_sqlradacct TIMESTAMP_START TIMESTAMP_END
4285 Returns the numbers of seconds all accounts (see L<FS::svc_acct>) in this
4286 package have been online between TIMESTAMP_START (inclusive) and TIMESTAMP_END
4289 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
4290 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
4296 sub seconds_since_sqlradacct {
4297 my($self, $start, $end) = @_;
4301 foreach my $cust_svc (
4303 my $part_svc = $_->part_svc;
4304 $part_svc->svcdb eq 'svc_acct'
4305 && scalar($part_svc->part_export_usage);
4308 $seconds += $cust_svc->seconds_since_sqlradacct($start, $end);
4315 =item attribute_since_sqlradacct TIMESTAMP_START TIMESTAMP_END ATTRIBUTE
4317 Returns the sum of the given attribute for all accounts (see L<FS::svc_acct>)
4318 in this package for sessions ending between TIMESTAMP_START (inclusive) and
4322 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
4323 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
4328 sub attribute_since_sqlradacct {
4329 my($self, $start, $end, $attrib) = @_;
4333 foreach my $cust_svc (
4335 my $part_svc = $_->part_svc;
4336 scalar($part_svc->part_export_usage);
4339 $sum += $cust_svc->attribute_since_sqlradacct($start, $end, $attrib);
4351 my( $self, $value ) = @_;
4352 if ( defined($value) ) {
4353 $self->setfield('quantity', $value);
4355 $self->getfield('quantity') || 1;
4358 =item transfer DEST_PKGNUM | DEST_CUST_PKG, [ OPTION => VALUE ... ]
4360 Transfers as many services as possible from this package to another package.
4362 The destination package can be specified by pkgnum by passing an FS::cust_pkg
4363 object. The destination package must already exist.
4365 Services are moved only if the destination allows services with the correct
4366 I<svcpart> (not svcdb), unless the B<change_svcpart> option is set true. Use
4367 this option with caution! No provision is made for export differences
4368 between the old and new service definitions. Probably only should be used
4369 when your exports for all service definitions of a given svcdb are identical.
4370 (attempt a transfer without it first, to move all possible svcpart-matching
4373 Any services that can't be moved remain in the original package.
4375 Returns an error, if there is one; otherwise, returns the number of services
4376 that couldn't be moved.
4381 my ($self, $dest_pkgnum, %opt) = @_;
4387 if (ref ($dest_pkgnum) eq 'FS::cust_pkg') {
4388 $dest = $dest_pkgnum;
4389 $dest_pkgnum = $dest->pkgnum;
4391 $dest = qsearchs('cust_pkg', { pkgnum => $dest_pkgnum });
4394 return ('Package does not exist: '.$dest_pkgnum) unless $dest;
4396 foreach my $pkg_svc ( $dest->part_pkg->pkg_svc ) {
4397 $target{$pkg_svc->svcpart} = $pkg_svc->quantity * ( $dest->quantity || 1 );
4400 unless ( $self->pkgnum == $dest->pkgnum ) {
4401 foreach my $cust_svc ($dest->cust_svc) {
4402 $target{$cust_svc->svcpart}--;
4406 my %svcpart2svcparts = ();
4407 if ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
4408 warn "change_svcpart option received, creating alternates list\n" if $DEBUG;
4409 foreach my $svcpart ( map { $_->svcpart } $self->cust_svc ) {
4410 next if exists $svcpart2svcparts{$svcpart};
4411 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
4412 $svcpart2svcparts{$svcpart} = [
4414 sort { $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] }
4416 my $pkg_svc = qsearchs( 'pkg_svc', { 'pkgpart' => $dest->pkgpart,
4417 'svcpart' => $_ } );
4419 $pkg_svc ? $pkg_svc->primary_svc : '',
4420 $pkg_svc ? $pkg_svc->quantity : 0,
4424 grep { $_ != $svcpart }
4426 qsearch('part_svc', { 'svcdb' => $part_svc->svcdb } )
4428 warn "alternates for svcpart $svcpart: ".
4429 join(', ', @{$svcpart2svcparts{$svcpart}}). "\n"
4435 foreach my $cust_svc ($self->cust_svc) {
4436 my $svcnum = $cust_svc->svcnum;
4438 if ( $target{$cust_svc->svcpart} > 0
4439 or $FS::cust_svc::ignore_quantity # maybe should be a 'force' option
4442 $target{$cust_svc->svcpart}--;
4444 local $FS::cust_svc::ignore_quantity = 1
4445 if $self->pkgnum == $dest->pkgnum;
4447 #why run replace at all in the $self->pkgnum == $dest->pkgnum case?
4448 # we do want to trigger location and pkg_change exports, but
4449 # without pkgnum changing from an old to new package, cust_svc->replace
4450 # doesn't know how to trigger those. :/
4451 # does this mean we scrap the whole idea of "safe to modify it in place",
4452 # or do we special-case and pass the info needed to cust_svc->replace? :/
4454 my $new = new FS::cust_svc { $cust_svc->hash };
4455 $new->pkgnum($dest_pkgnum);
4456 $error = $new->replace($cust_svc);
4458 } elsif ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
4461 warn "looking for alternates for svcpart ". $cust_svc->svcpart. "\n";
4462 warn "alternates to consider: ".
4463 join(', ', @{$svcpart2svcparts{$cust_svc->svcpart}}). "\n";
4466 my @alternate = grep {
4467 warn "considering alternate svcpart $_: ".
4468 "$target{$_} available in new package\n"
4471 } @{$svcpart2svcparts{$cust_svc->svcpart}};
4474 warn "alternate(s) found\n" if $DEBUG;
4475 my $change_svcpart = $alternate[0];
4476 $target{$change_svcpart}--;
4477 my $new = new FS::cust_svc { $cust_svc->hash };
4478 $new->svcpart($change_svcpart);
4479 $new->pkgnum($dest_pkgnum);
4480 $error = $new->replace($cust_svc);
4490 my @label = $cust_svc->label;
4491 return "$label[0] $label[1]: $error";
4498 =item grab_svcnums SVCNUM, SVCNUM ...
4500 Change the pkgnum for the provided services to this packages. If there is an
4501 error, returns the error, otherwise returns false.
4509 my $oldAutoCommit = $FS::UID::AutoCommit;
4510 local $FS::UID::AutoCommit = 0;
4513 foreach my $svcnum (@svcnum) {
4514 my $cust_svc = qsearchs('cust_svc', { svcnum=>$svcnum } ) or do {
4515 $dbh->rollback if $oldAutoCommit;
4516 return "unknown svcnum $svcnum";
4518 $cust_svc->pkgnum( $self->pkgnum );
4519 my $error = $cust_svc->replace;
4521 $dbh->rollback if $oldAutoCommit;
4526 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4533 This method is deprecated. See the I<depend_jobnum> option to the insert and
4534 order_pkgs methods in FS::cust_main for a better way to defer provisioning.
4538 #looks like this is still used by the order_pkg and change_pkg methods in
4539 # ClientAPI/MyAccount, need to look into those before removing
4543 my $oldAutoCommit = $FS::UID::AutoCommit;
4544 local $FS::UID::AutoCommit = 0;
4547 foreach my $cust_svc ( $self->cust_svc ) {
4548 #false laziness w/svc_Common::insert
4549 my $svc_x = $cust_svc->svc_x;
4550 foreach my $part_export ( $cust_svc->part_svc->part_export ) {
4551 my $error = $part_export->export_insert($svc_x);
4553 $dbh->rollback if $oldAutoCommit;
4559 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4564 =item export_pkg_change OLD_CUST_PKG
4566 Calls the "pkg_change" export action for all services attached to this package.
4570 sub export_pkg_change {
4571 my( $self, $old ) = ( shift, shift );
4573 my $oldAutoCommit = $FS::UID::AutoCommit;
4574 local $FS::UID::AutoCommit = 0;
4577 foreach my $svc_x ( map $_->svc_x, $self->cust_svc ) {
4578 my $error = $svc_x->export('pkg_change', $self, $old);
4580 $dbh->rollback if $oldAutoCommit;
4585 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4592 Associates this package with a (suspension or cancellation) reason (see
4593 L<FS::cust_pkg_reason>, possibly inserting a new reason on the fly (see
4596 Available options are:
4602 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.
4606 the access_user (see L<FS::access_user>) providing the reason
4614 the action (cancel, susp, adjourn, expire) associated with the reason
4618 If there is an error, returns the error, otherwise returns false.
4623 my ($self, %options) = @_;
4625 my $otaker = $options{reason_otaker} ||
4626 $FS::CurrentUser::CurrentUser->username;
4629 if ( $options{'reason'} =~ /^(\d+)$/ ) {
4633 } elsif ( ref($options{'reason'}) ) {
4635 return 'Enter a new reason (or select an existing one)'
4636 unless $options{'reason'}->{'reason'} !~ /^\s*$/;
4638 my $reason = new FS::reason({
4639 'reason_type' => $options{'reason'}->{'typenum'},
4640 'reason' => $options{'reason'}->{'reason'},
4642 my $error = $reason->insert;
4643 return $error if $error;
4645 $reasonnum = $reason->reasonnum;
4648 return "Unparseable reason: ". $options{'reason'};
4651 my $cust_pkg_reason =
4652 new FS::cust_pkg_reason({ 'pkgnum' => $self->pkgnum,
4653 'reasonnum' => $reasonnum,
4654 'otaker' => $otaker,
4655 'action' => substr(uc($options{'action'}),0,1),
4656 'date' => $options{'date'}
4661 $cust_pkg_reason->insert;
4664 =item insert_discount
4666 Associates this package with a discount (see L<FS::cust_pkg_discount>, possibly
4667 inserting a new discount on the fly (see L<FS::discount>).
4669 This will look at the cust_pkg for a pseudo-field named "setup_discountnum",
4670 and if present, will create a setup discount. If the discountnum is -1,
4671 a new discount definition will be inserted using the value in
4672 "setup_discountnum_amount" or "setup_discountnum_percent". Likewise for recur.
4674 If there is an error, returns the error, otherwise returns false.
4678 sub insert_discount {
4679 #my ($self, %options) = @_;
4682 foreach my $x (qw(setup recur)) {
4683 if ( my $discountnum = $self->get("${x}_discountnum") ) {
4684 my $cust_pkg_discount = FS::cust_pkg_discount->new( {
4685 'pkgnum' => $self->pkgnum,
4686 'discountnum' => $discountnum,
4689 'end_date' => '', #XXX
4690 #for the create a new discount case
4691 'amount' => $self->get("${x}_discountnum_amount"),
4692 'percent' => $self->get("${x}_discountnum_percent"),
4693 'months' => $self->get("${x}_discountnum_months"),
4695 if ( $x eq 'setup' ) {
4696 $cust_pkg_discount->setup('Y');
4697 $cust_pkg_discount->months('');
4699 my $error = $cust_pkg_discount->insert;
4700 return $error if $error;
4707 =item set_usage USAGE_VALUE_HASHREF
4709 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
4710 to which they should be set (see L<FS::svc_acct>). Currently seconds,
4711 upbytes, downbytes, and totalbytes are appropriate keys.
4713 All svc_accts which are part of this package have their values reset.
4718 my ($self, $valueref, %opt) = @_;
4720 #only svc_acct can set_usage for now
4721 foreach my $cust_svc ( $self->cust_svc( 'svcdb'=>'svc_acct' ) ) {
4722 my $svc_x = $cust_svc->svc_x;
4723 $svc_x->set_usage($valueref, %opt)
4724 if $svc_x->can("set_usage");
4728 =item recharge USAGE_VALUE_HASHREF
4730 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
4731 to which they should be set (see L<FS::svc_acct>). Currently seconds,
4732 upbytes, downbytes, and totalbytes are appropriate keys.
4734 All svc_accts which are part of this package have their values incremented.
4739 my ($self, $valueref) = @_;
4741 #only svc_acct can set_usage for now
4742 foreach my $cust_svc ( $self->cust_svc( 'svcdb'=>'svc_acct' ) ) {
4743 my $svc_x = $cust_svc->svc_x;
4744 $svc_x->recharge($valueref)
4745 if $svc_x->can("recharge");
4749 =item apply_usageprice
4753 sub apply_usageprice {
4756 my $oldAutoCommit = $FS::UID::AutoCommit;
4757 local $FS::UID::AutoCommit = 0;
4762 foreach my $cust_pkg_usageprice ( $self->cust_pkg_usageprice ) {
4763 $error ||= $cust_pkg_usageprice->apply;
4767 $dbh->rollback if $oldAutoCommit;
4768 die "error applying part_pkg_usageprice add-ons, pkgnum ". $self->pkgnum.
4771 $dbh->commit if $oldAutoCommit;
4777 =item cust_pkg_discount
4779 =item cust_pkg_discount_active
4783 sub cust_pkg_discount_active {
4785 grep { $_->status eq 'active' } $self->cust_pkg_discount;
4788 =item cust_pkg_usage
4790 Returns a list of all voice usage counters attached to this package.
4792 =item apply_usage OPTIONS
4794 Takes the following options:
4795 - cdr: a call detail record (L<FS::cdr>)
4796 - rate_detail: the rate determined for this call (L<FS::rate_detail>)
4797 - minutes: the maximum number of minutes to be charged
4799 Finds available usage minutes for a call of this class, and subtracts
4800 up to that many minutes from the usage pool. If the usage pool is empty,
4801 and the C<cdr-minutes_priority> global config option is set, minutes may
4802 be taken from other calls as well. Either way, an allocation record will
4803 be created (L<FS::cdr_cust_pkg_usage>) and this method will return the
4804 number of minutes of usage applied to the call.
4809 my ($self, %opt) = @_;
4810 my $cdr = $opt{cdr};
4811 my $rate_detail = $opt{rate_detail};
4812 my $minutes = $opt{minutes};
4813 my $classnum = $rate_detail->classnum;
4814 my $pkgnum = $self->pkgnum;
4815 my $custnum = $self->custnum;
4817 my $oldAutoCommit = $FS::UID::AutoCommit;
4818 local $FS::UID::AutoCommit = 0;
4821 my $order = FS::Conf->new->config('cdr-minutes_priority');
4825 $is_classnum = ' part_pkg_usage_class.classnum = '.$classnum;
4827 $is_classnum = ' part_pkg_usage_class.classnum IS NULL';
4829 my @usage_recs = qsearch({
4830 'table' => 'cust_pkg_usage',
4831 'addl_from' => ' JOIN part_pkg_usage USING (pkgusagepart)'.
4832 ' JOIN cust_pkg USING (pkgnum)'.
4833 ' JOIN part_pkg_usage_class USING (pkgusagepart)',
4834 'select' => 'cust_pkg_usage.*',
4835 'extra_sql' => " WHERE ( cust_pkg.pkgnum = $pkgnum OR ".
4836 " ( cust_pkg.custnum = $custnum AND ".
4837 " part_pkg_usage.shared IS NOT NULL ) ) AND ".
4838 $is_classnum . ' AND '.
4839 " cust_pkg_usage.minutes > 0",
4840 'order_by' => " ORDER BY priority ASC",
4843 my $orig_minutes = $minutes;
4845 while (!$error and $minutes > 0 and @usage_recs) {
4846 my $cust_pkg_usage = shift @usage_recs;
4847 $cust_pkg_usage->select_for_update;
4848 my $cdr_cust_pkg_usage = FS::cdr_cust_pkg_usage->new({
4849 pkgusagenum => $cust_pkg_usage->pkgusagenum,
4850 acctid => $cdr->acctid,
4851 minutes => min($cust_pkg_usage->minutes, $minutes),
4853 $cust_pkg_usage->set('minutes',
4854 $cust_pkg_usage->minutes - $cdr_cust_pkg_usage->minutes
4856 $error = $cust_pkg_usage->replace || $cdr_cust_pkg_usage->insert;
4857 $minutes -= $cdr_cust_pkg_usage->minutes;
4859 if ( $order and $minutes > 0 and !$error ) {
4860 # then try to steal minutes from another call
4862 'table' => 'cdr_cust_pkg_usage',
4863 'addl_from' => ' JOIN cust_pkg_usage USING (pkgusagenum)'.
4864 ' JOIN part_pkg_usage USING (pkgusagepart)'.
4865 ' JOIN cust_pkg USING (pkgnum)'.
4866 ' JOIN part_pkg_usage_class USING (pkgusagepart)'.
4867 ' JOIN cdr USING (acctid)',
4868 'select' => 'cdr_cust_pkg_usage.*',
4869 'extra_sql' => " WHERE cdr.freesidestatus = 'rated' AND ".
4870 " ( cust_pkg.pkgnum = $pkgnum OR ".
4871 " ( cust_pkg.custnum = $custnum AND ".
4872 " part_pkg_usage.shared IS NOT NULL ) ) AND ".
4873 " part_pkg_usage_class.classnum = $classnum",
4874 'order_by' => ' ORDER BY part_pkg_usage.priority ASC',
4876 if ( $order eq 'time' ) {
4877 # find CDRs that are using minutes, but have a later startdate
4879 my $startdate = $cdr->startdate;
4880 if ($startdate !~ /^\d+$/) {
4881 die "bad cdr startdate '$startdate'";
4883 $search{'extra_sql'} .= " AND cdr.startdate > $startdate";
4884 # minimize needless reshuffling
4885 $search{'order_by'} .= ', cdr.startdate DESC';
4887 # XXX may not work correctly with rate_time schedules. Could
4888 # fix this by storing ratedetailnum in cdr_cust_pkg_usage, I
4890 $search{'addl_from'} .=
4891 ' JOIN rate_detail'.
4892 ' ON (cdr.rated_ratedetailnum = rate_detail.ratedetailnum)';
4893 if ( $order eq 'rate_high' ) {
4894 $search{'extra_sql'} .= ' AND rate_detail.min_charge < '.
4895 $rate_detail->min_charge;
4896 $search{'order_by'} .= ', rate_detail.min_charge ASC';
4897 } elsif ( $order eq 'rate_low' ) {
4898 $search{'extra_sql'} .= ' AND rate_detail.min_charge > '.
4899 $rate_detail->min_charge;
4900 $search{'order_by'} .= ', rate_detail.min_charge DESC';
4902 # this should really never happen
4903 die "invalid cdr-minutes_priority value '$order'\n";
4906 my @cdr_usage_recs = qsearch(\%search);
4908 while (!$error and @cdr_usage_recs and $minutes > 0) {
4909 my $cdr_cust_pkg_usage = shift @cdr_usage_recs;
4910 my $cust_pkg_usage = $cdr_cust_pkg_usage->cust_pkg_usage;
4911 my $old_cdr = $cdr_cust_pkg_usage->cdr;
4912 $reproc_cdrs{$old_cdr->acctid} = $old_cdr;
4913 $cdr_cust_pkg_usage->select_for_update;
4914 $old_cdr->select_for_update;
4915 $cust_pkg_usage->select_for_update;
4916 # in case someone else stole the usage from this CDR
4917 # while waiting for the lock...
4918 next if $old_cdr->acctid != $cdr_cust_pkg_usage->acctid;
4919 # steal the usage allocation and flag the old CDR for reprocessing
4920 $cdr_cust_pkg_usage->set('acctid', $cdr->acctid);
4921 # if the allocation is more minutes than we need, adjust it...
4922 my $delta = $cdr_cust_pkg_usage->minutes - $minutes;
4924 $cdr_cust_pkg_usage->set('minutes', $minutes);
4925 $cust_pkg_usage->set('minutes', $cust_pkg_usage->minutes + $delta);
4926 $error = $cust_pkg_usage->replace;
4928 #warn 'CDR '.$cdr->acctid . ' stealing allocation '.$cdr_cust_pkg_usage->cdrusagenum.' from CDR '.$old_cdr->acctid."\n";
4929 $error ||= $cdr_cust_pkg_usage->replace;
4930 # deduct the stolen minutes
4931 $minutes -= $cdr_cust_pkg_usage->minutes;
4933 # after all minute-stealing is done, reset the affected CDRs
4934 foreach (values %reproc_cdrs) {
4935 $error ||= $_->set_status('');
4936 # XXX or should we just call $cdr->rate right here?
4937 # it's not like we can create a loop this way, since the min_charge
4938 # or call time has to go monotonically in one direction.
4939 # we COULD get some very deep recursions going, though...
4941 } # if $order and $minutes
4944 die "error applying included minutes\npkgnum ".$self->pkgnum.", class $classnum, acctid ".$cdr->acctid."\n$error\n"
4946 $dbh->commit if $oldAutoCommit;
4947 return $orig_minutes - $minutes;
4951 =item supplemental_pkgs
4953 Returns a list of all packages supplemental to this one.
4957 sub supplemental_pkgs {
4959 qsearch('cust_pkg', { 'main_pkgnum' => $self->pkgnum });
4964 Returns the package that this one is supplemental to, if any.
4970 if ( $self->main_pkgnum ) {
4971 return FS::cust_pkg->by_key($self->main_pkgnum);
4978 =head1 CLASS METHODS
4984 Returns an SQL expression identifying recurring packages.
4988 sub recurring_sql { "
4989 '0' != ( select freq from part_pkg
4990 where cust_pkg.pkgpart = part_pkg.pkgpart )
4995 Returns an SQL expression identifying one-time packages.
5000 '0' = ( select freq from part_pkg
5001 where cust_pkg.pkgpart = part_pkg.pkgpart )
5006 Returns an SQL expression identifying ordered packages (recurring packages not
5012 $_[0]->recurring_sql. " AND ". $_[0]->not_yet_billed_sql;
5017 Returns an SQL expression identifying active packages.
5022 $_[0]->recurring_sql. "
5023 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
5024 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
5025 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
5028 =item not_yet_billed_sql
5030 Returns an SQL expression identifying packages which have not yet been billed.
5034 sub not_yet_billed_sql { "
5035 ( cust_pkg.setup IS NULL OR cust_pkg.setup = 0 )
5036 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
5037 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
5042 Returns an SQL expression identifying inactive packages (one-time packages
5043 that are otherwise unsuspended/uncancelled).
5047 sub inactive_sql { "
5048 ". $_[0]->onetime_sql(). "
5049 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
5050 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
5051 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
5056 Returns an SQL expression identifying on-hold packages.
5061 #$_[0]->recurring_sql(). ' AND '.
5063 ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
5064 AND cust_pkg.susp IS NOT NULL AND cust_pkg.susp != 0
5065 AND ( cust_pkg.setup IS NULL OR cust_pkg.setup = 0 )
5072 Returns an SQL expression identifying suspended packages.
5076 sub suspended_sql { susp_sql(@_); }
5078 #$_[0]->recurring_sql(). ' AND '.
5080 ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
5081 AND cust_pkg.susp IS NOT NULL AND cust_pkg.susp != 0
5082 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
5089 Returns an SQL exprression identifying cancelled packages.
5093 sub cancelled_sql { cancel_sql(@_); }
5095 #$_[0]->recurring_sql(). ' AND '.
5096 "cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0";
5099 =item ncancelled_recurring_sql
5101 Returns an SQL expression identifying un-cancelled, recurring packages.
5105 sub ncancelled_recurring_sql {
5106 $_[0]->recurring_sql().
5107 " AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 ) ";
5112 Returns an SQL expression to give the package status as a string.
5118 WHEN cust_pkg.cancel IS NOT NULL THEN 'cancelled'
5119 WHEN ( cust_pkg.susp IS NOT NULL AND cust_pkg.setup IS NULL ) THEN 'on hold'
5120 WHEN cust_pkg.susp IS NOT NULL THEN 'suspended'
5121 WHEN cust_pkg.setup IS NULL THEN 'not yet billed'
5122 WHEN ".onetime_sql()." THEN 'one-time charge'
5129 Returns a list of two package counts. The first is a count of packages
5130 based on the supplied criteria and the second is the count of residential
5131 packages with those same criteria. Criteria are specified as in the search
5137 my ($class, $params) = @_;
5139 my $sql_query = $class->search( $params );
5141 my $count_sql = delete($sql_query->{'count_query'});
5142 $count_sql =~ s/ FROM/,count(CASE WHEN cust_main.company IS NULL OR cust_main.company = '' THEN 1 END) FROM/
5143 or die "couldn't parse count_sql";
5145 my $count_sth = dbh->prepare($count_sql)
5146 or die "Error preparing $count_sql: ". dbh->errstr;
5148 or die "Error executing $count_sql: ". $count_sth->errstr;
5149 my $count_arrayref = $count_sth->fetchrow_arrayref;
5151 return ( @$count_arrayref );
5155 =item tax_locationnum_sql
5157 Returns an SQL expression for the tax location for a package, based
5158 on the settings of 'tax-pkg_address' and 'tax-ship_address'.
5162 sub tax_locationnum_sql {
5163 my $conf = FS::Conf->new;
5164 if ( $conf->exists('tax-pkg_address') ) {
5165 'cust_pkg.locationnum';
5167 elsif ( $conf->exists('tax-ship_address') ) {
5168 'cust_main.ship_locationnum';
5171 'cust_main.bill_locationnum';
5177 Returns a list: the first item is an SQL fragment identifying matching
5178 packages/customers via location (taking into account shipping and package
5179 address taxation, if enabled), and subsequent items are the parameters to
5180 substitute for the placeholders in that fragment.
5185 my($class, %opt) = @_;
5186 my $ornull = $opt{'ornull'};
5188 my $conf = new FS::Conf;
5190 # '?' placeholders in _location_sql_where
5191 my $x = $ornull ? 3 : 2;
5202 if ( $conf->exists('tax-ship_address') ) {
5205 ( ( ship_last IS NULL OR ship_last = '' )
5206 AND ". _location_sql_where('cust_main', '', $ornull ). "
5208 OR ( ship_last IS NOT NULL AND ship_last != ''
5209 AND ". _location_sql_where('cust_main', 'ship_', $ornull ). "
5212 # AND payby != 'COMP'
5214 @main_param = ( @bill_param, @bill_param );
5218 $main_where = _location_sql_where('cust_main'); # AND payby != 'COMP'
5219 @main_param = @bill_param;
5225 if ( $conf->exists('tax-pkg_address') ) {
5227 my $loc_where = _location_sql_where( 'cust_location', '', $ornull );
5230 ( cust_pkg.locationnum IS NULL AND $main_where )
5231 OR ( cust_pkg.locationnum IS NOT NULL AND $loc_where )
5234 @param = ( @main_param, @bill_param );
5238 $where = $main_where;
5239 @param = @main_param;
5247 #subroutine, helper for location_sql
5248 sub _location_sql_where {
5250 my $prefix = @_ ? shift : '';
5251 my $ornull = @_ ? shift : '';
5253 # $ornull = $ornull ? " OR ( ? IS NULL AND $table.${prefix}county IS NULL ) " : '';
5255 $ornull = $ornull ? ' OR ? IS NULL ' : '';
5257 my $or_empty_city = " OR ( ? = '' AND $table.${prefix}city IS NULL )";
5258 my $or_empty_county = " OR ( ? = '' AND $table.${prefix}county IS NULL )";
5259 my $or_empty_state = " OR ( ? = '' AND $table.${prefix}state IS NULL )";
5261 my $text = (driver_name =~ /^mysql/i) ? 'char' : 'text';
5263 # ( $table.${prefix}city = ? $or_empty_city $ornull )
5265 ( $table.district = ? OR ? = '' OR CAST(? AS $text) IS NULL )
5266 AND ( $table.${prefix}city = ? OR ? = '' OR CAST(? AS $text) IS NULL )
5267 AND ( $table.${prefix}county = ? $or_empty_county $ornull )
5268 AND ( $table.${prefix}state = ? $or_empty_state $ornull )
5269 AND $table.${prefix}country = ?
5274 my( $self, $what ) = @_;
5276 my $what_show_zero = $what. '_show_zero';
5277 length($self->$what_show_zero())
5278 ? ($self->$what_show_zero() eq 'Y')
5279 : $self->part_pkg->$what_show_zero();
5286 =item order CUSTNUM, PKGPARTS_ARYREF, [ REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF [ REFNUM ] ] ]
5288 Bulk cancel + order subroutine. Perhaps slightly deprecated, only used by the
5289 bulk cancel+order in the web UI and nowhere else (edit/process/cust_pkg.cgi)
5291 CUSTNUM is a customer (see L<FS::cust_main>)
5293 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
5294 L<FS::part_pkg>) to order for this customer. Duplicates are of course
5297 REMOVE_PKGNUMS is an optional list of pkgnums specifying the billing items to
5298 remove for this customer. The services (see L<FS::cust_svc>) are moved to the
5299 new billing items. An error is returned if this is not possible (see
5300 L<FS::pkg_svc>). An empty arrayref is equivalent to not specifying this
5303 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
5304 newly-created cust_pkg objects.
5306 REFNUM, if specified, will specify the FS::pkg_referral record to be created
5307 and inserted. Multiple FS::pkg_referral records can be created by
5308 setting I<refnum> to an array reference of refnums or a hash reference with
5309 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
5310 record will be created corresponding to cust_main.refnum.
5315 my ($custnum, $pkgparts, $remove_pkgnum, $return_cust_pkg, $refnum) = @_;
5317 my $conf = new FS::Conf;
5319 # Transactionize this whole mess
5320 my $oldAutoCommit = $FS::UID::AutoCommit;
5321 local $FS::UID::AutoCommit = 0;
5325 # my $cust_main = qsearchs('cust_main', { custnum => $custnum });
5326 # return "Customer not found: $custnum" unless $cust_main;
5328 warn "$me order: pkgnums to remove: ". join(',', @$remove_pkgnum). "\n"
5331 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
5334 my $change = scalar(@old_cust_pkg) != 0;
5337 if ( scalar(@old_cust_pkg) == 1 && scalar(@$pkgparts) == 1 ) {
5339 warn "$me order: changing pkgnum ". $old_cust_pkg[0]->pkgnum.
5340 " to pkgpart ". $pkgparts->[0]. "\n"
5343 my $err_or_cust_pkg =
5344 $old_cust_pkg[0]->change( 'pkgpart' => $pkgparts->[0],
5345 'refnum' => $refnum,
5348 unless (ref($err_or_cust_pkg)) {
5349 $dbh->rollback if $oldAutoCommit;
5350 return $err_or_cust_pkg;
5353 push @$return_cust_pkg, $err_or_cust_pkg;
5354 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5359 # Create the new packages.
5360 foreach my $pkgpart (@$pkgparts) {
5362 warn "$me order: inserting pkgpart $pkgpart\n" if $DEBUG;
5364 my $cust_pkg = new FS::cust_pkg { custnum => $custnum,
5365 pkgpart => $pkgpart,
5369 $error = $cust_pkg->insert( 'change' => $change );
5370 push @$return_cust_pkg, $cust_pkg;
5372 foreach my $link ($cust_pkg->part_pkg->supp_part_pkg_link) {
5373 my $supp_pkg = FS::cust_pkg->new({
5374 custnum => $custnum,
5375 pkgpart => $link->dst_pkgpart,
5377 main_pkgnum => $cust_pkg->pkgnum,
5380 $error ||= $supp_pkg->insert( 'change' => $change );
5381 push @$return_cust_pkg, $supp_pkg;
5385 $dbh->rollback if $oldAutoCommit;
5390 # $return_cust_pkg now contains refs to all of the newly
5393 # Transfer services and cancel old packages.
5394 foreach my $old_pkg (@old_cust_pkg) {
5396 warn "$me order: transferring services from pkgnum ". $old_pkg->pkgnum. "\n"
5399 foreach my $new_pkg (@$return_cust_pkg) {
5400 $error = $old_pkg->transfer($new_pkg);
5401 if ($error and $error == 0) {
5402 # $old_pkg->transfer failed.
5403 $dbh->rollback if $oldAutoCommit;
5408 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
5409 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
5410 foreach my $new_pkg (@$return_cust_pkg) {
5411 $error = $old_pkg->transfer($new_pkg, 'change_svcpart'=>1 );
5412 if ($error and $error == 0) {
5413 # $old_pkg->transfer failed.
5414 $dbh->rollback if $oldAutoCommit;
5421 # Transfers were successful, but we went through all of the
5422 # new packages and still had services left on the old package.
5423 # We can't cancel the package under the circumstances, so abort.
5424 $dbh->rollback if $oldAutoCommit;
5425 return "Unable to transfer all services from package ".$old_pkg->pkgnum;
5427 $error = $old_pkg->cancel( quiet=>1, 'no_delay_cancel'=>1 );
5433 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5437 =item bulk_change PKGPARTS_ARYREF, REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF ]
5439 A bulk change method to change packages for multiple customers.
5441 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
5442 L<FS::part_pkg>) to order for each customer. Duplicates are of course
5445 REMOVE_PKGNUMS is an list of pkgnums specifying the billing items to
5446 replace. The services (see L<FS::cust_svc>) are moved to the
5447 new billing items. An error is returned if this is not possible (see
5450 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
5451 newly-created cust_pkg objects.
5456 my ($pkgparts, $remove_pkgnum, $return_cust_pkg) = @_;
5458 # Transactionize this whole mess
5459 my $oldAutoCommit = $FS::UID::AutoCommit;
5460 local $FS::UID::AutoCommit = 0;
5464 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
5467 while(scalar(@old_cust_pkg)) {
5469 my $custnum = $old_cust_pkg[0]->custnum;
5470 my (@remove) = map { $_->pkgnum }
5471 grep { $_->custnum == $custnum } @old_cust_pkg;
5472 @old_cust_pkg = grep { $_->custnum != $custnum } @old_cust_pkg;
5474 my $error = order $custnum, $pkgparts, \@remove, \@return;
5476 push @errors, $error
5478 push @$return_cust_pkg, @return;
5481 if (scalar(@errors)) {
5482 $dbh->rollback if $oldAutoCommit;
5483 return join(' / ', @errors);
5486 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5490 =item forward_emails
5492 Returns a hash of svcnums and corresponding email addresses
5493 for svc_acct services that can be used as source or dest
5494 for svc_forward services provisioned in this package.
5496 Accepts options I<svc_forward> OR I<svcnum> for a svc_forward
5497 service; if included, will ensure the current values of the
5498 specified service are included in the list, even if for some
5499 other reason they wouldn't be. If called as a class method
5500 with a specified service, returns only these current values.
5502 Caution: does not actually check if svc_forward services are
5503 available to be provisioned on this package.
5507 sub forward_emails {
5511 #load optional service, thoroughly validated
5512 die "Use svcnum or svc_forward, not both"
5513 if $opt{'svcnum'} && $opt{'svc_forward'};
5514 my $svc_forward = $opt{'svc_forward'};
5515 $svc_forward ||= qsearchs('svc_forward',{ 'svcnum' => $opt{'svcnum'} })
5517 die "Specified service is not a forward service"
5518 if $svc_forward && (ref($svc_forward) ne 'FS::svc_forward');
5519 die "Specified service not found"
5520 if ($opt{'svcnum'} || $opt{'svc_forward'}) && !$svc_forward;
5524 ## everything below was basically copied from httemplate/edit/svc_forward.cgi
5525 ## with minimal refactoring, not sure why we can't just load all svc_accts for this custnum
5527 #add current values from specified service, if there was one
5529 foreach my $method (qw( srcsvc_acct dstsvc_acct )) {
5530 my $svc_acct = $svc_forward->$method();
5531 $email{$svc_acct->svcnum} = $svc_acct->email if $svc_acct;
5535 if (ref($self) eq 'FS::cust_pkg') {
5537 #and including the rest for this customer
5538 my($u_part_svc,@u_acct_svcparts);
5539 foreach $u_part_svc ( qsearch('part_svc',{'svcdb'=>'svc_acct'}) ) {
5540 push @u_acct_svcparts,$u_part_svc->getfield('svcpart');
5543 my $custnum = $self->getfield('custnum');
5544 foreach my $i_cust_pkg ( qsearch('cust_pkg',{'custnum'=>$custnum}) ) {
5545 my $cust_pkgnum = $i_cust_pkg->getfield('pkgnum');
5546 #now find the corresponding record(s) in cust_svc (for this pkgnum!)
5547 foreach my $acct_svcpart (@u_acct_svcparts) {
5548 foreach my $i_cust_svc (
5549 qsearch( 'cust_svc', { 'pkgnum' => $cust_pkgnum,
5550 'svcpart' => $acct_svcpart } )
5552 my $svc_acct = qsearchs( 'svc_acct', { 'svcnum' => $i_cust_svc->svcnum } );
5553 $email{$svc_acct->svcnum} = $svc_acct->email;
5562 # Used by FS::Upgrade to migrate to a new database.
5563 sub _upgrade_schema { # class method
5564 my ($class, %opts) = @_;
5567 UPDATE cust_pkg SET change_to_pkgnum = NULL
5568 WHERE change_to_pkgnum IS NOT NULL
5569 AND NOT EXISTS ( SELECT 1 FROM cust_pkg AS ctcp
5570 WHERE ctcp.pkgnum = cust_pkg.change_to_pkgnum
5574 my $sth = dbh->prepare($sql) or die dbh->errstr;
5575 $sth->execute or die $sth->errstr;
5579 # Used by FS::Upgrade to migrate to a new database.
5580 sub _upgrade_data { # class method
5581 my ($class, %opts) = @_;
5582 $class->_upgrade_otaker(%opts);
5584 # RT#10139, bug resulting in contract_end being set when it shouldn't
5585 'UPDATE cust_pkg SET contract_end = NULL WHERE contract_end = -1',
5586 # RT#10830, bad calculation of prorate date near end of year
5587 # the date range for bill is December 2009, and we move it forward
5588 # one year if it's before the previous bill date (which it should
5590 'UPDATE cust_pkg SET bill = bill + (365*24*60*60) WHERE bill < last_bill
5591 AND bill > 1259654400 AND bill < 1262332800 AND (SELECT plan FROM part_pkg
5592 WHERE part_pkg.pkgpart = cust_pkg.pkgpart) = \'prorate\'',
5593 # RT6628, add order_date to cust_pkg
5594 'update cust_pkg set order_date = (select history_date from h_cust_pkg
5595 where h_cust_pkg.pkgnum = cust_pkg.pkgnum and
5596 history_action = \'insert\') where order_date is null',
5598 foreach my $sql (@statements) {
5599 my $sth = dbh->prepare($sql);
5600 $sth->execute or die $sth->errstr;
5603 # RT31194: supplemental package links that are deleted don't clean up
5605 my @pkglinknums = qsearch({
5606 'select' => 'DISTINCT cust_pkg.pkglinknum',
5607 'table' => 'cust_pkg',
5608 'addl_from' => ' LEFT JOIN part_pkg_link USING (pkglinknum) ',
5609 'extra_sql' => ' WHERE cust_pkg.pkglinknum IS NOT NULL
5610 AND part_pkg_link.pkglinknum IS NULL',
5612 foreach (@pkglinknums) {
5613 my $pkglinknum = $_->pkglinknum;
5614 warn "cleaning part_pkg_link #$pkglinknum\n";
5615 my $part_pkg_link = FS::part_pkg_link->new({pkglinknum => $pkglinknum});
5616 my $error = $part_pkg_link->remove_linked;
5617 die $error if $error;
5620 # RT#73607: canceling a package with billing addons sometimes changes its
5622 # Find records where the last replace_new record for the package before it
5623 # was canceled has a different pkgpart from the package itself.
5624 my @cust_pkg = qsearch({
5625 'table' => 'cust_pkg',
5626 'select' => 'cust_pkg.*, h_cust_pkg.pkgpart AS h_pkgpart',
5627 'addl_from' => ' JOIN (
5628 SELECT pkgnum, MAX(historynum) AS historynum FROM h_cust_pkg
5629 WHERE cancel IS NULL
5630 AND history_action = \'replace_new\'
5632 ) AS last_history USING (pkgnum)
5633 JOIN h_cust_pkg USING (historynum)',
5634 'extra_sql' => ' WHERE cust_pkg.cancel is not null
5635 AND cust_pkg.pkgpart != h_cust_pkg.pkgpart'
5637 foreach my $cust_pkg ( @cust_pkg ) {
5638 my $pkgnum = $cust_pkg->pkgnum;
5639 warn "fixing pkgpart on canceled pkg#$pkgnum\n";
5640 $cust_pkg->set('pkgpart', $cust_pkg->h_pkgpart);
5641 my $error = $cust_pkg->replace;
5642 die $error if $error;
5651 sub order is not OO. Perhaps it should be moved to FS::cust_main and made so?
5653 In sub order, the @pkgparts array (passed by reference) is clobbered.
5655 Also in sub order, no money is adjusted. Once FS::part_pkg defines a standard
5656 method to pass dates to the recur_prog expression, it should do so.
5658 FS::svc_acct, FS::svc_domain, FS::svc_www, FS::svc_ip and FS::svc_forward are
5659 loaded via 'use' at compile time, rather than via 'require' in sub { setup,
5660 suspend, unsuspend, cancel } because they use %FS::UID::callback to load
5661 configuration values. Probably need a subroutine which decides what to do
5662 based on whether or not we've fetched the user yet, rather than a hash. See
5663 FS::UID and the TODO.
5665 Now that things are transactional should the check in the insert method be
5670 L<FS::Record>, L<FS::cust_main>, L<FS::part_pkg>, L<FS::cust_svc>,
5671 L<FS::pkg_svc>, schema.html from the base documentation