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::Record qw( qsearch qsearchs fields );
22 use FS::cust_location;
24 use FS::cust_bill_pkg;
25 use FS::cust_pkg_detail;
26 use FS::cust_pkg_usage;
27 use FS::cdr_cust_pkg_usage;
32 use FS::cust_pkg_reason;
34 use FS::cust_pkg_usageprice;
35 use FS::cust_pkg_discount;
41 # temporary fix; remove this once (un)suspend admin notices are cleaned up
42 use FS::Misc qw(send_email);
44 # need to 'use' these instead of 'require' in sub { cancel, suspend, unsuspend,
46 # because they load configuration by setting FS::UID::callback (see TODO)
52 # for sending cancel emails in sub cancel
55 our ($disable_agentcheck, $DEBUG, $me, $import) = (0, 0, '[FS::cust_pkg]', 0);
57 our $upgrade = 0; #go away after setup+start dates cleaned up for old customers
60 my( $self, $hashref ) = @_;
61 if ( $hashref->{'pkg'} ) {
62 $self->{'_pkgpart'} = FS::part_pkg->new($hashref);
68 my ( $hashref, $cache ) = @_;
69 # #if ( $hashref->{'pkgpart'} ) {
70 # if ( $hashref->{'pkg'} ) {
71 # # #@{ $self->{'_pkgnum'} } = ();
72 # # my $subcache = $cache->subcache('pkgpart', 'part_pkg');
73 # # $self->{'_pkgpart'} = $subcache;
74 # # #push @{ $self->{'_pkgnum'} },
75 # # FS::part_pkg->new_or_cached($hashref, $subcache);
76 # $self->{'_pkgpart'} = FS::part_pkg->new($hashref);
78 if ( exists $hashref->{'svcnum'} ) {
79 #@{ $self->{'_pkgnum'} } = ();
80 my $subcache = $cache->subcache('svcnum', 'cust_svc', $hashref->{pkgnum});
81 $self->{'_svcnum'} = $subcache;
82 #push @{ $self->{'_pkgnum'} },
83 FS::cust_svc->new_or_cached($hashref, $subcache) if $hashref->{svcnum};
89 FS::cust_pkg - Object methods for cust_pkg objects
95 $record = new FS::cust_pkg \%hash;
96 $record = new FS::cust_pkg { 'column' => 'value' };
98 $error = $record->insert;
100 $error = $new_record->replace($old_record);
102 $error = $record->delete;
104 $error = $record->check;
106 $error = $record->cancel;
108 $error = $record->suspend;
110 $error = $record->unsuspend;
112 $part_pkg = $record->part_pkg;
114 @labels = $record->labels;
116 $seconds = $record->seconds_since($timestamp);
118 #bulk cancel+order... perhaps slightly deprecated, only used by the bulk
119 # cancel+order in the web UI and nowhere else (edit/process/cust_pkg.cgi)
120 $error = FS::cust_pkg::order( $custnum, \@pkgparts );
121 $error = FS::cust_pkg::order( $custnum, \@pkgparts, \@remove_pkgnums ] );
125 An FS::cust_pkg object represents a customer billing item. FS::cust_pkg
126 inherits from FS::Record. The following fields are currently supported:
132 Primary key (assigned automatically for new billing items)
136 Customer (see L<FS::cust_main>)
140 Billing item definition (see L<FS::part_pkg>)
144 Optional link to package location (see L<FS::location>)
148 date package was ordered (also remains same on changes)
160 date (next bill date)
188 order taker (see L<FS::access_user>)
192 If this field is set to 1, disables the automatic
193 unsuspension of this package when using the B<unsuspendauto> config option.
197 If not set, defaults to 1
201 Date of change from previous package
211 =item change_locationnum
219 The pkgnum of the package that this package is supplemental to, if any.
223 The package link (L<FS::part_pkg_link>) that defines this supplemental
224 package, if it is one.
226 =item change_to_pkgnum
228 The pkgnum of the package this one will be "changed to" in the future
229 (on its expiration date).
233 Note: setup, last_bill, bill, adjourn, susp, expire, cancel and change_date
234 are specified as UNIX timestamps; see L<perlfunc/"time">. Also see
235 L<Time::Local> and L<Date::Parse> for conversion functions.
243 Create a new billing item. To add the item to the database, see L<"insert">.
247 sub table { 'cust_pkg'; }
248 sub cust_linked { $_[0]->cust_main_custnum || $_[0]->custnum }
249 sub cust_unlinked_msg {
251 "WARNING: can't find cust_main.custnum ". $self->custnum.
252 ' (cust_pkg.pkgnum '. $self->pkgnum. ')';
255 =item set_initial_timers
257 If required by the package definition, sets any automatic expire, adjourn,
258 or contract_end timers to some number of months after the start date
259 (or setup date, if the package has already been setup). If the package has
260 a delayed setup fee after a period of "free days", will also set the
261 start date to the end of that period.
263 If the package has an automatic transfer rule (C<change_to_pkgnum>), then
264 this will also order the package and set its start date.
268 sub set_initial_timers {
270 my $part_pkg = $self->part_pkg;
271 my $start = $self->start_date || $self->setup || time;
273 foreach my $action ( qw(expire adjourn contract_end) ) {
274 my $months = $part_pkg->get("${action}_months");
275 if($months and !$self->get($action)) {
276 $self->set($action, $part_pkg->add_freq($start, $months) );
280 # if this package has an expire date and a change_to_pkgpart, set automatic
282 # (but don't call change_later, as that would call $self->replace, and we're
283 # probably in the middle of $self->insert right now)
284 if ( $part_pkg->expire_months and $part_pkg->change_to_pkgpart ) {
285 if ( $self->change_to_pkgnum ) {
286 # this can happen if a package is ordered on hold, scheduled for a
287 # future change _while on hold_, and then released from hold, causing
288 # the automatic transfer to schedule.
290 # what's correct behavior in that case? I think it's to disallow
291 # future-changing an on-hold package that has an automatic transfer.
292 # but if we DO get into this situation, let the manual package change
294 warn "pkgnum ".$self->pkgnum.": manual future package change blocks ".
295 "automatic transfer.\n";
297 my $change_to = FS::cust_pkg->new( {
298 start_date => $self->get('expire'),
299 pkgpart => $part_pkg->change_to_pkgpart,
300 map { $_ => $self->get($_) }
301 qw( custnum locationnum quantity refnum salesnum contract_end )
303 my $error = $change_to->insert;
305 return $error if $error;
306 $self->set('change_to_pkgnum', $change_to->pkgnum);
310 # if this package has "free days" and delayed setup fee, then
311 # set start date that many days in the future.
312 # (this should have been set in the UI, but enforce it here)
313 if ( $part_pkg->option('free_days',1)
314 && $part_pkg->option('delay_setup',1)
317 $self->start_date( $part_pkg->default_start_date );
323 =item insert [ OPTION => VALUE ... ]
325 Adds this billing item to the database ("Orders" the item). If there is an
326 error, returns the error, otherwise returns false.
328 If the additional field I<promo_code> is defined instead of I<pkgpart>, it
329 will be used to look up the package definition and agent restrictions will be
332 If the additional field I<refnum> is defined, an FS::pkg_referral record will
333 be created and inserted. Multiple FS::pkg_referral records can be created by
334 setting I<refnum> to an array reference of refnums or a hash reference with
335 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
336 record will be created corresponding to cust_main.refnum.
338 If the additional field I<cust_pkg_usageprice> is defined, it will be treated
339 as an arrayref of FS::cust_pkg_usageprice objects, which will be inserted.
340 (Note that this field cannot be set with a usual ->cust_pkg_usageprice method.
341 It can be set as part of the hash when creating the object, or with the B<set>
344 The following options are available:
350 If set true, supresses actions that should only be taken for new package
351 orders. (Currently this includes: intro periods when delay_setup is on,
352 auto-adding a 1st start date, auto-adding expiration/adjourn/contract_end dates)
356 cust_pkg_option records will be created
360 a ticket will be added to this customer with this subject
364 an optional queue name for ticket additions
368 Don't check the legality of the package definition. This should be used
369 when performing a package change that doesn't change the pkgpart (i.e.
377 my( $self, %options ) = @_;
379 my $oldAutoCommit = $FS::UID::AutoCommit;
380 local $FS::UID::AutoCommit = 0;
384 $error = $self->check_pkgpart unless $options{'allow_pkgpart'};
386 my $part_pkg = $self->part_pkg;
388 if ( ! $import && ! $options{'change'} ) {
390 # set order date to now
391 $self->order_date(time) unless ($import && $self->order_date);
393 # if the package def says to start only on the first of the month:
394 if ( $part_pkg->option('start_1st', 1) && !$self->start_date ) {
395 my ($sec,$min,$hour,$mday,$mon,$year) = (localtime(time) )[0,1,2,3,4,5];
396 $mon += 1 unless $mday == 1;
397 until ( $mon < 12 ) { $mon -= 12; $year++; }
398 $self->start_date( timelocal_nocheck(0,0,0,1,$mon,$year) );
401 if ($self->susp eq 'now' or $part_pkg->start_on_hold) {
402 # if the package was ordered on hold:
404 # - don't set the start date (it will be started manually)
405 $self->set('susp', $self->order_date);
406 $self->set('start_date', '');
408 # set expire/adjourn/contract_end timers, and free days, if appropriate
409 # and automatic package transfer, which can fail, so capture the result
410 $error = $self->set_initial_timers;
412 } # else this is a package change, and shouldn't have "new package" behavior
414 $error ||= $self->SUPER::insert($options{options} ? %{$options{options}} : ());
416 $dbh->rollback if $oldAutoCommit;
420 $self->refnum($self->cust_main->refnum) unless $self->refnum;
421 $self->refnum( [ $self->refnum ] ) unless ref($self->refnum);
422 $self->process_m2m( 'link_table' => 'pkg_referral',
423 'target_table' => 'part_referral',
424 'params' => $self->refnum,
427 if ( $self->hashref->{cust_pkg_usageprice} ) {
428 for my $cust_pkg_usageprice ( @{ $self->hashref->{cust_pkg_usageprice} } ) {
429 $cust_pkg_usageprice->pkgnum( $self->pkgnum );
430 my $error = $cust_pkg_usageprice->insert;
432 $dbh->rollback if $oldAutoCommit;
438 if ( $self->setup_discountnum || $self->recur_discountnum ) {
439 my $error = $self->insert_discount();
441 $dbh->rollback if $oldAutoCommit;
446 my $conf = new FS::Conf;
448 if ( ! $import && $conf->config('ticket_system') && $options{ticket_subject} ) {
450 #this init stuff is still inefficient, but at least its limited to
451 # the small number (any?) folks using ticket emailing on pkg order
454 # use lib ( "/opt/rt3/local/lib", "/opt/rt3/lib" );
461 use FS::TicketSystem;
462 FS::TicketSystem->init();
464 my $q = new RT::Queue($RT::SystemUser);
465 $q->Load($options{ticket_queue}) if $options{ticket_queue};
466 my $t = new RT::Ticket($RT::SystemUser);
467 my $mime = new MIME::Entity;
468 $mime->build( Type => 'text/plain', Data => $options{ticket_subject} );
469 $t->Create( $options{ticket_queue} ? (Queue => $q) : (),
470 Subject => $options{ticket_subject},
473 $t->AddLink( Type => 'MemberOf',
474 Target => 'freeside://freeside/cust_main/'. $self->custnum,
478 if (! $import && $conf->config('welcome_letter') && $self->cust_main->num_pkgs == 1) {
479 my $queue = new FS::queue {
480 'job' => 'FS::cust_main::queueable_print',
482 $error = $queue->insert(
483 'custnum' => $self->custnum,
484 'template' => 'welcome_letter',
488 warn "can't send welcome letter: $error";
493 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
500 This method now works but you probably shouldn't use it.
502 You don't want to delete packages, because there would then be no record
503 the customer ever purchased the package. Instead, see the cancel method and
504 hide cancelled packages.
508 # this is still used internally to abort future package changes, so it
514 # The following foreign keys to cust_pkg are not cleaned up here, and will
515 # cause package deletion to fail:
517 # cust_credit.pkgnum and commission_pkgnum (and cust_credit_void)
518 # cust_credit_bill.pkgnum
519 # cust_pay_pending.pkgnum
520 # cust_pay.pkgnum (and cust_pay_void)
521 # cust_bill_pay.pkgnum (wtf, shouldn't reference pkgnum)
522 # cust_pkg_usage.pkgnum
523 # cust_pkg.uncancel_pkgnum, change_pkgnum, main_pkgnum, and change_to_pkgnum
525 # cust_svc is handled by canceling the package before deleting it
526 # cust_pkg_option is handled via option_Common
528 my $oldAutoCommit = $FS::UID::AutoCommit;
529 local $FS::UID::AutoCommit = 0;
532 foreach my $cust_pkg_discount ($self->cust_pkg_discount) {
533 my $error = $cust_pkg_discount->delete;
535 $dbh->rollback if $oldAutoCommit;
539 #cust_bill_pkg_discount?
541 foreach my $cust_pkg_detail ($self->cust_pkg_detail) {
542 my $error = $cust_pkg_detail->delete;
544 $dbh->rollback if $oldAutoCommit;
549 foreach my $cust_pkg_reason (
551 'table' => 'cust_pkg_reason',
552 'hashref' => { 'pkgnum' => $self->pkgnum },
556 my $error = $cust_pkg_reason->delete;
558 $dbh->rollback if $oldAutoCommit;
563 foreach my $pkg_referral ( $self->pkg_referral ) {
564 my $error = $pkg_referral->delete;
566 $dbh->rollback if $oldAutoCommit;
571 my $error = $self->SUPER::delete(@_);
573 $dbh->rollback if $oldAutoCommit;
577 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
583 =item replace [ OLD_RECORD ] [ HASHREF | OPTION => VALUE ... ]
585 Replaces the OLD_RECORD with this one in the database. If there is an error,
586 returns the error, otherwise returns false.
588 Currently, custnum, setup, bill, adjourn, susp, expire, and cancel may be changed.
590 Changing pkgpart may have disasterous effects. See the order subroutine.
592 setup and bill are normally updated by calling the bill method of a customer
593 object (see L<FS::cust_main>).
595 suspend is normally updated by the suspend and unsuspend methods.
597 cancel is normally updated by the cancel method (and also the order subroutine
600 Available options are:
606 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.
610 the access_user (see L<FS::access_user>) providing the reason
614 hashref of keys and values - cust_pkg_option records will be created, updated or removed as appopriate
623 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
628 ( ref($_[0]) eq 'HASH' )
632 #return "Can't (yet?) change pkgpart!" if $old->pkgpart != $new->pkgpart;
633 #return "Can't change otaker!" if $old->otaker ne $new->otaker;
636 #return "Can't change setup once it exists!"
637 # if $old->getfield('setup') &&
638 # $old->getfield('setup') != $new->getfield('setup');
640 #some logic for bill, susp, cancel?
642 local($disable_agentcheck) = 1 if $old->pkgpart == $new->pkgpart;
644 my $oldAutoCommit = $FS::UID::AutoCommit;
645 local $FS::UID::AutoCommit = 0;
648 foreach my $method ( qw(adjourn expire) ) { # How many reasons?
649 if ($options->{'reason'} && $new->$method && $old->$method ne $new->$method) {
650 my $error = $new->insert_reason(
651 'reason' => $options->{'reason'},
652 'date' => $new->$method,
654 'reason_otaker' => $options->{'reason_otaker'},
657 dbh->rollback if $oldAutoCommit;
658 return "Error inserting cust_pkg_reason: $error";
663 #save off and freeze RADIUS attributes for any associated svc_acct records
665 if ( $old->part_pkg->is_prepaid || $new->part_pkg->is_prepaid ) {
667 #also check for specific exports?
668 # to avoid spurious modify export events
669 @svc_acct = map { $_->svc_x }
670 grep { $_->part_svc->svcdb eq 'svc_acct' }
673 $_->snapshot foreach @svc_acct;
677 my $error = $new->export_pkg_change($old)
678 || $new->SUPER::replace( $old,
680 ? $options->{options}
684 $dbh->rollback if $oldAutoCommit;
688 #for prepaid packages,
689 #trigger export of new RADIUS Expiration attribute when cust_pkg.bill changes
690 foreach my $old_svc_acct ( @svc_acct ) {
691 my $new_svc_acct = new FS::svc_acct { $old_svc_acct->hash };
693 $new_svc_acct->replace( $old_svc_acct,
694 'depend_jobnum' => $options->{depend_jobnum},
697 $dbh->rollback if $oldAutoCommit;
702 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
709 Checks all fields to make sure this is a valid billing item. If there is an
710 error, returns the error, otherwise returns false. Called by the insert and
718 if ( !$self->locationnum or $self->locationnum == -1 ) {
719 $self->set('locationnum', $self->cust_main->ship_locationnum);
723 $self->ut_numbern('pkgnum')
724 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum')
725 || $self->ut_numbern('pkgpart')
726 || $self->ut_foreign_keyn('contactnum', 'contact', 'contactnum' )
727 || $self->ut_foreign_keyn('locationnum', 'cust_location', 'locationnum')
728 || $self->ut_foreign_keyn('salesnum', 'sales', 'salesnum')
729 || $self->ut_numbern('quantity')
730 || $self->ut_numbern('start_date')
731 || $self->ut_numbern('setup')
732 || $self->ut_numbern('bill')
733 || $self->ut_numbern('susp')
734 || $self->ut_numbern('cancel')
735 || $self->ut_numbern('adjourn')
736 || $self->ut_numbern('resume')
737 || $self->ut_numbern('expire')
738 || $self->ut_numbern('dundate')
739 || $self->ut_flag('no_auto', [ '', 'Y' ])
740 || $self->ut_flag('waive_setup', [ '', 'Y' ])
741 || $self->ut_flag('separate_bill')
742 || $self->ut_textn('agent_pkgid')
743 || $self->ut_enum('recur_show_zero', [ '', 'Y', 'N', ])
744 || $self->ut_enum('setup_show_zero', [ '', 'Y', 'N', ])
745 || $self->ut_foreign_keyn('main_pkgnum', 'cust_pkg', 'pkgnum')
746 || $self->ut_foreign_keyn('pkglinknum', 'part_pkg_link', 'pkglinknum')
747 || $self->ut_foreign_keyn('change_to_pkgnum', 'cust_pkg', 'pkgnum')
749 return $error if $error;
751 return "A package with both start date (future start) and setup date (already started) will never bill"
752 if $self->start_date && $self->setup && ! $upgrade;
754 return "A future unsuspend date can only be set for a package with a suspend date"
755 if $self->resume and !$self->susp and !$self->adjourn;
757 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
759 if ( $self->dbdef_table->column('manual_flag') ) {
760 $self->manual_flag('') if $self->manual_flag eq ' ';
761 $self->manual_flag =~ /^([01]?)$/
762 or return "Illegal manual_flag ". $self->manual_flag;
763 $self->manual_flag($1);
771 Check the pkgpart to make sure it's allowed with the reg_code and/or
772 promo_code of the package (if present) and with the customer's agent.
773 Called from C<insert>, unless we are doing a package change that doesn't
781 # my $error = $self->ut_numbern('pkgpart'); # already done
784 if ( $self->reg_code ) {
786 unless ( grep { $self->pkgpart == $_->pkgpart }
787 map { $_->reg_code_pkg }
788 qsearchs( 'reg_code', { 'code' => $self->reg_code,
789 'agentnum' => $self->cust_main->agentnum })
791 return "Unknown registration code";
794 } elsif ( $self->promo_code ) {
797 qsearchs('part_pkg', {
798 'pkgpart' => $self->pkgpart,
799 'promo_code' => { op=>'ILIKE', value=>$self->promo_code },
801 return 'Unknown promotional code' unless $promo_part_pkg;
805 unless ( $disable_agentcheck ) {
807 qsearchs( 'agent', { 'agentnum' => $self->cust_main->agentnum } );
808 return "agent ". $agent->agentnum. ':'. $agent->agent.
809 " can't purchase pkgpart ". $self->pkgpart
810 unless $agent->pkgpart_hashref->{ $self->pkgpart }
811 || $agent->agentnum == $self->part_pkg->agentnum;
814 $error = $self->ut_foreign_key('pkgpart', 'part_pkg', 'pkgpart' );
815 return $error if $error;
823 =item cancel [ OPTION => VALUE ... ]
825 Cancels and removes all services (see L<FS::cust_svc> and L<FS::part_svc>)
826 in this package, then cancels the package itself (sets the cancel field to
829 Available options are:
833 =item quiet - can be set true to supress email cancellation notices.
835 =item time - can be set to cancel the package based on a specific future or
836 historical date. Using time ensures that the remaining amount is calculated
837 correctly. Note however that this is an immediate cancel and just changes
838 the date. You are PROBABLY looking to expire the account instead of using
841 =item reason - can be set to a cancellation reason (see L<FS:reason>),
842 either a reasonnum of an existing reason, or passing a hashref will create
843 a new reason. The hashref should have the following keys: typenum - Reason
844 type (see L<FS::reason_type>, reason - Text of the new reason.
846 =item date - can be set to a unix style timestamp to specify when to
849 =item nobill - can be set true to skip billing if it might otherwise be done.
851 =item unused_credit - can be set to 1 to credit the remaining time, or 0 to
852 not credit it. This must be set (by change()) when changing the package
853 to a different pkgpart or location, and probably shouldn't be in any other
854 case. If it's not set, the 'unused_credit_cancel' part_pkg option will
857 =item no_delay_cancel - prevents delay_cancel behavior
858 no matter what other options say, for use when changing packages (or any
859 other time you're really sure you want an immediate cancel)
863 If there is an error, returns the error, otherwise returns false.
867 #NOT DOCUMENTING - this should only be used when calling recursively
868 #=item delay_cancel - for internal use, to allow proper handling of
869 #supplemental packages when the main package is flagged to suspend
870 #before cancelling, probably shouldn't be used otherwise (set the
871 #corresponding package option instead)
874 my( $self, %options ) = @_;
877 # supplemental packages can now be separately canceled, though the UI
878 # shouldn't permit it
880 ## pass all suspend/cancel actions to the main package
881 ## (unless the pkglinknum has been removed, then the link is defunct and
882 ## this package can be canceled on its own)
883 #if ( $self->main_pkgnum and $self->pkglinknum and !$options{'from_main'} ) {
884 # return $self->main_pkg->cancel(%options);
887 my $conf = new FS::Conf;
889 warn "cust_pkg::cancel called with options".
890 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
893 my $oldAutoCommit = $FS::UID::AutoCommit;
894 local $FS::UID::AutoCommit = 0;
897 my $old = $self->select_for_update;
899 if ( $old->get('cancel') || $self->get('cancel') ) {
900 dbh->rollback if $oldAutoCommit;
901 return ""; # no error
904 # XXX possibly set cancel_time to the expire date?
905 my $cancel_time = $options{'time'} || time;
906 my $date = $options{'date'} if $options{'date'}; # expire/cancel later
907 $date = '' if ($date && $date <= $cancel_time); # complain instead?
909 my $delay_cancel = $options{'no_delay_cancel'} ? 0 : $options{'delay_cancel'};
910 if ( !$date && $self->part_pkg->option('delay_cancel',1)
911 && (($self->status eq 'active') || ($self->status eq 'suspended'))
912 && !$options{'no_delay_cancel'}
914 my $expdays = $conf->config('part_pkg-delay_cancel-days') || 1;
915 my $expsecs = 60*60*24*$expdays;
916 my $suspfor = $self->susp ? $cancel_time - $self->susp : 0;
917 $expsecs = $expsecs - $suspfor if $suspfor;
918 unless ($expsecs <= 0) { #if it's already been suspended long enough, don't re-suspend
920 $date = $cancel_time + $expsecs;
924 #race condition: usage could be ongoing until unprovisioned
925 #resolved by performing a change package instead (which unprovisions) and
927 if ( !$options{nobill} && !$date ) {
928 # && $conf->exists('bill_usage_on_cancel') ) { #calc_cancel checks this
929 my $copy = $self->new({$self->hash});
931 $copy->cust_main->bill( 'pkg_list' => [ $copy ],
933 'time' => $cancel_time );
934 warn "Error billing during cancel, custnum ".
935 #$self->cust_main->custnum. ": $error"
940 if ( $options{'reason'} ) {
941 $error = $self->insert_reason( 'reason' => $options{'reason'},
942 'action' => $date ? 'expire' : 'cancel',
943 'date' => $date ? $date : $cancel_time,
944 'reason_otaker' => $options{'reason_otaker'},
947 dbh->rollback if $oldAutoCommit;
948 return "Error inserting cust_pkg_reason: $error";
952 my %svc_cancel_opt = ();
953 $svc_cancel_opt{'date'} = $date if $date;
954 foreach my $cust_svc (
957 sort { $a->[1] <=> $b->[1] }
958 map { [ $_, $_->svc_x ? $_->svc_x->table_info->{'cancel_weight'} : -1 ]; }
959 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
961 my $part_svc = $cust_svc->part_svc;
962 next if ( defined($part_svc) and $part_svc->preserve );
963 my $error = $cust_svc->cancel( %svc_cancel_opt );
966 $dbh->rollback if $oldAutoCommit;
967 return 'Error '. ($svc_cancel_opt{'date'} ? 'expiring' : 'canceling' ).
972 # if a reasonnum was passed, get the actual reason object so we can check
976 if ($options{'reason'} =~ /^\d+$/) {
977 $reason = FS::reason->by_key($options{'reason'});
981 # credit remaining time if any of these are true:
982 # - unused_credit => 1 was passed (this happens when canceling a package
983 # for a package change when unused_credit_change is set)
984 # - no unused_credit option, and there is a cancel reason, and the cancel
985 # reason says to credit the package
986 # - no unused_credit option, and the package definition says to credit the
987 # package on cancellation
989 if ( exists($options{'unused_credit'}) ) {
990 $do_credit = $options{'unused_credit'};
991 } elsif ( defined($reason) && $reason->unused_credit ) {
994 $do_credit = $self->part_pkg->option('unused_credit_cancel', 1);
997 my $error = $self->credit_remaining('cancel', $cancel_time);
999 $dbh->rollback if $oldAutoCommit;
1005 my %hash = $self->hash;
1007 $hash{'expire'} = $date;
1008 if ($delay_cancel) {
1009 # just to be sure these are clear
1010 $hash{'adjourn'} = undef;
1011 $hash{'resume'} = undef;
1014 $hash{'cancel'} = $cancel_time;
1016 $hash{'change_custnum'} = $options{'change_custnum'};
1018 # if this is a supplemental package that's lost its part_pkg_link, and it's
1019 # being canceled for real, unlink it completely
1020 if ( !$date and ! $self->pkglinknum ) {
1021 $hash{main_pkgnum} = '';
1024 # if there is a future package change scheduled, unlink from it (like
1025 # abort_change) first, then delete it.
1026 $hash{'change_to_pkgnum'} = '';
1028 # save the package state
1029 my $new = new FS::cust_pkg ( \%hash );
1030 $error = $new->replace( $self, options => { $self->options } );
1032 if ( $self->change_to_pkgnum ) {
1033 my $change_to = FS::cust_pkg->by_key($self->change_to_pkgnum);
1034 $error ||= $change_to->cancel('no_delay_cancel' => 1) || $change_to->delete;
1037 $dbh->rollback if $oldAutoCommit;
1041 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1042 $error = $supp_pkg->cancel(%options,
1044 'date' => $date, #in case it got changed by delay_cancel
1045 'delay_cancel' => $delay_cancel,
1048 $dbh->rollback if $oldAutoCommit;
1049 return "canceling supplemental pkg#".$supp_pkg->pkgnum.": $error";
1053 if ($delay_cancel && !$options{'from_main'}) {
1054 $error = $new->suspend(
1056 'time' => $cancel_time
1061 foreach my $usage ( $self->cust_pkg_usage ) {
1062 $error = $usage->delete;
1064 $dbh->rollback if $oldAutoCommit;
1065 return "deleting usage pools: $error";
1070 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1071 return '' if $date; #no errors
1073 my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ } $self->cust_main->invoicing_list;
1074 if ( !$options{'quiet'} &&
1075 $conf->exists('emailcancel', $self->cust_main->agentnum) &&
1077 my $msgnum = $conf->config('cancel_msgnum', $self->cust_main->agentnum);
1080 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum });
1081 $error = $msg_template->send( 'cust_main' => $self->cust_main,
1082 'object' => $self );
1084 #should this do something on errors?
1091 =item cancel_if_expired [ NOW_TIMESTAMP ]
1093 Cancels this package if its expire date has been reached.
1097 sub cancel_if_expired {
1099 my $time = shift || time;
1100 return '' unless $self->expire && $self->expire <= $time;
1101 my $error = $self->cancel;
1103 return "Error cancelling expired pkg ". $self->pkgnum. " for custnum ".
1104 $self->custnum. ": $error";
1111 "Un-cancels" this package: Orders a new package with the same custnum, pkgpart,
1112 locationnum, (other fields?). Attempts to re-provision cancelled services
1113 using history information (errors at this stage are not fatal).
1115 cust_pkg: pass a scalar reference, will be filled in with the new cust_pkg object
1117 svc_fatal: service provisioning errors are fatal
1119 svc_errors: pass an array reference, will be filled in with any provisioning errors
1121 main_pkgnum: link the package as a supplemental package of this one. For
1127 my( $self, %options ) = @_;
1129 #in case you try do do $uncancel-date = $cust_pkg->uncacel
1130 return '' unless $self->get('cancel');
1132 if ( $self->main_pkgnum and !$options{'main_pkgnum'} ) {
1133 return $self->main_pkg->uncancel(%options);
1140 my $oldAutoCommit = $FS::UID::AutoCommit;
1141 local $FS::UID::AutoCommit = 0;
1145 # insert the new package
1148 my $cust_pkg = new FS::cust_pkg {
1149 last_bill => ( $options{'last_bill'} || $self->get('last_bill') ),
1150 bill => ( $options{'bill'} || $self->get('bill') ),
1152 uncancel_pkgnum => $self->pkgnum,
1153 main_pkgnum => ($options{'main_pkgnum'} || ''),
1154 map { $_ => $self->get($_) } qw(
1155 custnum pkgpart locationnum
1157 susp adjourn resume expire start_date contract_end dundate
1158 change_date change_pkgpart change_locationnum
1159 manual_flag no_auto separate_bill quantity agent_pkgid
1160 recur_show_zero setup_show_zero
1164 my $error = $cust_pkg->insert(
1165 'change' => 1, #supresses any referral credit to a referring customer
1166 'allow_pkgpart' => 1, # allow this even if the package def is disabled
1169 $dbh->rollback if $oldAutoCommit;
1177 #find historical services within this timeframe before the package cancel
1178 # (incompatible with "time" option to cust_pkg->cancel?)
1179 my $fuzz = 2 * 60; #2 minutes? too much? (might catch separate unprovision)
1180 # too little? (unprovisioing export delay?)
1181 my($end, $start) = ( $self->get('cancel'), $self->get('cancel') - $fuzz );
1182 my @h_cust_svc = $self->h_cust_svc( $end, $start );
1185 foreach my $h_cust_svc (@h_cust_svc) {
1186 my $h_svc_x = $h_cust_svc->h_svc_x( $end, $start );
1187 #next unless $h_svc_x; #should this happen?
1188 (my $table = $h_svc_x->table) =~ s/^h_//;
1189 require "FS/$table.pm";
1190 my $class = "FS::$table";
1191 my $svc_x = $class->new( {
1192 'pkgnum' => $cust_pkg->pkgnum,
1193 'svcpart' => $h_cust_svc->svcpart,
1194 map { $_ => $h_svc_x->get($_) } fields($table)
1198 if ( $h_svc_x->isa('FS::h_svc_Radius_Mixin') ) {
1199 $svc_x->usergroup( [ $h_svc_x->h_usergroup($end, $start) ] );
1202 my $svc_error = $svc_x->insert;
1204 if ( $options{svc_fatal} ) {
1205 $dbh->rollback if $oldAutoCommit;
1208 # if we've failed to insert the svc_x object, svc_Common->insert
1209 # will have removed the cust_svc already. if not, then both records
1210 # were inserted but we failed for some other reason (export, most
1211 # likely). in that case, report the error and delete the records.
1212 push @svc_errors, $svc_error;
1213 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svc_x->svcnum });
1215 # except if export_insert failed, export_delete probably won't be
1217 local $FS::svc_Common::noexport_hack = 1;
1218 my $cleanup_error = $svc_x->delete; # also deletes cust_svc
1219 if ( $cleanup_error ) { # and if THAT fails, then run away
1220 $dbh->rollback if $oldAutoCommit;
1221 return $cleanup_error;
1226 } #foreach $h_cust_svc
1228 #these are pretty rare, but should handle them
1229 # - dsl_device (mac addresses)
1230 # - phone_device (mac addresses)
1231 # - dsl_note (ikano notes)
1232 # - domain_record (i.e. restore DNS information w/domains)
1233 # - inventory_item(?) (inventory w/un-cancelling service?)
1234 # - nas (svc_broaband nas stuff)
1235 #this stuff is unused in the wild afaik
1236 # - mailinglistmember
1238 # - svc_domain.parent_svcnum?
1239 # - acct_snarf (ancient mail fetching config)
1240 # - cgp_rule (communigate)
1241 # - cust_svc_option (used by our Tron stuff)
1242 # - acct_rt_transaction (used by our time worked stuff)
1245 # also move over any services that didn't unprovision at cancellation
1248 foreach my $cust_svc ( qsearch('cust_svc', { pkgnum => $self->pkgnum } ) ) {
1249 $cust_svc->pkgnum( $cust_pkg->pkgnum );
1250 my $error = $cust_svc->replace;
1252 $dbh->rollback if $oldAutoCommit;
1258 # Uncancel any supplemental packages, and make them supplemental to the
1262 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1264 $error = $supp_pkg->uncancel(%options, 'main_pkgnum' => $cust_pkg->pkgnum);
1266 $dbh->rollback if $oldAutoCommit;
1267 return "canceling supplemental pkg#".$supp_pkg->pkgnum.": $error";
1275 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1277 ${ $options{cust_pkg} } = $cust_pkg if ref($options{cust_pkg});
1278 @{ $options{svc_errors} } = @svc_errors if ref($options{svc_errors});
1285 Cancels any pending expiration (sets the expire field to null).
1287 If there is an error, returns the error, otherwise returns false.
1292 my( $self, %options ) = @_;
1295 my $oldAutoCommit = $FS::UID::AutoCommit;
1296 local $FS::UID::AutoCommit = 0;
1299 my $old = $self->select_for_update;
1301 my $pkgnum = $old->pkgnum;
1302 if ( $old->get('cancel') || $self->get('cancel') ) {
1303 dbh->rollback if $oldAutoCommit;
1304 return "Can't unexpire cancelled package $pkgnum";
1305 # or at least it's pointless
1308 unless ( $old->get('expire') && $self->get('expire') ) {
1309 dbh->rollback if $oldAutoCommit;
1310 return ""; # no error
1313 my %hash = $self->hash;
1314 $hash{'expire'} = '';
1315 my $new = new FS::cust_pkg ( \%hash );
1316 $error = $new->replace( $self, options => { $self->options } );
1318 $dbh->rollback if $oldAutoCommit;
1322 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1328 =item suspend [ OPTION => VALUE ... ]
1330 Suspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
1331 package, then suspends the package itself (sets the susp field to now).
1333 Available options are:
1337 =item reason - can be set to a cancellation reason (see L<FS:reason>),
1338 either a reasonnum of an existing reason, or passing a hashref will create
1339 a new reason. The hashref should have the following keys:
1340 - typenum - Reason type (see L<FS::reason_type>
1341 - reason - Text of the new reason.
1343 =item date - can be set to a unix style timestamp to specify when to
1346 =item time - can be set to override the current time, for calculation
1347 of final invoices or unused-time credits
1349 =item resume_date - can be set to a time when the package should be
1350 unsuspended. This may be more convenient than calling C<unsuspend()>
1353 =item from_main - allows a supplemental package to be suspended, rather
1354 than redirecting the method call to its main package. For internal use.
1356 =item from_cancel - used when suspending from the cancel method, forces
1357 this to skip everything besides basic suspension. For internal use.
1361 If there is an error, returns the error, otherwise returns false.
1366 my( $self, %options ) = @_;
1369 # supplemental packages still can't be separately suspended, but silently
1370 # exit instead of failing or passing the action to the main package (so
1371 # that the "Suspend customer" action doesn't trip over the supplemental
1374 if ( $self->main_pkgnum and !$options{'from_main'} ) {
1378 my $oldAutoCommit = $FS::UID::AutoCommit;
1379 local $FS::UID::AutoCommit = 0;
1382 my $old = $self->select_for_update;
1384 my $pkgnum = $old->pkgnum;
1385 if ( $old->get('cancel') || $self->get('cancel') ) {
1386 dbh->rollback if $oldAutoCommit;
1387 return "Can't suspend cancelled package $pkgnum";
1390 if ( $old->get('susp') || $self->get('susp') ) {
1391 dbh->rollback if $oldAutoCommit;
1392 return ""; # no error # complain on adjourn?
1395 my $suspend_time = $options{'time'} || time;
1396 my $date = $options{date} if $options{date}; # adjourn/suspend later
1397 $date = '' if ($date && $date <= $suspend_time); # complain instead?
1399 if ( $date && $old->get('expire') && $old->get('expire') < $date ) {
1400 dbh->rollback if $oldAutoCommit;
1401 return "Package $pkgnum expires before it would be suspended.";
1404 # some false laziness with sub cancel
1405 if ( !$options{nobill} && !$date && !$options{'from_cancel'} &&
1406 $self->part_pkg->option('bill_suspend_as_cancel',1) ) {
1407 # kind of a kludge--'bill_suspend_as_cancel' to avoid having to
1408 # make the entire cust_main->bill path recognize 'suspend' and
1409 # 'cancel' separately.
1410 warn "Billing $pkgnum on suspension (at $suspend_time)\n" if $DEBUG;
1411 my $copy = $self->new({$self->hash});
1413 $copy->cust_main->bill( 'pkg_list' => [ $copy ],
1415 'time' => $suspend_time );
1416 warn "Error billing during suspend, custnum ".
1417 #$self->cust_main->custnum. ": $error"
1422 my $cust_pkg_reason;
1423 if ( $options{'reason'} ) {
1424 $error = $self->insert_reason( 'reason' => $options{'reason'},
1425 'action' => $date ? 'adjourn' : 'suspend',
1426 'date' => $date ? $date : $suspend_time,
1427 'reason_otaker' => $options{'reason_otaker'},
1430 dbh->rollback if $oldAutoCommit;
1431 return "Error inserting cust_pkg_reason: $error";
1433 $cust_pkg_reason = qsearchs('cust_pkg_reason', {
1434 'date' => $date ? $date : $suspend_time,
1435 'action' => $date ? 'A' : 'S',
1436 'pkgnum' => $self->pkgnum,
1440 # if a reasonnum was passed, get the actual reason object so we can check
1442 # (passing a reason hashref is still allowed, but it can't be used with
1443 # the fancy behavioral options.)
1446 if ($options{'reason'} =~ /^\d+$/) {
1447 $reason = FS::reason->by_key($options{'reason'});
1450 my %hash = $self->hash;
1452 $hash{'adjourn'} = $date;
1454 $hash{'susp'} = $suspend_time;
1457 my $resume_date = $options{'resume_date'} || 0;
1458 if ( $resume_date > ($date || $suspend_time) ) {
1459 $hash{'resume'} = $resume_date;
1462 $options{options} ||= {};
1464 my $new = new FS::cust_pkg ( \%hash );
1465 $error = $new->replace( $self, options => { $self->options,
1466 %{ $options{options} },
1470 $dbh->rollback if $oldAutoCommit;
1474 unless ( $date ) { # then we are suspending now
1476 unless ($options{'from_cancel'}) {
1477 # credit remaining time if appropriate
1478 # (if required by the package def, or the suspend reason)
1479 my $unused_credit = $self->part_pkg->option('unused_credit_suspend',1)
1480 || ( defined($reason) && $reason->unused_credit );
1482 if ( $unused_credit ) {
1483 warn "crediting unused time on pkg#".$self->pkgnum."\n" if $DEBUG;
1484 my $error = $self->credit_remaining('suspend', $suspend_time);
1486 $dbh->rollback if $oldAutoCommit;
1492 my @cust_svc = qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } );
1494 #attempt ordering ala cust_svc_suspend_cascade (without infinite-looping
1495 # on the circular dep case)
1496 # (this is too simple for multi-level deps, we need to use something
1497 # to resolve the DAG properly when possible)
1499 $svcpart{$_->svcpart} = 0 foreach @cust_svc;
1500 foreach my $svcpart ( keys %svcpart ) {
1501 foreach my $part_svc_link (
1502 FS::part_svc_link->by_agentnum($self->cust_main->agentnum,
1503 src_svcpart => $svcpart,
1504 link_type => 'cust_svc_suspend_cascade'
1507 $svcpart{$part_svc_link->dst_svcpart} = max(
1508 $svcpart{$part_svc_link->dst_svcpart},
1509 $svcpart{$part_svc_link->src_svcpart} + 1
1513 @cust_svc = sort { $svcpart{ $a->svcpart } <=> $svcpart{ $b->svcpart } }
1517 foreach my $cust_svc ( @cust_svc ) {
1518 $cust_svc->suspend( 'labels_arrayref' => \@labels );
1521 # suspension fees: if there is a feepart, and it's not an unsuspend fee,
1522 # and this is not a suspend-before-cancel
1523 if ( $cust_pkg_reason ) {
1524 my $reason_obj = $cust_pkg_reason->reason;
1525 if ( $reason_obj->feepart and
1526 ! $reason_obj->fee_on_unsuspend and
1527 ! $options{'from_cancel'} ) {
1529 # register the need to charge a fee, cust_main->bill will do the rest
1530 warn "registering suspend fee: pkgnum ".$self->pkgnum.", feepart ".$reason->feepart."\n"
1532 my $cust_pkg_reason_fee = FS::cust_pkg_reason_fee->new({
1533 'pkgreasonnum' => $cust_pkg_reason->num,
1534 'pkgnum' => $self->pkgnum,
1535 'feepart' => $reason->feepart,
1536 'nextbill' => $reason->fee_hold,
1538 $error ||= $cust_pkg_reason_fee->insert;
1542 my $conf = new FS::Conf;
1543 if ( $conf->config('suspend_email_admin') && !$options{'from_cancel'} ) {
1545 my $error = send_email(
1546 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
1547 #invoice_from ??? well as good as any
1548 'to' => $conf->config('suspend_email_admin'),
1549 'subject' => 'FREESIDE NOTIFICATION: Customer package suspended',
1551 "This is an automatic message from your Freeside installation\n",
1552 "informing you that the following customer package has been suspended:\n",
1554 'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
1555 'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
1556 ( map { "Service : $_\n" } @labels ),
1558 'custnum' => $self->custnum,
1559 'msgtype' => 'admin'
1563 warn "WARNING: can't send suspension admin email (suspending anyway): ".
1571 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1572 $error = $supp_pkg->suspend(%options, 'from_main' => 1);
1574 $dbh->rollback if $oldAutoCommit;
1575 return "suspending supplemental pkg#".$supp_pkg->pkgnum.": $error";
1579 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1584 =item credit_remaining MODE TIME
1586 Generate a credit for this package for the time remaining in the current
1587 billing period. MODE is either "suspend" or "cancel" (determines the
1588 credit type). TIME is the time of suspension/cancellation. Both arguments
1593 # Implementation note:
1595 # If you pkgpart-change a package that has been billed, and it's set to give
1596 # credit on package change, then this method gets called and then the new
1597 # package will have no last_bill date. Therefore the customer will be credited
1598 # only once (per billing period) even if there are multiple package changes.
1600 # If you location-change a package that has been billed, this method will NOT
1601 # be called and the new package WILL have the last bill date of the old
1604 # If the new package is then canceled within the same billing cycle,
1605 # credit_remaining needs to run calc_remain on the OLD package to determine
1606 # the amount of unused time to credit.
1608 sub credit_remaining {
1609 # Add a credit for remaining service
1610 my ($self, $mode, $time) = @_;
1611 die 'credit_remaining requires suspend or cancel'
1612 unless $mode eq 'suspend' or $mode eq 'cancel';
1613 die 'no suspend/cancel time' unless $time > 0;
1615 my $conf = FS::Conf->new;
1616 my $reason_type = $conf->config($mode.'_credit_type');
1618 my $last_bill = $self->getfield('last_bill') || 0;
1619 my $next_bill = $self->getfield('bill') || 0;
1620 if ( $last_bill > 0 # the package has been billed
1621 and $next_bill > 0 # the package has a next bill date
1622 and $next_bill >= $time # which is in the future
1624 my @cust_credit_source_bill_pkg = ();
1625 my $remaining_value = 0;
1627 my $remain_pkg = $self;
1628 $remaining_value = $remain_pkg->calc_remain(
1630 'cust_credit_source_bill_pkg' => \@cust_credit_source_bill_pkg,
1633 # we may have to walk back past some package changes to get to the
1634 # one that actually has unused time
1635 while ( $remaining_value == 0 ) {
1636 if ( $remain_pkg->change_pkgnum ) {
1637 $remain_pkg = FS::cust_pkg->by_key($remain_pkg->change_pkgnum);
1639 # the package has really never been billed
1642 $remaining_value = $remain_pkg->calc_remain(
1644 'cust_credit_source_bill_pkg' => \@cust_credit_source_bill_pkg,
1648 if ( $remaining_value > 0 ) {
1649 warn "Crediting for $remaining_value on package ".$self->pkgnum."\n"
1651 my $error = $self->cust_main->credit(
1653 'Credit for unused time on '. $self->part_pkg->pkg,
1654 'reason_type' => $reason_type,
1655 'cust_credit_source_bill_pkg' => \@cust_credit_source_bill_pkg,
1657 return "Error crediting customer \$$remaining_value for unused time".
1658 " on ". $self->part_pkg->pkg. ": $error"
1660 } #if $remaining_value
1661 } #if $last_bill, etc.
1665 =item unsuspend [ OPTION => VALUE ... ]
1667 Unsuspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
1668 package, then unsuspends the package itself (clears the susp field and the
1669 adjourn field if it is in the past). If the suspend reason includes an
1670 unsuspension package, that package will be ordered.
1672 Available options are:
1678 Can be set to a date to unsuspend the package in the future (the 'resume'
1681 =item adjust_next_bill
1683 Can be set true to adjust the next bill date forward by
1684 the amount of time the account was inactive. This was set true by default
1685 in the past (from 1.4.2 and 1.5.0pre6 through 1.7.0), but now needs to be
1686 explicitly requested with this option or in the price plan.
1690 If there is an error, returns the error, otherwise returns false.
1695 my( $self, %opt ) = @_;
1698 # pass all suspend/cancel actions to the main package
1699 if ( $self->main_pkgnum and !$opt{'from_main'} ) {
1700 return $self->main_pkg->unsuspend(%opt);
1703 my $oldAutoCommit = $FS::UID::AutoCommit;
1704 local $FS::UID::AutoCommit = 0;
1707 my $old = $self->select_for_update;
1709 my $pkgnum = $old->pkgnum;
1710 if ( $old->get('cancel') || $self->get('cancel') ) {
1711 $dbh->rollback if $oldAutoCommit;
1712 return "Can't unsuspend cancelled package $pkgnum";
1715 unless ( $old->get('susp') && $self->get('susp') ) {
1716 $dbh->rollback if $oldAutoCommit;
1717 return ""; # no error # complain instead?
1720 # handle the case of setting a future unsuspend (resume) date
1721 # and do not continue to actually unsuspend the package
1722 my $date = $opt{'date'};
1723 if ( $date and $date > time ) { # return an error if $date <= time?
1725 if ( $old->get('expire') && $old->get('expire') < $date ) {
1726 $dbh->rollback if $oldAutoCommit;
1727 return "Package $pkgnum expires before it would be unsuspended.";
1730 my $new = new FS::cust_pkg { $self->hash };
1731 $new->set('resume', $date);
1732 $error = $new->replace($self, options => $self->options);
1735 $dbh->rollback if $oldAutoCommit;
1739 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1745 if (!$self->setup) {
1746 # then this package is being released from on-hold status
1747 $error = $self->set_initial_timers;
1749 $dbh->rollback if $oldAutoCommit;
1756 foreach my $cust_svc (
1757 qsearch('cust_svc',{'pkgnum'=> $self->pkgnum } )
1759 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
1761 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
1762 $dbh->rollback if $oldAutoCommit;
1763 return "Illegal svcdb value in part_svc!";
1766 require "FS/$svcdb.pm";
1768 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
1770 $error = $svc->unsuspend;
1772 $dbh->rollback if $oldAutoCommit;
1775 my( $label, $value ) = $cust_svc->label;
1776 push @labels, "$label: $value";
1781 my $cust_pkg_reason = $self->last_cust_pkg_reason('susp');
1782 my $reason = $cust_pkg_reason ? $cust_pkg_reason->reason : '';
1784 my %hash = $self->hash;
1785 my $inactive = time - $hash{'susp'};
1787 my $conf = new FS::Conf;
1789 #adjust the next bill date forward
1790 # increment next bill date if certain conditions are met:
1791 # - it was due to be billed at some point
1792 # - either the global or local config says to do this
1793 my $adjust_bill = 0;
1796 && ( $hash{'bill'} || $hash{'setup'} )
1797 && ( $opt{'adjust_next_bill'}
1798 || $conf->exists('unsuspend-always_adjust_next_bill_date')
1799 || $self->part_pkg->option('unsuspend_adjust_bill', 1)
1806 # - the package billed during suspension
1807 # - or it was ordered on hold
1808 # - or the customer was credited for the unused time
1810 if ( $self->option('suspend_bill',1)
1811 or ( $self->part_pkg->option('suspend_bill',1)
1812 and ! $self->option('no_suspend_bill',1)
1814 or $hash{'order_date'} == $hash{'susp'}
1819 if ( $adjust_bill ) {
1820 if ( $self->part_pkg->option('unused_credit_suspend')
1821 or ( ref($reason) and $reason->unused_credit ) ) {
1822 # then the customer was credited for the unused time before suspending,
1823 # so their next bill should be immediate
1824 $hash{'bill'} = time;
1826 # add the length of time suspended to the bill date
1827 $hash{'bill'} = ( $hash{'bill'} || $hash{'setup'} ) + $inactive;
1832 $hash{'adjourn'} = '' if $hash{'adjourn'} and $hash{'adjourn'} < time;
1833 $hash{'resume'} = '' if !$hash{'adjourn'};
1834 my $new = new FS::cust_pkg ( \%hash );
1835 $error = $new->replace( $self, options => { $self->options } );
1837 $dbh->rollback if $oldAutoCommit;
1844 if ( $reason->unsuspend_pkgpart ) {
1845 warn "Suspend reason '".$reason->reason."' uses deprecated unsuspend_pkgpart feature.\n";
1846 my $part_pkg = FS::part_pkg->by_key($reason->unsuspend_pkgpart)
1847 or $error = "Unsuspend package definition ".$reason->unsuspend_pkgpart.
1849 my $start_date = $self->cust_main->next_bill_date
1850 if $reason->unsuspend_hold;
1853 $unsusp_pkg = FS::cust_pkg->new({
1854 'custnum' => $self->custnum,
1855 'pkgpart' => $reason->unsuspend_pkgpart,
1856 'start_date' => $start_date,
1857 'locationnum' => $self->locationnum,
1858 # discount? probably not...
1861 $error ||= $self->cust_main->order_pkg( 'cust_pkg' => $unsusp_pkg );
1864 # new way, using fees
1865 if ( $reason->feepart and $reason->fee_on_unsuspend ) {
1866 # register the need to charge a fee, cust_main->bill will do the rest
1867 warn "registering unsuspend fee: pkgnum ".$self->pkgnum.", feepart ".$reason->feepart."\n"
1869 my $cust_pkg_reason_fee = FS::cust_pkg_reason_fee->new({
1870 'pkgreasonnum' => $cust_pkg_reason->num,
1871 'pkgnum' => $self->pkgnum,
1872 'feepart' => $reason->feepart,
1873 'nextbill' => $reason->fee_hold,
1875 $error ||= $cust_pkg_reason_fee->insert;
1879 $dbh->rollback if $oldAutoCommit;
1884 if ( $conf->config('unsuspend_email_admin') ) {
1886 my $error = send_email(
1887 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
1888 #invoice_from ??? well as good as any
1889 'to' => $conf->config('unsuspend_email_admin'),
1890 'subject' => 'FREESIDE NOTIFICATION: Customer package unsuspended', 'body' => [
1891 "This is an automatic message from your Freeside installation\n",
1892 "informing you that the following customer package has been unsuspended:\n",
1894 'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
1895 'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
1896 ( map { "Service : $_\n" } @labels ),
1898 "An unsuspension fee was charged: ".
1899 $unsusp_pkg->part_pkg->pkg_comment."\n"
1903 'custnum' => $self->custnum,
1904 'msgtype' => 'admin',
1908 warn "WARNING: can't send unsuspension admin email (unsuspending anyway): ".
1914 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1915 $error = $supp_pkg->unsuspend(%opt, 'from_main' => 1);
1917 $dbh->rollback if $oldAutoCommit;
1918 return "unsuspending supplemental pkg#".$supp_pkg->pkgnum.": $error";
1922 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1929 Cancels any pending suspension (sets the adjourn field to null).
1931 If there is an error, returns the error, otherwise returns false.
1936 my( $self, %options ) = @_;
1939 my $oldAutoCommit = $FS::UID::AutoCommit;
1940 local $FS::UID::AutoCommit = 0;
1943 my $old = $self->select_for_update;
1945 my $pkgnum = $old->pkgnum;
1946 if ( $old->get('cancel') || $self->get('cancel') ) {
1947 dbh->rollback if $oldAutoCommit;
1948 return "Can't unadjourn cancelled package $pkgnum";
1949 # or at least it's pointless
1952 if ( $old->get('susp') || $self->get('susp') ) {
1953 dbh->rollback if $oldAutoCommit;
1954 return "Can't unadjourn suspended package $pkgnum";
1955 # perhaps this is arbitrary
1958 unless ( $old->get('adjourn') && $self->get('adjourn') ) {
1959 dbh->rollback if $oldAutoCommit;
1960 return ""; # no error
1963 my %hash = $self->hash;
1964 $hash{'adjourn'} = '';
1965 $hash{'resume'} = '';
1966 my $new = new FS::cust_pkg ( \%hash );
1967 $error = $new->replace( $self, options => { $self->options } );
1969 $dbh->rollback if $oldAutoCommit;
1973 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1980 =item change HASHREF | OPTION => VALUE ...
1982 Changes this package: cancels it and creates a new one, with a different
1983 pkgpart or locationnum or both. All services are transferred to the new
1984 package (no change will be made if this is not possible).
1986 Options may be passed as a list of key/value pairs or as a hash reference.
1993 New locationnum, to change the location for this package.
1997 New FS::cust_location object, to create a new location and assign it
2002 New FS::cust_main object, to create a new customer and assign the new package
2007 New pkgpart (see L<FS::part_pkg>).
2011 New refnum (see L<FS::part_referral>).
2015 New quantity; if unspecified, the new package will have the same quantity
2020 "New" (existing) FS::cust_pkg object. The package's services and other
2021 attributes will be transferred to this package.
2025 Set to true to transfer billing dates (start_date, setup, last_bill, bill,
2026 susp, adjourn, cancel, expire, and contract_end) to the new package.
2028 =item unprotect_svcs
2030 Normally, change() will rollback and return an error if some services
2031 can't be transferred (also see the I<cust_pkg-change_svcpart> config option).
2032 If unprotect_svcs is true, this method will transfer as many services as
2033 it can and then unconditionally cancel the old package.
2037 If specified, sets this value for the contract_end date on the new package
2038 (without regard for keep_dates or the usual date-preservation behavior.)
2039 Will throw an error if defined but false; the UI doesn't allow editing
2040 this unless it already exists, making removal impossible to undo.
2044 At least one of locationnum, cust_location, pkgpart, refnum, cust_main, or
2045 cust_pkg must be specified (otherwise, what's the point?)
2047 Returns either the new FS::cust_pkg object or a scalar error.
2051 my $err_or_new_cust_pkg = $old_cust_pkg->change
2055 #used by change and change_later
2056 #didn't put with documented check methods because it depends on change-specific opts
2057 #and it also possibly edits the value of opts
2061 if ( defined($opt->{'contract_end'}) ) {
2062 my $current_contract_end = $self->get('contract_end');
2063 unless ($opt->{'contract_end'}) {
2064 if ($current_contract_end) {
2065 return "Cannot remove contract end date when changing packages";
2067 #shouldn't even pass this option if there's not a current value
2068 #but can be handled gracefully if the option is empty
2069 warn "Contract end date passed unexpectedly";
2070 delete $opt->{'contract_end'};
2074 unless ($current_contract_end) {
2075 #option shouldn't be passed, throw error if it's non-empty
2076 return "Cannot add contract end date when changing packages " . $self->pkgnum;
2082 #some false laziness w/order
2085 my $opt = ref($_[0]) ? shift : { @_ };
2087 my $conf = new FS::Conf;
2089 # handle contract_end on cust_pkg same as passed option
2090 if ( $opt->{'cust_pkg'} ) {
2091 $opt->{'contract_end'} = $opt->{'cust_pkg'}->contract_end;
2092 delete $opt->{'contract_end'} unless $opt->{'contract_end'};
2095 # check contract_end, prevent adding/removing
2096 my $error = $self->_check_change($opt);
2097 return $error if $error;
2099 # Transactionize this whole mess
2100 my $oldAutoCommit = $FS::UID::AutoCommit;
2101 local $FS::UID::AutoCommit = 0;
2104 if ( $opt->{'cust_location'} ) {
2105 $error = $opt->{'cust_location'}->find_or_insert;
2107 $dbh->rollback if $oldAutoCommit;
2108 return "creating location record: $error";
2110 $opt->{'locationnum'} = $opt->{'cust_location'}->locationnum;
2113 # Before going any further here: if the package is still in the pre-setup
2114 # state, it's safe to modify it in place. No need to charge/credit for
2115 # partial period, transfer services, transfer usage pools, copy invoice
2116 # details, or change any dates.
2117 if ( ! $self->setup and ! $opt->{cust_pkg} and ! $opt->{cust_main} ) {
2118 foreach ( qw( locationnum pkgpart quantity refnum salesnum ) ) {
2119 if ( length($opt->{$_}) ) {
2120 $self->set($_, $opt->{$_});
2123 # almost. if the new pkgpart specifies start/adjourn/expire timers,
2125 if ( $opt->{'pkgpart'} and $opt->{'pkgpart'} != $self->pkgpart ) {
2126 $error ||= $self->set_initial_timers;
2128 # but if contract_end was explicitly specified, that overrides all else
2129 $self->set('contract_end', $opt->{'contract_end'})
2130 if $opt->{'contract_end'};
2131 $error ||= $self->replace;
2133 $dbh->rollback if $oldAutoCommit;
2134 return "modifying package: $error";
2136 $dbh->commit if $oldAutoCommit;
2145 $hash{'setup'} = $time if $self->setup;
2147 $hash{'change_date'} = $time;
2148 $hash{"change_$_"} = $self->$_()
2149 foreach qw( pkgnum pkgpart locationnum );
2151 if ( $opt->{'cust_pkg'} ) {
2152 # treat changing to a package with a different pkgpart as a
2153 # pkgpart change (because it is)
2154 $opt->{'pkgpart'} = $opt->{'cust_pkg'}->pkgpart;
2157 # whether to override pkgpart checking on the new package
2158 my $same_pkgpart = 1;
2159 if ( $opt->{'pkgpart'} and ( $opt->{'pkgpart'} != $self->pkgpart ) ) {
2163 my $unused_credit = 0;
2164 my $keep_dates = $opt->{'keep_dates'};
2166 # Special case. If the pkgpart is changing, and the customer is
2167 # going to be credited for remaining time, don't keep setup, bill,
2168 # or last_bill dates, and DO pass the flag to cancel() to credit
2170 if ( $opt->{'pkgpart'}
2171 and $opt->{'pkgpart'} != $self->pkgpart
2172 and $self->part_pkg->option('unused_credit_change', 1) ) {
2175 $hash{$_} = '' foreach qw(setup bill last_bill);
2178 if ( $keep_dates ) {
2179 foreach my $date ( qw(setup bill last_bill) ) {
2180 $hash{$date} = $self->getfield($date);
2183 # always keep the following dates
2184 foreach my $date (qw(order_date susp adjourn cancel expire resume
2185 start_date contract_end)) {
2186 $hash{$date} = $self->getfield($date);
2188 # but if contract_end was explicitly specified, that overrides all else
2189 $hash{'contract_end'} = $opt->{'contract_end'}
2190 if $opt->{'contract_end'};
2192 # allow $opt->{'locationnum'} = '' to specifically set it to null
2193 # (i.e. customer default location)
2194 $opt->{'locationnum'} = $self->locationnum if !exists($opt->{'locationnum'});
2196 # usually this doesn't matter. the two cases where it does are:
2197 # 1. unused_credit_change + pkgpart change + setup fee on the new package
2199 # 2. (more importantly) changing a package before it's billed
2200 $hash{'waive_setup'} = $self->waive_setup;
2202 # if this package is scheduled for a future package change, preserve that
2203 $hash{'change_to_pkgnum'} = $self->change_to_pkgnum;
2205 my $custnum = $self->custnum;
2206 if ( $opt->{cust_main} ) {
2207 my $cust_main = $opt->{cust_main};
2208 unless ( $cust_main->custnum ) {
2209 my $error = $cust_main->insert( @{ $opt->{cust_main_insert_args}||[] } );
2211 $dbh->rollback if $oldAutoCommit;
2212 return "inserting customer record: $error";
2215 $custnum = $cust_main->custnum;
2218 $hash{'contactnum'} = $opt->{'contactnum'} if $opt->{'contactnum'};
2221 if ( $opt->{'cust_pkg'} ) {
2222 # The target package already exists; update it to show that it was
2223 # changed from this package.
2224 $cust_pkg = $opt->{'cust_pkg'};
2226 # follow all the above rules for date changes, etc.
2227 foreach (keys %hash) {
2228 $cust_pkg->set($_, $hash{$_});
2230 # except those that implement the future package change behavior
2231 foreach (qw(change_to_pkgnum start_date expire)) {
2232 $cust_pkg->set($_, '');
2235 $error = $cust_pkg->replace;
2238 # Create the new package.
2239 $cust_pkg = new FS::cust_pkg {
2240 custnum => $custnum,
2241 locationnum => $opt->{'locationnum'},
2242 ( map { $_ => ( $opt->{$_} || $self->$_() ) }
2243 qw( pkgpart quantity refnum salesnum )
2247 $error = $cust_pkg->insert( 'change' => 1,
2248 'allow_pkgpart' => $same_pkgpart );
2251 $dbh->rollback if $oldAutoCommit;
2252 return "inserting new package: $error";
2255 # Transfer services and cancel old package.
2256 # Enforce service limits only if this is a pkgpart change.
2257 local $FS::cust_svc::ignore_quantity;
2258 $FS::cust_svc::ignore_quantity = 1 if $same_pkgpart;
2259 $error = $self->transfer($cust_pkg);
2260 if ($error and $error == 0) {
2261 # $old_pkg->transfer failed.
2262 $dbh->rollback if $oldAutoCommit;
2263 return "transferring $error";
2266 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
2267 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
2268 $error = $self->transfer($cust_pkg, 'change_svcpart'=>1 );
2269 if ($error and $error == 0) {
2270 # $old_pkg->transfer failed.
2271 $dbh->rollback if $oldAutoCommit;
2272 return "converting $error";
2276 # We set unprotect_svcs when executing a "future package change". It's
2277 # not a user-interactive operation, so returning an error means the
2278 # package change will just fail. Rather than have that happen, we'll
2279 # let leftover services be deleted.
2280 if ($error > 0 and !$opt->{'unprotect_svcs'}) {
2281 # Transfers were successful, but we still had services left on the old
2282 # package. We can't change the package under this circumstances, so abort.
2283 $dbh->rollback if $oldAutoCommit;
2284 return "unable to transfer all services";
2287 #reset usage if changing pkgpart
2288 # AND usage rollover is off (otherwise adds twice, now and at package bill)
2289 if ($self->pkgpart != $cust_pkg->pkgpart) {
2290 my $part_pkg = $cust_pkg->part_pkg;
2291 $error = $part_pkg->reset_usage($cust_pkg, $part_pkg->is_prepaid
2295 if $part_pkg->can('reset_usage') && ! $part_pkg->option('usage_rollover',1);
2298 $dbh->rollback if $oldAutoCommit;
2299 return "setting usage values: $error";
2302 # if NOT changing pkgpart, transfer any usage pools over
2303 foreach my $usage ($self->cust_pkg_usage) {
2304 $usage->set('pkgnum', $cust_pkg->pkgnum);
2305 $error = $usage->replace;
2307 $dbh->rollback if $oldAutoCommit;
2308 return "transferring usage pools: $error";
2313 # transfer usage pricing add-ons, if we're not changing pkgpart or if they were specified
2314 if ( $same_pkgpart || $opt->{'cust_pkg_usageprice'}) {
2315 my @old_cust_pkg_usageprice;
2316 if ($opt->{'cust_pkg_usageprice'}) {
2317 @old_cust_pkg_usageprice = @{ $opt->{'cust_pkg_usageprice'} };
2319 @old_cust_pkg_usageprice = $self->cust_pkg_usageprice;
2321 foreach my $old_cust_pkg_usageprice (@old_cust_pkg_usageprice) {
2322 my $new_cust_pkg_usageprice = new FS::cust_pkg_usageprice {
2323 'pkgnum' => $cust_pkg->pkgnum,
2324 'usagepricepart' => $old_cust_pkg_usageprice->usagepricepart,
2325 'quantity' => $old_cust_pkg_usageprice->quantity,
2327 $error = $new_cust_pkg_usageprice->insert;
2329 $dbh->rollback if $oldAutoCommit;
2330 return "Error transferring usage pricing add-on: $error";
2335 # transfer discounts, if we're not changing pkgpart
2336 if ( $same_pkgpart ) {
2337 foreach my $old_discount ($self->cust_pkg_discount_active) {
2338 # don't remove the old discount, we may still need to bill that package.
2339 my $new_discount = new FS::cust_pkg_discount {
2340 'pkgnum' => $cust_pkg->pkgnum,
2341 'discountnum' => $old_discount->discountnum,
2342 'months_used' => $old_discount->months_used,
2344 $error = $new_discount->insert;
2346 $dbh->rollback if $oldAutoCommit;
2347 return "transferring discounts: $error";
2352 # transfer (copy) invoice details
2353 foreach my $detail ($self->cust_pkg_detail) {
2354 my $new_detail = FS::cust_pkg_detail->new({ $detail->hash });
2355 $new_detail->set('pkgdetailnum', '');
2356 $new_detail->set('pkgnum', $cust_pkg->pkgnum);
2357 $error = $new_detail->insert;
2359 $dbh->rollback if $oldAutoCommit;
2360 return "transferring package notes: $error";
2366 if ( !$opt->{'cust_pkg'} ) {
2367 # Order any supplemental packages.
2368 my $part_pkg = $cust_pkg->part_pkg;
2369 my @old_supp_pkgs = $self->supplemental_pkgs;
2370 foreach my $link ($part_pkg->supp_part_pkg_link) {
2372 foreach (@old_supp_pkgs) {
2373 if ($_->pkgpart == $link->dst_pkgpart) {
2375 $_->pkgpart(0); # so that it can't match more than once
2379 # false laziness with FS::cust_main::Packages::order_pkg
2380 my $new = FS::cust_pkg->new({
2381 pkgpart => $link->dst_pkgpart,
2382 pkglinknum => $link->pkglinknum,
2383 custnum => $custnum,
2384 main_pkgnum => $cust_pkg->pkgnum,
2385 locationnum => $cust_pkg->locationnum,
2386 start_date => $cust_pkg->start_date,
2387 order_date => $cust_pkg->order_date,
2388 expire => $cust_pkg->expire,
2389 adjourn => $cust_pkg->adjourn,
2390 contract_end => $cust_pkg->contract_end,
2391 refnum => $cust_pkg->refnum,
2392 discountnum => $cust_pkg->discountnum,
2393 waive_setup => $cust_pkg->waive_setup,
2395 if ( $old and $opt->{'keep_dates'} ) {
2396 foreach (qw(setup bill last_bill)) {
2397 $new->set($_, $old->get($_));
2400 $error = $new->insert( allow_pkgpart => $same_pkgpart );
2403 $error ||= $old->transfer($new);
2405 if ( $error and $error > 0 ) {
2406 # no reason why this should ever fail, but still...
2407 $error = "Unable to transfer all services from supplemental package ".
2411 $dbh->rollback if $oldAutoCommit;
2414 push @new_supp_pkgs, $new;
2416 } # if !$opt->{'cust_pkg'}
2417 # because if there is one, then supplemental packages would already
2418 # have been created for it.
2420 #Good to go, cancel old package. Notify 'cancel' of whether to credit
2422 #Don't allow billing the package (preceding period packages and/or
2423 #outstanding usage) if we are keeping dates (i.e. location changing),
2424 #because the new package will be billed for the same date range.
2425 #Supplemental packages are also canceled here.
2427 # during scheduled changes, avoid canceling the package we just
2429 $self->set('change_to_pkgnum' => '');
2431 $error = $self->cancel(
2433 unused_credit => $unused_credit,
2434 nobill => $keep_dates,
2435 change_custnum => ( $self->custnum != $custnum ? $custnum : '' ),
2436 no_delay_cancel => 1,
2439 $dbh->rollback if $oldAutoCommit;
2440 return "canceling old package: $error";
2443 if ( $conf->exists('cust_pkg-change_pkgpart-bill_now') ) {
2445 my $error = $cust_pkg->cust_main->bill(
2446 'pkg_list' => [ $cust_pkg, @new_supp_pkgs ]
2449 $dbh->rollback if $oldAutoCommit;
2450 return "billing new package: $error";
2454 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2460 =item change_later OPTION => VALUE...
2462 Schedule a package change for a later date. This actually orders the new
2463 package immediately, but sets its start date for a future date, and sets
2464 the current package to expire on the same date.
2466 If the package is already scheduled for a change, this can be called with
2467 'start_date' to change the scheduled date, or with pkgpart and/or
2468 locationnum to modify the package change. To cancel the scheduled change
2469 entirely, see C<abort_change>.
2477 The date for the package change. Required, and must be in the future.
2487 The pkgpart, locationnum, quantity and optional contract_end of the new
2488 package, with the same meaning as in C<change>.
2496 my $opt = ref($_[0]) ? shift : { @_ };
2498 # check contract_end, prevent adding/removing
2499 my $error = $self->_check_change($opt);
2500 return $error if $error;
2502 my $oldAutoCommit = $FS::UID::AutoCommit;
2503 local $FS::UID::AutoCommit = 0;
2506 my $cust_main = $self->cust_main;
2508 my $date = delete $opt->{'start_date'} or return 'start_date required';
2510 if ( $date <= time ) {
2511 $dbh->rollback if $oldAutoCommit;
2512 return "start_date $date is in the past";
2515 if ( $self->change_to_pkgnum ) {
2516 my $change_to = FS::cust_pkg->by_key($self->change_to_pkgnum);
2517 my $new_pkgpart = $opt->{'pkgpart'}
2518 if $opt->{'pkgpart'} and $opt->{'pkgpart'} != $change_to->pkgpart;
2519 my $new_locationnum = $opt->{'locationnum'}
2520 if $opt->{'locationnum'} and $opt->{'locationnum'} != $change_to->locationnum;
2521 my $new_quantity = $opt->{'quantity'}
2522 if $opt->{'quantity'} and $opt->{'quantity'} != $change_to->quantity;
2523 my $new_contract_end = $opt->{'contract_end'}
2524 if $opt->{'contract_end'} and $opt->{'contract_end'} != $change_to->contract_end;
2525 if ( $new_pkgpart or $new_locationnum or $new_quantity or $new_contract_end ) {
2526 # it hasn't been billed yet, so in principle we could just edit
2527 # it in place (w/o a package change), but that's bad form.
2528 # So change the package according to the new options...
2529 my $err_or_pkg = $change_to->change(%$opt);
2530 if ( ref $err_or_pkg ) {
2531 # Then set that package up for a future start.
2532 $self->set('change_to_pkgnum', $err_or_pkg->pkgnum);
2533 $self->set('expire', $date); # in case it's different
2534 $err_or_pkg->set('start_date', $date);
2535 $err_or_pkg->set('change_date', '');
2536 $err_or_pkg->set('change_pkgnum', '');
2538 $error = $self->replace ||
2539 $err_or_pkg->replace ||
2540 #because change() might've edited existing scheduled change in place
2541 (($err_or_pkg->pkgnum == $change_to->pkgnum) ? '' :
2542 $change_to->cancel('no_delay_cancel' => 1) ||
2543 $change_to->delete);
2545 $error = $err_or_pkg;
2547 } else { # change the start date only.
2548 $self->set('expire', $date);
2549 $change_to->set('start_date', $date);
2550 $error = $self->replace || $change_to->replace;
2553 $dbh->rollback if $oldAutoCommit;
2556 $dbh->commit if $oldAutoCommit;
2559 } # if $self->change_to_pkgnum
2561 my $new_pkgpart = $opt->{'pkgpart'}
2562 if $opt->{'pkgpart'} and $opt->{'pkgpart'} != $self->pkgpart;
2563 my $new_locationnum = $opt->{'locationnum'}
2564 if $opt->{'locationnum'} and $opt->{'locationnum'} != $self->locationnum;
2565 my $new_quantity = $opt->{'quantity'}
2566 if $opt->{'quantity'} and $opt->{'quantity'} != $self->quantity;
2567 my $new_contract_end = $opt->{'contract_end'}
2568 if $opt->{'contract_end'} and $opt->{'contract_end'} != $self->contract_end;
2570 return '' unless $new_pkgpart or $new_locationnum or $new_quantity or $new_contract_end; # wouldn't do anything
2572 # allow $opt->{'locationnum'} = '' to specifically set it to null
2573 # (i.e. customer default location)
2574 $opt->{'locationnum'} = $self->locationnum if !exists($opt->{'locationnum'});
2576 my $new = FS::cust_pkg->new( {
2577 custnum => $self->custnum,
2578 locationnum => $opt->{'locationnum'},
2579 start_date => $date,
2580 map { $_ => ( $opt->{$_} || $self->$_() ) }
2581 qw( pkgpart quantity refnum salesnum contract_end )
2583 $error = $new->insert('change' => 1,
2584 'allow_pkgpart' => ($new_pkgpart ? 0 : 1));
2586 $self->set('change_to_pkgnum', $new->pkgnum);
2587 $self->set('expire', $date);
2588 $error = $self->replace;
2591 $dbh->rollback if $oldAutoCommit;
2593 $dbh->commit if $oldAutoCommit;
2601 Cancels a future package change scheduled by C<change_later>.
2607 my $oldAutoCommit = $FS::UID::AutoCommit;
2608 local $FS::UID::AutoCommit = 0;
2610 my $pkgnum = $self->change_to_pkgnum;
2611 my $change_to = FS::cust_pkg->by_key($pkgnum) if $pkgnum;
2613 $self->set('change_to_pkgnum', '');
2614 $self->set('expire', '');
2615 $error = $self->replace;
2617 $error ||= $change_to->cancel || $change_to->delete;
2620 if ( $oldAutoCommit ) {
2631 =item set_quantity QUANTITY
2633 Change the package's quantity field. This is one of the few package properties
2634 that can safely be changed without canceling and reordering the package
2635 (because it doesn't affect tax eligibility). Returns an error or an
2642 $self = $self->replace_old; # just to make sure
2643 $self->quantity(shift);
2647 =item set_salesnum SALESNUM
2649 Change the package's salesnum (sales person) field. This is one of the few
2650 package properties that can safely be changed without canceling and reordering
2651 the package (because it doesn't affect tax eligibility). Returns an error or
2658 $self = $self->replace_old; # just to make sure
2659 $self->salesnum(shift);
2661 # XXX this should probably reassign any credit that's already been given
2664 =item modify_charge OPTIONS
2666 Change the properties of a one-time charge. The following properties can
2667 be changed this way:
2668 - pkg: the package description
2669 - classnum: the package class
2670 - additional: arrayref of additional invoice details to add to this package
2672 and, I<if the charge has not yet been billed>:
2673 - start_date: the date when it will be billed
2674 - amount: the setup fee to be charged
2675 - quantity: the multiplier for the setup fee
2676 - separate_bill: whether to put the charge on a separate invoice
2678 If you pass 'adjust_commission' => 1, and the classnum changes, and there are
2679 commission credits linked to this charge, they will be recalculated.
2686 my $part_pkg = $self->part_pkg;
2687 my $pkgnum = $self->pkgnum;
2690 my $oldAutoCommit = $FS::UID::AutoCommit;
2691 local $FS::UID::AutoCommit = 0;
2693 return "Can't use modify_charge except on one-time charges"
2694 unless $part_pkg->freq eq '0';
2696 if ( length($opt{'pkg'}) and $part_pkg->pkg ne $opt{'pkg'} ) {
2697 $part_pkg->set('pkg', $opt{'pkg'});
2700 my %pkg_opt = $part_pkg->options;
2701 my $pkg_opt_modified = 0;
2703 $opt{'additional'} ||= [];
2706 foreach (grep /^additional/, keys %pkg_opt) {
2707 ($i) = ($_ =~ /^additional_info(\d+)$/);
2708 $old_additional[$i] = $pkg_opt{$_} if $i;
2709 delete $pkg_opt{$_};
2712 for ( $i = 0; exists($opt{'additional'}->[$i]); $i++ ) {
2713 $pkg_opt{ "additional_info$i" } = $opt{'additional'}->[$i];
2714 if (!exists($old_additional[$i])
2715 or $old_additional[$i] ne $opt{'additional'}->[$i])
2717 $pkg_opt_modified = 1;
2720 $pkg_opt_modified = 1 if (scalar(@old_additional) - 1) != $i;
2721 $pkg_opt{'additional_count'} = $i if $i > 0;
2724 if ( exists($opt{'classnum'}) and $part_pkg->classnum ne $opt{'classnum'} )
2727 $old_classnum = $part_pkg->classnum;
2728 $part_pkg->set('classnum', $opt{'classnum'});
2731 if ( !$self->get('setup') ) {
2732 # not yet billed, so allow amount, setup_cost, quantity, start_date,
2735 if ( exists($opt{'amount'})
2736 and $part_pkg->option('setup_fee') != $opt{'amount'}
2737 and $opt{'amount'} > 0 ) {
2739 $pkg_opt{'setup_fee'} = $opt{'amount'};
2740 $pkg_opt_modified = 1;
2743 if ( exists($opt{'setup_cost'})
2744 and $part_pkg->setup_cost != $opt{'setup_cost'}
2745 and $opt{'setup_cost'} > 0 ) {
2747 $part_pkg->set('setup_cost', $opt{'setup_cost'});
2750 if ( exists($opt{'quantity'})
2751 and $opt{'quantity'} != $self->quantity
2752 and $opt{'quantity'} > 0 ) {
2754 $self->set('quantity', $opt{'quantity'});
2757 if ( exists($opt{'start_date'})
2758 and $opt{'start_date'} != $self->start_date ) {
2760 $self->set('start_date', $opt{'start_date'});
2763 if ( exists($opt{'separate_bill'})
2764 and $opt{'separate_bill'} ne $self->separate_bill ) {
2766 $self->set('separate_bill', $opt{'separate_bill'});
2770 } # else simply ignore them; the UI shouldn't allow editing the fields
2773 if ( exists($opt{'taxclass'})
2774 and $part_pkg->taxclass ne $opt{'taxclass'}) {
2776 $part_pkg->set('taxclass', $opt{'taxclass'});
2780 if ( $part_pkg->modified or $pkg_opt_modified ) {
2781 # can we safely modify the package def?
2782 # Yes, if it's not available for purchase, and this is the only instance
2784 if ( $part_pkg->disabled
2785 and FS::cust_pkg->count('pkgpart = '.$part_pkg->pkgpart) == 1
2786 and FS::quotation_pkg->count('pkgpart = '.$part_pkg->pkgpart) == 0
2788 $error = $part_pkg->replace( options => \%pkg_opt );
2791 $part_pkg = $part_pkg->clone;
2792 $part_pkg->set('disabled' => 'Y');
2793 $error = $part_pkg->insert( options => \%pkg_opt );
2794 # and associate this as yet-unbilled package to the new package def
2795 $self->set('pkgpart' => $part_pkg->pkgpart);
2798 $dbh->rollback if $oldAutoCommit;
2803 if ($self->modified) { # for quantity or start_date change, or if we had
2804 # to clone the existing package def
2805 my $error = $self->replace;
2806 return $error if $error;
2808 if (defined $old_classnum) {
2809 # fix invoice grouping records
2810 my $old_catname = $old_classnum
2811 ? FS::pkg_class->by_key($old_classnum)->categoryname
2813 my $new_catname = $opt{'classnum'}
2814 ? $part_pkg->pkg_class->categoryname
2816 if ( $old_catname ne $new_catname ) {
2817 foreach my $cust_bill_pkg ($self->cust_bill_pkg) {
2818 # (there should only be one...)
2819 my @display = qsearch( 'cust_bill_pkg_display', {
2820 'billpkgnum' => $cust_bill_pkg->billpkgnum,
2821 'section' => $old_catname,
2823 foreach (@display) {
2824 $_->set('section', $new_catname);
2825 $error = $_->replace;
2827 $dbh->rollback if $oldAutoCommit;
2831 } # foreach $cust_bill_pkg
2834 if ( $opt{'adjust_commission'} ) {
2835 # fix commission credits...tricky.
2836 foreach my $cust_event ($self->cust_event) {
2837 my $part_event = $cust_event->part_event;
2838 foreach my $table (qw(sales agent)) {
2840 "FS::part_event::Action::Mixin::credit_${table}_pkg_class";
2841 my $credit = qsearchs('cust_credit', {
2842 'eventnum' => $cust_event->eventnum,
2844 if ( $part_event->isa($class) ) {
2845 # Yes, this results in current commission rates being applied
2846 # retroactively to a one-time charge. For accounting purposes
2847 # there ought to be some kind of time limit on doing this.
2848 my $amount = $part_event->_calc_credit($self);
2849 if ( $credit and $credit->amount ne $amount ) {
2850 # Void the old credit.
2851 $error = $credit->void('Package class changed');
2853 $dbh->rollback if $oldAutoCommit;
2854 return "$error (adjusting commission credit)";
2857 # redo the event action to recreate the credit.
2859 eval { $part_event->do_action( $self, $cust_event ) };
2861 $dbh->rollback if $oldAutoCommit;
2864 } # if $part_event->isa($class)
2866 } # foreach $cust_event
2867 } # if $opt{'adjust_commission'}
2868 } # if defined $old_classnum
2870 $dbh->commit if $oldAutoCommit;
2877 sub process_bulk_cust_pkg {
2880 warn Dumper($param) if $DEBUG;
2882 my $old_part_pkg = qsearchs('part_pkg',
2883 { pkgpart => $param->{'old_pkgpart'} });
2884 my $new_part_pkg = qsearchs('part_pkg',
2885 { pkgpart => $param->{'new_pkgpart'} });
2886 die "Must select a new package type\n" unless $new_part_pkg;
2887 #my $keep_dates = $param->{'keep_dates'} || 0;
2888 my $keep_dates = 1; # there is no good reason to turn this off
2890 my $oldAutoCommit = $FS::UID::AutoCommit;
2891 local $FS::UID::AutoCommit = 0;
2894 my @cust_pkgs = qsearch('cust_pkg', { 'pkgpart' => $param->{'old_pkgpart'} } );
2897 foreach my $old_cust_pkg ( @cust_pkgs ) {
2899 $job->update_statustext(int(100*$i/(scalar @cust_pkgs)));
2900 if ( $old_cust_pkg->getfield('cancel') ) {
2901 warn '[process_bulk_cust_pkg ] skipping canceled pkgnum '.
2902 $old_cust_pkg->pkgnum."\n"
2906 warn '[process_bulk_cust_pkg] changing pkgnum '.$old_cust_pkg->pkgnum."\n"
2908 my $error = $old_cust_pkg->change(
2909 'pkgpart' => $param->{'new_pkgpart'},
2910 'keep_dates' => $keep_dates
2912 if ( !ref($error) ) { # change returns the cust_pkg on success
2914 die "Error changing pkgnum ".$old_cust_pkg->pkgnum.": '$error'\n";
2917 $dbh->commit if $oldAutoCommit;
2923 Returns the last bill date, or if there is no last bill date, the setup date.
2924 Useful for billing metered services.
2930 return $self->setfield('last_bill', $_[0]) if @_;
2931 return $self->getfield('last_bill') if $self->getfield('last_bill');
2932 my $cust_bill_pkg = qsearchs('cust_bill_pkg', { 'pkgnum' => $self->pkgnum,
2933 'edate' => $self->bill, } );
2934 $cust_bill_pkg ? $cust_bill_pkg->sdate : $self->setup || 0;
2937 =item last_cust_pkg_reason ACTION
2939 Returns the most recent ACTION FS::cust_pkg_reason associated with the package.
2940 Returns false if there is no reason or the package is not currenly ACTION'd
2941 ACTION is one of adjourn, susp, cancel, or expire.
2945 sub last_cust_pkg_reason {
2946 my ( $self, $action ) = ( shift, shift );
2947 my $date = $self->get($action);
2949 'table' => 'cust_pkg_reason',
2950 'hashref' => { 'pkgnum' => $self->pkgnum,
2951 'action' => substr(uc($action), 0, 1),
2954 'order_by' => 'ORDER BY num DESC LIMIT 1',
2958 =item last_reason ACTION
2960 Returns the most recent ACTION FS::reason associated with the package.
2961 Returns false if there is no reason or the package is not currenly ACTION'd
2962 ACTION is one of adjourn, susp, cancel, or expire.
2967 my $cust_pkg_reason = shift->last_cust_pkg_reason(@_);
2968 $cust_pkg_reason->reason
2969 if $cust_pkg_reason;
2974 Returns the definition for this billing item, as an FS::part_pkg object (see
2981 return $self->{'_pkgpart'} if $self->{'_pkgpart'};
2982 cluck "cust_pkg->part_pkg called" if $DEBUG > 1;
2983 qsearchs( 'part_pkg', { 'pkgpart' => $self->pkgpart } );
2988 Returns the cancelled package this package was changed from, if any.
2994 return '' unless $self->change_pkgnum;
2995 qsearchs('cust_pkg', { 'pkgnum' => $self->change_pkgnum } );
2998 =item change_cust_main
3000 Returns the customter this package was detached to, if any.
3004 sub change_cust_main {
3006 return '' unless $self->change_custnum;
3007 qsearchs('cust_main', { 'custnum' => $self->change_custnum } );
3012 Calls the I<calc_setup> of the FS::part_pkg object associated with this billing
3019 $self->part_pkg->calc_setup($self, @_);
3024 Calls the I<calc_recur> of the FS::part_pkg object associated with this billing
3031 $self->part_pkg->calc_recur($self, @_);
3036 Calls the I<base_setup> of the FS::part_pkg object associated with this billing
3043 $self->part_pkg->base_setup($self, @_);
3048 Calls the I<base_recur> of the FS::part_pkg object associated with this billing
3055 $self->part_pkg->base_recur($self, @_);
3060 Calls the I<calc_remain> of the FS::part_pkg object associated with this
3067 $self->part_pkg->calc_remain($self, @_);
3072 Calls the I<calc_cancel> of the FS::part_pkg object associated with this
3079 $self->part_pkg->calc_cancel($self, @_);
3084 Returns any invoice line items for this package (see L<FS::cust_bill_pkg>).
3090 qsearch( 'cust_bill_pkg', { 'pkgnum' => $self->pkgnum } );
3093 =item cust_pkg_detail [ DETAILTYPE ]
3095 Returns any customer package details for this package (see
3096 L<FS::cust_pkg_detail>).
3098 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
3102 sub cust_pkg_detail {
3104 my %hash = ( 'pkgnum' => $self->pkgnum );
3105 $hash{detailtype} = shift if @_;
3107 'table' => 'cust_pkg_detail',
3108 'hashref' => \%hash,
3109 'order_by' => 'ORDER BY weight, pkgdetailnum',
3113 =item set_cust_pkg_detail DETAILTYPE [ DETAIL, DETAIL, ... ]
3115 Sets customer package details for this package (see L<FS::cust_pkg_detail>).
3117 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
3119 If there is an error, returns the error, otherwise returns false.
3123 sub set_cust_pkg_detail {
3124 my( $self, $detailtype, @details ) = @_;
3126 my $oldAutoCommit = $FS::UID::AutoCommit;
3127 local $FS::UID::AutoCommit = 0;
3130 foreach my $current ( $self->cust_pkg_detail($detailtype) ) {
3131 my $error = $current->delete;
3133 $dbh->rollback if $oldAutoCommit;
3134 return "error removing old detail: $error";
3138 foreach my $detail ( @details ) {
3139 my $cust_pkg_detail = new FS::cust_pkg_detail {
3140 'pkgnum' => $self->pkgnum,
3141 'detailtype' => $detailtype,
3142 'detail' => $detail,
3144 my $error = $cust_pkg_detail->insert;
3146 $dbh->rollback if $oldAutoCommit;
3147 return "error adding new detail: $error";
3152 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3159 Returns the customer billing events (see L<FS::cust_event>) for this invoice.
3163 #false laziness w/cust_bill.pm
3167 'table' => 'cust_event',
3168 'addl_from' => 'JOIN part_event USING ( eventpart )',
3169 'hashref' => { 'tablenum' => $self->pkgnum },
3170 'extra_sql' => " AND eventtable = 'cust_pkg' ",
3174 =item num_cust_event
3176 Returns the number of customer billing events (see L<FS::cust_event>) for this package.
3180 #false laziness w/cust_bill.pm
3181 sub num_cust_event {
3183 my $sql = "SELECT COUNT(*) ". $self->_from_cust_event_where;
3184 $self->_prep_ex($sql, $self->pkgnum)->fetchrow_arrayref->[0];
3187 =item exists_cust_event
3189 Returns true if there are customer billing events (see L<FS::cust_event>) for this package. More efficient than using num_cust_event.
3193 sub exists_cust_event {
3195 my $sql = "SELECT 1 ". $self->_from_cust_event_where. " LIMIT 1";
3196 my $row = $self->_prep_ex($sql, $self->pkgnum)->fetchrow_arrayref;
3197 $row ? $row->[0] : '';
3200 sub _from_cust_event_where {
3202 " FROM cust_event JOIN part_event USING ( eventpart ) ".
3203 " WHERE tablenum = ? AND eventtable = 'cust_pkg' ";
3207 my( $self, $sql, @args ) = @_;
3208 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
3209 $sth->execute(@args) or die $sth->errstr. " executing $sql";
3213 =item part_pkg_currency_option OPTIONNAME
3215 Returns a two item list consisting of the currency of this customer, if any,
3216 and a value for the provided option. If the customer has a currency, the value
3217 is the option value the given name and the currency (see
3218 L<FS::part_pkg_currency>). Otherwise, if the customer has no currency, is the
3219 regular option value for the given name (see L<FS::part_pkg_option>).
3223 sub part_pkg_currency_option {
3224 my( $self, $optionname ) = @_;
3225 my $part_pkg = $self->part_pkg;
3226 if ( my $currency = $self->cust_main->currency ) {
3227 ($currency, $part_pkg->part_pkg_currency_option($currency, $optionname) );
3229 ('', $part_pkg->option($optionname) );
3233 =item cust_svc [ SVCPART ] (old, deprecated usage)
3235 =item cust_svc [ OPTION => VALUE ... ] (current usage)
3237 =item cust_svc_unsorted [ OPTION => VALUE ... ]
3239 Returns the services for this package, as FS::cust_svc objects (see
3240 L<FS::cust_svc>). Available options are svcpart and svcdb. If either is
3241 spcififed, returns only the matching services.
3243 As an optimization, use the cust_svc_unsorted version if you are not displaying
3250 cluck "cust_pkg->cust_svc called" if $DEBUG > 2;
3251 $self->_sort_cust_svc( $self->cust_svc_unsorted_arrayref(@_) );
3254 sub cust_svc_unsorted {
3256 @{ $self->cust_svc_unsorted_arrayref(@_) };
3259 sub cust_svc_unsorted_arrayref {
3262 return [] unless $self->num_cust_svc(@_);
3265 if ( @_ && $_[0] =~ /^\d+/ ) {
3266 $opt{svcpart} = shift;
3267 } elsif ( @_ && ref($_[0]) eq 'HASH' ) {
3274 'table' => 'cust_svc',
3275 'hashref' => { 'pkgnum' => $self->pkgnum },
3277 if ( $opt{svcpart} ) {
3278 $search{hashref}->{svcpart} = $opt{'svcpart'};
3280 if ( $opt{'svcdb'} ) {
3281 $search{addl_from} = ' LEFT JOIN part_svc USING ( svcpart ) ';
3282 $search{extra_sql} = ' AND svcdb = '. dbh->quote( $opt{'svcdb'} );
3285 [ qsearch(\%search) ];
3289 =item overlimit [ SVCPART ]
3291 Returns the services for this package which have exceeded their
3292 usage limit as FS::cust_svc objects (see L<FS::cust_svc>). If a svcpart
3293 is specified, return only the matching services.
3299 return () unless $self->num_cust_svc(@_);
3300 grep { $_->overlimit } $self->cust_svc(@_);
3303 =item h_cust_svc END_TIMESTAMP [ START_TIMESTAMP ] [ MODE ]
3305 Returns historical services for this package created before END TIMESTAMP and
3306 (optionally) not cancelled before START_TIMESTAMP, as FS::h_cust_svc objects
3307 (see L<FS::h_cust_svc>). If MODE is 'I' (for 'invoice'), services with the
3308 I<pkg_svc.hidden> flag will be omitted.
3314 warn "$me _h_cust_svc called on $self\n"
3317 my ($end, $start, $mode) = @_;
3319 local($FS::Record::qsearch_qualify_columns) = 0;
3321 my @cust_svc = $self->_sort_cust_svc(
3322 [ qsearch( 'h_cust_svc',
3323 { 'pkgnum' => $self->pkgnum, },
3324 FS::h_cust_svc->sql_h_search(@_),
3328 if ( defined($mode) && $mode eq 'I' ) {
3329 my %hidden_svcpart = map { $_->svcpart => $_->hidden } $self->part_svc;
3330 return grep { !$hidden_svcpart{$_->svcpart} } @cust_svc;
3336 sub _sort_cust_svc {
3337 my( $self, $arrayref ) = @_;
3340 sub ($$) { my ($a, $b) = @_; $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] };
3342 my %pkg_svc = map { $_->svcpart => $_ }
3343 qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
3348 my $pkg_svc = $pkg_svc{ $_->svcpart } || '';
3350 $pkg_svc ? $pkg_svc->primary_svc : '',
3351 $pkg_svc ? $pkg_svc->quantity : 0,
3358 =item num_cust_svc [ SVCPART ] (old, deprecated usage)
3360 =item num_cust_svc [ OPTION => VALUE ... ] (current usage)
3362 Returns the number of services for this package. Available options are svcpart
3363 and svcdb. If either is spcififed, returns only the matching services.
3370 return $self->{'_num_cust_svc'}
3372 && exists($self->{'_num_cust_svc'})
3373 && $self->{'_num_cust_svc'} =~ /\d/;
3375 cluck "cust_pkg->num_cust_svc called, _num_cust_svc:".$self->{'_num_cust_svc'}
3379 if ( @_ && $_[0] =~ /^\d+/ ) {
3380 $opt{svcpart} = shift;
3381 } elsif ( @_ && ref($_[0]) eq 'HASH' ) {
3387 my $select = 'SELECT COUNT(*) FROM cust_svc ';
3388 my $where = ' WHERE pkgnum = ? ';
3389 my @param = ($self->pkgnum);
3391 if ( $opt{'svcpart'} ) {
3392 $where .= ' AND svcpart = ? ';
3393 push @param, $opt{'svcpart'};
3395 if ( $opt{'svcdb'} ) {
3396 $select .= ' LEFT JOIN part_svc USING ( svcpart ) ';
3397 $where .= ' AND svcdb = ? ';
3398 push @param, $opt{'svcdb'};
3401 my $sth = dbh->prepare("$select $where") or die dbh->errstr;
3402 $sth->execute(@param) or die $sth->errstr;
3403 $sth->fetchrow_arrayref->[0];
3406 =item available_part_svc
3408 Returns a list of FS::part_svc objects representing services included in this
3409 package but not yet provisioned. Each FS::part_svc object also has an extra
3410 field, I<num_avail>, which specifies the number of available services.
3412 Accepts option I<provision_hold>; if true, only returns part_svc for which the
3413 associated pkg_svc has the provision_hold flag set.
3417 sub available_part_svc {
3421 my $pkg_quantity = $self->quantity || 1;
3423 grep { $_->num_avail > 0 }
3425 my $part_svc = $_->part_svc;
3426 $part_svc->{'Hash'}{'num_avail'} = #evil encapsulation-breaking
3427 $pkg_quantity * $_->quantity - $self->num_cust_svc($_->svcpart);
3429 # more evil encapsulation breakage
3430 if ($part_svc->{'Hash'}{'num_avail'} > 0) {
3431 my @exports = $part_svc->part_export_did;
3432 $part_svc->{'Hash'}{'can_get_dids'} = scalar(@exports);
3437 grep { $opt{'provision_hold'} ? $_->provision_hold : 1 }
3438 $self->part_pkg->pkg_svc;
3441 =item part_svc [ OPTION => VALUE ... ]
3443 Returns a list of FS::part_svc objects representing provisioned and available
3444 services included in this package. Each FS::part_svc object also has the
3445 following extra fields:
3459 (services) - array reference containing the provisioned services, as cust_svc objects
3463 Accepts two options:
3467 =item summarize_size
3469 If true, will omit the extra cust_pkg_svc option for objects where num_cust_svc
3470 is this size or greater.
3472 =item hide_discontinued
3474 If true, will omit looking for services that are no longer avaialble in the
3482 #label -> ($cust_svc->label)[1]
3488 my $pkg_quantity = $self->quantity || 1;
3490 #XXX some sort of sort order besides numeric by svcpart...
3491 my @part_svc = sort { $a->svcpart <=> $b->svcpart } map {
3493 my $part_svc = $pkg_svc->part_svc;
3494 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
3495 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #more evil
3496 $part_svc->{'Hash'}{'num_avail'} =
3497 max( 0, $pkg_quantity * $pkg_svc->quantity - $num_cust_svc );
3498 $part_svc->{'Hash'}{'cust_pkg_svc'} =
3499 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : []
3500 unless exists($opt{summarize_size}) && $opt{summarize_size} > 0
3501 && $num_cust_svc >= $opt{summarize_size};
3502 $part_svc->{'Hash'}{'hidden'} = $pkg_svc->hidden;
3504 } $self->part_pkg->pkg_svc;
3506 unless ( $opt{hide_discontinued} ) {
3508 push @part_svc, map {
3510 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
3511 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #speak no evail
3512 $part_svc->{'Hash'}{'num_avail'} = 0; #0-$num_cust_svc ?
3513 $part_svc->{'Hash'}{'cust_pkg_svc'} =
3514 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : [];
3516 } $self->extra_part_svc;
3523 =item extra_part_svc
3525 Returns a list of FS::part_svc objects corresponding to services in this
3526 package which are still provisioned but not (any longer) available in the
3531 sub extra_part_svc {
3534 my $pkgnum = $self->pkgnum;
3535 #my $pkgpart = $self->pkgpart;
3538 # 'table' => 'part_svc',
3541 # "WHERE 0 = ( SELECT COUNT(*) FROM pkg_svc
3542 # WHERE pkg_svc.svcpart = part_svc.svcpart
3543 # AND pkg_svc.pkgpart = ?
3546 # AND 0 < ( SELECT COUNT(*) FROM cust_svc
3547 # LEFT JOIN cust_pkg USING ( pkgnum )
3548 # WHERE cust_svc.svcpart = part_svc.svcpart
3551 # 'extra_param' => [ [$self->pkgpart=>'int'], [$self->pkgnum=>'int'] ],
3554 #seems to benchmark slightly faster... (or did?)
3556 my @pkgparts = map $_->pkgpart, $self->part_pkg->self_and_svc_linked;
3557 my $pkgparts = join(',', @pkgparts);
3560 #'select' => 'DISTINCT ON (svcpart) part_svc.*',
3561 #MySQL doesn't grok DISINCT ON
3562 'select' => 'DISTINCT part_svc.*',
3563 'table' => 'part_svc',
3565 "LEFT JOIN pkg_svc ON ( pkg_svc.svcpart = part_svc.svcpart
3566 AND pkg_svc.pkgpart IN ($pkgparts)
3569 LEFT JOIN cust_svc ON ( cust_svc.svcpart = part_svc.svcpart )
3570 LEFT JOIN cust_pkg USING ( pkgnum )
3573 'extra_sql' => "WHERE pkgsvcnum IS NULL AND cust_pkg.pkgnum = ? ",
3574 'extra_param' => [ [$self->pkgnum=>'int'] ],
3580 Returns a short status string for this package, currently:
3586 =item not yet billed
3588 =item one-time charge
3603 my $freq = length($self->freq) ? $self->freq : $self->part_pkg->freq;
3605 return 'cancelled' if $self->get('cancel');
3606 return 'on hold' if $self->susp && ! $self->setup;
3607 return 'suspended' if $self->susp;
3608 return 'not yet billed' unless $self->setup;
3609 return 'one-time charge' if $freq =~ /^(0|$)/;
3613 =item ucfirst_status
3615 Returns the status with the first character capitalized.
3619 sub ucfirst_status {
3620 ucfirst(shift->status);
3625 Class method that returns the list of possible status strings for packages
3626 (see L<the status method|/status>). For example:
3628 @statuses = FS::cust_pkg->statuses();
3632 tie my %statuscolor, 'Tie::IxHash',
3633 'on hold' => 'FF00F5', #brighter purple!
3634 'not yet billed' => '009999', #teal? cyan?
3635 'one-time charge' => '0000CC', #blue #'000000',
3636 'active' => '00CC00',
3637 'suspended' => 'FF9900',
3638 'cancelled' => 'FF0000',
3642 my $self = shift; #could be class...
3643 #grep { $_ !~ /^(not yet billed)$/ } #this is a dumb status anyway
3644 # # mayble split btw one-time vs. recur
3655 Returns a hex triplet color string for this package's status.
3661 $statuscolor{$self->status};
3664 =item is_status_delay_cancel
3666 Returns true if part_pkg has option delay_cancel,
3667 cust_pkg status is 'suspended' and expire is set
3668 to cancel package within the next day (or however
3669 many days are set in global config part_pkg-delay_cancel-days.
3671 Accepts option I<part_pkg-delay_cancel-days> which should be
3672 the value of the config setting, to avoid looking it up again.
3674 This is not a real status, this only meant for hacking display
3675 values, because otherwise treating the package as suspended is
3676 really the whole point of the delay_cancel option.
3680 sub is_status_delay_cancel {
3681 my ($self,%opt) = @_;
3682 if ( $self->main_pkgnum and $self->pkglinknum ) {
3683 return $self->main_pkg->is_status_delay_cancel;
3685 return 0 unless $self->part_pkg->option('delay_cancel',1);
3686 return 0 unless $self->status eq 'suspended';
3687 return 0 unless $self->expire;
3688 my $expdays = $opt{'part_pkg-delay_cancel-days'};
3690 my $conf = new FS::Conf;
3691 $expdays = $conf->config('part_pkg-delay_cancel-days') || 1;
3693 my $expsecs = 60*60*24*$expdays;
3694 return 0 unless $self->expire < time + $expsecs;
3700 Returns a label for this package. (Currently "pkgnum: pkg - comment" or
3701 "pkg - comment" depending on user preference).
3707 my $label = $self->part_pkg->pkg_comment( cust_pkg=>$self, nopkgpart=>1 );
3708 $label = $self->pkgnum. ": $label"
3709 if $FS::CurrentUser::CurrentUser->option('show_pkgnum');
3713 =item pkg_label_long
3715 Returns a long label for this package, adding the primary service's label to
3720 sub pkg_label_long {
3722 my $label = $self->pkg_label;
3723 my $cust_svc = $self->primary_cust_svc;
3724 $label .= ' ('. ($cust_svc->label)[1]. ')' if $cust_svc;
3730 Returns a customer-localized label for this package.
3736 $self->part_pkg->pkg_locale( $self->cust_main->locale );
3739 =item primary_cust_svc
3741 Returns a primary service (as FS::cust_svc object) if one can be identified.
3745 #for labeling purposes - might not 100% match up with part_pkg->svcpart's idea
3747 sub primary_cust_svc {
3750 my @cust_svc = $self->cust_svc;
3752 return '' unless @cust_svc; #no serivces - irrelevant then
3754 return $cust_svc[0] if scalar(@cust_svc) == 1; #always return a single service
3756 # primary service as specified in the package definition
3757 # or exactly one service definition with quantity one
3758 my $svcpart = $self->part_pkg->svcpart;
3759 @cust_svc = grep { $_->svcpart == $svcpart } @cust_svc;
3760 return $cust_svc[0] if scalar(@cust_svc) == 1;
3762 #couldn't identify one thing..
3768 Returns a list of lists, calling the label method for all services
3769 (see L<FS::cust_svc>) of this billing item.
3775 map { [ $_->label ] } $self->cust_svc;
3778 =item h_labels END_TIMESTAMP [ START_TIMESTAMP ] [ MODE ]
3780 Like the labels method, but returns historical information on services that
3781 were active as of END_TIMESTAMP and (optionally) not cancelled before
3782 START_TIMESTAMP. If MODE is 'I' (for 'invoice'), services with the
3783 I<pkg_svc.hidden> flag will be omitted.
3785 Returns a list of lists, calling the label method for all (historical) services
3786 (see L<FS::h_cust_svc>) of this billing item.
3792 warn "$me _h_labels called on $self\n"
3794 map { [ $_->label(@_) ] } $self->h_cust_svc(@_);
3799 Like labels, except returns a simple flat list, and shortens long
3800 (currently >5 or the cust_bill-max_same_services configuration value) lists of
3801 identical services to one line that lists the service label and the number of
3802 individual services rather than individual items.
3807 shift->_labels_short( 'labels', @_ );
3810 =item h_labels_short END_TIMESTAMP [ START_TIMESTAMP ]
3812 Like h_labels, except returns a simple flat list, and shortens long
3813 (currently >5 or the cust_bill-max_same_services configuration value) lists of
3814 identical services to one line that lists the service label and the number of
3815 individual services rather than individual items.
3819 sub h_labels_short {
3820 shift->_labels_short( 'h_labels', @_ );
3824 my( $self, $method ) = ( shift, shift );
3826 warn "$me _labels_short called on $self with $method method\n"
3829 my $conf = new FS::Conf;
3830 my $max_same_services = $conf->config('cust_bill-max_same_services') || 5;
3832 warn "$me _labels_short populating \%labels\n"
3836 #tie %labels, 'Tie::IxHash';
3837 push @{ $labels{$_->[0]} }, $_->[1]
3838 foreach $self->$method(@_);
3840 warn "$me _labels_short populating \@labels\n"
3844 foreach my $label ( keys %labels ) {
3846 my @values = grep { ! $seen{$_}++ } @{ $labels{$label} };
3847 my $num = scalar(@values);
3848 warn "$me _labels_short $num items for $label\n"
3851 if ( $num > $max_same_services ) {
3852 warn "$me _labels_short more than $max_same_services, so summarizing\n"
3854 push @labels, "$label ($num)";
3856 if ( $conf->exists('cust_bill-consolidate_services') ) {
3857 warn "$me _labels_short consolidating services\n"
3859 # push @labels, "$label: ". join(', ', @values);
3861 my $detail = "$label: ";
3862 $detail .= shift(@values). ', '
3864 && ( length($detail.$values[0]) < 78 || $detail eq "$label: " );
3866 push @labels, $detail;
3868 warn "$me _labels_short done consolidating services\n"
3871 warn "$me _labels_short adding service data\n"
3873 push @labels, map { "$label: $_" } @values;
3884 Returns the parent customer object (see L<FS::cust_main>).
3888 Returns the balance for this specific package, when using
3889 experimental package balance.
3895 $self->cust_main->balance_pkgnum( $self->pkgnum );
3898 #these subs are in location_Mixin.pm now... unfortunately the POD doesn't mixin
3902 Returns the location object, if any (see L<FS::cust_location>).
3904 =item cust_location_or_main
3906 If this package is associated with a location, returns the locaiton (see
3907 L<FS::cust_location>), otherwise returns the customer (see L<FS::cust_main>).
3909 =item location_label [ OPTION => VALUE ... ]
3911 Returns the label of the location object (see L<FS::cust_location>).
3915 #end of subs in location_Mixin.pm now... unfortunately the POD doesn't mixin
3917 =item tax_locationnum
3919 Returns the foreign key to a L<FS::cust_location> object for calculating
3920 tax on this package, as determined by the C<tax-pkg_address> and
3921 C<tax-ship_address> configuration flags.
3925 sub tax_locationnum {
3927 my $conf = FS::Conf->new;
3928 if ( $conf->exists('tax-pkg_address') ) {
3929 return $self->locationnum;
3931 elsif ( $conf->exists('tax-ship_address') ) {
3932 return $self->cust_main->ship_locationnum;
3935 return $self->cust_main->bill_locationnum;
3941 Returns the L<FS::cust_location> object for tax_locationnum.
3947 my $conf = FS::Conf->new;
3948 if ( $conf->exists('tax-pkg_address') and $self->locationnum ) {
3949 return FS::cust_location->by_key($self->locationnum);
3951 elsif ( $conf->exists('tax-ship_address') ) {
3952 return $self->cust_main->ship_location;
3955 return $self->cust_main->bill_location;
3959 =item seconds_since TIMESTAMP
3961 Returns the number of seconds all accounts (see L<FS::svc_acct>) in this
3962 package have been online since TIMESTAMP, according to the session monitor.
3964 TIMESTAMP is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
3965 L<Time::Local> and L<Date::Parse> for conversion functions.
3970 my($self, $since) = @_;
3973 foreach my $cust_svc (
3974 grep { $_->part_svc->svcdb eq 'svc_acct' } $self->cust_svc
3976 $seconds += $cust_svc->seconds_since($since);
3983 =item seconds_since_sqlradacct TIMESTAMP_START TIMESTAMP_END
3985 Returns the numbers of seconds all accounts (see L<FS::svc_acct>) in this
3986 package have been online between TIMESTAMP_START (inclusive) and TIMESTAMP_END
3989 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
3990 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
3996 sub seconds_since_sqlradacct {
3997 my($self, $start, $end) = @_;
4001 foreach my $cust_svc (
4003 my $part_svc = $_->part_svc;
4004 $part_svc->svcdb eq 'svc_acct'
4005 && scalar($part_svc->part_export_usage);
4008 $seconds += $cust_svc->seconds_since_sqlradacct($start, $end);
4015 =item attribute_since_sqlradacct TIMESTAMP_START TIMESTAMP_END ATTRIBUTE
4017 Returns the sum of the given attribute for all accounts (see L<FS::svc_acct>)
4018 in this package for sessions ending between TIMESTAMP_START (inclusive) and
4022 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
4023 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
4028 sub attribute_since_sqlradacct {
4029 my($self, $start, $end, $attrib) = @_;
4033 foreach my $cust_svc (
4035 my $part_svc = $_->part_svc;
4036 scalar($part_svc->part_export_usage);
4039 $sum += $cust_svc->attribute_since_sqlradacct($start, $end, $attrib);
4051 my( $self, $value ) = @_;
4052 if ( defined($value) ) {
4053 $self->setfield('quantity', $value);
4055 $self->getfield('quantity') || 1;
4058 =item transfer DEST_PKGNUM | DEST_CUST_PKG, [ OPTION => VALUE ... ]
4060 Transfers as many services as possible from this package to another package.
4062 The destination package can be specified by pkgnum by passing an FS::cust_pkg
4063 object. The destination package must already exist.
4065 Services are moved only if the destination allows services with the correct
4066 I<svcpart> (not svcdb), unless the B<change_svcpart> option is set true. Use
4067 this option with caution! No provision is made for export differences
4068 between the old and new service definitions. Probably only should be used
4069 when your exports for all service definitions of a given svcdb are identical.
4070 (attempt a transfer without it first, to move all possible svcpart-matching
4073 Any services that can't be moved remain in the original package.
4075 Returns an error, if there is one; otherwise, returns the number of services
4076 that couldn't be moved.
4081 my ($self, $dest_pkgnum, %opt) = @_;
4087 if (ref ($dest_pkgnum) eq 'FS::cust_pkg') {
4088 $dest = $dest_pkgnum;
4089 $dest_pkgnum = $dest->pkgnum;
4091 $dest = qsearchs('cust_pkg', { pkgnum => $dest_pkgnum });
4094 return ('Package does not exist: '.$dest_pkgnum) unless $dest;
4096 foreach my $pkg_svc ( $dest->part_pkg->pkg_svc ) {
4097 $target{$pkg_svc->svcpart} = $pkg_svc->quantity * ( $dest->quantity || 1 );
4100 foreach my $cust_svc ($dest->cust_svc) {
4101 $target{$cust_svc->svcpart}--;
4104 my %svcpart2svcparts = ();
4105 if ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
4106 warn "change_svcpart option received, creating alternates list\n" if $DEBUG;
4107 foreach my $svcpart ( map { $_->svcpart } $self->cust_svc ) {
4108 next if exists $svcpart2svcparts{$svcpart};
4109 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
4110 $svcpart2svcparts{$svcpart} = [
4112 sort { $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] }
4114 my $pkg_svc = qsearchs( 'pkg_svc', { 'pkgpart' => $dest->pkgpart,
4115 'svcpart' => $_ } );
4117 $pkg_svc ? $pkg_svc->primary_svc : '',
4118 $pkg_svc ? $pkg_svc->quantity : 0,
4122 grep { $_ != $svcpart }
4124 qsearch('part_svc', { 'svcdb' => $part_svc->svcdb } )
4126 warn "alternates for svcpart $svcpart: ".
4127 join(', ', @{$svcpart2svcparts{$svcpart}}). "\n"
4133 foreach my $cust_svc ($self->cust_svc) {
4134 my $svcnum = $cust_svc->svcnum;
4135 if($target{$cust_svc->svcpart} > 0
4136 or $FS::cust_svc::ignore_quantity) { # maybe should be a 'force' option
4137 $target{$cust_svc->svcpart}--;
4138 my $new = new FS::cust_svc { $cust_svc->hash };
4139 $new->pkgnum($dest_pkgnum);
4140 $error = $new->replace($cust_svc);
4141 } elsif ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
4143 warn "looking for alternates for svcpart ". $cust_svc->svcpart. "\n";
4144 warn "alternates to consider: ".
4145 join(', ', @{$svcpart2svcparts{$cust_svc->svcpart}}). "\n";
4147 my @alternate = grep {
4148 warn "considering alternate svcpart $_: ".
4149 "$target{$_} available in new package\n"
4152 } @{$svcpart2svcparts{$cust_svc->svcpart}};
4154 warn "alternate(s) found\n" if $DEBUG;
4155 my $change_svcpart = $alternate[0];
4156 $target{$change_svcpart}--;
4157 my $new = new FS::cust_svc { $cust_svc->hash };
4158 $new->svcpart($change_svcpart);
4159 $new->pkgnum($dest_pkgnum);
4160 $error = $new->replace($cust_svc);
4168 my @label = $cust_svc->label;
4169 return "$label[0] $label[1]: $error";
4175 =item grab_svcnums SVCNUM, SVCNUM ...
4177 Change the pkgnum for the provided services to this packages. If there is an
4178 error, returns the error, otherwise returns false.
4186 my $oldAutoCommit = $FS::UID::AutoCommit;
4187 local $FS::UID::AutoCommit = 0;
4190 foreach my $svcnum (@svcnum) {
4191 my $cust_svc = qsearchs('cust_svc', { svcnum=>$svcnum } ) or do {
4192 $dbh->rollback if $oldAutoCommit;
4193 return "unknown svcnum $svcnum";
4195 $cust_svc->pkgnum( $self->pkgnum );
4196 my $error = $cust_svc->replace;
4198 $dbh->rollback if $oldAutoCommit;
4203 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4210 This method is deprecated. See the I<depend_jobnum> option to the insert and
4211 order_pkgs methods in FS::cust_main for a better way to defer provisioning.
4215 #looks like this is still used by the order_pkg and change_pkg methods in
4216 # ClientAPI/MyAccount, need to look into those before removing
4220 my $oldAutoCommit = $FS::UID::AutoCommit;
4221 local $FS::UID::AutoCommit = 0;
4224 foreach my $cust_svc ( $self->cust_svc ) {
4225 #false laziness w/svc_Common::insert
4226 my $svc_x = $cust_svc->svc_x;
4227 foreach my $part_export ( $cust_svc->part_svc->part_export ) {
4228 my $error = $part_export->export_insert($svc_x);
4230 $dbh->rollback if $oldAutoCommit;
4236 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4241 =item export_pkg_change OLD_CUST_PKG
4243 Calls the "pkg_change" export action for all services attached to this package.
4247 sub export_pkg_change {
4248 my( $self, $old ) = ( shift, shift );
4250 my $oldAutoCommit = $FS::UID::AutoCommit;
4251 local $FS::UID::AutoCommit = 0;
4254 foreach my $svc_x ( map $_->svc_x, $self->cust_svc ) {
4255 my $error = $svc_x->export('pkg_change', $self, $old);
4257 $dbh->rollback if $oldAutoCommit;
4262 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4269 Associates this package with a (suspension or cancellation) reason (see
4270 L<FS::cust_pkg_reason>, possibly inserting a new reason on the fly (see
4273 Available options are:
4279 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.
4283 the access_user (see L<FS::access_user>) providing the reason
4291 the action (cancel, susp, adjourn, expire) associated with the reason
4295 If there is an error, returns the error, otherwise returns false.
4300 my ($self, %options) = @_;
4302 my $otaker = $options{reason_otaker} ||
4303 $FS::CurrentUser::CurrentUser->username;
4306 if ( $options{'reason'} =~ /^(\d+)$/ ) {
4310 } elsif ( ref($options{'reason'}) ) {
4312 return 'Enter a new reason (or select an existing one)'
4313 unless $options{'reason'}->{'reason'} !~ /^\s*$/;
4315 my $reason = new FS::reason({
4316 'reason_type' => $options{'reason'}->{'typenum'},
4317 'reason' => $options{'reason'}->{'reason'},
4319 my $error = $reason->insert;
4320 return $error if $error;
4322 $reasonnum = $reason->reasonnum;
4325 return "Unparseable reason: ". $options{'reason'};
4328 my $cust_pkg_reason =
4329 new FS::cust_pkg_reason({ 'pkgnum' => $self->pkgnum,
4330 'reasonnum' => $reasonnum,
4331 'otaker' => $otaker,
4332 'action' => substr(uc($options{'action'}),0,1),
4333 'date' => $options{'date'}
4338 $cust_pkg_reason->insert;
4341 =item insert_discount
4343 Associates this package with a discount (see L<FS::cust_pkg_discount>, possibly
4344 inserting a new discount on the fly (see L<FS::discount>).
4346 This will look at the cust_pkg for a pseudo-field named "setup_discountnum",
4347 and if present, will create a setup discount. If the discountnum is -1,
4348 a new discount definition will be inserted using the value in
4349 "setup_discountnum_amount" or "setup_discountnum_percent". Likewise for recur.
4351 If there is an error, returns the error, otherwise returns false.
4355 sub insert_discount {
4356 #my ($self, %options) = @_;
4359 foreach my $x (qw(setup recur)) {
4360 if ( my $discountnum = $self->get("${x}_discountnum") ) {
4361 my $cust_pkg_discount = FS::cust_pkg_discount->new( {
4362 'pkgnum' => $self->pkgnum,
4363 'discountnum' => $discountnum,
4366 'end_date' => '', #XXX
4367 #for the create a new discount case
4368 'amount' => $self->get("${x}_discountnum_amount"),
4369 'percent' => $self->get("${x}_discountnum_percent"),
4370 'months' => $self->get("${x}_discountnum_months"),
4372 if ( $x eq 'setup' ) {
4373 $cust_pkg_discount->setup('Y');
4374 $cust_pkg_discount->months('');
4376 my $error = $cust_pkg_discount->insert;
4377 return $error if $error;
4384 =item set_usage USAGE_VALUE_HASHREF
4386 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
4387 to which they should be set (see L<FS::svc_acct>). Currently seconds,
4388 upbytes, downbytes, and totalbytes are appropriate keys.
4390 All svc_accts which are part of this package have their values reset.
4395 my ($self, $valueref, %opt) = @_;
4397 #only svc_acct can set_usage for now
4398 foreach my $cust_svc ( $self->cust_svc( 'svcdb'=>'svc_acct' ) ) {
4399 my $svc_x = $cust_svc->svc_x;
4400 $svc_x->set_usage($valueref, %opt)
4401 if $svc_x->can("set_usage");
4405 =item recharge USAGE_VALUE_HASHREF
4407 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
4408 to which they should be set (see L<FS::svc_acct>). Currently seconds,
4409 upbytes, downbytes, and totalbytes are appropriate keys.
4411 All svc_accts which are part of this package have their values incremented.
4416 my ($self, $valueref) = @_;
4418 #only svc_acct can set_usage for now
4419 foreach my $cust_svc ( $self->cust_svc( 'svcdb'=>'svc_acct' ) ) {
4420 my $svc_x = $cust_svc->svc_x;
4421 $svc_x->recharge($valueref)
4422 if $svc_x->can("recharge");
4426 =item apply_usageprice
4430 sub apply_usageprice {
4433 my $oldAutoCommit = $FS::UID::AutoCommit;
4434 local $FS::UID::AutoCommit = 0;
4439 foreach my $cust_pkg_usageprice ( $self->cust_pkg_usageprice ) {
4440 $error ||= $cust_pkg_usageprice->apply;
4444 $dbh->rollback if $oldAutoCommit;
4445 die "error applying part_pkg_usageprice add-ons, pkgnum ". $self->pkgnum.
4448 $dbh->commit if $oldAutoCommit;
4454 =item cust_pkg_discount
4456 =item cust_pkg_discount_active
4460 sub cust_pkg_discount_active {
4462 grep { $_->status eq 'active' } $self->cust_pkg_discount;
4465 =item cust_pkg_usage
4467 Returns a list of all voice usage counters attached to this package.
4469 =item apply_usage OPTIONS
4471 Takes the following options:
4472 - cdr: a call detail record (L<FS::cdr>)
4473 - rate_detail: the rate determined for this call (L<FS::rate_detail>)
4474 - minutes: the maximum number of minutes to be charged
4476 Finds available usage minutes for a call of this class, and subtracts
4477 up to that many minutes from the usage pool. If the usage pool is empty,
4478 and the C<cdr-minutes_priority> global config option is set, minutes may
4479 be taken from other calls as well. Either way, an allocation record will
4480 be created (L<FS::cdr_cust_pkg_usage>) and this method will return the
4481 number of minutes of usage applied to the call.
4486 my ($self, %opt) = @_;
4487 my $cdr = $opt{cdr};
4488 my $rate_detail = $opt{rate_detail};
4489 my $minutes = $opt{minutes};
4490 my $classnum = $rate_detail->classnum;
4491 my $pkgnum = $self->pkgnum;
4492 my $custnum = $self->custnum;
4494 my $oldAutoCommit = $FS::UID::AutoCommit;
4495 local $FS::UID::AutoCommit = 0;
4498 my $order = FS::Conf->new->config('cdr-minutes_priority');
4502 $is_classnum = ' part_pkg_usage_class.classnum = '.$classnum;
4504 $is_classnum = ' part_pkg_usage_class.classnum IS NULL';
4506 my @usage_recs = qsearch({
4507 'table' => 'cust_pkg_usage',
4508 'addl_from' => ' JOIN part_pkg_usage USING (pkgusagepart)'.
4509 ' JOIN cust_pkg USING (pkgnum)'.
4510 ' JOIN part_pkg_usage_class USING (pkgusagepart)',
4511 'select' => 'cust_pkg_usage.*',
4512 'extra_sql' => " WHERE ( cust_pkg.pkgnum = $pkgnum OR ".
4513 " ( cust_pkg.custnum = $custnum AND ".
4514 " part_pkg_usage.shared IS NOT NULL ) ) AND ".
4515 $is_classnum . ' AND '.
4516 " cust_pkg_usage.minutes > 0",
4517 'order_by' => " ORDER BY priority ASC",
4520 my $orig_minutes = $minutes;
4522 while (!$error and $minutes > 0 and @usage_recs) {
4523 my $cust_pkg_usage = shift @usage_recs;
4524 $cust_pkg_usage->select_for_update;
4525 my $cdr_cust_pkg_usage = FS::cdr_cust_pkg_usage->new({
4526 pkgusagenum => $cust_pkg_usage->pkgusagenum,
4527 acctid => $cdr->acctid,
4528 minutes => min($cust_pkg_usage->minutes, $minutes),
4530 $cust_pkg_usage->set('minutes',
4531 $cust_pkg_usage->minutes - $cdr_cust_pkg_usage->minutes
4533 $error = $cust_pkg_usage->replace || $cdr_cust_pkg_usage->insert;
4534 $minutes -= $cdr_cust_pkg_usage->minutes;
4536 if ( $order and $minutes > 0 and !$error ) {
4537 # then try to steal minutes from another call
4539 'table' => 'cdr_cust_pkg_usage',
4540 'addl_from' => ' JOIN cust_pkg_usage USING (pkgusagenum)'.
4541 ' JOIN part_pkg_usage USING (pkgusagepart)'.
4542 ' JOIN cust_pkg USING (pkgnum)'.
4543 ' JOIN part_pkg_usage_class USING (pkgusagepart)'.
4544 ' JOIN cdr USING (acctid)',
4545 'select' => 'cdr_cust_pkg_usage.*',
4546 'extra_sql' => " WHERE cdr.freesidestatus = 'rated' AND ".
4547 " ( cust_pkg.pkgnum = $pkgnum OR ".
4548 " ( cust_pkg.custnum = $custnum AND ".
4549 " part_pkg_usage.shared IS NOT NULL ) ) AND ".
4550 " part_pkg_usage_class.classnum = $classnum",
4551 'order_by' => ' ORDER BY part_pkg_usage.priority ASC',
4553 if ( $order eq 'time' ) {
4554 # find CDRs that are using minutes, but have a later startdate
4556 my $startdate = $cdr->startdate;
4557 if ($startdate !~ /^\d+$/) {
4558 die "bad cdr startdate '$startdate'";
4560 $search{'extra_sql'} .= " AND cdr.startdate > $startdate";
4561 # minimize needless reshuffling
4562 $search{'order_by'} .= ', cdr.startdate DESC';
4564 # XXX may not work correctly with rate_time schedules. Could
4565 # fix this by storing ratedetailnum in cdr_cust_pkg_usage, I
4567 $search{'addl_from'} .=
4568 ' JOIN rate_detail'.
4569 ' ON (cdr.rated_ratedetailnum = rate_detail.ratedetailnum)';
4570 if ( $order eq 'rate_high' ) {
4571 $search{'extra_sql'} .= ' AND rate_detail.min_charge < '.
4572 $rate_detail->min_charge;
4573 $search{'order_by'} .= ', rate_detail.min_charge ASC';
4574 } elsif ( $order eq 'rate_low' ) {
4575 $search{'extra_sql'} .= ' AND rate_detail.min_charge > '.
4576 $rate_detail->min_charge;
4577 $search{'order_by'} .= ', rate_detail.min_charge DESC';
4579 # this should really never happen
4580 die "invalid cdr-minutes_priority value '$order'\n";
4583 my @cdr_usage_recs = qsearch(\%search);
4585 while (!$error and @cdr_usage_recs and $minutes > 0) {
4586 my $cdr_cust_pkg_usage = shift @cdr_usage_recs;
4587 my $cust_pkg_usage = $cdr_cust_pkg_usage->cust_pkg_usage;
4588 my $old_cdr = $cdr_cust_pkg_usage->cdr;
4589 $reproc_cdrs{$old_cdr->acctid} = $old_cdr;
4590 $cdr_cust_pkg_usage->select_for_update;
4591 $old_cdr->select_for_update;
4592 $cust_pkg_usage->select_for_update;
4593 # in case someone else stole the usage from this CDR
4594 # while waiting for the lock...
4595 next if $old_cdr->acctid != $cdr_cust_pkg_usage->acctid;
4596 # steal the usage allocation and flag the old CDR for reprocessing
4597 $cdr_cust_pkg_usage->set('acctid', $cdr->acctid);
4598 # if the allocation is more minutes than we need, adjust it...
4599 my $delta = $cdr_cust_pkg_usage->minutes - $minutes;
4601 $cdr_cust_pkg_usage->set('minutes', $minutes);
4602 $cust_pkg_usage->set('minutes', $cust_pkg_usage->minutes + $delta);
4603 $error = $cust_pkg_usage->replace;
4605 #warn 'CDR '.$cdr->acctid . ' stealing allocation '.$cdr_cust_pkg_usage->cdrusagenum.' from CDR '.$old_cdr->acctid."\n";
4606 $error ||= $cdr_cust_pkg_usage->replace;
4607 # deduct the stolen minutes
4608 $minutes -= $cdr_cust_pkg_usage->minutes;
4610 # after all minute-stealing is done, reset the affected CDRs
4611 foreach (values %reproc_cdrs) {
4612 $error ||= $_->set_status('');
4613 # XXX or should we just call $cdr->rate right here?
4614 # it's not like we can create a loop this way, since the min_charge
4615 # or call time has to go monotonically in one direction.
4616 # we COULD get some very deep recursions going, though...
4618 } # if $order and $minutes
4621 die "error applying included minutes\npkgnum ".$self->pkgnum.", class $classnum, acctid ".$cdr->acctid."\n$error\n"
4623 $dbh->commit if $oldAutoCommit;
4624 return $orig_minutes - $minutes;
4628 =item supplemental_pkgs
4630 Returns a list of all packages supplemental to this one.
4634 sub supplemental_pkgs {
4636 qsearch('cust_pkg', { 'main_pkgnum' => $self->pkgnum });
4641 Returns the package that this one is supplemental to, if any.
4647 if ( $self->main_pkgnum ) {
4648 return FS::cust_pkg->by_key($self->main_pkgnum);
4655 =head1 CLASS METHODS
4661 Returns an SQL expression identifying recurring packages.
4665 sub recurring_sql { "
4666 '0' != ( select freq from part_pkg
4667 where cust_pkg.pkgpart = part_pkg.pkgpart )
4672 Returns an SQL expression identifying one-time packages.
4677 '0' = ( select freq from part_pkg
4678 where cust_pkg.pkgpart = part_pkg.pkgpart )
4683 Returns an SQL expression identifying ordered packages (recurring packages not
4689 $_[0]->recurring_sql. " AND ". $_[0]->not_yet_billed_sql;
4694 Returns an SQL expression identifying active packages.
4699 $_[0]->recurring_sql. "
4700 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
4701 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4702 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
4705 =item not_yet_billed_sql
4707 Returns an SQL expression identifying packages which have not yet been billed.
4711 sub not_yet_billed_sql { "
4712 ( cust_pkg.setup IS NULL OR cust_pkg.setup = 0 )
4713 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4714 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
4719 Returns an SQL expression identifying inactive packages (one-time packages
4720 that are otherwise unsuspended/uncancelled).
4724 sub inactive_sql { "
4725 ". $_[0]->onetime_sql(). "
4726 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
4727 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4728 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
4733 Returns an SQL expression identifying on-hold packages.
4738 #$_[0]->recurring_sql(). ' AND '.
4740 ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4741 AND cust_pkg.susp IS NOT NULL AND cust_pkg.susp != 0
4742 AND ( cust_pkg.setup IS NULL OR cust_pkg.setup = 0 )
4749 Returns an SQL expression identifying suspended packages.
4753 sub suspended_sql { susp_sql(@_); }
4755 #$_[0]->recurring_sql(). ' AND '.
4757 ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4758 AND cust_pkg.susp IS NOT NULL AND cust_pkg.susp != 0
4759 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
4766 Returns an SQL exprression identifying cancelled packages.
4770 sub cancelled_sql { cancel_sql(@_); }
4772 #$_[0]->recurring_sql(). ' AND '.
4773 "cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0";
4778 Returns an SQL expression to give the package status as a string.
4784 WHEN cust_pkg.cancel IS NOT NULL THEN 'cancelled'
4785 WHEN ( cust_pkg.susp IS NOT NULL AND cust_pkg.setup IS NULL ) THEN 'on hold'
4786 WHEN cust_pkg.susp IS NOT NULL THEN 'suspended'
4787 WHEN cust_pkg.setup IS NULL THEN 'not yet billed'
4788 WHEN ".onetime_sql()." THEN 'one-time charge'
4795 Returns a list of two package counts. The first is a count of packages
4796 based on the supplied criteria and the second is the count of residential
4797 packages with those same criteria. Criteria are specified as in the search
4803 my ($class, $params) = @_;
4805 my $sql_query = $class->search( $params );
4807 my $count_sql = delete($sql_query->{'count_query'});
4808 $count_sql =~ s/ FROM/,count(CASE WHEN cust_main.company IS NULL OR cust_main.company = '' THEN 1 END) FROM/
4809 or die "couldn't parse count_sql";
4811 my $count_sth = dbh->prepare($count_sql)
4812 or die "Error preparing $count_sql: ". dbh->errstr;
4814 or die "Error executing $count_sql: ". $count_sth->errstr;
4815 my $count_arrayref = $count_sth->fetchrow_arrayref;
4817 return ( @$count_arrayref );
4821 =item tax_locationnum_sql
4823 Returns an SQL expression for the tax location for a package, based
4824 on the settings of 'tax-pkg_address' and 'tax-ship_address'.
4828 sub tax_locationnum_sql {
4829 my $conf = FS::Conf->new;
4830 if ( $conf->exists('tax-pkg_address') ) {
4831 'cust_pkg.locationnum';
4833 elsif ( $conf->exists('tax-ship_address') ) {
4834 'cust_main.ship_locationnum';
4837 'cust_main.bill_locationnum';
4843 Returns a list: the first item is an SQL fragment identifying matching
4844 packages/customers via location (taking into account shipping and package
4845 address taxation, if enabled), and subsequent items are the parameters to
4846 substitute for the placeholders in that fragment.
4851 my($class, %opt) = @_;
4852 my $ornull = $opt{'ornull'};
4854 my $conf = new FS::Conf;
4856 # '?' placeholders in _location_sql_where
4857 my $x = $ornull ? 3 : 2;
4868 if ( $conf->exists('tax-ship_address') ) {
4871 ( ( ship_last IS NULL OR ship_last = '' )
4872 AND ". _location_sql_where('cust_main', '', $ornull ). "
4874 OR ( ship_last IS NOT NULL AND ship_last != ''
4875 AND ". _location_sql_where('cust_main', 'ship_', $ornull ). "
4878 # AND payby != 'COMP'
4880 @main_param = ( @bill_param, @bill_param );
4884 $main_where = _location_sql_where('cust_main'); # AND payby != 'COMP'
4885 @main_param = @bill_param;
4891 if ( $conf->exists('tax-pkg_address') ) {
4893 my $loc_where = _location_sql_where( 'cust_location', '', $ornull );
4896 ( cust_pkg.locationnum IS NULL AND $main_where )
4897 OR ( cust_pkg.locationnum IS NOT NULL AND $loc_where )
4900 @param = ( @main_param, @bill_param );
4904 $where = $main_where;
4905 @param = @main_param;
4913 #subroutine, helper for location_sql
4914 sub _location_sql_where {
4916 my $prefix = @_ ? shift : '';
4917 my $ornull = @_ ? shift : '';
4919 # $ornull = $ornull ? " OR ( ? IS NULL AND $table.${prefix}county IS NULL ) " : '';
4921 $ornull = $ornull ? ' OR ? IS NULL ' : '';
4923 my $or_empty_city = " OR ( ? = '' AND $table.${prefix}city IS NULL )";
4924 my $or_empty_county = " OR ( ? = '' AND $table.${prefix}county IS NULL )";
4925 my $or_empty_state = " OR ( ? = '' AND $table.${prefix}state IS NULL )";
4927 my $text = (driver_name =~ /^mysql/i) ? 'char' : 'text';
4929 # ( $table.${prefix}city = ? $or_empty_city $ornull )
4931 ( $table.district = ? OR ? = '' OR CAST(? AS $text) IS NULL )
4932 AND ( $table.${prefix}city = ? OR ? = '' OR CAST(? AS $text) IS NULL )
4933 AND ( $table.${prefix}county = ? $or_empty_county $ornull )
4934 AND ( $table.${prefix}state = ? $or_empty_state $ornull )
4935 AND $table.${prefix}country = ?
4940 my( $self, $what ) = @_;
4942 my $what_show_zero = $what. '_show_zero';
4943 length($self->$what_show_zero())
4944 ? ($self->$what_show_zero() eq 'Y')
4945 : $self->part_pkg->$what_show_zero();
4952 =item order CUSTNUM, PKGPARTS_ARYREF, [ REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF [ REFNUM ] ] ]
4954 Bulk cancel + order subroutine. Perhaps slightly deprecated, only used by the
4955 bulk cancel+order in the web UI and nowhere else (edit/process/cust_pkg.cgi)
4957 CUSTNUM is a customer (see L<FS::cust_main>)
4959 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
4960 L<FS::part_pkg>) to order for this customer. Duplicates are of course
4963 REMOVE_PKGNUMS is an optional list of pkgnums specifying the billing items to
4964 remove for this customer. The services (see L<FS::cust_svc>) are moved to the
4965 new billing items. An error is returned if this is not possible (see
4966 L<FS::pkg_svc>). An empty arrayref is equivalent to not specifying this
4969 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
4970 newly-created cust_pkg objects.
4972 REFNUM, if specified, will specify the FS::pkg_referral record to be created
4973 and inserted. Multiple FS::pkg_referral records can be created by
4974 setting I<refnum> to an array reference of refnums or a hash reference with
4975 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
4976 record will be created corresponding to cust_main.refnum.
4981 my ($custnum, $pkgparts, $remove_pkgnum, $return_cust_pkg, $refnum) = @_;
4983 my $conf = new FS::Conf;
4985 # Transactionize this whole mess
4986 my $oldAutoCommit = $FS::UID::AutoCommit;
4987 local $FS::UID::AutoCommit = 0;
4991 # my $cust_main = qsearchs('cust_main', { custnum => $custnum });
4992 # return "Customer not found: $custnum" unless $cust_main;
4994 warn "$me order: pkgnums to remove: ". join(',', @$remove_pkgnum). "\n"
4997 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
5000 my $change = scalar(@old_cust_pkg) != 0;
5003 if ( scalar(@old_cust_pkg) == 1 && scalar(@$pkgparts) == 1 ) {
5005 warn "$me order: changing pkgnum ". $old_cust_pkg[0]->pkgnum.
5006 " to pkgpart ". $pkgparts->[0]. "\n"
5009 my $err_or_cust_pkg =
5010 $old_cust_pkg[0]->change( 'pkgpart' => $pkgparts->[0],
5011 'refnum' => $refnum,
5014 unless (ref($err_or_cust_pkg)) {
5015 $dbh->rollback if $oldAutoCommit;
5016 return $err_or_cust_pkg;
5019 push @$return_cust_pkg, $err_or_cust_pkg;
5020 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5025 # Create the new packages.
5026 foreach my $pkgpart (@$pkgparts) {
5028 warn "$me order: inserting pkgpart $pkgpart\n" if $DEBUG;
5030 my $cust_pkg = new FS::cust_pkg { custnum => $custnum,
5031 pkgpart => $pkgpart,
5035 $error = $cust_pkg->insert( 'change' => $change );
5036 push @$return_cust_pkg, $cust_pkg;
5038 foreach my $link ($cust_pkg->part_pkg->supp_part_pkg_link) {
5039 my $supp_pkg = FS::cust_pkg->new({
5040 custnum => $custnum,
5041 pkgpart => $link->dst_pkgpart,
5043 main_pkgnum => $cust_pkg->pkgnum,
5046 $error ||= $supp_pkg->insert( 'change' => $change );
5047 push @$return_cust_pkg, $supp_pkg;
5051 $dbh->rollback if $oldAutoCommit;
5056 # $return_cust_pkg now contains refs to all of the newly
5059 # Transfer services and cancel old packages.
5060 foreach my $old_pkg (@old_cust_pkg) {
5062 warn "$me order: transferring services from pkgnum ". $old_pkg->pkgnum. "\n"
5065 foreach my $new_pkg (@$return_cust_pkg) {
5066 $error = $old_pkg->transfer($new_pkg);
5067 if ($error and $error == 0) {
5068 # $old_pkg->transfer failed.
5069 $dbh->rollback if $oldAutoCommit;
5074 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
5075 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
5076 foreach my $new_pkg (@$return_cust_pkg) {
5077 $error = $old_pkg->transfer($new_pkg, 'change_svcpart'=>1 );
5078 if ($error and $error == 0) {
5079 # $old_pkg->transfer failed.
5080 $dbh->rollback if $oldAutoCommit;
5087 # Transfers were successful, but we went through all of the
5088 # new packages and still had services left on the old package.
5089 # We can't cancel the package under the circumstances, so abort.
5090 $dbh->rollback if $oldAutoCommit;
5091 return "Unable to transfer all services from package ".$old_pkg->pkgnum;
5093 $error = $old_pkg->cancel( quiet=>1, 'no_delay_cancel'=>1 );
5099 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5103 =item bulk_change PKGPARTS_ARYREF, REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF ]
5105 A bulk change method to change packages for multiple customers.
5107 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
5108 L<FS::part_pkg>) to order for each customer. Duplicates are of course
5111 REMOVE_PKGNUMS is an list of pkgnums specifying the billing items to
5112 replace. The services (see L<FS::cust_svc>) are moved to the
5113 new billing items. An error is returned if this is not possible (see
5116 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
5117 newly-created cust_pkg objects.
5122 my ($pkgparts, $remove_pkgnum, $return_cust_pkg) = @_;
5124 # Transactionize this whole mess
5125 my $oldAutoCommit = $FS::UID::AutoCommit;
5126 local $FS::UID::AutoCommit = 0;
5130 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
5133 while(scalar(@old_cust_pkg)) {
5135 my $custnum = $old_cust_pkg[0]->custnum;
5136 my (@remove) = map { $_->pkgnum }
5137 grep { $_->custnum == $custnum } @old_cust_pkg;
5138 @old_cust_pkg = grep { $_->custnum != $custnum } @old_cust_pkg;
5140 my $error = order $custnum, $pkgparts, \@remove, \@return;
5142 push @errors, $error
5144 push @$return_cust_pkg, @return;
5147 if (scalar(@errors)) {
5148 $dbh->rollback if $oldAutoCommit;
5149 return join(' / ', @errors);
5152 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5156 =item forward_emails
5158 Returns a hash of svcnums and corresponding email addresses
5159 for svc_acct services that can be used as source or dest
5160 for svc_forward services provisioned in this package.
5162 Accepts options I<svc_forward> OR I<svcnum> for a svc_forward
5163 service; if included, will ensure the current values of the
5164 specified service are included in the list, even if for some
5165 other reason they wouldn't be. If called as a class method
5166 with a specified service, returns only these current values.
5168 Caution: does not actually check if svc_forward services are
5169 available to be provisioned on this package.
5173 sub forward_emails {
5177 #load optional service, thoroughly validated
5178 die "Use svcnum or svc_forward, not both"
5179 if $opt{'svcnum'} && $opt{'svc_forward'};
5180 my $svc_forward = $opt{'svc_forward'};
5181 $svc_forward ||= qsearchs('svc_forward',{ 'svcnum' => $opt{'svcnum'} })
5183 die "Specified service is not a forward service"
5184 if $svc_forward && (ref($svc_forward) ne 'FS::svc_forward');
5185 die "Specified service not found"
5186 if ($opt{'svcnum'} || $opt{'svc_forward'}) && !$svc_forward;
5190 ## everything below was basically copied from httemplate/edit/svc_forward.cgi
5191 ## with minimal refactoring, not sure why we can't just load all svc_accts for this custnum
5193 #add current values from specified service, if there was one
5195 foreach my $method (qw( srcsvc_acct dstsvc_acct )) {
5196 my $svc_acct = $svc_forward->$method();
5197 $email{$svc_acct->svcnum} = $svc_acct->email if $svc_acct;
5201 if (ref($self) eq 'FS::cust_pkg') {
5203 #and including the rest for this customer
5204 my($u_part_svc,@u_acct_svcparts);
5205 foreach $u_part_svc ( qsearch('part_svc',{'svcdb'=>'svc_acct'}) ) {
5206 push @u_acct_svcparts,$u_part_svc->getfield('svcpart');
5209 my $custnum = $self->getfield('custnum');
5210 foreach my $i_cust_pkg ( qsearch('cust_pkg',{'custnum'=>$custnum}) ) {
5211 my $cust_pkgnum = $i_cust_pkg->getfield('pkgnum');
5212 #now find the corresponding record(s) in cust_svc (for this pkgnum!)
5213 foreach my $acct_svcpart (@u_acct_svcparts) {
5214 foreach my $i_cust_svc (
5215 qsearch( 'cust_svc', { 'pkgnum' => $cust_pkgnum,
5216 'svcpart' => $acct_svcpart } )
5218 my $svc_acct = qsearchs( 'svc_acct', { 'svcnum' => $i_cust_svc->svcnum } );
5219 $email{$svc_acct->svcnum} = $svc_acct->email;
5228 # Used by FS::Upgrade to migrate to a new database.
5229 sub _upgrade_data { # class method
5230 my ($class, %opts) = @_;
5231 $class->_upgrade_otaker(%opts);
5233 # RT#10139, bug resulting in contract_end being set when it shouldn't
5234 'UPDATE cust_pkg SET contract_end = NULL WHERE contract_end = -1',
5235 # RT#10830, bad calculation of prorate date near end of year
5236 # the date range for bill is December 2009, and we move it forward
5237 # one year if it's before the previous bill date (which it should
5239 'UPDATE cust_pkg SET bill = bill + (365*24*60*60) WHERE bill < last_bill
5240 AND bill > 1259654400 AND bill < 1262332800 AND (SELECT plan FROM part_pkg
5241 WHERE part_pkg.pkgpart = cust_pkg.pkgpart) = \'prorate\'',
5242 # RT6628, add order_date to cust_pkg
5243 'update cust_pkg set order_date = (select history_date from h_cust_pkg
5244 where h_cust_pkg.pkgnum = cust_pkg.pkgnum and
5245 history_action = \'insert\') where order_date is null',
5247 foreach my $sql (@statements) {
5248 my $sth = dbh->prepare($sql);
5249 $sth->execute or die $sth->errstr;
5252 # RT31194: supplemental package links that are deleted don't clean up
5254 my @pkglinknums = qsearch({
5255 'select' => 'DISTINCT cust_pkg.pkglinknum',
5256 'table' => 'cust_pkg',
5257 'addl_from' => ' LEFT JOIN part_pkg_link USING (pkglinknum) ',
5258 'extra_sql' => ' WHERE cust_pkg.pkglinknum IS NOT NULL
5259 AND part_pkg_link.pkglinknum IS NULL',
5261 foreach (@pkglinknums) {
5262 my $pkglinknum = $_->pkglinknum;
5263 warn "cleaning part_pkg_link #$pkglinknum\n";
5264 my $part_pkg_link = FS::part_pkg_link->new({pkglinknum => $pkglinknum});
5265 my $error = $part_pkg_link->remove_linked;
5266 die $error if $error;
5274 sub order is not OO. Perhaps it should be moved to FS::cust_main and made so?
5276 In sub order, the @pkgparts array (passed by reference) is clobbered.
5278 Also in sub order, no money is adjusted. Once FS::part_pkg defines a standard
5279 method to pass dates to the recur_prog expression, it should do so.
5281 FS::svc_acct, FS::svc_domain, FS::svc_www, FS::svc_ip and FS::svc_forward are
5282 loaded via 'use' at compile time, rather than via 'require' in sub { setup,
5283 suspend, unsuspend, cancel } because they use %FS::UID::callback to load
5284 configuration values. Probably need a subroutine which decides what to do
5285 based on whether or not we've fetched the user yet, rather than a hash. See
5286 FS::UID and the TODO.
5288 Now that things are transactional should the check in the insert method be
5293 L<FS::Record>, L<FS::cust_main>, L<FS::part_pkg>, L<FS::cust_svc>,
5294 L<FS::pkg_svc>, schema.html from the base documentation