2 use base qw( FS::cust_pkg::Search FS::cust_pkg::API
3 FS::otaker_Mixin FS::cust_main_Mixin FS::Sales_Mixin
4 FS::contact_Mixin FS::location_Mixin
5 FS::m2m_Common FS::option_Common
10 use Scalar::Util qw( blessed );
11 use List::Util qw(min max);
13 use Time::Local qw( timelocal timelocal_nocheck );
15 use FS::UID qw( dbh driver_name );
16 use FS::Misc qw( send_email );
17 use FS::Record qw( qsearch qsearchs fields );
23 use FS::cust_location;
25 use FS::cust_bill_pkg;
26 use FS::cust_pkg_detail;
27 use FS::cust_pkg_usage;
28 use FS::cdr_cust_pkg_usage;
33 use FS::cust_pkg_reason;
35 use FS::cust_pkg_usageprice;
36 use FS::cust_pkg_discount;
42 # need to 'use' these instead of 'require' in sub { cancel, suspend, unsuspend,
44 # because they load configuration by setting FS::UID::callback (see TODO)
50 # for sending cancel emails in sub cancel
53 our ($disable_agentcheck, $DEBUG, $me, $import) = (0, 0, '[FS::cust_pkg]', 0);
55 our $upgrade = 0; #go away after setup+start dates cleaned up for old customers
59 my ( $hashref, $cache ) = @_;
60 #if ( $hashref->{'pkgpart'} ) {
61 if ( $hashref->{'pkg'} ) {
62 # #@{ $self->{'_pkgnum'} } = ();
63 # my $subcache = $cache->subcache('pkgpart', 'part_pkg');
64 # $self->{'_pkgpart'} = $subcache;
65 # #push @{ $self->{'_pkgnum'} },
66 # FS::part_pkg->new_or_cached($hashref, $subcache);
67 $self->{'_pkgpart'} = FS::part_pkg->new($hashref);
69 if ( exists $hashref->{'svcnum'} ) {
70 #@{ $self->{'_pkgnum'} } = ();
71 my $subcache = $cache->subcache('svcnum', 'cust_svc', $hashref->{pkgnum});
72 $self->{'_svcnum'} = $subcache;
73 #push @{ $self->{'_pkgnum'} },
74 FS::cust_svc->new_or_cached($hashref, $subcache) if $hashref->{svcnum};
80 FS::cust_pkg - Object methods for cust_pkg objects
86 $record = new FS::cust_pkg \%hash;
87 $record = new FS::cust_pkg { 'column' => 'value' };
89 $error = $record->insert;
91 $error = $new_record->replace($old_record);
93 $error = $record->delete;
95 $error = $record->check;
97 $error = $record->cancel;
99 $error = $record->suspend;
101 $error = $record->unsuspend;
103 $part_pkg = $record->part_pkg;
105 @labels = $record->labels;
107 $seconds = $record->seconds_since($timestamp);
109 #bulk cancel+order... perhaps slightly deprecated, only used by the bulk
110 # cancel+order in the web UI and nowhere else (edit/process/cust_pkg.cgi)
111 $error = FS::cust_pkg::order( $custnum, \@pkgparts );
112 $error = FS::cust_pkg::order( $custnum, \@pkgparts, \@remove_pkgnums ] );
116 An FS::cust_pkg object represents a customer billing item. FS::cust_pkg
117 inherits from FS::Record. The following fields are currently supported:
123 Primary key (assigned automatically for new billing items)
127 Customer (see L<FS::cust_main>)
131 Billing item definition (see L<FS::part_pkg>)
135 Optional link to package location (see L<FS::location>)
139 date package was ordered (also remains same on changes)
151 date (next bill date)
179 order taker (see L<FS::access_user>)
183 If this field is set to 1, disables the automatic
184 unsuspension of this package when using the B<unsuspendauto> config option.
188 If not set, defaults to 1
192 Date of change from previous package
202 =item change_locationnum
210 The pkgnum of the package that this package is supplemental to, if any.
214 The package link (L<FS::part_pkg_link>) that defines this supplemental
215 package, if it is one.
217 =item change_to_pkgnum
219 The pkgnum of the package this one will be "changed to" in the future
220 (on its expiration date).
224 Note: setup, last_bill, bill, adjourn, susp, expire, cancel and change_date
225 are specified as UNIX timestamps; see L<perlfunc/"time">. Also see
226 L<Time::Local> and L<Date::Parse> for conversion functions.
234 Create a new billing item. To add the item to the database, see L<"insert">.
238 sub table { 'cust_pkg'; }
239 sub cust_linked { $_[0]->cust_main_custnum || $_[0]->custnum }
240 sub cust_unlinked_msg {
242 "WARNING: can't find cust_main.custnum ". $self->custnum.
243 ' (cust_pkg.pkgnum '. $self->pkgnum. ')';
246 =item set_initial_timers
248 If required by the package definition, sets any automatic expire, adjourn,
249 or contract_end timers to some number of months after the start date
250 (or setup date, if the package has already been setup). If the package has
251 a delayed setup fee after a period of "free days", will also set the
252 start date to the end of that period.
256 sub set_initial_timers {
258 my $part_pkg = $self->part_pkg;
259 foreach my $action ( qw(expire adjourn contract_end) ) {
260 my $months = $part_pkg->option("${action}_months",1);
261 if($months and !$self->get($action)) {
262 my $start = $self->start_date || $self->setup || time;
263 $self->set($action, $part_pkg->add_freq($start, $months) );
267 # if this package has "free days" and delayed setup fee, then
268 # set start date that many days in the future.
269 # (this should have been set in the UI, but enforce it here)
270 if ( $part_pkg->option('free_days',1)
271 && $part_pkg->option('delay_setup',1)
274 $self->start_date( $part_pkg->default_start_date );
279 =item insert [ OPTION => VALUE ... ]
281 Adds this billing item to the database ("Orders" the item). If there is an
282 error, returns the error, otherwise returns false.
284 If the additional field I<promo_code> is defined instead of I<pkgpart>, it
285 will be used to look up the package definition and agent restrictions will be
288 If the additional field I<refnum> is defined, an FS::pkg_referral record will
289 be created and inserted. Multiple FS::pkg_referral records can be created by
290 setting I<refnum> to an array reference of refnums or a hash reference with
291 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
292 record will be created corresponding to cust_main.refnum.
294 If the additional field I<cust_pkg_usageprice> is defined, it will be treated
295 as an arrayref of FS::cust_pkg_usageprice objects, which will be inserted.
296 (Note that this field cannot be set with a usual ->cust_pkg_usageprice method.
297 It can be set as part of the hash when creating the object, or with the B<set>
300 The following options are available:
306 If set true, supresses actions that should only be taken for new package
307 orders. (Currently this includes: intro periods when delay_setup is on,
308 auto-adding a 1st start date, auto-adding expiration/adjourn/contract_end dates)
312 cust_pkg_option records will be created
316 a ticket will be added to this customer with this subject
320 an optional queue name for ticket additions
324 Don't check the legality of the package definition. This should be used
325 when performing a package change that doesn't change the pkgpart (i.e.
333 my( $self, %options ) = @_;
336 $error = $self->check_pkgpart unless $options{'allow_pkgpart'};
337 return $error if $error;
339 my $part_pkg = $self->part_pkg;
341 if ( ! $import && ! $options{'change'} ) {
343 # set order date to now
344 $self->order_date(time) unless ($import && $self->order_date);
346 # if the package def says to start only on the first of the month:
347 if ( $part_pkg->option('start_1st', 1) && !$self->start_date ) {
348 my ($sec,$min,$hour,$mday,$mon,$year) = (localtime(time) )[0,1,2,3,4,5];
349 $mon += 1 unless $mday == 1;
350 until ( $mon < 12 ) { $mon -= 12; $year++; }
351 $self->start_date( timelocal_nocheck(0,0,0,1,$mon,$year) );
354 if ($self->susp eq 'now' or $part_pkg->start_on_hold) {
355 # if the package was ordered on hold:
357 # - don't set the start date (it will be started manually)
358 $self->set('susp', $self->order_date);
359 $self->set('start_date', '');
361 # set expire/adjourn/contract_end timers, and free days, if appropriate
362 $self->set_initial_timers;
364 } # else this is a package change, and shouldn't have "new package" behavior
366 my $oldAutoCommit = $FS::UID::AutoCommit;
367 local $FS::UID::AutoCommit = 0;
370 $error = $self->SUPER::insert($options{options} ? %{$options{options}} : ());
372 $dbh->rollback if $oldAutoCommit;
376 $self->refnum($self->cust_main->refnum) unless $self->refnum;
377 $self->refnum( [ $self->refnum ] ) unless ref($self->refnum);
378 $self->process_m2m( 'link_table' => 'pkg_referral',
379 'target_table' => 'part_referral',
380 'params' => $self->refnum,
383 if ( $self->hashref->{cust_pkg_usageprice} ) {
384 for my $cust_pkg_usageprice ( @{ $self->hashref->{cust_pkg_usageprice} } ) {
385 $cust_pkg_usageprice->pkgnum( $self->pkgnum );
386 my $error = $cust_pkg_usageprice->insert;
388 $dbh->rollback if $oldAutoCommit;
394 if ( $self->discountnum ) {
395 my $error = $self->insert_discount();
397 $dbh->rollback if $oldAutoCommit;
402 my $conf = new FS::Conf;
404 if ( ! $import && $conf->config('ticket_system') && $options{ticket_subject} ) {
406 #this init stuff is still inefficient, but at least its limited to
407 # the small number (any?) folks using ticket emailing on pkg order
410 # use lib ( "/opt/rt3/local/lib", "/opt/rt3/lib" );
417 use FS::TicketSystem;
418 FS::TicketSystem->init();
420 my $q = new RT::Queue($RT::SystemUser);
421 $q->Load($options{ticket_queue}) if $options{ticket_queue};
422 my $t = new RT::Ticket($RT::SystemUser);
423 my $mime = new MIME::Entity;
424 $mime->build( Type => 'text/plain', Data => $options{ticket_subject} );
425 $t->Create( $options{ticket_queue} ? (Queue => $q) : (),
426 Subject => $options{ticket_subject},
429 $t->AddLink( Type => 'MemberOf',
430 Target => 'freeside://freeside/cust_main/'. $self->custnum,
434 if (! $import && $conf->config('welcome_letter') && $self->cust_main->num_pkgs == 1) {
435 my $queue = new FS::queue {
436 'job' => 'FS::cust_main::queueable_print',
438 $error = $queue->insert(
439 'custnum' => $self->custnum,
440 'template' => 'welcome_letter',
444 warn "can't send welcome letter: $error";
449 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
456 This method now works but you probably shouldn't use it.
458 You don't want to delete packages, because there would then be no record
459 the customer ever purchased the package. Instead, see the cancel method and
460 hide cancelled packages.
467 my $oldAutoCommit = $FS::UID::AutoCommit;
468 local $FS::UID::AutoCommit = 0;
471 foreach my $cust_pkg_discount ($self->cust_pkg_discount) {
472 my $error = $cust_pkg_discount->delete;
474 $dbh->rollback if $oldAutoCommit;
478 #cust_bill_pkg_discount?
480 foreach my $cust_pkg_detail ($self->cust_pkg_detail) {
481 my $error = $cust_pkg_detail->delete;
483 $dbh->rollback if $oldAutoCommit;
488 foreach my $cust_pkg_reason (
490 'table' => 'cust_pkg_reason',
491 'hashref' => { 'pkgnum' => $self->pkgnum },
495 my $error = $cust_pkg_reason->delete;
497 $dbh->rollback if $oldAutoCommit;
504 my $error = $self->SUPER::delete(@_);
506 $dbh->rollback if $oldAutoCommit;
510 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
516 =item replace [ OLD_RECORD ] [ HASHREF | OPTION => VALUE ... ]
518 Replaces the OLD_RECORD with this one in the database. If there is an error,
519 returns the error, otherwise returns false.
521 Currently, custnum, setup, bill, adjourn, susp, expire, and cancel may be changed.
523 Changing pkgpart may have disasterous effects. See the order subroutine.
525 setup and bill are normally updated by calling the bill method of a customer
526 object (see L<FS::cust_main>).
528 suspend is normally updated by the suspend and unsuspend methods.
530 cancel is normally updated by the cancel method (and also the order subroutine
533 Available options are:
539 can be set to a cancellation reason (see L<FS:reason>), either a reasonnum of an existing reason, or passing a hashref will create a new reason. The hashref should have the following keys: typenum - Reason type (see L<FS::reason_type>, reason - Text of the new reason.
543 the access_user (see L<FS::access_user>) providing the reason
547 hashref of keys and values - cust_pkg_option records will be created, updated or removed as appopriate
556 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
561 ( ref($_[0]) eq 'HASH' )
565 #return "Can't (yet?) change pkgpart!" if $old->pkgpart != $new->pkgpart;
566 #return "Can't change otaker!" if $old->otaker ne $new->otaker;
569 #return "Can't change setup once it exists!"
570 # if $old->getfield('setup') &&
571 # $old->getfield('setup') != $new->getfield('setup');
573 #some logic for bill, susp, cancel?
575 local($disable_agentcheck) = 1 if $old->pkgpart == $new->pkgpart;
577 my $oldAutoCommit = $FS::UID::AutoCommit;
578 local $FS::UID::AutoCommit = 0;
581 foreach my $method ( qw(adjourn expire) ) { # How many reasons?
582 if ($options->{'reason'} && $new->$method && $old->$method ne $new->$method) {
583 my $error = $new->insert_reason(
584 'reason' => $options->{'reason'},
585 'date' => $new->$method,
587 'reason_otaker' => $options->{'reason_otaker'},
590 dbh->rollback if $oldAutoCommit;
591 return "Error inserting cust_pkg_reason: $error";
596 #save off and freeze RADIUS attributes for any associated svc_acct records
598 if ( $old->part_pkg->is_prepaid || $new->part_pkg->is_prepaid ) {
600 #also check for specific exports?
601 # to avoid spurious modify export events
602 @svc_acct = map { $_->svc_x }
603 grep { $_->part_svc->svcdb eq 'svc_acct' }
606 $_->snapshot foreach @svc_acct;
610 my $error = $new->export_pkg_change($old)
611 || $new->SUPER::replace( $old,
613 ? $options->{options}
617 $dbh->rollback if $oldAutoCommit;
621 #for prepaid packages,
622 #trigger export of new RADIUS Expiration attribute when cust_pkg.bill changes
623 foreach my $old_svc_acct ( @svc_acct ) {
624 my $new_svc_acct = new FS::svc_acct { $old_svc_acct->hash };
626 $new_svc_acct->replace( $old_svc_acct,
627 'depend_jobnum' => $options->{depend_jobnum},
630 $dbh->rollback if $oldAutoCommit;
635 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
642 Checks all fields to make sure this is a valid billing item. If there is an
643 error, returns the error, otherwise returns false. Called by the insert and
651 if ( !$self->locationnum or $self->locationnum == -1 ) {
652 $self->set('locationnum', $self->cust_main->ship_locationnum);
656 $self->ut_numbern('pkgnum')
657 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum')
658 || $self->ut_numbern('pkgpart')
659 || $self->ut_foreign_keyn('contactnum', 'contact', 'contactnum' )
660 || $self->ut_foreign_keyn('locationnum', 'cust_location', 'locationnum')
661 || $self->ut_foreign_keyn('salesnum', 'sales', 'salesnum')
662 || $self->ut_numbern('quantity')
663 || $self->ut_numbern('start_date')
664 || $self->ut_numbern('setup')
665 || $self->ut_numbern('bill')
666 || $self->ut_numbern('susp')
667 || $self->ut_numbern('cancel')
668 || $self->ut_numbern('adjourn')
669 || $self->ut_numbern('resume')
670 || $self->ut_numbern('expire')
671 || $self->ut_numbern('dundate')
672 || $self->ut_flag('no_auto', [ '', 'Y' ])
673 || $self->ut_flag('waive_setup', [ '', 'Y' ])
674 || $self->ut_flag('separate_bill')
675 || $self->ut_textn('agent_pkgid')
676 || $self->ut_enum('recur_show_zero', [ '', 'Y', 'N', ])
677 || $self->ut_enum('setup_show_zero', [ '', 'Y', 'N', ])
678 || $self->ut_foreign_keyn('main_pkgnum', 'cust_pkg', 'pkgnum')
679 || $self->ut_foreign_keyn('pkglinknum', 'part_pkg_link', 'pkglinknum')
680 || $self->ut_foreign_keyn('change_to_pkgnum', 'cust_pkg', 'pkgnum')
682 return $error if $error;
684 return "A package with both start date (future start) and setup date (already started) will never bill"
685 if $self->start_date && $self->setup && ! $upgrade;
687 return "A future unsuspend date can only be set for a package with a suspend date"
688 if $self->resume and !$self->susp and !$self->adjourn;
690 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
692 if ( $self->dbdef_table->column('manual_flag') ) {
693 $self->manual_flag('') if $self->manual_flag eq ' ';
694 $self->manual_flag =~ /^([01]?)$/
695 or return "Illegal manual_flag ". $self->manual_flag;
696 $self->manual_flag($1);
704 Check the pkgpart to make sure it's allowed with the reg_code and/or
705 promo_code of the package (if present) and with the customer's agent.
706 Called from C<insert>, unless we are doing a package change that doesn't
714 # my $error = $self->ut_numbern('pkgpart'); # already done
717 if ( $self->reg_code ) {
719 unless ( grep { $self->pkgpart == $_->pkgpart }
720 map { $_->reg_code_pkg }
721 qsearchs( 'reg_code', { 'code' => $self->reg_code,
722 'agentnum' => $self->cust_main->agentnum })
724 return "Unknown registration code";
727 } elsif ( $self->promo_code ) {
730 qsearchs('part_pkg', {
731 'pkgpart' => $self->pkgpart,
732 'promo_code' => { op=>'ILIKE', value=>$self->promo_code },
734 return 'Unknown promotional code' unless $promo_part_pkg;
738 unless ( $disable_agentcheck ) {
740 qsearchs( 'agent', { 'agentnum' => $self->cust_main->agentnum } );
741 return "agent ". $agent->agentnum. ':'. $agent->agent.
742 " can't purchase pkgpart ". $self->pkgpart
743 unless $agent->pkgpart_hashref->{ $self->pkgpart }
744 || $agent->agentnum == $self->part_pkg->agentnum;
747 $error = $self->ut_foreign_key('pkgpart', 'part_pkg', 'pkgpart' );
748 return $error if $error;
756 =item cancel [ OPTION => VALUE ... ]
758 Cancels and removes all services (see L<FS::cust_svc> and L<FS::part_svc>)
759 in this package, then cancels the package itself (sets the cancel field to
762 Available options are:
766 =item quiet - can be set true to supress email cancellation notices.
768 =item time - can be set to cancel the package based on a specific future or
769 historical date. Using time ensures that the remaining amount is calculated
770 correctly. Note however that this is an immediate cancel and just changes
771 the date. You are PROBABLY looking to expire the account instead of using
774 =item reason - can be set to a cancellation reason (see L<FS:reason>),
775 either a reasonnum of an existing reason, or passing a hashref will create
776 a new reason. The hashref should have the following keys: typenum - Reason
777 type (see L<FS::reason_type>, reason - Text of the new reason.
779 =item date - can be set to a unix style timestamp to specify when to
782 =item nobill - can be set true to skip billing if it might otherwise be done.
784 =item unused_credit - can be set to 1 to credit the remaining time, or 0 to
785 not credit it. This must be set (by change()) when changing the package
786 to a different pkgpart or location, and probably shouldn't be in any other
787 case. If it's not set, the 'unused_credit_cancel' part_pkg option will
790 =item no_delay_cancel - prevents delay_cancel behavior
791 no matter what other options say, for use when changing packages (or any
792 other time you're really sure you want an immediate cancel)
796 If there is an error, returns the error, otherwise returns false.
800 #NOT DOCUMENTING - this should only be used when calling recursively
801 #=item delay_cancel - for internal use, to allow proper handling of
802 #supplemental packages when the main package is flagged to suspend
803 #before cancelling, probably shouldn't be used otherwise (set the
804 #corresponding package option instead)
807 my( $self, %options ) = @_;
810 # pass all suspend/cancel actions to the main package
811 # (unless the pkglinknum has been removed, then the link is defunct and
812 # this package can be canceled on its own)
813 if ( $self->main_pkgnum and $self->pkglinknum and !$options{'from_main'} ) {
814 return $self->main_pkg->cancel(%options);
817 my $conf = new FS::Conf;
819 warn "cust_pkg::cancel called with options".
820 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
823 my $oldAutoCommit = $FS::UID::AutoCommit;
824 local $FS::UID::AutoCommit = 0;
827 my $old = $self->select_for_update;
829 if ( $old->get('cancel') || $self->get('cancel') ) {
830 dbh->rollback if $oldAutoCommit;
831 return ""; # no error
834 # XXX possibly set cancel_time to the expire date?
835 my $cancel_time = $options{'time'} || time;
836 my $date = $options{'date'} if $options{'date'}; # expire/cancel later
837 $date = '' if ($date && $date <= $cancel_time); # complain instead?
839 my $delay_cancel = $options{'no_delay_cancel'} ? 0 : $options{'delay_cancel'};
840 if ( !$date && $self->part_pkg->option('delay_cancel',1)
841 && (($self->status eq 'active') || ($self->status eq 'suspended'))
842 && !$options{'no_delay_cancel'}
844 my $expdays = $conf->config('part_pkg-delay_cancel-days') || 1;
845 my $expsecs = 60*60*24*$expdays;
846 my $suspfor = $self->susp ? $cancel_time - $self->susp : 0;
847 $expsecs = $expsecs - $suspfor if $suspfor;
848 unless ($expsecs <= 0) { #if it's already been suspended long enough, don't re-suspend
850 $date = $cancel_time + $expsecs;
854 #race condition: usage could be ongoing until unprovisioned
855 #resolved by performing a change package instead (which unprovisions) and
857 if ( !$options{nobill} && !$date ) {
858 # && $conf->exists('bill_usage_on_cancel') ) { #calc_cancel checks this
859 my $copy = $self->new({$self->hash});
861 $copy->cust_main->bill( 'pkg_list' => [ $copy ],
863 'time' => $cancel_time );
864 warn "Error billing during cancel, custnum ".
865 #$self->cust_main->custnum. ": $error"
870 if ( $options{'reason'} ) {
871 $error = $self->insert_reason( 'reason' => $options{'reason'},
872 'action' => $date ? 'expire' : 'cancel',
873 'date' => $date ? $date : $cancel_time,
874 'reason_otaker' => $options{'reason_otaker'},
877 dbh->rollback if $oldAutoCommit;
878 return "Error inserting cust_pkg_reason: $error";
882 my %svc_cancel_opt = ();
883 $svc_cancel_opt{'date'} = $date if $date;
884 foreach my $cust_svc (
887 sort { $a->[1] <=> $b->[1] }
888 map { [ $_, $_->svc_x ? $_->svc_x->table_info->{'cancel_weight'} : -1 ]; }
889 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
891 my $part_svc = $cust_svc->part_svc;
892 next if ( defined($part_svc) and $part_svc->preserve );
893 my $error = $cust_svc->cancel( %svc_cancel_opt );
896 $dbh->rollback if $oldAutoCommit;
897 return 'Error '. ($svc_cancel_opt{'date'} ? 'expiring' : 'canceling' ).
903 # credit remaining time if appropriate
905 if ( exists($options{'unused_credit'}) ) {
906 $do_credit = $options{'unused_credit'};
909 $do_credit = $self->part_pkg->option('unused_credit_cancel', 1);
912 my $error = $self->credit_remaining('cancel', $cancel_time);
914 $dbh->rollback if $oldAutoCommit;
920 my %hash = $self->hash;
922 $hash{'expire'} = $date;
924 # just to be sure these are clear
925 $hash{'adjourn'} = undef;
926 $hash{'resume'} = undef;
929 $hash{'cancel'} = $cancel_time;
931 $hash{'change_custnum'} = $options{'change_custnum'};
933 # if this is a supplemental package that's lost its part_pkg_link, and it's
934 # being canceled for real, unlink it completely
935 if ( !$date and ! $self->pkglinknum ) {
936 $hash{main_pkgnum} = '';
939 my $new = new FS::cust_pkg ( \%hash );
940 $error = $new->replace( $self, options => { $self->options } );
941 if ( $self->change_to_pkgnum ) {
942 my $change_to = FS::cust_pkg->by_key($self->change_to_pkgnum);
943 $error ||= $change_to->cancel('no_delay_cancel' => 1) || $change_to->delete;
946 $dbh->rollback if $oldAutoCommit;
950 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
951 $error = $supp_pkg->cancel(%options,
953 'date' => $date, #in case it got changed by delay_cancel
954 'delay_cancel' => $delay_cancel,
957 $dbh->rollback if $oldAutoCommit;
958 return "canceling supplemental pkg#".$supp_pkg->pkgnum.": $error";
962 if ($delay_cancel && !$options{'from_main'}) {
963 $error = $new->suspend(
965 'time' => $cancel_time
970 foreach my $usage ( $self->cust_pkg_usage ) {
971 $error = $usage->delete;
973 $dbh->rollback if $oldAutoCommit;
974 return "deleting usage pools: $error";
979 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
980 return '' if $date; #no errors
982 my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ } $self->cust_main->invoicing_list;
983 if ( !$options{'quiet'} &&
984 $conf->exists('emailcancel', $self->cust_main->agentnum) &&
986 my $msgnum = $conf->config('cancel_msgnum', $self->cust_main->agentnum);
989 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum });
990 $error = $msg_template->send( 'cust_main' => $self->cust_main,
995 'from' => $conf->invoice_from_full( $self->cust_main->agentnum ),
996 'to' => \@invoicing_list,
997 'subject' => ( $conf->config('cancelsubject') || 'Cancellation Notice' ),
998 'body' => [ map "$_\n", $conf->config('cancelmessage') ],
999 'custnum' => $self->custnum,
1000 'msgtype' => '', #admin?
1003 #should this do something on errors?
1010 =item cancel_if_expired [ NOW_TIMESTAMP ]
1012 Cancels this package if its expire date has been reached.
1016 sub cancel_if_expired {
1018 my $time = shift || time;
1019 return '' unless $self->expire && $self->expire <= $time;
1020 my $error = $self->cancel;
1022 return "Error cancelling expired pkg ". $self->pkgnum. " for custnum ".
1023 $self->custnum. ": $error";
1030 "Un-cancels" this package: Orders a new package with the same custnum, pkgpart,
1031 locationnum, (other fields?). Attempts to re-provision cancelled services
1032 using history information (errors at this stage are not fatal).
1034 cust_pkg: pass a scalar reference, will be filled in with the new cust_pkg object
1036 svc_fatal: service provisioning errors are fatal
1038 svc_errors: pass an array reference, will be filled in with any provisioning errors
1040 main_pkgnum: link the package as a supplemental package of this one. For
1046 my( $self, %options ) = @_;
1048 #in case you try do do $uncancel-date = $cust_pkg->uncacel
1049 return '' unless $self->get('cancel');
1051 if ( $self->main_pkgnum and !$options{'main_pkgnum'} ) {
1052 return $self->main_pkg->uncancel(%options);
1059 my $oldAutoCommit = $FS::UID::AutoCommit;
1060 local $FS::UID::AutoCommit = 0;
1064 # insert the new package
1067 my $cust_pkg = new FS::cust_pkg {
1068 last_bill => ( $options{'last_bill'} || $self->get('last_bill') ),
1069 bill => ( $options{'bill'} || $self->get('bill') ),
1071 uncancel_pkgnum => $self->pkgnum,
1072 main_pkgnum => ($options{'main_pkgnum'} || ''),
1073 map { $_ => $self->get($_) } qw(
1074 custnum pkgpart locationnum
1076 susp adjourn resume expire start_date contract_end dundate
1077 change_date change_pkgpart change_locationnum
1078 manual_flag no_auto separate_bill quantity agent_pkgid
1079 recur_show_zero setup_show_zero
1083 my $error = $cust_pkg->insert(
1084 'change' => 1, #supresses any referral credit to a referring customer
1085 'allow_pkgpart' => 1, # allow this even if the package def is disabled
1088 $dbh->rollback if $oldAutoCommit;
1096 #find historical services within this timeframe before the package cancel
1097 # (incompatible with "time" option to cust_pkg->cancel?)
1098 my $fuzz = 2 * 60; #2 minutes? too much? (might catch separate unprovision)
1099 # too little? (unprovisioing export delay?)
1100 my($end, $start) = ( $self->get('cancel'), $self->get('cancel') - $fuzz );
1101 my @h_cust_svc = $self->h_cust_svc( $end, $start );
1104 foreach my $h_cust_svc (@h_cust_svc) {
1105 my $h_svc_x = $h_cust_svc->h_svc_x( $end, $start );
1106 #next unless $h_svc_x; #should this happen?
1107 (my $table = $h_svc_x->table) =~ s/^h_//;
1108 require "FS/$table.pm";
1109 my $class = "FS::$table";
1110 my $svc_x = $class->new( {
1111 'pkgnum' => $cust_pkg->pkgnum,
1112 'svcpart' => $h_cust_svc->svcpart,
1113 map { $_ => $h_svc_x->get($_) } fields($table)
1117 if ( $h_svc_x->isa('FS::h_svc_Radius_Mixin') ) {
1118 $svc_x->usergroup( [ $h_svc_x->h_usergroup($end, $start) ] );
1121 my $svc_error = $svc_x->insert;
1123 if ( $options{svc_fatal} ) {
1124 $dbh->rollback if $oldAutoCommit;
1127 # if we've failed to insert the svc_x object, svc_Common->insert
1128 # will have removed the cust_svc already. if not, then both records
1129 # were inserted but we failed for some other reason (export, most
1130 # likely). in that case, report the error and delete the records.
1131 push @svc_errors, $svc_error;
1132 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svc_x->svcnum });
1134 # except if export_insert failed, export_delete probably won't be
1136 local $FS::svc_Common::noexport_hack = 1;
1137 my $cleanup_error = $svc_x->delete; # also deletes cust_svc
1138 if ( $cleanup_error ) { # and if THAT fails, then run away
1139 $dbh->rollback if $oldAutoCommit;
1140 return $cleanup_error;
1145 } #foreach $h_cust_svc
1147 #these are pretty rare, but should handle them
1148 # - dsl_device (mac addresses)
1149 # - phone_device (mac addresses)
1150 # - dsl_note (ikano notes)
1151 # - domain_record (i.e. restore DNS information w/domains)
1152 # - inventory_item(?) (inventory w/un-cancelling service?)
1153 # - nas (svc_broaband nas stuff)
1154 #this stuff is unused in the wild afaik
1155 # - mailinglistmember
1157 # - svc_domain.parent_svcnum?
1158 # - acct_snarf (ancient mail fetching config)
1159 # - cgp_rule (communigate)
1160 # - cust_svc_option (used by our Tron stuff)
1161 # - acct_rt_transaction (used by our time worked stuff)
1164 # also move over any services that didn't unprovision at cancellation
1167 foreach my $cust_svc ( qsearch('cust_svc', { pkgnum => $self->pkgnum } ) ) {
1168 $cust_svc->pkgnum( $cust_pkg->pkgnum );
1169 my $error = $cust_svc->replace;
1171 $dbh->rollback if $oldAutoCommit;
1177 # Uncancel any supplemental packages, and make them supplemental to the
1181 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1183 $error = $supp_pkg->uncancel(%options, 'main_pkgnum' => $cust_pkg->pkgnum);
1185 $dbh->rollback if $oldAutoCommit;
1186 return "canceling supplemental pkg#".$supp_pkg->pkgnum.": $error";
1194 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1196 ${ $options{cust_pkg} } = $cust_pkg if ref($options{cust_pkg});
1197 @{ $options{svc_errors} } = @svc_errors if ref($options{svc_errors});
1204 Cancels any pending expiration (sets the expire field to null).
1206 If there is an error, returns the error, otherwise returns false.
1211 my( $self, %options ) = @_;
1214 my $oldAutoCommit = $FS::UID::AutoCommit;
1215 local $FS::UID::AutoCommit = 0;
1218 my $old = $self->select_for_update;
1220 my $pkgnum = $old->pkgnum;
1221 if ( $old->get('cancel') || $self->get('cancel') ) {
1222 dbh->rollback if $oldAutoCommit;
1223 return "Can't unexpire cancelled package $pkgnum";
1224 # or at least it's pointless
1227 unless ( $old->get('expire') && $self->get('expire') ) {
1228 dbh->rollback if $oldAutoCommit;
1229 return ""; # no error
1232 my %hash = $self->hash;
1233 $hash{'expire'} = '';
1234 my $new = new FS::cust_pkg ( \%hash );
1235 $error = $new->replace( $self, options => { $self->options } );
1237 $dbh->rollback if $oldAutoCommit;
1241 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1247 =item suspend [ OPTION => VALUE ... ]
1249 Suspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
1250 package, then suspends the package itself (sets the susp field to now).
1252 Available options are:
1256 =item reason - can be set to a cancellation reason (see L<FS:reason>),
1257 either a reasonnum of an existing reason, or passing a hashref will create
1258 a new reason. The hashref should have the following keys:
1259 - typenum - Reason type (see L<FS::reason_type>
1260 - reason - Text of the new reason.
1262 =item date - can be set to a unix style timestamp to specify when to
1265 =item time - can be set to override the current time, for calculation
1266 of final invoices or unused-time credits
1268 =item resume_date - can be set to a time when the package should be
1269 unsuspended. This may be more convenient than calling C<unsuspend()>
1272 =item from_main - allows a supplemental package to be suspended, rather
1273 than redirecting the method call to its main package. For internal use.
1275 =item from_cancel - used when suspending from the cancel method, forces
1276 this to skip everything besides basic suspension. For internal use.
1280 If there is an error, returns the error, otherwise returns false.
1285 my( $self, %options ) = @_;
1288 # pass all suspend/cancel actions to the main package
1289 if ( $self->main_pkgnum and !$options{'from_main'} ) {
1290 return $self->main_pkg->suspend(%options);
1293 my $oldAutoCommit = $FS::UID::AutoCommit;
1294 local $FS::UID::AutoCommit = 0;
1297 my $old = $self->select_for_update;
1299 my $pkgnum = $old->pkgnum;
1300 if ( $old->get('cancel') || $self->get('cancel') ) {
1301 dbh->rollback if $oldAutoCommit;
1302 return "Can't suspend cancelled package $pkgnum";
1305 if ( $old->get('susp') || $self->get('susp') ) {
1306 dbh->rollback if $oldAutoCommit;
1307 return ""; # no error # complain on adjourn?
1310 my $suspend_time = $options{'time'} || time;
1311 my $date = $options{date} if $options{date}; # adjourn/suspend later
1312 $date = '' if ($date && $date <= $suspend_time); # complain instead?
1314 if ( $date && $old->get('expire') && $old->get('expire') < $date ) {
1315 dbh->rollback if $oldAutoCommit;
1316 return "Package $pkgnum expires before it would be suspended.";
1319 # some false laziness with sub cancel
1320 if ( !$options{nobill} && !$date && !$options{'from_cancel'} &&
1321 $self->part_pkg->option('bill_suspend_as_cancel',1) ) {
1322 # kind of a kludge--'bill_suspend_as_cancel' to avoid having to
1323 # make the entire cust_main->bill path recognize 'suspend' and
1324 # 'cancel' separately.
1325 warn "Billing $pkgnum on suspension (at $suspend_time)\n" if $DEBUG;
1326 my $copy = $self->new({$self->hash});
1328 $copy->cust_main->bill( 'pkg_list' => [ $copy ],
1330 'time' => $suspend_time );
1331 warn "Error billing during suspend, custnum ".
1332 #$self->cust_main->custnum. ": $error"
1337 my $cust_pkg_reason;
1338 if ( $options{'reason'} ) {
1339 $error = $self->insert_reason( 'reason' => $options{'reason'},
1340 'action' => $date ? 'adjourn' : 'suspend',
1341 'date' => $date ? $date : $suspend_time,
1342 'reason_otaker' => $options{'reason_otaker'},
1345 dbh->rollback if $oldAutoCommit;
1346 return "Error inserting cust_pkg_reason: $error";
1348 $cust_pkg_reason = qsearchs('cust_pkg_reason', {
1349 'date' => $date ? $date : $suspend_time,
1350 'action' => $date ? 'A' : 'S',
1351 'pkgnum' => $self->pkgnum,
1355 # if a reasonnum was passed, get the actual reason object so we can check
1357 # (passing a reason hashref is still allowed, but it can't be used with
1358 # the fancy behavioral options.)
1361 if ($options{'reason'} =~ /^\d+$/) {
1362 $reason = FS::reason->by_key($options{'reason'});
1365 my %hash = $self->hash;
1367 $hash{'adjourn'} = $date;
1369 $hash{'susp'} = $suspend_time;
1372 my $resume_date = $options{'resume_date'} || 0;
1373 if ( $resume_date > ($date || $suspend_time) ) {
1374 $hash{'resume'} = $resume_date;
1377 $options{options} ||= {};
1379 my $new = new FS::cust_pkg ( \%hash );
1380 $error = $new->replace( $self, options => { $self->options,
1381 %{ $options{options} },
1385 $dbh->rollback if $oldAutoCommit;
1389 unless ( $date ) { # then we are suspending now
1391 unless ($options{'from_cancel'}) {
1392 # credit remaining time if appropriate
1393 # (if required by the package def, or the suspend reason)
1394 my $unused_credit = $self->part_pkg->option('unused_credit_suspend',1)
1395 || ( defined($reason) && $reason->unused_credit );
1397 if ( $unused_credit ) {
1398 warn "crediting unused time on pkg#".$self->pkgnum."\n" if $DEBUG;
1399 my $error = $self->credit_remaining('suspend', $suspend_time);
1401 $dbh->rollback if $oldAutoCommit;
1407 my @cust_svc = qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } );
1409 #attempt ordering ala cust_svc_suspend_cascade (without infinite-looping
1410 # on the circular dep case)
1411 # (this is too simple for multi-level deps, we need to use something
1412 # to resolve the DAG properly when possible)
1414 $svcpart{$_->svcpart} = 0 foreach @cust_svc;
1415 foreach my $svcpart ( keys %svcpart ) {
1416 foreach my $part_svc_link (
1417 FS::part_svc_link->by_agentnum($self->cust_main->agentnum,
1418 src_svcpart => $svcpart,
1419 link_type => 'cust_svc_suspend_cascade'
1422 $svcpart{$part_svc_link->dst_svcpart} = max(
1423 $svcpart{$part_svc_link->dst_svcpart},
1424 $svcpart{$part_svc_link->src_svcpart} + 1
1428 @cust_svc = sort { $svcpart{ $a->svcpart } <=> $svcpart{ $b->svcpart } }
1432 foreach my $cust_svc ( @cust_svc ) {
1433 $cust_svc->suspend( 'labels_arrayref' => \@labels );
1436 # suspension fees: if there is a feepart, and it's not an unsuspend fee,
1437 # and this is not a suspend-before-cancel
1438 if ( $cust_pkg_reason ) {
1439 my $reason_obj = $cust_pkg_reason->reason;
1440 if ( $reason_obj->feepart and
1441 ! $reason_obj->fee_on_unsuspend and
1442 ! $options{'from_cancel'} ) {
1444 # register the need to charge a fee, cust_main->bill will do the rest
1445 warn "registering suspend fee: pkgnum ".$self->pkgnum.", feepart ".$reason->feepart."\n"
1447 my $cust_pkg_reason_fee = FS::cust_pkg_reason_fee->new({
1448 'pkgreasonnum' => $cust_pkg_reason->num,
1449 'pkgnum' => $self->pkgnum,
1450 'feepart' => $reason->feepart,
1451 'nextbill' => $reason->fee_hold,
1453 $error ||= $cust_pkg_reason_fee->insert;
1457 my $conf = new FS::Conf;
1458 if ( $conf->config('suspend_email_admin') && !$options{'from_cancel'} ) {
1460 my $error = send_email(
1461 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
1462 #invoice_from ??? well as good as any
1463 'to' => $conf->config('suspend_email_admin'),
1464 'subject' => 'FREESIDE NOTIFICATION: Customer package suspended',
1466 "This is an automatic message from your Freeside installation\n",
1467 "informing you that the following customer package has been suspended:\n",
1469 'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
1470 'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
1471 ( map { "Service : $_\n" } @labels ),
1473 'custnum' => $self->custnum,
1474 'msgtype' => 'admin'
1478 warn "WARNING: can't send suspension admin email (suspending anyway): ".
1486 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1487 $error = $supp_pkg->suspend(%options, 'from_main' => 1);
1489 $dbh->rollback if $oldAutoCommit;
1490 return "suspending supplemental pkg#".$supp_pkg->pkgnum.": $error";
1494 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1499 =item credit_remaining MODE TIME
1501 Generate a credit for this package for the time remaining in the current
1502 billing period. MODE is either "suspend" or "cancel" (determines the
1503 credit type). TIME is the time of suspension/cancellation. Both arguments
1508 # Implementation note:
1510 # If you pkgpart-change a package that has been billed, and it's set to give
1511 # credit on package change, then this method gets called and then the new
1512 # package will have no last_bill date. Therefore the customer will be credited
1513 # only once (per billing period) even if there are multiple package changes.
1515 # If you location-change a package that has been billed, this method will NOT
1516 # be called and the new package WILL have the last bill date of the old
1519 # If the new package is then canceled within the same billing cycle,
1520 # credit_remaining needs to run calc_remain on the OLD package to determine
1521 # the amount of unused time to credit.
1523 sub credit_remaining {
1524 # Add a credit for remaining service
1525 my ($self, $mode, $time) = @_;
1526 die 'credit_remaining requires suspend or cancel'
1527 unless $mode eq 'suspend' or $mode eq 'cancel';
1528 die 'no suspend/cancel time' unless $time > 0;
1530 my $conf = FS::Conf->new;
1531 my $reason_type = $conf->config($mode.'_credit_type');
1533 my $last_bill = $self->getfield('last_bill') || 0;
1534 my $next_bill = $self->getfield('bill') || 0;
1535 if ( $last_bill > 0 # the package has been billed
1536 and $next_bill > 0 # the package has a next bill date
1537 and $next_bill >= $time # which is in the future
1539 my @cust_credit_source_bill_pkg = ();
1540 my $remaining_value = 0;
1542 my $remain_pkg = $self;
1543 $remaining_value = $remain_pkg->calc_remain(
1545 'cust_credit_source_bill_pkg' => \@cust_credit_source_bill_pkg,
1548 # we may have to walk back past some package changes to get to the
1549 # one that actually has unused time
1550 while ( $remaining_value == 0 ) {
1551 if ( $remain_pkg->change_pkgnum ) {
1552 $remain_pkg = FS::cust_pkg->by_key($remain_pkg->change_pkgnum);
1554 # the package has really never been billed
1557 $remaining_value = $remain_pkg->calc_remain(
1559 'cust_credit_source_bill_pkg' => \@cust_credit_source_bill_pkg,
1563 if ( $remaining_value > 0 ) {
1564 warn "Crediting for $remaining_value on package ".$self->pkgnum."\n"
1566 my $error = $self->cust_main->credit(
1568 'Credit for unused time on '. $self->part_pkg->pkg,
1569 'reason_type' => $reason_type,
1570 'cust_credit_source_bill_pkg' => \@cust_credit_source_bill_pkg,
1572 return "Error crediting customer \$$remaining_value for unused time".
1573 " on ". $self->part_pkg->pkg. ": $error"
1575 } #if $remaining_value
1576 } #if $last_bill, etc.
1580 =item unsuspend [ OPTION => VALUE ... ]
1582 Unsuspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
1583 package, then unsuspends the package itself (clears the susp field and the
1584 adjourn field if it is in the past). If the suspend reason includes an
1585 unsuspension package, that package will be ordered.
1587 Available options are:
1593 Can be set to a date to unsuspend the package in the future (the 'resume'
1596 =item adjust_next_bill
1598 Can be set true to adjust the next bill date forward by
1599 the amount of time the account was inactive. This was set true by default
1600 in the past (from 1.4.2 and 1.5.0pre6 through 1.7.0), but now needs to be
1601 explicitly requested with this option or in the price plan.
1605 If there is an error, returns the error, otherwise returns false.
1610 my( $self, %opt ) = @_;
1613 # pass all suspend/cancel actions to the main package
1614 if ( $self->main_pkgnum and !$opt{'from_main'} ) {
1615 return $self->main_pkg->unsuspend(%opt);
1618 my $oldAutoCommit = $FS::UID::AutoCommit;
1619 local $FS::UID::AutoCommit = 0;
1622 my $old = $self->select_for_update;
1624 my $pkgnum = $old->pkgnum;
1625 if ( $old->get('cancel') || $self->get('cancel') ) {
1626 $dbh->rollback if $oldAutoCommit;
1627 return "Can't unsuspend cancelled package $pkgnum";
1630 unless ( $old->get('susp') && $self->get('susp') ) {
1631 $dbh->rollback if $oldAutoCommit;
1632 return ""; # no error # complain instead?
1635 # handle the case of setting a future unsuspend (resume) date
1636 # and do not continue to actually unsuspend the package
1637 my $date = $opt{'date'};
1638 if ( $date and $date > time ) { # return an error if $date <= time?
1640 if ( $old->get('expire') && $old->get('expire') < $date ) {
1641 $dbh->rollback if $oldAutoCommit;
1642 return "Package $pkgnum expires before it would be unsuspended.";
1645 my $new = new FS::cust_pkg { $self->hash };
1646 $new->set('resume', $date);
1647 $error = $new->replace($self, options => $self->options);
1650 $dbh->rollback if $oldAutoCommit;
1654 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1660 if (!$self->setup) {
1661 # then this package is being released from on-hold status
1662 $self->set_initial_timers;
1667 foreach my $cust_svc (
1668 qsearch('cust_svc',{'pkgnum'=> $self->pkgnum } )
1670 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
1672 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
1673 $dbh->rollback if $oldAutoCommit;
1674 return "Illegal svcdb value in part_svc!";
1677 require "FS/$svcdb.pm";
1679 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
1681 $error = $svc->unsuspend;
1683 $dbh->rollback if $oldAutoCommit;
1686 my( $label, $value ) = $cust_svc->label;
1687 push @labels, "$label: $value";
1692 my $cust_pkg_reason = $self->last_cust_pkg_reason('susp');
1693 my $reason = $cust_pkg_reason ? $cust_pkg_reason->reason : '';
1695 my %hash = $self->hash;
1696 my $inactive = time - $hash{'susp'};
1698 my $conf = new FS::Conf;
1700 #adjust the next bill date forward
1701 # increment next bill date if certain conditions are met:
1702 # - it was due to be billed at some point
1703 # - either the global or local config says to do this
1704 my $adjust_bill = 0;
1707 && ( $hash{'bill'} || $hash{'setup'} )
1708 && ( $opt{'adjust_next_bill'}
1709 || $conf->exists('unsuspend-always_adjust_next_bill_date')
1710 || $self->part_pkg->option('unsuspend_adjust_bill', 1)
1717 # - the package billed during suspension
1718 # - or it was ordered on hold
1719 # - or the customer was credited for the unused time
1721 if ( $self->option('suspend_bill',1)
1722 or ( $self->part_pkg->option('suspend_bill',1)
1723 and ! $self->option('no_suspend_bill',1)
1725 or $hash{'order_date'} == $hash{'susp'}
1730 if ( $adjust_bill ) {
1731 if ( $self->part_pkg->option('unused_credit_suspend')
1732 or ( ref($reason) and $reason->unused_credit ) ) {
1733 # then the customer was credited for the unused time before suspending,
1734 # so their next bill should be immediate
1735 $hash{'bill'} = time;
1737 # add the length of time suspended to the bill date
1738 $hash{'bill'} = ( $hash{'bill'} || $hash{'setup'} ) + $inactive;
1743 $hash{'adjourn'} = '' if $hash{'adjourn'} and $hash{'adjourn'} < time;
1744 $hash{'resume'} = '' if !$hash{'adjourn'};
1745 my $new = new FS::cust_pkg ( \%hash );
1746 $error = $new->replace( $self, options => { $self->options } );
1748 $dbh->rollback if $oldAutoCommit;
1755 if ( $reason->unsuspend_pkgpart ) {
1756 warn "Suspend reason '".$reason->reason."' uses deprecated unsuspend_pkgpart feature.\n";
1757 my $part_pkg = FS::part_pkg->by_key($reason->unsuspend_pkgpart)
1758 or $error = "Unsuspend package definition ".$reason->unsuspend_pkgpart.
1760 my $start_date = $self->cust_main->next_bill_date
1761 if $reason->unsuspend_hold;
1764 $unsusp_pkg = FS::cust_pkg->new({
1765 'custnum' => $self->custnum,
1766 'pkgpart' => $reason->unsuspend_pkgpart,
1767 'start_date' => $start_date,
1768 'locationnum' => $self->locationnum,
1769 # discount? probably not...
1772 $error ||= $self->cust_main->order_pkg( 'cust_pkg' => $unsusp_pkg );
1775 # new way, using fees
1776 if ( $reason->feepart and $reason->fee_on_unsuspend ) {
1777 # register the need to charge a fee, cust_main->bill will do the rest
1778 warn "registering unsuspend fee: pkgnum ".$self->pkgnum.", feepart ".$reason->feepart."\n"
1780 my $cust_pkg_reason_fee = FS::cust_pkg_reason_fee->new({
1781 'pkgreasonnum' => $cust_pkg_reason->num,
1782 'pkgnum' => $self->pkgnum,
1783 'feepart' => $reason->feepart,
1784 'nextbill' => $reason->fee_hold,
1786 $error ||= $cust_pkg_reason_fee->insert;
1790 $dbh->rollback if $oldAutoCommit;
1795 if ( $conf->config('unsuspend_email_admin') ) {
1797 my $error = send_email(
1798 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
1799 #invoice_from ??? well as good as any
1800 'to' => $conf->config('unsuspend_email_admin'),
1801 'subject' => 'FREESIDE NOTIFICATION: Customer package unsuspended', 'body' => [
1802 "This is an automatic message from your Freeside installation\n",
1803 "informing you that the following customer package has been unsuspended:\n",
1805 'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
1806 'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
1807 ( map { "Service : $_\n" } @labels ),
1809 "An unsuspension fee was charged: ".
1810 $unsusp_pkg->part_pkg->pkg_comment."\n"
1814 'custnum' => $self->custnum,
1815 'msgtype' => 'admin',
1819 warn "WARNING: can't send unsuspension admin email (unsuspending anyway): ".
1825 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1826 $error = $supp_pkg->unsuspend(%opt, 'from_main' => 1);
1828 $dbh->rollback if $oldAutoCommit;
1829 return "unsuspending supplemental pkg#".$supp_pkg->pkgnum.": $error";
1833 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1840 Cancels any pending suspension (sets the adjourn field to null).
1842 If there is an error, returns the error, otherwise returns false.
1847 my( $self, %options ) = @_;
1850 my $oldAutoCommit = $FS::UID::AutoCommit;
1851 local $FS::UID::AutoCommit = 0;
1854 my $old = $self->select_for_update;
1856 my $pkgnum = $old->pkgnum;
1857 if ( $old->get('cancel') || $self->get('cancel') ) {
1858 dbh->rollback if $oldAutoCommit;
1859 return "Can't unadjourn cancelled package $pkgnum";
1860 # or at least it's pointless
1863 if ( $old->get('susp') || $self->get('susp') ) {
1864 dbh->rollback if $oldAutoCommit;
1865 return "Can't unadjourn suspended package $pkgnum";
1866 # perhaps this is arbitrary
1869 unless ( $old->get('adjourn') && $self->get('adjourn') ) {
1870 dbh->rollback if $oldAutoCommit;
1871 return ""; # no error
1874 my %hash = $self->hash;
1875 $hash{'adjourn'} = '';
1876 $hash{'resume'} = '';
1877 my $new = new FS::cust_pkg ( \%hash );
1878 $error = $new->replace( $self, options => { $self->options } );
1880 $dbh->rollback if $oldAutoCommit;
1884 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1891 =item change HASHREF | OPTION => VALUE ...
1893 Changes this package: cancels it and creates a new one, with a different
1894 pkgpart or locationnum or both. All services are transferred to the new
1895 package (no change will be made if this is not possible).
1897 Options may be passed as a list of key/value pairs or as a hash reference.
1904 New locationnum, to change the location for this package.
1908 New FS::cust_location object, to create a new location and assign it
1913 New FS::cust_main object, to create a new customer and assign the new package
1918 New pkgpart (see L<FS::part_pkg>).
1922 New refnum (see L<FS::part_referral>).
1926 New quantity; if unspecified, the new package will have the same quantity
1931 "New" (existing) FS::cust_pkg object. The package's services and other
1932 attributes will be transferred to this package.
1936 Set to true to transfer billing dates (start_date, setup, last_bill, bill,
1937 susp, adjourn, cancel, expire, and contract_end) to the new package.
1939 =item unprotect_svcs
1941 Normally, change() will rollback and return an error if some services
1942 can't be transferred (also see the I<cust_pkg-change_svcpart> config option).
1943 If unprotect_svcs is true, this method will transfer as many services as
1944 it can and then unconditionally cancel the old package.
1948 If specified, sets this value for the contract_end date on the new package
1949 (without regard for keep_dates or the usual date-preservation behavior.)
1950 Will throw an error if defined but false; the UI doesn't allow editing
1951 this unless it already exists, making removal impossible to undo.
1955 At least one of locationnum, cust_location, pkgpart, refnum, cust_main, or
1956 cust_pkg must be specified (otherwise, what's the point?)
1958 Returns either the new FS::cust_pkg object or a scalar error.
1962 my $err_or_new_cust_pkg = $old_cust_pkg->change
1966 #used by change and change_later
1967 #didn't put with documented check methods because it depends on change-specific opts
1968 #and it also possibly edits the value of opts
1972 if ( defined($opt->{'contract_end'}) ) {
1973 my $current_contract_end = $self->get('contract_end');
1974 unless ($opt->{'contract_end'}) {
1975 if ($current_contract_end) {
1976 return "Cannot remove contract end date when changing packages";
1978 #shouldn't even pass this option if there's not a current value
1979 #but can be handled gracefully if the option is empty
1980 warn "Contract end date passed unexpectedly";
1981 delete $opt->{'contract_end'};
1985 unless ($current_contract_end) {
1986 #option shouldn't be passed, throw error if it's non-empty
1987 return "Cannot add contract end date when changing packages " . $self->pkgnum;
1993 #some false laziness w/order
1996 my $opt = ref($_[0]) ? shift : { @_ };
1998 my $conf = new FS::Conf;
2000 # handle contract_end on cust_pkg same as passed option
2001 if ( $opt->{'cust_pkg'} ) {
2002 $opt->{'contract_end'} = $opt->{'cust_pkg'}->contract_end;
2003 delete $opt->{'contract_end'} unless $opt->{'contract_end'};
2006 # check contract_end, prevent adding/removing
2007 my $error = $self->_check_change($opt);
2008 return $error if $error;
2010 # Transactionize this whole mess
2011 my $oldAutoCommit = $FS::UID::AutoCommit;
2012 local $FS::UID::AutoCommit = 0;
2015 if ( $opt->{'cust_location'} ) {
2016 $error = $opt->{'cust_location'}->find_or_insert;
2018 $dbh->rollback if $oldAutoCommit;
2019 return "creating location record: $error";
2021 $opt->{'locationnum'} = $opt->{'cust_location'}->locationnum;
2024 # Before going any further here: if the package is still in the pre-setup
2025 # state, it's safe to modify it in place. No need to charge/credit for
2026 # partial period, transfer services, transfer usage pools, copy invoice
2027 # details, or change any dates.
2028 if ( ! $self->setup and ! $opt->{cust_pkg} and ! $opt->{cust_main} ) {
2029 foreach ( qw( locationnum pkgpart quantity refnum salesnum ) ) {
2030 if ( length($opt->{$_}) ) {
2031 $self->set($_, $opt->{$_});
2034 # almost. if the new pkgpart specifies start/adjourn/expire timers,
2036 if ( $opt->{'pkgpart'} and $opt->{'pkgpart'} != $self->pkgpart ) {
2037 $self->set_initial_timers;
2039 # but if contract_end was explicitly specified, that overrides all else
2040 $self->set('contract_end', $opt->{'contract_end'})
2041 if $opt->{'contract_end'};
2042 $error = $self->replace;
2044 $dbh->rollback if $oldAutoCommit;
2045 return "modifying package: $error";
2047 $dbh->commit if $oldAutoCommit;
2056 $hash{'setup'} = $time if $self->setup;
2058 $hash{'change_date'} = $time;
2059 $hash{"change_$_"} = $self->$_()
2060 foreach qw( pkgnum pkgpart locationnum );
2062 if ( $opt->{'cust_pkg'} ) {
2063 # treat changing to a package with a different pkgpart as a
2064 # pkgpart change (because it is)
2065 $opt->{'pkgpart'} = $opt->{'cust_pkg'}->pkgpart;
2068 # whether to override pkgpart checking on the new package
2069 my $same_pkgpart = 1;
2070 if ( $opt->{'pkgpart'} and ( $opt->{'pkgpart'} != $self->pkgpart ) ) {
2074 my $unused_credit = 0;
2075 my $keep_dates = $opt->{'keep_dates'};
2077 # Special case. If the pkgpart is changing, and the customer is
2078 # going to be credited for remaining time, don't keep setup, bill,
2079 # or last_bill dates, and DO pass the flag to cancel() to credit
2081 if ( $opt->{'pkgpart'}
2082 and $opt->{'pkgpart'} != $self->pkgpart
2083 and $self->part_pkg->option('unused_credit_change', 1) ) {
2086 $hash{$_} = '' foreach qw(setup bill last_bill);
2089 if ( $keep_dates ) {
2090 foreach my $date ( qw(setup bill last_bill) ) {
2091 $hash{$date} = $self->getfield($date);
2094 # always keep the following dates
2095 foreach my $date (qw(order_date susp adjourn cancel expire resume
2096 start_date contract_end)) {
2097 $hash{$date} = $self->getfield($date);
2099 # but if contract_end was explicitly specified, that overrides all else
2100 $hash{'contract_end'} = $opt->{'contract_end'}
2101 if $opt->{'contract_end'};
2103 # allow $opt->{'locationnum'} = '' to specifically set it to null
2104 # (i.e. customer default location)
2105 $opt->{'locationnum'} = $self->locationnum if !exists($opt->{'locationnum'});
2107 # usually this doesn't matter. the two cases where it does are:
2108 # 1. unused_credit_change + pkgpart change + setup fee on the new package
2110 # 2. (more importantly) changing a package before it's billed
2111 $hash{'waive_setup'} = $self->waive_setup;
2113 # if this package is scheduled for a future package change, preserve that
2114 $hash{'change_to_pkgnum'} = $self->change_to_pkgnum;
2116 my $custnum = $self->custnum;
2117 if ( $opt->{cust_main} ) {
2118 my $cust_main = $opt->{cust_main};
2119 unless ( $cust_main->custnum ) {
2120 my $error = $cust_main->insert( @{ $opt->{cust_main_insert_args}||[] } );
2122 $dbh->rollback if $oldAutoCommit;
2123 return "inserting customer record: $error";
2126 $custnum = $cust_main->custnum;
2129 $hash{'contactnum'} = $opt->{'contactnum'} if $opt->{'contactnum'};
2132 if ( $opt->{'cust_pkg'} ) {
2133 # The target package already exists; update it to show that it was
2134 # changed from this package.
2135 $cust_pkg = $opt->{'cust_pkg'};
2137 # follow all the above rules for date changes, etc.
2138 foreach (keys %hash) {
2139 $cust_pkg->set($_, $hash{$_});
2141 # except those that implement the future package change behavior
2142 foreach (qw(change_to_pkgnum start_date expire)) {
2143 $cust_pkg->set($_, '');
2146 $error = $cust_pkg->replace;
2149 # Create the new package.
2150 $cust_pkg = new FS::cust_pkg {
2151 custnum => $custnum,
2152 locationnum => $opt->{'locationnum'},
2153 ( map { $_ => ( $opt->{$_} || $self->$_() ) }
2154 qw( pkgpart quantity refnum salesnum )
2158 $error = $cust_pkg->insert( 'change' => 1,
2159 'allow_pkgpart' => $same_pkgpart );
2162 $dbh->rollback if $oldAutoCommit;
2163 return "inserting new package: $error";
2166 # Transfer services and cancel old package.
2167 # Enforce service limits only if this is a pkgpart change.
2168 local $FS::cust_svc::ignore_quantity;
2169 $FS::cust_svc::ignore_quantity = 1 if $same_pkgpart;
2170 $error = $self->transfer($cust_pkg);
2171 if ($error and $error == 0) {
2172 # $old_pkg->transfer failed.
2173 $dbh->rollback if $oldAutoCommit;
2174 return "transferring $error";
2177 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
2178 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
2179 $error = $self->transfer($cust_pkg, 'change_svcpart'=>1 );
2180 if ($error and $error == 0) {
2181 # $old_pkg->transfer failed.
2182 $dbh->rollback if $oldAutoCommit;
2183 return "converting $error";
2187 # We set unprotect_svcs when executing a "future package change". It's
2188 # not a user-interactive operation, so returning an error means the
2189 # package change will just fail. Rather than have that happen, we'll
2190 # let leftover services be deleted.
2191 if ($error > 0 and !$opt->{'unprotect_svcs'}) {
2192 # Transfers were successful, but we still had services left on the old
2193 # package. We can't change the package under this circumstances, so abort.
2194 $dbh->rollback if $oldAutoCommit;
2195 return "unable to transfer all services";
2198 #reset usage if changing pkgpart
2199 # AND usage rollover is off (otherwise adds twice, now and at package bill)
2200 if ($self->pkgpart != $cust_pkg->pkgpart) {
2201 my $part_pkg = $cust_pkg->part_pkg;
2202 $error = $part_pkg->reset_usage($cust_pkg, $part_pkg->is_prepaid
2206 if $part_pkg->can('reset_usage') && ! $part_pkg->option('usage_rollover',1);
2209 $dbh->rollback if $oldAutoCommit;
2210 return "setting usage values: $error";
2213 # if NOT changing pkgpart, transfer any usage pools over
2214 foreach my $usage ($self->cust_pkg_usage) {
2215 $usage->set('pkgnum', $cust_pkg->pkgnum);
2216 $error = $usage->replace;
2218 $dbh->rollback if $oldAutoCommit;
2219 return "transferring usage pools: $error";
2224 # transfer usage pricing add-ons, if we're not changing pkgpart
2225 if ( $same_pkgpart ) {
2226 foreach my $old_cust_pkg_usageprice ($self->cust_pkg_usageprice) {
2227 my $new_cust_pkg_usageprice = new FS::cust_pkg_usageprice {
2228 'pkgnum' => $cust_pkg->pkgnum,
2229 'usagepricepart' => $old_cust_pkg_usageprice->usagepricepart,
2230 'quantity' => $old_cust_pkg_usageprice->quantity,
2232 $error = $new_cust_pkg_usageprice->insert;
2234 $dbh->rollback if $oldAutoCommit;
2235 return "Error transferring usage pricing add-on: $error";
2240 # transfer discounts, if we're not changing pkgpart
2241 if ( $same_pkgpart ) {
2242 foreach my $old_discount ($self->cust_pkg_discount_active) {
2243 # don't remove the old discount, we may still need to bill that package.
2244 my $new_discount = new FS::cust_pkg_discount {
2245 'pkgnum' => $cust_pkg->pkgnum,
2246 'discountnum' => $old_discount->discountnum,
2247 'months_used' => $old_discount->months_used,
2249 $error = $new_discount->insert;
2251 $dbh->rollback if $oldAutoCommit;
2252 return "transferring discounts: $error";
2257 # transfer (copy) invoice details
2258 foreach my $detail ($self->cust_pkg_detail) {
2259 my $new_detail = FS::cust_pkg_detail->new({ $detail->hash });
2260 $new_detail->set('pkgdetailnum', '');
2261 $new_detail->set('pkgnum', $cust_pkg->pkgnum);
2262 $error = $new_detail->insert;
2264 $dbh->rollback if $oldAutoCommit;
2265 return "transferring package notes: $error";
2271 if ( !$opt->{'cust_pkg'} ) {
2272 # Order any supplemental packages.
2273 my $part_pkg = $cust_pkg->part_pkg;
2274 my @old_supp_pkgs = $self->supplemental_pkgs;
2275 foreach my $link ($part_pkg->supp_part_pkg_link) {
2277 foreach (@old_supp_pkgs) {
2278 if ($_->pkgpart == $link->dst_pkgpart) {
2280 $_->pkgpart(0); # so that it can't match more than once
2284 # false laziness with FS::cust_main::Packages::order_pkg
2285 my $new = FS::cust_pkg->new({
2286 pkgpart => $link->dst_pkgpart,
2287 pkglinknum => $link->pkglinknum,
2288 custnum => $custnum,
2289 main_pkgnum => $cust_pkg->pkgnum,
2290 locationnum => $cust_pkg->locationnum,
2291 start_date => $cust_pkg->start_date,
2292 order_date => $cust_pkg->order_date,
2293 expire => $cust_pkg->expire,
2294 adjourn => $cust_pkg->adjourn,
2295 contract_end => $cust_pkg->contract_end,
2296 refnum => $cust_pkg->refnum,
2297 discountnum => $cust_pkg->discountnum,
2298 waive_setup => $cust_pkg->waive_setup,
2300 if ( $old and $opt->{'keep_dates'} ) {
2301 foreach (qw(setup bill last_bill)) {
2302 $new->set($_, $old->get($_));
2305 $error = $new->insert( allow_pkgpart => $same_pkgpart );
2308 $error ||= $old->transfer($new);
2310 if ( $error and $error > 0 ) {
2311 # no reason why this should ever fail, but still...
2312 $error = "Unable to transfer all services from supplemental package ".
2316 $dbh->rollback if $oldAutoCommit;
2319 push @new_supp_pkgs, $new;
2321 } # if !$opt->{'cust_pkg'}
2322 # because if there is one, then supplemental packages would already
2323 # have been created for it.
2325 #Good to go, cancel old package. Notify 'cancel' of whether to credit
2327 #Don't allow billing the package (preceding period packages and/or
2328 #outstanding usage) if we are keeping dates (i.e. location changing),
2329 #because the new package will be billed for the same date range.
2330 #Supplemental packages are also canceled here.
2332 # during scheduled changes, avoid canceling the package we just
2334 $self->set('change_to_pkgnum' => '');
2336 $error = $self->cancel(
2338 unused_credit => $unused_credit,
2339 nobill => $keep_dates,
2340 change_custnum => ( $self->custnum != $custnum ? $custnum : '' ),
2341 no_delay_cancel => 1,
2344 $dbh->rollback if $oldAutoCommit;
2345 return "canceling old package: $error";
2348 if ( $conf->exists('cust_pkg-change_pkgpart-bill_now') ) {
2350 my $error = $cust_pkg->cust_main->bill(
2351 'pkg_list' => [ $cust_pkg, @new_supp_pkgs ]
2354 $dbh->rollback if $oldAutoCommit;
2355 return "billing new package: $error";
2359 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2365 =item change_later OPTION => VALUE...
2367 Schedule a package change for a later date. This actually orders the new
2368 package immediately, but sets its start date for a future date, and sets
2369 the current package to expire on the same date.
2371 If the package is already scheduled for a change, this can be called with
2372 'start_date' to change the scheduled date, or with pkgpart and/or
2373 locationnum to modify the package change. To cancel the scheduled change
2374 entirely, see C<abort_change>.
2382 The date for the package change. Required, and must be in the future.
2392 The pkgpart, locationnum, quantity and optional contract_end of the new
2393 package, with the same meaning as in C<change>.
2401 my $opt = ref($_[0]) ? shift : { @_ };
2403 # check contract_end, prevent adding/removing
2404 my $error = $self->_check_change($opt);
2405 return $error if $error;
2407 my $oldAutoCommit = $FS::UID::AutoCommit;
2408 local $FS::UID::AutoCommit = 0;
2411 my $cust_main = $self->cust_main;
2413 my $date = delete $opt->{'start_date'} or return 'start_date required';
2415 if ( $date <= time ) {
2416 $dbh->rollback if $oldAutoCommit;
2417 return "start_date $date is in the past";
2420 if ( $self->change_to_pkgnum ) {
2421 my $change_to = FS::cust_pkg->by_key($self->change_to_pkgnum);
2422 my $new_pkgpart = $opt->{'pkgpart'}
2423 if $opt->{'pkgpart'} and $opt->{'pkgpart'} != $change_to->pkgpart;
2424 my $new_locationnum = $opt->{'locationnum'}
2425 if $opt->{'locationnum'} and $opt->{'locationnum'} != $change_to->locationnum;
2426 my $new_quantity = $opt->{'quantity'}
2427 if $opt->{'quantity'} and $opt->{'quantity'} != $change_to->quantity;
2428 my $new_contract_end = $opt->{'contract_end'}
2429 if $opt->{'contract_end'} and $opt->{'contract_end'} != $change_to->contract_end;
2430 if ( $new_pkgpart or $new_locationnum or $new_quantity or $new_contract_end ) {
2431 # it hasn't been billed yet, so in principle we could just edit
2432 # it in place (w/o a package change), but that's bad form.
2433 # So change the package according to the new options...
2434 my $err_or_pkg = $change_to->change(%$opt);
2435 if ( ref $err_or_pkg ) {
2436 # Then set that package up for a future start.
2437 $self->set('change_to_pkgnum', $err_or_pkg->pkgnum);
2438 $self->set('expire', $date); # in case it's different
2439 $err_or_pkg->set('start_date', $date);
2440 $err_or_pkg->set('change_date', '');
2441 $err_or_pkg->set('change_pkgnum', '');
2443 $error = $self->replace ||
2444 $err_or_pkg->replace ||
2445 #because change() might've edited existing scheduled change in place
2446 (($err_or_pkg->pkgnum == $change_to->pkgnum) ? '' :
2447 $change_to->cancel('no_delay_cancel' => 1) ||
2448 $change_to->delete);
2450 $error = $err_or_pkg;
2452 } else { # change the start date only.
2453 $self->set('expire', $date);
2454 $change_to->set('start_date', $date);
2455 $error = $self->replace || $change_to->replace;
2458 $dbh->rollback if $oldAutoCommit;
2461 $dbh->commit if $oldAutoCommit;
2464 } # if $self->change_to_pkgnum
2466 my $new_pkgpart = $opt->{'pkgpart'}
2467 if $opt->{'pkgpart'} and $opt->{'pkgpart'} != $self->pkgpart;
2468 my $new_locationnum = $opt->{'locationnum'}
2469 if $opt->{'locationnum'} and $opt->{'locationnum'} != $self->locationnum;
2470 my $new_quantity = $opt->{'quantity'}
2471 if $opt->{'quantity'} and $opt->{'quantity'} != $self->quantity;
2472 my $new_contract_end = $opt->{'contract_end'}
2473 if $opt->{'contract_end'} and $opt->{'contract_end'} != $self->contract_end;
2475 return '' unless $new_pkgpart or $new_locationnum or $new_quantity or $new_contract_end; # wouldn't do anything
2477 # allow $opt->{'locationnum'} = '' to specifically set it to null
2478 # (i.e. customer default location)
2479 $opt->{'locationnum'} = $self->locationnum if !exists($opt->{'locationnum'});
2481 my $new = FS::cust_pkg->new( {
2482 custnum => $self->custnum,
2483 locationnum => $opt->{'locationnum'},
2484 start_date => $date,
2485 map { $_ => ( $opt->{$_} || $self->$_() ) }
2486 qw( pkgpart quantity refnum salesnum contract_end )
2488 $error = $new->insert('change' => 1,
2489 'allow_pkgpart' => ($new_pkgpart ? 0 : 1));
2491 $self->set('change_to_pkgnum', $new->pkgnum);
2492 $self->set('expire', $date);
2493 $error = $self->replace;
2496 $dbh->rollback if $oldAutoCommit;
2498 $dbh->commit if $oldAutoCommit;
2506 Cancels a future package change scheduled by C<change_later>.
2512 my $pkgnum = $self->change_to_pkgnum;
2513 my $change_to = FS::cust_pkg->by_key($pkgnum) if $pkgnum;
2516 $error = $change_to->cancel || $change_to->delete;
2517 return $error if $error;
2519 $self->set('change_to_pkgnum', '');
2520 $self->set('expire', '');
2524 =item set_quantity QUANTITY
2526 Change the package's quantity field. This is one of the few package properties
2527 that can safely be changed without canceling and reordering the package
2528 (because it doesn't affect tax eligibility). Returns an error or an
2535 $self = $self->replace_old; # just to make sure
2536 $self->quantity(shift);
2540 =item set_salesnum SALESNUM
2542 Change the package's salesnum (sales person) field. This is one of the few
2543 package properties that can safely be changed without canceling and reordering
2544 the package (because it doesn't affect tax eligibility). Returns an error or
2551 $self = $self->replace_old; # just to make sure
2552 $self->salesnum(shift);
2554 # XXX this should probably reassign any credit that's already been given
2557 =item modify_charge OPTIONS
2559 Change the properties of a one-time charge. The following properties can
2560 be changed this way:
2561 - pkg: the package description
2562 - classnum: the package class
2563 - additional: arrayref of additional invoice details to add to this package
2565 and, I<if the charge has not yet been billed>:
2566 - start_date: the date when it will be billed
2567 - amount: the setup fee to be charged
2568 - quantity: the multiplier for the setup fee
2569 - separate_bill: whether to put the charge on a separate invoice
2571 If you pass 'adjust_commission' => 1, and the classnum changes, and there are
2572 commission credits linked to this charge, they will be recalculated.
2579 my $part_pkg = $self->part_pkg;
2580 my $pkgnum = $self->pkgnum;
2583 my $oldAutoCommit = $FS::UID::AutoCommit;
2584 local $FS::UID::AutoCommit = 0;
2586 return "Can't use modify_charge except on one-time charges"
2587 unless $part_pkg->freq eq '0';
2589 if ( length($opt{'pkg'}) and $part_pkg->pkg ne $opt{'pkg'} ) {
2590 $part_pkg->set('pkg', $opt{'pkg'});
2593 my %pkg_opt = $part_pkg->options;
2594 my $pkg_opt_modified = 0;
2596 $opt{'additional'} ||= [];
2599 foreach (grep /^additional/, keys %pkg_opt) {
2600 ($i) = ($_ =~ /^additional_info(\d+)$/);
2601 $old_additional[$i] = $pkg_opt{$_} if $i;
2602 delete $pkg_opt{$_};
2605 for ( $i = 0; exists($opt{'additional'}->[$i]); $i++ ) {
2606 $pkg_opt{ "additional_info$i" } = $opt{'additional'}->[$i];
2607 if (!exists($old_additional[$i])
2608 or $old_additional[$i] ne $opt{'additional'}->[$i])
2610 $pkg_opt_modified = 1;
2613 $pkg_opt_modified = 1 if (scalar(@old_additional) - 1) != $i;
2614 $pkg_opt{'additional_count'} = $i if $i > 0;
2617 if ( exists($opt{'classnum'}) and $part_pkg->classnum ne $opt{'classnum'} )
2620 $old_classnum = $part_pkg->classnum;
2621 $part_pkg->set('classnum', $opt{'classnum'});
2624 if ( !$self->get('setup') ) {
2625 # not yet billed, so allow amount, setup_cost, quantity, start_date,
2628 if ( exists($opt{'amount'})
2629 and $part_pkg->option('setup_fee') != $opt{'amount'}
2630 and $opt{'amount'} > 0 ) {
2632 $pkg_opt{'setup_fee'} = $opt{'amount'};
2633 $pkg_opt_modified = 1;
2636 if ( exists($opt{'setup_cost'})
2637 and $part_pkg->setup_cost != $opt{'setup_cost'}
2638 and $opt{'setup_cost'} > 0 ) {
2640 $part_pkg->set('setup_cost', $opt{'setup_cost'});
2643 if ( exists($opt{'quantity'})
2644 and $opt{'quantity'} != $self->quantity
2645 and $opt{'quantity'} > 0 ) {
2647 $self->set('quantity', $opt{'quantity'});
2650 if ( exists($opt{'start_date'})
2651 and $opt{'start_date'} != $self->start_date ) {
2653 $self->set('start_date', $opt{'start_date'});
2656 if ( exists($opt{'separate_bill'})
2657 and $opt{'separate_bill'} ne $self->separate_bill ) {
2659 $self->set('separate_bill', $opt{'separate_bill'});
2663 } # else simply ignore them; the UI shouldn't allow editing the fields
2666 if ( exists($opt{'taxclass'})
2667 and $part_pkg->taxclass ne $opt{'taxclass'}) {
2669 $part_pkg->set('taxclass', $opt{'taxclass'});
2673 if ( $part_pkg->modified or $pkg_opt_modified ) {
2674 # can we safely modify the package def?
2675 # Yes, if it's not available for purchase, and this is the only instance
2677 if ( $part_pkg->disabled
2678 and FS::cust_pkg->count('pkgpart = '.$part_pkg->pkgpart) == 1
2679 and FS::quotation_pkg->count('pkgpart = '.$part_pkg->pkgpart) == 0
2681 $error = $part_pkg->replace( options => \%pkg_opt );
2684 $part_pkg = $part_pkg->clone;
2685 $part_pkg->set('disabled' => 'Y');
2686 $error = $part_pkg->insert( options => \%pkg_opt );
2687 # and associate this as yet-unbilled package to the new package def
2688 $self->set('pkgpart' => $part_pkg->pkgpart);
2691 $dbh->rollback if $oldAutoCommit;
2696 if ($self->modified) { # for quantity or start_date change, or if we had
2697 # to clone the existing package def
2698 my $error = $self->replace;
2699 return $error if $error;
2701 if (defined $old_classnum) {
2702 # fix invoice grouping records
2703 my $old_catname = $old_classnum
2704 ? FS::pkg_class->by_key($old_classnum)->categoryname
2706 my $new_catname = $opt{'classnum'}
2707 ? $part_pkg->pkg_class->categoryname
2709 if ( $old_catname ne $new_catname ) {
2710 foreach my $cust_bill_pkg ($self->cust_bill_pkg) {
2711 # (there should only be one...)
2712 my @display = qsearch( 'cust_bill_pkg_display', {
2713 'billpkgnum' => $cust_bill_pkg->billpkgnum,
2714 'section' => $old_catname,
2716 foreach (@display) {
2717 $_->set('section', $new_catname);
2718 $error = $_->replace;
2720 $dbh->rollback if $oldAutoCommit;
2724 } # foreach $cust_bill_pkg
2727 if ( $opt{'adjust_commission'} ) {
2728 # fix commission credits...tricky.
2729 foreach my $cust_event ($self->cust_event) {
2730 my $part_event = $cust_event->part_event;
2731 foreach my $table (qw(sales agent)) {
2733 "FS::part_event::Action::Mixin::credit_${table}_pkg_class";
2734 my $credit = qsearchs('cust_credit', {
2735 'eventnum' => $cust_event->eventnum,
2737 if ( $part_event->isa($class) ) {
2738 # Yes, this results in current commission rates being applied
2739 # retroactively to a one-time charge. For accounting purposes
2740 # there ought to be some kind of time limit on doing this.
2741 my $amount = $part_event->_calc_credit($self);
2742 if ( $credit and $credit->amount ne $amount ) {
2743 # Void the old credit.
2744 $error = $credit->void('Package class changed');
2746 $dbh->rollback if $oldAutoCommit;
2747 return "$error (adjusting commission credit)";
2750 # redo the event action to recreate the credit.
2752 eval { $part_event->do_action( $self, $cust_event ) };
2754 $dbh->rollback if $oldAutoCommit;
2757 } # if $part_event->isa($class)
2759 } # foreach $cust_event
2760 } # if $opt{'adjust_commission'}
2761 } # if defined $old_classnum
2763 $dbh->commit if $oldAutoCommit;
2770 sub process_bulk_cust_pkg {
2773 warn Dumper($param) if $DEBUG;
2775 my $old_part_pkg = qsearchs('part_pkg',
2776 { pkgpart => $param->{'old_pkgpart'} });
2777 my $new_part_pkg = qsearchs('part_pkg',
2778 { pkgpart => $param->{'new_pkgpart'} });
2779 die "Must select a new package type\n" unless $new_part_pkg;
2780 #my $keep_dates = $param->{'keep_dates'} || 0;
2781 my $keep_dates = 1; # there is no good reason to turn this off
2783 my $oldAutoCommit = $FS::UID::AutoCommit;
2784 local $FS::UID::AutoCommit = 0;
2787 my @cust_pkgs = qsearch('cust_pkg', { 'pkgpart' => $param->{'old_pkgpart'} } );
2790 foreach my $old_cust_pkg ( @cust_pkgs ) {
2792 $job->update_statustext(int(100*$i/(scalar @cust_pkgs)));
2793 if ( $old_cust_pkg->getfield('cancel') ) {
2794 warn '[process_bulk_cust_pkg ] skipping canceled pkgnum '.
2795 $old_cust_pkg->pkgnum."\n"
2799 warn '[process_bulk_cust_pkg] changing pkgnum '.$old_cust_pkg->pkgnum."\n"
2801 my $error = $old_cust_pkg->change(
2802 'pkgpart' => $param->{'new_pkgpart'},
2803 'keep_dates' => $keep_dates
2805 if ( !ref($error) ) { # change returns the cust_pkg on success
2807 die "Error changing pkgnum ".$old_cust_pkg->pkgnum.": '$error'\n";
2810 $dbh->commit if $oldAutoCommit;
2816 Returns the last bill date, or if there is no last bill date, the setup date.
2817 Useful for billing metered services.
2823 return $self->setfield('last_bill', $_[0]) if @_;
2824 return $self->getfield('last_bill') if $self->getfield('last_bill');
2825 my $cust_bill_pkg = qsearchs('cust_bill_pkg', { 'pkgnum' => $self->pkgnum,
2826 'edate' => $self->bill, } );
2827 $cust_bill_pkg ? $cust_bill_pkg->sdate : $self->setup || 0;
2830 =item last_cust_pkg_reason ACTION
2832 Returns the most recent ACTION FS::cust_pkg_reason associated with the package.
2833 Returns false if there is no reason or the package is not currenly ACTION'd
2834 ACTION is one of adjourn, susp, cancel, or expire.
2838 sub last_cust_pkg_reason {
2839 my ( $self, $action ) = ( shift, shift );
2840 my $date = $self->get($action);
2842 'table' => 'cust_pkg_reason',
2843 'hashref' => { 'pkgnum' => $self->pkgnum,
2844 'action' => substr(uc($action), 0, 1),
2847 'order_by' => 'ORDER BY num DESC LIMIT 1',
2851 =item last_reason ACTION
2853 Returns the most recent ACTION FS::reason associated with the package.
2854 Returns false if there is no reason or the package is not currenly ACTION'd
2855 ACTION is one of adjourn, susp, cancel, or expire.
2860 my $cust_pkg_reason = shift->last_cust_pkg_reason(@_);
2861 $cust_pkg_reason->reason
2862 if $cust_pkg_reason;
2867 Returns the definition for this billing item, as an FS::part_pkg object (see
2874 return $self->{'_pkgpart'} if $self->{'_pkgpart'};
2875 cluck "cust_pkg->part_pkg called" if $DEBUG > 1;
2876 qsearchs( 'part_pkg', { 'pkgpart' => $self->pkgpart } );
2881 Returns the cancelled package this package was changed from, if any.
2887 return '' unless $self->change_pkgnum;
2888 qsearchs('cust_pkg', { 'pkgnum' => $self->change_pkgnum } );
2891 =item change_cust_main
2893 Returns the customter this package was detached to, if any.
2897 sub change_cust_main {
2899 return '' unless $self->change_custnum;
2900 qsearchs('cust_main', { 'custnum' => $self->change_custnum } );
2905 Calls the I<calc_setup> of the FS::part_pkg object associated with this billing
2912 $self->part_pkg->calc_setup($self, @_);
2917 Calls the I<calc_recur> of the FS::part_pkg object associated with this billing
2924 $self->part_pkg->calc_recur($self, @_);
2929 Calls the I<base_setup> of the FS::part_pkg object associated with this billing
2936 $self->part_pkg->base_setup($self, @_);
2941 Calls the I<base_recur> of the FS::part_pkg object associated with this billing
2948 $self->part_pkg->base_recur($self, @_);
2953 Calls the I<calc_remain> of the FS::part_pkg object associated with this
2960 $self->part_pkg->calc_remain($self, @_);
2965 Calls the I<calc_cancel> of the FS::part_pkg object associated with this
2972 $self->part_pkg->calc_cancel($self, @_);
2977 Returns any invoice line items for this package (see L<FS::cust_bill_pkg>).
2983 qsearch( 'cust_bill_pkg', { 'pkgnum' => $self->pkgnum } );
2986 =item cust_pkg_detail [ DETAILTYPE ]
2988 Returns any customer package details for this package (see
2989 L<FS::cust_pkg_detail>).
2991 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
2995 sub cust_pkg_detail {
2997 my %hash = ( 'pkgnum' => $self->pkgnum );
2998 $hash{detailtype} = shift if @_;
3000 'table' => 'cust_pkg_detail',
3001 'hashref' => \%hash,
3002 'order_by' => 'ORDER BY weight, pkgdetailnum',
3006 =item set_cust_pkg_detail DETAILTYPE [ DETAIL, DETAIL, ... ]
3008 Sets customer package details for this package (see L<FS::cust_pkg_detail>).
3010 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
3012 If there is an error, returns the error, otherwise returns false.
3016 sub set_cust_pkg_detail {
3017 my( $self, $detailtype, @details ) = @_;
3019 my $oldAutoCommit = $FS::UID::AutoCommit;
3020 local $FS::UID::AutoCommit = 0;
3023 foreach my $current ( $self->cust_pkg_detail($detailtype) ) {
3024 my $error = $current->delete;
3026 $dbh->rollback if $oldAutoCommit;
3027 return "error removing old detail: $error";
3031 foreach my $detail ( @details ) {
3032 my $cust_pkg_detail = new FS::cust_pkg_detail {
3033 'pkgnum' => $self->pkgnum,
3034 'detailtype' => $detailtype,
3035 'detail' => $detail,
3037 my $error = $cust_pkg_detail->insert;
3039 $dbh->rollback if $oldAutoCommit;
3040 return "error adding new detail: $error";
3045 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3052 Returns the customer billing events (see L<FS::cust_event>) for this invoice.
3056 #false laziness w/cust_bill.pm
3060 'table' => 'cust_event',
3061 'addl_from' => 'JOIN part_event USING ( eventpart )',
3062 'hashref' => { 'tablenum' => $self->pkgnum },
3063 'extra_sql' => " AND eventtable = 'cust_pkg' ",
3067 =item num_cust_event
3069 Returns the number of customer billing events (see L<FS::cust_event>) for this package.
3073 #false laziness w/cust_bill.pm
3074 sub num_cust_event {
3076 my $sql = "SELECT COUNT(*) ". $self->_from_cust_event_where;
3077 $self->_prep_ex($sql, $self->pkgnum)->fetchrow_arrayref->[0];
3080 =item exists_cust_event
3082 Returns true if there are customer billing events (see L<FS::cust_event>) for this package. More efficient than using num_cust_event.
3086 sub exists_cust_event {
3088 my $sql = "SELECT 1 ". $self->_from_cust_event_where. " LIMIT 1";
3089 my $row = $self->_prep_ex($sql, $self->pkgnum)->fetchrow_arrayref;
3090 $row ? $row->[0] : '';
3093 sub _from_cust_event_where {
3095 " FROM cust_event JOIN part_event USING ( eventpart ) ".
3096 " WHERE tablenum = ? AND eventtable = 'cust_pkg' ";
3100 my( $self, $sql, @args ) = @_;
3101 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
3102 $sth->execute(@args) or die $sth->errstr. " executing $sql";
3106 =item part_pkg_currency_option OPTIONNAME
3108 Returns a two item list consisting of the currency of this customer, if any,
3109 and a value for the provided option. If the customer has a currency, the value
3110 is the option value the given name and the currency (see
3111 L<FS::part_pkg_currency>). Otherwise, if the customer has no currency, is the
3112 regular option value for the given name (see L<FS::part_pkg_option>).
3116 sub part_pkg_currency_option {
3117 my( $self, $optionname ) = @_;
3118 my $part_pkg = $self->part_pkg;
3119 if ( my $currency = $self->cust_main->currency ) {
3120 ($currency, $part_pkg->part_pkg_currency_option($currency, $optionname) );
3122 ('', $part_pkg->option($optionname) );
3126 =item cust_svc [ SVCPART ] (old, deprecated usage)
3128 =item cust_svc [ OPTION => VALUE ... ] (current usage)
3130 =item cust_svc_unsorted [ OPTION => VALUE ... ]
3132 Returns the services for this package, as FS::cust_svc objects (see
3133 L<FS::cust_svc>). Available options are svcpart and svcdb. If either is
3134 spcififed, returns only the matching services.
3136 As an optimization, use the cust_svc_unsorted version if you are not displaying
3143 cluck "cust_pkg->cust_svc called" if $DEBUG > 2;
3144 $self->_sort_cust_svc( $self->cust_svc_unsorted_arrayref(@_) );
3147 sub cust_svc_unsorted {
3149 @{ $self->cust_svc_unsorted_arrayref(@_) };
3152 sub cust_svc_unsorted_arrayref {
3155 return [] unless $self->num_cust_svc(@_);
3158 if ( @_ && $_[0] =~ /^\d+/ ) {
3159 $opt{svcpart} = shift;
3160 } elsif ( @_ && ref($_[0]) eq 'HASH' ) {
3167 'table' => 'cust_svc',
3168 'hashref' => { 'pkgnum' => $self->pkgnum },
3170 if ( $opt{svcpart} ) {
3171 $search{hashref}->{svcpart} = $opt{'svcpart'};
3173 if ( $opt{'svcdb'} ) {
3174 $search{addl_from} = ' LEFT JOIN part_svc USING ( svcpart ) ';
3175 $search{extra_sql} = ' AND svcdb = '. dbh->quote( $opt{'svcdb'} );
3178 [ qsearch(\%search) ];
3182 =item overlimit [ SVCPART ]
3184 Returns the services for this package which have exceeded their
3185 usage limit as FS::cust_svc objects (see L<FS::cust_svc>). If a svcpart
3186 is specified, return only the matching services.
3192 return () unless $self->num_cust_svc(@_);
3193 grep { $_->overlimit } $self->cust_svc(@_);
3196 =item h_cust_svc END_TIMESTAMP [ START_TIMESTAMP ] [ MODE ]
3198 Returns historical services for this package created before END TIMESTAMP and
3199 (optionally) not cancelled before START_TIMESTAMP, as FS::h_cust_svc objects
3200 (see L<FS::h_cust_svc>). If MODE is 'I' (for 'invoice'), services with the
3201 I<pkg_svc.hidden> flag will be omitted.
3207 warn "$me _h_cust_svc called on $self\n"
3210 my ($end, $start, $mode) = @_;
3212 local($FS::Record::qsearch_qualify_columns) = 0;
3214 my @cust_svc = $self->_sort_cust_svc(
3215 [ qsearch( 'h_cust_svc',
3216 { 'pkgnum' => $self->pkgnum, },
3217 FS::h_cust_svc->sql_h_search(@_),
3221 if ( defined($mode) && $mode eq 'I' ) {
3222 my %hidden_svcpart = map { $_->svcpart => $_->hidden } $self->part_svc;
3223 return grep { !$hidden_svcpart{$_->svcpart} } @cust_svc;
3229 sub _sort_cust_svc {
3230 my( $self, $arrayref ) = @_;
3233 sub ($$) { my ($a, $b) = @_; $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] };
3235 my %pkg_svc = map { $_->svcpart => $_ }
3236 qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
3241 my $pkg_svc = $pkg_svc{ $_->svcpart } || '';
3243 $pkg_svc ? $pkg_svc->primary_svc : '',
3244 $pkg_svc ? $pkg_svc->quantity : 0,
3251 =item num_cust_svc [ SVCPART ] (old, deprecated usage)
3253 =item num_cust_svc [ OPTION => VALUE ... ] (current usage)
3255 Returns the number of services for this package. Available options are svcpart
3256 and svcdb. If either is spcififed, returns only the matching services.
3263 return $self->{'_num_cust_svc'}
3265 && exists($self->{'_num_cust_svc'})
3266 && $self->{'_num_cust_svc'} =~ /\d/;
3268 cluck "cust_pkg->num_cust_svc called, _num_cust_svc:".$self->{'_num_cust_svc'}
3272 if ( @_ && $_[0] =~ /^\d+/ ) {
3273 $opt{svcpart} = shift;
3274 } elsif ( @_ && ref($_[0]) eq 'HASH' ) {
3280 my $select = 'SELECT COUNT(*) FROM cust_svc ';
3281 my $where = ' WHERE pkgnum = ? ';
3282 my @param = ($self->pkgnum);
3284 if ( $opt{'svcpart'} ) {
3285 $where .= ' AND svcpart = ? ';
3286 push @param, $opt{'svcpart'};
3288 if ( $opt{'svcdb'} ) {
3289 $select .= ' LEFT JOIN part_svc USING ( svcpart ) ';
3290 $where .= ' AND svcdb = ? ';
3291 push @param, $opt{'svcdb'};
3294 my $sth = dbh->prepare("$select $where") or die dbh->errstr;
3295 $sth->execute(@param) or die $sth->errstr;
3296 $sth->fetchrow_arrayref->[0];
3299 =item available_part_svc
3301 Returns a list of FS::part_svc objects representing services included in this
3302 package but not yet provisioned. Each FS::part_svc object also has an extra
3303 field, I<num_avail>, which specifies the number of available services.
3307 sub available_part_svc {
3310 my $pkg_quantity = $self->quantity || 1;
3312 grep { $_->num_avail > 0 }
3314 my $part_svc = $_->part_svc;
3315 $part_svc->{'Hash'}{'num_avail'} = #evil encapsulation-breaking
3316 $pkg_quantity * $_->quantity - $self->num_cust_svc($_->svcpart);
3318 # more evil encapsulation breakage
3319 if($part_svc->{'Hash'}{'num_avail'} > 0) {
3320 my @exports = $part_svc->part_export_did;
3321 $part_svc->{'Hash'}{'can_get_dids'} = scalar(@exports);
3326 $self->part_pkg->pkg_svc;
3329 =item part_svc [ OPTION => VALUE ... ]
3331 Returns a list of FS::part_svc objects representing provisioned and available
3332 services included in this package. Each FS::part_svc object also has the
3333 following extra fields:
3347 (services) - array reference containing the provisioned services, as cust_svc objects
3351 Accepts two options:
3355 =item summarize_size
3357 If true, will omit the extra cust_pkg_svc option for objects where num_cust_svc
3358 is this size or greater.
3360 =item hide_discontinued
3362 If true, will omit looking for services that are no longer avaialble in the
3370 #label -> ($cust_svc->label)[1]
3376 my $pkg_quantity = $self->quantity || 1;
3378 #XXX some sort of sort order besides numeric by svcpart...
3379 my @part_svc = sort { $a->svcpart <=> $b->svcpart } map {
3381 my $part_svc = $pkg_svc->part_svc;
3382 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
3383 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #more evil
3384 $part_svc->{'Hash'}{'num_avail'} =
3385 max( 0, $pkg_quantity * $pkg_svc->quantity - $num_cust_svc );
3386 $part_svc->{'Hash'}{'cust_pkg_svc'} =
3387 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : []
3388 unless exists($opt{summarize_size}) && $opt{summarize_size} > 0
3389 && $num_cust_svc >= $opt{summarize_size};
3390 $part_svc->{'Hash'}{'hidden'} = $pkg_svc->hidden;
3392 } $self->part_pkg->pkg_svc;
3394 unless ( $opt{hide_discontinued} ) {
3396 push @part_svc, map {
3398 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
3399 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #speak no evail
3400 $part_svc->{'Hash'}{'num_avail'} = 0; #0-$num_cust_svc ?
3401 $part_svc->{'Hash'}{'cust_pkg_svc'} =
3402 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : [];
3404 } $self->extra_part_svc;
3411 =item extra_part_svc
3413 Returns a list of FS::part_svc objects corresponding to services in this
3414 package which are still provisioned but not (any longer) available in the
3419 sub extra_part_svc {
3422 my $pkgnum = $self->pkgnum;
3423 #my $pkgpart = $self->pkgpart;
3426 # 'table' => 'part_svc',
3429 # "WHERE 0 = ( SELECT COUNT(*) FROM pkg_svc
3430 # WHERE pkg_svc.svcpart = part_svc.svcpart
3431 # AND pkg_svc.pkgpart = ?
3434 # AND 0 < ( SELECT COUNT(*) FROM cust_svc
3435 # LEFT JOIN cust_pkg USING ( pkgnum )
3436 # WHERE cust_svc.svcpart = part_svc.svcpart
3439 # 'extra_param' => [ [$self->pkgpart=>'int'], [$self->pkgnum=>'int'] ],
3442 #seems to benchmark slightly faster... (or did?)
3444 my @pkgparts = map $_->pkgpart, $self->part_pkg->self_and_svc_linked;
3445 my $pkgparts = join(',', @pkgparts);
3448 #'select' => 'DISTINCT ON (svcpart) part_svc.*',
3449 #MySQL doesn't grok DISINCT ON
3450 'select' => 'DISTINCT part_svc.*',
3451 'table' => 'part_svc',
3453 "LEFT JOIN pkg_svc ON ( pkg_svc.svcpart = part_svc.svcpart
3454 AND pkg_svc.pkgpart IN ($pkgparts)
3457 LEFT JOIN cust_svc ON ( cust_svc.svcpart = part_svc.svcpart )
3458 LEFT JOIN cust_pkg USING ( pkgnum )
3461 'extra_sql' => "WHERE pkgsvcnum IS NULL AND cust_pkg.pkgnum = ? ",
3462 'extra_param' => [ [$self->pkgnum=>'int'] ],
3468 Returns a short status string for this package, currently:
3474 =item not yet billed
3476 =item one-time charge
3491 my $freq = length($self->freq) ? $self->freq : $self->part_pkg->freq;
3493 return 'cancelled' if $self->get('cancel');
3494 return 'on hold' if $self->susp && ! $self->setup;
3495 return 'suspended' if $self->susp;
3496 return 'not yet billed' unless $self->setup;
3497 return 'one-time charge' if $freq =~ /^(0|$)/;
3501 =item ucfirst_status
3503 Returns the status with the first character capitalized.
3507 sub ucfirst_status {
3508 ucfirst(shift->status);
3513 Class method that returns the list of possible status strings for packages
3514 (see L<the status method|/status>). For example:
3516 @statuses = FS::cust_pkg->statuses();
3520 tie my %statuscolor, 'Tie::IxHash',
3521 'on hold' => 'FF00F5', #brighter purple!
3522 'not yet billed' => '009999', #teal? cyan?
3523 'one-time charge' => '0000CC', #blue #'000000',
3524 'active' => '00CC00',
3525 'suspended' => 'FF9900',
3526 'cancelled' => 'FF0000',
3530 my $self = shift; #could be class...
3531 #grep { $_ !~ /^(not yet billed)$/ } #this is a dumb status anyway
3532 # # mayble split btw one-time vs. recur
3543 Returns a hex triplet color string for this package's status.
3549 $statuscolor{$self->status};
3552 =item is_status_delay_cancel
3554 Returns true if part_pkg has option delay_cancel,
3555 cust_pkg status is 'suspended' and expire is set
3556 to cancel package within the next day (or however
3557 many days are set in global config part_pkg-delay_cancel-days.
3559 Accepts option I<part_pkg-delay_cancel-days> which should be
3560 the value of the config setting, to avoid looking it up again.
3562 This is not a real status, this only meant for hacking display
3563 values, because otherwise treating the package as suspended is
3564 really the whole point of the delay_cancel option.
3568 sub is_status_delay_cancel {
3569 my ($self,%opt) = @_;
3570 if ( $self->main_pkgnum and $self->pkglinknum ) {
3571 return $self->main_pkg->is_status_delay_cancel;
3573 return 0 unless $self->part_pkg->option('delay_cancel',1);
3574 return 0 unless $self->status eq 'suspended';
3575 return 0 unless $self->expire;
3576 my $expdays = $opt{'part_pkg-delay_cancel-days'};
3578 my $conf = new FS::Conf;
3579 $expdays = $conf->config('part_pkg-delay_cancel-days') || 1;
3581 my $expsecs = 60*60*24*$expdays;
3582 return 0 unless $self->expire < time + $expsecs;
3588 Returns a label for this package. (Currently "pkgnum: pkg - comment" or
3589 "pkg - comment" depending on user preference).
3595 my $label = $self->part_pkg->pkg_comment( cust_pkg=>$self, nopkgpart=>1 );
3596 $label = $self->pkgnum. ": $label"
3597 if $FS::CurrentUser::CurrentUser->option('show_pkgnum');
3601 =item pkg_label_long
3603 Returns a long label for this package, adding the primary service's label to
3608 sub pkg_label_long {
3610 my $label = $self->pkg_label;
3611 my $cust_svc = $self->primary_cust_svc;
3612 $label .= ' ('. ($cust_svc->label)[1]. ')' if $cust_svc;
3618 Returns a customer-localized label for this package.
3624 $self->part_pkg->pkg_locale( $self->cust_main->locale );
3627 =item primary_cust_svc
3629 Returns a primary service (as FS::cust_svc object) if one can be identified.
3633 #for labeling purposes - might not 100% match up with part_pkg->svcpart's idea
3635 sub primary_cust_svc {
3638 my @cust_svc = $self->cust_svc;
3640 return '' unless @cust_svc; #no serivces - irrelevant then
3642 return $cust_svc[0] if scalar(@cust_svc) == 1; #always return a single service
3644 # primary service as specified in the package definition
3645 # or exactly one service definition with quantity one
3646 my $svcpart = $self->part_pkg->svcpart;
3647 @cust_svc = grep { $_->svcpart == $svcpart } @cust_svc;
3648 return $cust_svc[0] if scalar(@cust_svc) == 1;
3650 #couldn't identify one thing..
3656 Returns a list of lists, calling the label method for all services
3657 (see L<FS::cust_svc>) of this billing item.
3663 map { [ $_->label ] } $self->cust_svc;
3666 =item h_labels END_TIMESTAMP [ START_TIMESTAMP ] [ MODE ]
3668 Like the labels method, but returns historical information on services that
3669 were active as of END_TIMESTAMP and (optionally) not cancelled before
3670 START_TIMESTAMP. If MODE is 'I' (for 'invoice'), services with the
3671 I<pkg_svc.hidden> flag will be omitted.
3673 Returns a list of lists, calling the label method for all (historical) services
3674 (see L<FS::h_cust_svc>) of this billing item.
3680 warn "$me _h_labels called on $self\n"
3682 map { [ $_->label(@_) ] } $self->h_cust_svc(@_);
3687 Like labels, except returns a simple flat list, and shortens long
3688 (currently >5 or the cust_bill-max_same_services configuration value) lists of
3689 identical services to one line that lists the service label and the number of
3690 individual services rather than individual items.
3695 shift->_labels_short( 'labels', @_ );
3698 =item h_labels_short END_TIMESTAMP [ START_TIMESTAMP ]
3700 Like h_labels, except returns a simple flat list, and shortens long
3701 (currently >5 or the cust_bill-max_same_services configuration value) lists of
3702 identical services to one line that lists the service label and the number of
3703 individual services rather than individual items.
3707 sub h_labels_short {
3708 shift->_labels_short( 'h_labels', @_ );
3712 my( $self, $method ) = ( shift, shift );
3714 warn "$me _labels_short called on $self with $method method\n"
3717 my $conf = new FS::Conf;
3718 my $max_same_services = $conf->config('cust_bill-max_same_services') || 5;
3720 warn "$me _labels_short populating \%labels\n"
3724 #tie %labels, 'Tie::IxHash';
3725 push @{ $labels{$_->[0]} }, $_->[1]
3726 foreach $self->$method(@_);
3728 warn "$me _labels_short populating \@labels\n"
3732 foreach my $label ( keys %labels ) {
3734 my @values = grep { ! $seen{$_}++ } @{ $labels{$label} };
3735 my $num = scalar(@values);
3736 warn "$me _labels_short $num items for $label\n"
3739 if ( $num > $max_same_services ) {
3740 warn "$me _labels_short more than $max_same_services, so summarizing\n"
3742 push @labels, "$label ($num)";
3744 if ( $conf->exists('cust_bill-consolidate_services') ) {
3745 warn "$me _labels_short consolidating services\n"
3747 # push @labels, "$label: ". join(', ', @values);
3749 my $detail = "$label: ";
3750 $detail .= shift(@values). ', '
3752 && ( length($detail.$values[0]) < 78 || $detail eq "$label: " );
3754 push @labels, $detail;
3756 warn "$me _labels_short done consolidating services\n"
3759 warn "$me _labels_short adding service data\n"
3761 push @labels, map { "$label: $_" } @values;
3772 Returns the parent customer object (see L<FS::cust_main>).
3776 Returns the balance for this specific package, when using
3777 experimental package balance.
3783 $self->cust_main->balance_pkgnum( $self->pkgnum );
3786 #these subs are in location_Mixin.pm now... unfortunately the POD doesn't mixin
3790 Returns the location object, if any (see L<FS::cust_location>).
3792 =item cust_location_or_main
3794 If this package is associated with a location, returns the locaiton (see
3795 L<FS::cust_location>), otherwise returns the customer (see L<FS::cust_main>).
3797 =item location_label [ OPTION => VALUE ... ]
3799 Returns the label of the location object (see L<FS::cust_location>).
3803 #end of subs in location_Mixin.pm now... unfortunately the POD doesn't mixin
3805 =item tax_locationnum
3807 Returns the foreign key to a L<FS::cust_location> object for calculating
3808 tax on this package, as determined by the C<tax-pkg_address> and
3809 C<tax-ship_address> configuration flags.
3813 sub tax_locationnum {
3815 my $conf = FS::Conf->new;
3816 if ( $conf->exists('tax-pkg_address') ) {
3817 return $self->locationnum;
3819 elsif ( $conf->exists('tax-ship_address') ) {
3820 return $self->cust_main->ship_locationnum;
3823 return $self->cust_main->bill_locationnum;
3829 Returns the L<FS::cust_location> object for tax_locationnum.
3835 my $conf = FS::Conf->new;
3836 if ( $conf->exists('tax-pkg_address') and $self->locationnum ) {
3837 return FS::cust_location->by_key($self->locationnum);
3839 elsif ( $conf->exists('tax-ship_address') ) {
3840 return $self->cust_main->ship_location;
3843 return $self->cust_main->bill_location;
3847 =item seconds_since TIMESTAMP
3849 Returns the number of seconds all accounts (see L<FS::svc_acct>) in this
3850 package have been online since TIMESTAMP, according to the session monitor.
3852 TIMESTAMP is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
3853 L<Time::Local> and L<Date::Parse> for conversion functions.
3858 my($self, $since) = @_;
3861 foreach my $cust_svc (
3862 grep { $_->part_svc->svcdb eq 'svc_acct' } $self->cust_svc
3864 $seconds += $cust_svc->seconds_since($since);
3871 =item seconds_since_sqlradacct TIMESTAMP_START TIMESTAMP_END
3873 Returns the numbers of seconds all accounts (see L<FS::svc_acct>) in this
3874 package have been online between TIMESTAMP_START (inclusive) and TIMESTAMP_END
3877 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
3878 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
3884 sub seconds_since_sqlradacct {
3885 my($self, $start, $end) = @_;
3889 foreach my $cust_svc (
3891 my $part_svc = $_->part_svc;
3892 $part_svc->svcdb eq 'svc_acct'
3893 && scalar($part_svc->part_export_usage);
3896 $seconds += $cust_svc->seconds_since_sqlradacct($start, $end);
3903 =item attribute_since_sqlradacct TIMESTAMP_START TIMESTAMP_END ATTRIBUTE
3905 Returns the sum of the given attribute for all accounts (see L<FS::svc_acct>)
3906 in this package for sessions ending between TIMESTAMP_START (inclusive) and
3910 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
3911 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
3916 sub attribute_since_sqlradacct {
3917 my($self, $start, $end, $attrib) = @_;
3921 foreach my $cust_svc (
3923 my $part_svc = $_->part_svc;
3924 scalar($part_svc->part_export_usage);
3927 $sum += $cust_svc->attribute_since_sqlradacct($start, $end, $attrib);
3939 my( $self, $value ) = @_;
3940 if ( defined($value) ) {
3941 $self->setfield('quantity', $value);
3943 $self->getfield('quantity') || 1;
3946 =item transfer DEST_PKGNUM | DEST_CUST_PKG, [ OPTION => VALUE ... ]
3948 Transfers as many services as possible from this package to another package.
3950 The destination package can be specified by pkgnum by passing an FS::cust_pkg
3951 object. The destination package must already exist.
3953 Services are moved only if the destination allows services with the correct
3954 I<svcpart> (not svcdb), unless the B<change_svcpart> option is set true. Use
3955 this option with caution! No provision is made for export differences
3956 between the old and new service definitions. Probably only should be used
3957 when your exports for all service definitions of a given svcdb are identical.
3958 (attempt a transfer without it first, to move all possible svcpart-matching
3961 Any services that can't be moved remain in the original package.
3963 Returns an error, if there is one; otherwise, returns the number of services
3964 that couldn't be moved.
3969 my ($self, $dest_pkgnum, %opt) = @_;
3975 if (ref ($dest_pkgnum) eq 'FS::cust_pkg') {
3976 $dest = $dest_pkgnum;
3977 $dest_pkgnum = $dest->pkgnum;
3979 $dest = qsearchs('cust_pkg', { pkgnum => $dest_pkgnum });
3982 return ('Package does not exist: '.$dest_pkgnum) unless $dest;
3984 foreach my $pkg_svc ( $dest->part_pkg->pkg_svc ) {
3985 $target{$pkg_svc->svcpart} = $pkg_svc->quantity * ( $dest->quantity || 1 );
3988 foreach my $cust_svc ($dest->cust_svc) {
3989 $target{$cust_svc->svcpart}--;
3992 my %svcpart2svcparts = ();
3993 if ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
3994 warn "change_svcpart option received, creating alternates list\n" if $DEBUG;
3995 foreach my $svcpart ( map { $_->svcpart } $self->cust_svc ) {
3996 next if exists $svcpart2svcparts{$svcpart};
3997 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
3998 $svcpart2svcparts{$svcpart} = [
4000 sort { $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] }
4002 my $pkg_svc = qsearchs( 'pkg_svc', { 'pkgpart' => $dest->pkgpart,
4003 'svcpart' => $_ } );
4005 $pkg_svc ? $pkg_svc->primary_svc : '',
4006 $pkg_svc ? $pkg_svc->quantity : 0,
4010 grep { $_ != $svcpart }
4012 qsearch('part_svc', { 'svcdb' => $part_svc->svcdb } )
4014 warn "alternates for svcpart $svcpart: ".
4015 join(', ', @{$svcpart2svcparts{$svcpart}}). "\n"
4021 foreach my $cust_svc ($self->cust_svc) {
4022 my $svcnum = $cust_svc->svcnum;
4023 if($target{$cust_svc->svcpart} > 0
4024 or $FS::cust_svc::ignore_quantity) { # maybe should be a 'force' option
4025 $target{$cust_svc->svcpart}--;
4026 my $new = new FS::cust_svc { $cust_svc->hash };
4027 $new->pkgnum($dest_pkgnum);
4028 $error = $new->replace($cust_svc);
4029 } elsif ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
4031 warn "looking for alternates for svcpart ". $cust_svc->svcpart. "\n";
4032 warn "alternates to consider: ".
4033 join(', ', @{$svcpart2svcparts{$cust_svc->svcpart}}). "\n";
4035 my @alternate = grep {
4036 warn "considering alternate svcpart $_: ".
4037 "$target{$_} available in new package\n"
4040 } @{$svcpart2svcparts{$cust_svc->svcpart}};
4042 warn "alternate(s) found\n" if $DEBUG;
4043 my $change_svcpart = $alternate[0];
4044 $target{$change_svcpart}--;
4045 my $new = new FS::cust_svc { $cust_svc->hash };
4046 $new->svcpart($change_svcpart);
4047 $new->pkgnum($dest_pkgnum);
4048 $error = $new->replace($cust_svc);
4056 my @label = $cust_svc->label;
4057 return "$label[0] $label[1]: $error";
4063 =item grab_svcnums SVCNUM, SVCNUM ...
4065 Change the pkgnum for the provided services to this packages. If there is an
4066 error, returns the error, otherwise returns false.
4074 my $oldAutoCommit = $FS::UID::AutoCommit;
4075 local $FS::UID::AutoCommit = 0;
4078 foreach my $svcnum (@svcnum) {
4079 my $cust_svc = qsearchs('cust_svc', { svcnum=>$svcnum } ) or do {
4080 $dbh->rollback if $oldAutoCommit;
4081 return "unknown svcnum $svcnum";
4083 $cust_svc->pkgnum( $self->pkgnum );
4084 my $error = $cust_svc->replace;
4086 $dbh->rollback if $oldAutoCommit;
4091 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4098 This method is deprecated. See the I<depend_jobnum> option to the insert and
4099 order_pkgs methods in FS::cust_main for a better way to defer provisioning.
4103 #looks like this is still used by the order_pkg and change_pkg methods in
4104 # ClientAPI/MyAccount, need to look into those before removing
4108 my $oldAutoCommit = $FS::UID::AutoCommit;
4109 local $FS::UID::AutoCommit = 0;
4112 foreach my $cust_svc ( $self->cust_svc ) {
4113 #false laziness w/svc_Common::insert
4114 my $svc_x = $cust_svc->svc_x;
4115 foreach my $part_export ( $cust_svc->part_svc->part_export ) {
4116 my $error = $part_export->export_insert($svc_x);
4118 $dbh->rollback if $oldAutoCommit;
4124 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4129 =item export_pkg_change OLD_CUST_PKG
4131 Calls the "pkg_change" export action for all services attached to this package.
4135 sub export_pkg_change {
4136 my( $self, $old ) = ( shift, shift );
4138 my $oldAutoCommit = $FS::UID::AutoCommit;
4139 local $FS::UID::AutoCommit = 0;
4142 foreach my $svc_x ( map $_->svc_x, $self->cust_svc ) {
4143 my $error = $svc_x->export('pkg_change', $self, $old);
4145 $dbh->rollback if $oldAutoCommit;
4150 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4157 Associates this package with a (suspension or cancellation) reason (see
4158 L<FS::cust_pkg_reason>, possibly inserting a new reason on the fly (see
4161 Available options are:
4167 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.
4171 the access_user (see L<FS::access_user>) providing the reason
4179 the action (cancel, susp, adjourn, expire) associated with the reason
4183 If there is an error, returns the error, otherwise returns false.
4188 my ($self, %options) = @_;
4190 my $otaker = $options{reason_otaker} ||
4191 $FS::CurrentUser::CurrentUser->username;
4194 if ( $options{'reason'} =~ /^(\d+)$/ ) {
4198 } elsif ( ref($options{'reason'}) ) {
4200 return 'Enter a new reason (or select an existing one)'
4201 unless $options{'reason'}->{'reason'} !~ /^\s*$/;
4203 my $reason = new FS::reason({
4204 'reason_type' => $options{'reason'}->{'typenum'},
4205 'reason' => $options{'reason'}->{'reason'},
4207 my $error = $reason->insert;
4208 return $error if $error;
4210 $reasonnum = $reason->reasonnum;
4213 return "Unparseable reason: ". $options{'reason'};
4216 my $cust_pkg_reason =
4217 new FS::cust_pkg_reason({ 'pkgnum' => $self->pkgnum,
4218 'reasonnum' => $reasonnum,
4219 'otaker' => $otaker,
4220 'action' => substr(uc($options{'action'}),0,1),
4221 'date' => $options{'date'}
4226 $cust_pkg_reason->insert;
4229 =item insert_discount
4231 Associates this package with a discount (see L<FS::cust_pkg_discount>, possibly
4232 inserting a new discount on the fly (see L<FS::discount>).
4234 Available options are:
4242 If there is an error, returns the error, otherwise returns false.
4246 sub insert_discount {
4247 #my ($self, %options) = @_;
4250 my $cust_pkg_discount = new FS::cust_pkg_discount {
4251 'pkgnum' => $self->pkgnum,
4252 'discountnum' => $self->discountnum,
4254 'end_date' => '', #XXX
4255 #for the create a new discount case
4256 '_type' => $self->discountnum__type,
4257 'amount' => $self->discountnum_amount,
4258 'percent' => $self->discountnum_percent,
4259 'months' => $self->discountnum_months,
4260 'setup' => $self->discountnum_setup,
4261 #'disabled' => $self->discountnum_disabled,
4264 $cust_pkg_discount->insert;
4267 =item set_usage USAGE_VALUE_HASHREF
4269 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
4270 to which they should be set (see L<FS::svc_acct>). Currently seconds,
4271 upbytes, downbytes, and totalbytes are appropriate keys.
4273 All svc_accts which are part of this package have their values reset.
4278 my ($self, $valueref, %opt) = @_;
4280 #only svc_acct can set_usage for now
4281 foreach my $cust_svc ( $self->cust_svc( 'svcdb'=>'svc_acct' ) ) {
4282 my $svc_x = $cust_svc->svc_x;
4283 $svc_x->set_usage($valueref, %opt)
4284 if $svc_x->can("set_usage");
4288 =item recharge USAGE_VALUE_HASHREF
4290 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
4291 to which they should be set (see L<FS::svc_acct>). Currently seconds,
4292 upbytes, downbytes, and totalbytes are appropriate keys.
4294 All svc_accts which are part of this package have their values incremented.
4299 my ($self, $valueref) = @_;
4301 #only svc_acct can set_usage for now
4302 foreach my $cust_svc ( $self->cust_svc( 'svcdb'=>'svc_acct' ) ) {
4303 my $svc_x = $cust_svc->svc_x;
4304 $svc_x->recharge($valueref)
4305 if $svc_x->can("recharge");
4309 =item apply_usageprice
4313 sub apply_usageprice {
4316 my $oldAutoCommit = $FS::UID::AutoCommit;
4317 local $FS::UID::AutoCommit = 0;
4322 foreach my $cust_pkg_usageprice ( $self->cust_pkg_usageprice ) {
4323 $error ||= $cust_pkg_usageprice->apply;
4327 $dbh->rollback if $oldAutoCommit;
4328 die "error applying part_pkg_usageprice add-ons, pkgnum ". $self->pkgnum.
4331 $dbh->commit if $oldAutoCommit;
4337 =item cust_pkg_discount
4339 =item cust_pkg_discount_active
4343 sub cust_pkg_discount_active {
4345 grep { $_->status eq 'active' } $self->cust_pkg_discount;
4348 =item cust_pkg_usage
4350 Returns a list of all voice usage counters attached to this package.
4352 =item apply_usage OPTIONS
4354 Takes the following options:
4355 - cdr: a call detail record (L<FS::cdr>)
4356 - rate_detail: the rate determined for this call (L<FS::rate_detail>)
4357 - minutes: the maximum number of minutes to be charged
4359 Finds available usage minutes for a call of this class, and subtracts
4360 up to that many minutes from the usage pool. If the usage pool is empty,
4361 and the C<cdr-minutes_priority> global config option is set, minutes may
4362 be taken from other calls as well. Either way, an allocation record will
4363 be created (L<FS::cdr_cust_pkg_usage>) and this method will return the
4364 number of minutes of usage applied to the call.
4369 my ($self, %opt) = @_;
4370 my $cdr = $opt{cdr};
4371 my $rate_detail = $opt{rate_detail};
4372 my $minutes = $opt{minutes};
4373 my $classnum = $rate_detail->classnum;
4374 my $pkgnum = $self->pkgnum;
4375 my $custnum = $self->custnum;
4377 my $oldAutoCommit = $FS::UID::AutoCommit;
4378 local $FS::UID::AutoCommit = 0;
4381 my $order = FS::Conf->new->config('cdr-minutes_priority');
4385 $is_classnum = ' part_pkg_usage_class.classnum = '.$classnum;
4387 $is_classnum = ' part_pkg_usage_class.classnum IS NULL';
4389 my @usage_recs = qsearch({
4390 'table' => 'cust_pkg_usage',
4391 'addl_from' => ' JOIN part_pkg_usage USING (pkgusagepart)'.
4392 ' JOIN cust_pkg USING (pkgnum)'.
4393 ' JOIN part_pkg_usage_class USING (pkgusagepart)',
4394 'select' => 'cust_pkg_usage.*',
4395 'extra_sql' => " WHERE ( cust_pkg.pkgnum = $pkgnum OR ".
4396 " ( cust_pkg.custnum = $custnum AND ".
4397 " part_pkg_usage.shared IS NOT NULL ) ) AND ".
4398 $is_classnum . ' AND '.
4399 " cust_pkg_usage.minutes > 0",
4400 'order_by' => " ORDER BY priority ASC",
4403 my $orig_minutes = $minutes;
4405 while (!$error and $minutes > 0 and @usage_recs) {
4406 my $cust_pkg_usage = shift @usage_recs;
4407 $cust_pkg_usage->select_for_update;
4408 my $cdr_cust_pkg_usage = FS::cdr_cust_pkg_usage->new({
4409 pkgusagenum => $cust_pkg_usage->pkgusagenum,
4410 acctid => $cdr->acctid,
4411 minutes => min($cust_pkg_usage->minutes, $minutes),
4413 $cust_pkg_usage->set('minutes',
4414 $cust_pkg_usage->minutes - $cdr_cust_pkg_usage->minutes
4416 $error = $cust_pkg_usage->replace || $cdr_cust_pkg_usage->insert;
4417 $minutes -= $cdr_cust_pkg_usage->minutes;
4419 if ( $order and $minutes > 0 and !$error ) {
4420 # then try to steal minutes from another call
4422 'table' => 'cdr_cust_pkg_usage',
4423 'addl_from' => ' JOIN cust_pkg_usage USING (pkgusagenum)'.
4424 ' JOIN part_pkg_usage USING (pkgusagepart)'.
4425 ' JOIN cust_pkg USING (pkgnum)'.
4426 ' JOIN part_pkg_usage_class USING (pkgusagepart)'.
4427 ' JOIN cdr USING (acctid)',
4428 'select' => 'cdr_cust_pkg_usage.*',
4429 'extra_sql' => " WHERE cdr.freesidestatus = 'rated' AND ".
4430 " ( cust_pkg.pkgnum = $pkgnum OR ".
4431 " ( cust_pkg.custnum = $custnum AND ".
4432 " part_pkg_usage.shared IS NOT NULL ) ) AND ".
4433 " part_pkg_usage_class.classnum = $classnum",
4434 'order_by' => ' ORDER BY part_pkg_usage.priority ASC',
4436 if ( $order eq 'time' ) {
4437 # find CDRs that are using minutes, but have a later startdate
4439 my $startdate = $cdr->startdate;
4440 if ($startdate !~ /^\d+$/) {
4441 die "bad cdr startdate '$startdate'";
4443 $search{'extra_sql'} .= " AND cdr.startdate > $startdate";
4444 # minimize needless reshuffling
4445 $search{'order_by'} .= ', cdr.startdate DESC';
4447 # XXX may not work correctly with rate_time schedules. Could
4448 # fix this by storing ratedetailnum in cdr_cust_pkg_usage, I
4450 $search{'addl_from'} .=
4451 ' JOIN rate_detail'.
4452 ' ON (cdr.rated_ratedetailnum = rate_detail.ratedetailnum)';
4453 if ( $order eq 'rate_high' ) {
4454 $search{'extra_sql'} .= ' AND rate_detail.min_charge < '.
4455 $rate_detail->min_charge;
4456 $search{'order_by'} .= ', rate_detail.min_charge ASC';
4457 } elsif ( $order eq 'rate_low' ) {
4458 $search{'extra_sql'} .= ' AND rate_detail.min_charge > '.
4459 $rate_detail->min_charge;
4460 $search{'order_by'} .= ', rate_detail.min_charge DESC';
4462 # this should really never happen
4463 die "invalid cdr-minutes_priority value '$order'\n";
4466 my @cdr_usage_recs = qsearch(\%search);
4468 while (!$error and @cdr_usage_recs and $minutes > 0) {
4469 my $cdr_cust_pkg_usage = shift @cdr_usage_recs;
4470 my $cust_pkg_usage = $cdr_cust_pkg_usage->cust_pkg_usage;
4471 my $old_cdr = $cdr_cust_pkg_usage->cdr;
4472 $reproc_cdrs{$old_cdr->acctid} = $old_cdr;
4473 $cdr_cust_pkg_usage->select_for_update;
4474 $old_cdr->select_for_update;
4475 $cust_pkg_usage->select_for_update;
4476 # in case someone else stole the usage from this CDR
4477 # while waiting for the lock...
4478 next if $old_cdr->acctid != $cdr_cust_pkg_usage->acctid;
4479 # steal the usage allocation and flag the old CDR for reprocessing
4480 $cdr_cust_pkg_usage->set('acctid', $cdr->acctid);
4481 # if the allocation is more minutes than we need, adjust it...
4482 my $delta = $cdr_cust_pkg_usage->minutes - $minutes;
4484 $cdr_cust_pkg_usage->set('minutes', $minutes);
4485 $cust_pkg_usage->set('minutes', $cust_pkg_usage->minutes + $delta);
4486 $error = $cust_pkg_usage->replace;
4488 #warn 'CDR '.$cdr->acctid . ' stealing allocation '.$cdr_cust_pkg_usage->cdrusagenum.' from CDR '.$old_cdr->acctid."\n";
4489 $error ||= $cdr_cust_pkg_usage->replace;
4490 # deduct the stolen minutes
4491 $minutes -= $cdr_cust_pkg_usage->minutes;
4493 # after all minute-stealing is done, reset the affected CDRs
4494 foreach (values %reproc_cdrs) {
4495 $error ||= $_->set_status('');
4496 # XXX or should we just call $cdr->rate right here?
4497 # it's not like we can create a loop this way, since the min_charge
4498 # or call time has to go monotonically in one direction.
4499 # we COULD get some very deep recursions going, though...
4501 } # if $order and $minutes
4504 die "error applying included minutes\npkgnum ".$self->pkgnum.", class $classnum, acctid ".$cdr->acctid."\n$error\n"
4506 $dbh->commit if $oldAutoCommit;
4507 return $orig_minutes - $minutes;
4511 =item supplemental_pkgs
4513 Returns a list of all packages supplemental to this one.
4517 sub supplemental_pkgs {
4519 qsearch('cust_pkg', { 'main_pkgnum' => $self->pkgnum });
4524 Returns the package that this one is supplemental to, if any.
4530 if ( $self->main_pkgnum ) {
4531 return FS::cust_pkg->by_key($self->main_pkgnum);
4538 =head1 CLASS METHODS
4544 Returns an SQL expression identifying recurring packages.
4548 sub recurring_sql { "
4549 '0' != ( select freq from part_pkg
4550 where cust_pkg.pkgpart = part_pkg.pkgpart )
4555 Returns an SQL expression identifying one-time packages.
4560 '0' = ( select freq from part_pkg
4561 where cust_pkg.pkgpart = part_pkg.pkgpart )
4566 Returns an SQL expression identifying ordered packages (recurring packages not
4572 $_[0]->recurring_sql. " AND ". $_[0]->not_yet_billed_sql;
4577 Returns an SQL expression identifying active packages.
4582 $_[0]->recurring_sql. "
4583 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
4584 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4585 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
4588 =item not_yet_billed_sql
4590 Returns an SQL expression identifying packages which have not yet been billed.
4594 sub not_yet_billed_sql { "
4595 ( cust_pkg.setup IS NULL OR cust_pkg.setup = 0 )
4596 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4597 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
4602 Returns an SQL expression identifying inactive packages (one-time packages
4603 that are otherwise unsuspended/uncancelled).
4607 sub inactive_sql { "
4608 ". $_[0]->onetime_sql(). "
4609 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
4610 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4611 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
4616 Returns an SQL expression identifying on-hold packages.
4621 #$_[0]->recurring_sql(). ' AND '.
4623 ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4624 AND cust_pkg.susp IS NOT NULL AND cust_pkg.susp != 0
4625 AND ( cust_pkg.setup IS NULL OR cust_pkg.setup = 0 )
4632 Returns an SQL expression identifying suspended packages.
4636 sub suspended_sql { susp_sql(@_); }
4638 #$_[0]->recurring_sql(). ' AND '.
4640 ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4641 AND cust_pkg.susp IS NOT NULL AND cust_pkg.susp != 0
4642 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
4649 Returns an SQL exprression identifying cancelled packages.
4653 sub cancelled_sql { cancel_sql(@_); }
4655 #$_[0]->recurring_sql(). ' AND '.
4656 "cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0";
4661 Returns an SQL expression to give the package status as a string.
4667 WHEN cust_pkg.cancel IS NOT NULL THEN 'cancelled'
4668 WHEN ( cust_pkg.susp IS NOT NULL AND cust_pkg.setup IS NULL ) THEN 'on hold'
4669 WHEN cust_pkg.susp IS NOT NULL THEN 'suspended'
4670 WHEN cust_pkg.setup IS NULL THEN 'not yet billed'
4671 WHEN ".onetime_sql()." THEN 'one-time charge'
4678 Returns a list of two package counts. The first is a count of packages
4679 based on the supplied criteria and the second is the count of residential
4680 packages with those same criteria. Criteria are specified as in the search
4686 my ($class, $params) = @_;
4688 my $sql_query = $class->search( $params );
4690 my $count_sql = delete($sql_query->{'count_query'});
4691 $count_sql =~ s/ FROM/,count(CASE WHEN cust_main.company IS NULL OR cust_main.company = '' THEN 1 END) FROM/
4692 or die "couldn't parse count_sql";
4694 my $count_sth = dbh->prepare($count_sql)
4695 or die "Error preparing $count_sql: ". dbh->errstr;
4697 or die "Error executing $count_sql: ". $count_sth->errstr;
4698 my $count_arrayref = $count_sth->fetchrow_arrayref;
4700 return ( @$count_arrayref );
4704 =item tax_locationnum_sql
4706 Returns an SQL expression for the tax location for a package, based
4707 on the settings of 'tax-pkg_address' and 'tax-ship_address'.
4711 sub tax_locationnum_sql {
4712 my $conf = FS::Conf->new;
4713 if ( $conf->exists('tax-pkg_address') ) {
4714 'cust_pkg.locationnum';
4716 elsif ( $conf->exists('tax-ship_address') ) {
4717 'cust_main.ship_locationnum';
4720 'cust_main.bill_locationnum';
4726 Returns a list: the first item is an SQL fragment identifying matching
4727 packages/customers via location (taking into account shipping and package
4728 address taxation, if enabled), and subsequent items are the parameters to
4729 substitute for the placeholders in that fragment.
4734 my($class, %opt) = @_;
4735 my $ornull = $opt{'ornull'};
4737 my $conf = new FS::Conf;
4739 # '?' placeholders in _location_sql_where
4740 my $x = $ornull ? 3 : 2;
4751 if ( $conf->exists('tax-ship_address') ) {
4754 ( ( ship_last IS NULL OR ship_last = '' )
4755 AND ". _location_sql_where('cust_main', '', $ornull ). "
4757 OR ( ship_last IS NOT NULL AND ship_last != ''
4758 AND ". _location_sql_where('cust_main', 'ship_', $ornull ). "
4761 # AND payby != 'COMP'
4763 @main_param = ( @bill_param, @bill_param );
4767 $main_where = _location_sql_where('cust_main'); # AND payby != 'COMP'
4768 @main_param = @bill_param;
4774 if ( $conf->exists('tax-pkg_address') ) {
4776 my $loc_where = _location_sql_where( 'cust_location', '', $ornull );
4779 ( cust_pkg.locationnum IS NULL AND $main_where )
4780 OR ( cust_pkg.locationnum IS NOT NULL AND $loc_where )
4783 @param = ( @main_param, @bill_param );
4787 $where = $main_where;
4788 @param = @main_param;
4796 #subroutine, helper for location_sql
4797 sub _location_sql_where {
4799 my $prefix = @_ ? shift : '';
4800 my $ornull = @_ ? shift : '';
4802 # $ornull = $ornull ? " OR ( ? IS NULL AND $table.${prefix}county IS NULL ) " : '';
4804 $ornull = $ornull ? ' OR ? IS NULL ' : '';
4806 my $or_empty_city = " OR ( ? = '' AND $table.${prefix}city IS NULL )";
4807 my $or_empty_county = " OR ( ? = '' AND $table.${prefix}county IS NULL )";
4808 my $or_empty_state = " OR ( ? = '' AND $table.${prefix}state IS NULL )";
4810 my $text = (driver_name =~ /^mysql/i) ? 'char' : 'text';
4812 # ( $table.${prefix}city = ? $or_empty_city $ornull )
4814 ( $table.district = ? OR ? = '' OR CAST(? AS $text) IS NULL )
4815 AND ( $table.${prefix}city = ? OR ? = '' OR CAST(? AS $text) IS NULL )
4816 AND ( $table.${prefix}county = ? $or_empty_county $ornull )
4817 AND ( $table.${prefix}state = ? $or_empty_state $ornull )
4818 AND $table.${prefix}country = ?
4823 my( $self, $what ) = @_;
4825 my $what_show_zero = $what. '_show_zero';
4826 length($self->$what_show_zero())
4827 ? ($self->$what_show_zero() eq 'Y')
4828 : $self->part_pkg->$what_show_zero();
4835 =item order CUSTNUM, PKGPARTS_ARYREF, [ REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF [ REFNUM ] ] ]
4837 Bulk cancel + order subroutine. Perhaps slightly deprecated, only used by the
4838 bulk cancel+order in the web UI and nowhere else (edit/process/cust_pkg.cgi)
4840 CUSTNUM is a customer (see L<FS::cust_main>)
4842 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
4843 L<FS::part_pkg>) to order for this customer. Duplicates are of course
4846 REMOVE_PKGNUMS is an optional list of pkgnums specifying the billing items to
4847 remove for this customer. The services (see L<FS::cust_svc>) are moved to the
4848 new billing items. An error is returned if this is not possible (see
4849 L<FS::pkg_svc>). An empty arrayref is equivalent to not specifying this
4852 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
4853 newly-created cust_pkg objects.
4855 REFNUM, if specified, will specify the FS::pkg_referral record to be created
4856 and inserted. Multiple FS::pkg_referral records can be created by
4857 setting I<refnum> to an array reference of refnums or a hash reference with
4858 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
4859 record will be created corresponding to cust_main.refnum.
4864 my ($custnum, $pkgparts, $remove_pkgnum, $return_cust_pkg, $refnum) = @_;
4866 my $conf = new FS::Conf;
4868 # Transactionize this whole mess
4869 my $oldAutoCommit = $FS::UID::AutoCommit;
4870 local $FS::UID::AutoCommit = 0;
4874 # my $cust_main = qsearchs('cust_main', { custnum => $custnum });
4875 # return "Customer not found: $custnum" unless $cust_main;
4877 warn "$me order: pkgnums to remove: ". join(',', @$remove_pkgnum). "\n"
4880 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
4883 my $change = scalar(@old_cust_pkg) != 0;
4886 if ( scalar(@old_cust_pkg) == 1 && scalar(@$pkgparts) == 1 ) {
4888 warn "$me order: changing pkgnum ". $old_cust_pkg[0]->pkgnum.
4889 " to pkgpart ". $pkgparts->[0]. "\n"
4892 my $err_or_cust_pkg =
4893 $old_cust_pkg[0]->change( 'pkgpart' => $pkgparts->[0],
4894 'refnum' => $refnum,
4897 unless (ref($err_or_cust_pkg)) {
4898 $dbh->rollback if $oldAutoCommit;
4899 return $err_or_cust_pkg;
4902 push @$return_cust_pkg, $err_or_cust_pkg;
4903 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4908 # Create the new packages.
4909 foreach my $pkgpart (@$pkgparts) {
4911 warn "$me order: inserting pkgpart $pkgpart\n" if $DEBUG;
4913 my $cust_pkg = new FS::cust_pkg { custnum => $custnum,
4914 pkgpart => $pkgpart,
4918 $error = $cust_pkg->insert( 'change' => $change );
4919 push @$return_cust_pkg, $cust_pkg;
4921 foreach my $link ($cust_pkg->part_pkg->supp_part_pkg_link) {
4922 my $supp_pkg = FS::cust_pkg->new({
4923 custnum => $custnum,
4924 pkgpart => $link->dst_pkgpart,
4926 main_pkgnum => $cust_pkg->pkgnum,
4929 $error ||= $supp_pkg->insert( 'change' => $change );
4930 push @$return_cust_pkg, $supp_pkg;
4934 $dbh->rollback if $oldAutoCommit;
4939 # $return_cust_pkg now contains refs to all of the newly
4942 # Transfer services and cancel old packages.
4943 foreach my $old_pkg (@old_cust_pkg) {
4945 warn "$me order: transferring services from pkgnum ". $old_pkg->pkgnum. "\n"
4948 foreach my $new_pkg (@$return_cust_pkg) {
4949 $error = $old_pkg->transfer($new_pkg);
4950 if ($error and $error == 0) {
4951 # $old_pkg->transfer failed.
4952 $dbh->rollback if $oldAutoCommit;
4957 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
4958 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
4959 foreach my $new_pkg (@$return_cust_pkg) {
4960 $error = $old_pkg->transfer($new_pkg, 'change_svcpart'=>1 );
4961 if ($error and $error == 0) {
4962 # $old_pkg->transfer failed.
4963 $dbh->rollback if $oldAutoCommit;
4970 # Transfers were successful, but we went through all of the
4971 # new packages and still had services left on the old package.
4972 # We can't cancel the package under the circumstances, so abort.
4973 $dbh->rollback if $oldAutoCommit;
4974 return "Unable to transfer all services from package ".$old_pkg->pkgnum;
4976 $error = $old_pkg->cancel( quiet=>1, 'no_delay_cancel'=>1 );
4982 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4986 =item bulk_change PKGPARTS_ARYREF, REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF ]
4988 A bulk change method to change packages for multiple customers.
4990 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
4991 L<FS::part_pkg>) to order for each customer. Duplicates are of course
4994 REMOVE_PKGNUMS is an list of pkgnums specifying the billing items to
4995 replace. The services (see L<FS::cust_svc>) are moved to the
4996 new billing items. An error is returned if this is not possible (see
4999 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
5000 newly-created cust_pkg objects.
5005 my ($pkgparts, $remove_pkgnum, $return_cust_pkg) = @_;
5007 # Transactionize this whole mess
5008 my $oldAutoCommit = $FS::UID::AutoCommit;
5009 local $FS::UID::AutoCommit = 0;
5013 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
5016 while(scalar(@old_cust_pkg)) {
5018 my $custnum = $old_cust_pkg[0]->custnum;
5019 my (@remove) = map { $_->pkgnum }
5020 grep { $_->custnum == $custnum } @old_cust_pkg;
5021 @old_cust_pkg = grep { $_->custnum != $custnum } @old_cust_pkg;
5023 my $error = order $custnum, $pkgparts, \@remove, \@return;
5025 push @errors, $error
5027 push @$return_cust_pkg, @return;
5030 if (scalar(@errors)) {
5031 $dbh->rollback if $oldAutoCommit;
5032 return join(' / ', @errors);
5035 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5039 =item forward_emails
5041 Returns a hash of svcnums and corresponding email addresses
5042 for svc_acct services that can be used as source or dest
5043 for svc_forward services provisioned in this package.
5045 Accepts options I<svc_forward> OR I<svcnum> for a svc_forward
5046 service; if included, will ensure the current values of the
5047 specified service are included in the list, even if for some
5048 other reason they wouldn't be. If called as a class method
5049 with a specified service, returns only these current values.
5051 Caution: does not actually check if svc_forward services are
5052 available to be provisioned on this package.
5056 sub forward_emails {
5060 #load optional service, thoroughly validated
5061 die "Use svcnum or svc_forward, not both"
5062 if $opt{'svcnum'} && $opt{'svc_forward'};
5063 my $svc_forward = $opt{'svc_forward'};
5064 $svc_forward ||= qsearchs('svc_forward',{ 'svcnum' => $opt{'svcnum'} })
5066 die "Specified service is not a forward service"
5067 if $svc_forward && (ref($svc_forward) ne 'FS::svc_forward');
5068 die "Specified service not found"
5069 if ($opt{'svcnum'} || $opt{'svc_forward'}) && !$svc_forward;
5073 ## everything below was basically copied from httemplate/edit/svc_forward.cgi
5074 ## with minimal refactoring, not sure why we can't just load all svc_accts for this custnum
5076 #add current values from specified service, if there was one
5078 foreach my $method (qw( srcsvc_acct dstsvc_acct )) {
5079 my $svc_acct = $svc_forward->$method();
5080 $email{$svc_acct->svcnum} = $svc_acct->email if $svc_acct;
5084 if (ref($self) eq 'FS::cust_pkg') {
5086 #and including the rest for this customer
5087 my($u_part_svc,@u_acct_svcparts);
5088 foreach $u_part_svc ( qsearch('part_svc',{'svcdb'=>'svc_acct'}) ) {
5089 push @u_acct_svcparts,$u_part_svc->getfield('svcpart');
5092 my $custnum = $self->getfield('custnum');
5093 foreach my $i_cust_pkg ( qsearch('cust_pkg',{'custnum'=>$custnum}) ) {
5094 my $cust_pkgnum = $i_cust_pkg->getfield('pkgnum');
5095 #now find the corresponding record(s) in cust_svc (for this pkgnum!)
5096 foreach my $acct_svcpart (@u_acct_svcparts) {
5097 foreach my $i_cust_svc (
5098 qsearch( 'cust_svc', { 'pkgnum' => $cust_pkgnum,
5099 'svcpart' => $acct_svcpart } )
5101 my $svc_acct = qsearchs( 'svc_acct', { 'svcnum' => $i_cust_svc->svcnum } );
5102 $email{$svc_acct->svcnum} = $svc_acct->email;
5111 # Used by FS::Upgrade to migrate to a new database.
5112 sub _upgrade_data { # class method
5113 my ($class, %opts) = @_;
5114 $class->_upgrade_otaker(%opts);
5116 # RT#10139, bug resulting in contract_end being set when it shouldn't
5117 'UPDATE cust_pkg SET contract_end = NULL WHERE contract_end = -1',
5118 # RT#10830, bad calculation of prorate date near end of year
5119 # the date range for bill is December 2009, and we move it forward
5120 # one year if it's before the previous bill date (which it should
5122 'UPDATE cust_pkg SET bill = bill + (365*24*60*60) WHERE bill < last_bill
5123 AND bill > 1259654400 AND bill < 1262332800 AND (SELECT plan FROM part_pkg
5124 WHERE part_pkg.pkgpart = cust_pkg.pkgpart) = \'prorate\'',
5125 # RT6628, add order_date to cust_pkg
5126 'update cust_pkg set order_date = (select history_date from h_cust_pkg
5127 where h_cust_pkg.pkgnum = cust_pkg.pkgnum and
5128 history_action = \'insert\') where order_date is null',
5130 foreach my $sql (@statements) {
5131 my $sth = dbh->prepare($sql);
5132 $sth->execute or die $sth->errstr;
5135 # RT31194: supplemental package links that are deleted don't clean up
5137 my @pkglinknums = qsearch({
5138 'select' => 'DISTINCT cust_pkg.pkglinknum',
5139 'table' => 'cust_pkg',
5140 'addl_from' => ' LEFT JOIN part_pkg_link USING (pkglinknum) ',
5141 'extra_sql' => ' WHERE cust_pkg.pkglinknum IS NOT NULL
5142 AND part_pkg_link.pkglinknum IS NULL',
5144 foreach (@pkglinknums) {
5145 my $pkglinknum = $_->pkglinknum;
5146 warn "cleaning part_pkg_link #$pkglinknum\n";
5147 my $part_pkg_link = FS::part_pkg_link->new({pkglinknum => $pkglinknum});
5148 my $error = $part_pkg_link->remove_linked;
5149 die $error if $error;
5157 sub order is not OO. Perhaps it should be moved to FS::cust_main and made so?
5159 In sub order, the @pkgparts array (passed by reference) is clobbered.
5161 Also in sub order, no money is adjusted. Once FS::part_pkg defines a standard
5162 method to pass dates to the recur_prog expression, it should do so.
5164 FS::svc_acct, FS::svc_domain, FS::svc_www, FS::svc_ip and FS::svc_forward are
5165 loaded via 'use' at compile time, rather than via 'require' in sub { setup,
5166 suspend, unsuspend, cancel } because they use %FS::UID::callback to load
5167 configuration values. Probably need a subroutine which decides what to do
5168 based on whether or not we've fetched the user yet, rather than a hash. See
5169 FS::UID and the TODO.
5171 Now that things are transactional should the check in the insert method be
5176 L<FS::Record>, L<FS::cust_main>, L<FS::part_pkg>, L<FS::cust_svc>,
5177 L<FS::pkg_svc>, schema.html from the base documentation