2 use base qw( FS::otaker_Mixin FS::cust_main_Mixin FS::Sales_Mixin
3 FS::contact_Mixin FS::location_Mixin
4 FS::m2m_Common FS::option_Common );
8 use Scalar::Util qw( blessed );
9 use List::Util qw(min max);
11 use Time::Local qw( timelocal timelocal_nocheck );
13 use FS::UID qw( dbh driver_name );
14 use FS::Misc qw( send_email );
15 use FS::Record qw( qsearch qsearchs fields );
21 use FS::cust_location;
23 use FS::cust_bill_pkg;
24 use FS::cust_pkg_detail;
25 use FS::cust_pkg_usage;
26 use FS::cdr_cust_pkg_usage;
31 use FS::cust_pkg_reason;
33 use FS::cust_pkg_usageprice;
34 use FS::cust_pkg_discount;
41 # need to 'use' these instead of 'require' in sub { cancel, suspend, unsuspend,
43 # because they load configuration by setting FS::UID::callback (see TODO)
49 # for sending cancel emails in sub cancel
52 our ($disable_agentcheck, $DEBUG, $me, $import) = (0, 0, '[FS::cust_pkg]', 0);
54 our $upgrade = 0; #go away after setup+start dates cleaned up for old customers
58 my ( $hashref, $cache ) = @_;
59 #if ( $hashref->{'pkgpart'} ) {
60 if ( $hashref->{'pkg'} ) {
61 # #@{ $self->{'_pkgnum'} } = ();
62 # my $subcache = $cache->subcache('pkgpart', 'part_pkg');
63 # $self->{'_pkgpart'} = $subcache;
64 # #push @{ $self->{'_pkgnum'} },
65 # FS::part_pkg->new_or_cached($hashref, $subcache);
66 $self->{'_pkgpart'} = FS::part_pkg->new($hashref);
68 if ( exists $hashref->{'svcnum'} ) {
69 #@{ $self->{'_pkgnum'} } = ();
70 my $subcache = $cache->subcache('svcnum', 'cust_svc', $hashref->{pkgnum});
71 $self->{'_svcnum'} = $subcache;
72 #push @{ $self->{'_pkgnum'} },
73 FS::cust_svc->new_or_cached($hashref, $subcache) if $hashref->{svcnum};
79 FS::cust_pkg - Object methods for cust_pkg objects
85 $record = new FS::cust_pkg \%hash;
86 $record = new FS::cust_pkg { 'column' => 'value' };
88 $error = $record->insert;
90 $error = $new_record->replace($old_record);
92 $error = $record->delete;
94 $error = $record->check;
96 $error = $record->cancel;
98 $error = $record->suspend;
100 $error = $record->unsuspend;
102 $part_pkg = $record->part_pkg;
104 @labels = $record->labels;
106 $seconds = $record->seconds_since($timestamp);
108 $error = FS::cust_pkg::order( $custnum, \@pkgparts );
109 $error = FS::cust_pkg::order( $custnum, \@pkgparts, \@remove_pkgnums ] );
113 An FS::cust_pkg object represents a customer billing item. FS::cust_pkg
114 inherits from FS::Record. The following fields are currently supported:
120 Primary key (assigned automatically for new billing items)
124 Customer (see L<FS::cust_main>)
128 Billing item definition (see L<FS::part_pkg>)
132 Optional link to package location (see L<FS::location>)
136 date package was ordered (also remains same on changes)
148 date (next bill date)
176 order taker (see L<FS::access_user>)
180 If this field is set to 1, disables the automatic
181 unsuspension of this package when using the B<unsuspendauto> config option.
185 If not set, defaults to 1
189 Date of change from previous package
199 =item change_locationnum
207 The pkgnum of the package that this package is supplemental to, if any.
211 The package link (L<FS::part_pkg_link>) that defines this supplemental
212 package, if it is one.
214 =item change_to_pkgnum
216 The pkgnum of the package this one will be "changed to" in the future
217 (on its expiration date).
221 Note: setup, last_bill, bill, adjourn, susp, expire, cancel and change_date
222 are specified as UNIX timestamps; see L<perlfunc/"time">. Also see
223 L<Time::Local> and L<Date::Parse> for conversion functions.
231 Create a new billing item. To add the item to the database, see L<"insert">.
235 sub table { 'cust_pkg'; }
236 sub cust_linked { $_[0]->cust_main_custnum || $_[0]->custnum }
237 sub cust_unlinked_msg {
239 "WARNING: can't find cust_main.custnum ". $self->custnum.
240 ' (cust_pkg.pkgnum '. $self->pkgnum. ')';
243 =item insert [ OPTION => VALUE ... ]
245 Adds this billing item to the database ("Orders" the item). If there is an
246 error, returns the error, otherwise returns false.
248 If the additional field I<promo_code> is defined instead of I<pkgpart>, it
249 will be used to look up the package definition and agent restrictions will be
252 If the additional field I<refnum> is defined, an FS::pkg_referral record will
253 be created and inserted. Multiple FS::pkg_referral records can be created by
254 setting I<refnum> to an array reference of refnums or a hash reference with
255 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
256 record will be created corresponding to cust_main.refnum.
258 If the additional field I<cust_pkg_usageprice> is defined, it will be treated
259 as an arrayref of FS::cust_pkg_usageprice objects, which will be inserted.
260 (Note that this field cannot be set with a usual ->cust_pkg_usageprice method.
261 It can be set as part of the hash when creating the object, or with the B<set>
264 The following options are available:
270 If set true, supresses actions that should only be taken for new package
271 orders. (Currently this includes: intro periods when delay_setup is on.)
275 cust_pkg_option records will be created
279 a ticket will be added to this customer with this subject
283 an optional queue name for ticket additions
287 Don't check the legality of the package definition. This should be used
288 when performing a package change that doesn't change the pkgpart (i.e.
296 my( $self, %options ) = @_;
299 $error = $self->check_pkgpart unless $options{'allow_pkgpart'};
300 return $error if $error;
302 my $part_pkg = $self->part_pkg;
305 # if the package def says to start only on the first of the month:
306 if ( $part_pkg->option('start_1st', 1) && !$self->start_date ) {
307 my ($sec,$min,$hour,$mday,$mon,$year) = (localtime(time) )[0,1,2,3,4,5];
308 $mon += 1 unless $mday == 1;
309 until ( $mon < 12 ) { $mon -= 12; $year++; }
310 $self->start_date( timelocal_nocheck(0,0,0,1,$mon,$year) );
313 # set up any automatic expire/adjourn/contract_end timers
314 # based on the start date
315 foreach my $action ( qw(expire adjourn contract_end) ) {
316 my $months = $part_pkg->option("${action}_months",1);
317 if($months and !$self->$action) {
318 my $start = $self->start_date || $self->setup || time;
319 $self->$action( $part_pkg->add_freq($start, $months) );
323 # if this package has "free days" and delayed setup fee, tehn
324 # set start date that many days in the future.
325 # (this should have been set in the UI, but enforce it here)
326 if ( ! $options{'change'}
327 && ( my $free_days = $part_pkg->option('free_days',1) )
328 && $part_pkg->option('delay_setup',1)
329 #&& ! $self->start_date
332 $self->start_date( $part_pkg->default_start_date );
336 # set order date unless it was specified as part of an import
337 $self->order_date(time) unless $import && $self->order_date;
339 local $SIG{HUP} = 'IGNORE';
340 local $SIG{INT} = 'IGNORE';
341 local $SIG{QUIT} = 'IGNORE';
342 local $SIG{TERM} = 'IGNORE';
343 local $SIG{TSTP} = 'IGNORE';
344 local $SIG{PIPE} = 'IGNORE';
346 my $oldAutoCommit = $FS::UID::AutoCommit;
347 local $FS::UID::AutoCommit = 0;
350 $error = $self->SUPER::insert($options{options} ? %{$options{options}} : ());
352 $dbh->rollback if $oldAutoCommit;
356 $self->refnum($self->cust_main->refnum) unless $self->refnum;
357 $self->refnum( [ $self->refnum ] ) unless ref($self->refnum);
358 $self->process_m2m( 'link_table' => 'pkg_referral',
359 'target_table' => 'part_referral',
360 'params' => $self->refnum,
363 if ( $self->hashref->{cust_pkg_usageprice} ) {
364 for my $cust_pkg_usageprice ( @{ $self->hashref->{cust_pkg_usageprice} } ) {
365 $cust_pkg_usageprice->pkgnum( $self->pkgnum );
366 my $error = $cust_pkg_usageprice->insert;
368 $dbh->rollback if $oldAutoCommit;
374 if ( $self->discountnum ) {
375 my $error = $self->insert_discount();
377 $dbh->rollback if $oldAutoCommit;
382 my $conf = new FS::Conf;
384 if ( ! $import && $conf->config('ticket_system') && $options{ticket_subject} ) {
386 #this init stuff is still inefficient, but at least its limited to
387 # the small number (any?) folks using ticket emailing on pkg order
390 # use lib ( "/opt/rt3/local/lib", "/opt/rt3/lib" );
397 use FS::TicketSystem;
398 FS::TicketSystem->init();
400 my $q = new RT::Queue($RT::SystemUser);
401 $q->Load($options{ticket_queue}) if $options{ticket_queue};
402 my $t = new RT::Ticket($RT::SystemUser);
403 my $mime = new MIME::Entity;
404 $mime->build( Type => 'text/plain', Data => $options{ticket_subject} );
405 $t->Create( $options{ticket_queue} ? (Queue => $q) : (),
406 Subject => $options{ticket_subject},
409 $t->AddLink( Type => 'MemberOf',
410 Target => 'freeside://freeside/cust_main/'. $self->custnum,
414 if (! $import && $conf->config('welcome_letter') && $self->cust_main->num_pkgs == 1) {
415 my $queue = new FS::queue {
416 'job' => 'FS::cust_main::queueable_print',
418 $error = $queue->insert(
419 'custnum' => $self->custnum,
420 'template' => 'welcome_letter',
424 warn "can't send welcome letter: $error";
429 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
436 This method now works but you probably shouldn't use it.
438 You don't want to delete packages, because there would then be no record
439 the customer ever purchased the package. Instead, see the cancel method and
440 hide cancelled packages.
447 local $SIG{HUP} = 'IGNORE';
448 local $SIG{INT} = 'IGNORE';
449 local $SIG{QUIT} = 'IGNORE';
450 local $SIG{TERM} = 'IGNORE';
451 local $SIG{TSTP} = 'IGNORE';
452 local $SIG{PIPE} = 'IGNORE';
454 my $oldAutoCommit = $FS::UID::AutoCommit;
455 local $FS::UID::AutoCommit = 0;
458 foreach my $cust_pkg_discount ($self->cust_pkg_discount) {
459 my $error = $cust_pkg_discount->delete;
461 $dbh->rollback if $oldAutoCommit;
465 #cust_bill_pkg_discount?
467 foreach my $cust_pkg_detail ($self->cust_pkg_detail) {
468 my $error = $cust_pkg_detail->delete;
470 $dbh->rollback if $oldAutoCommit;
475 foreach my $cust_pkg_reason (
477 'table' => 'cust_pkg_reason',
478 'hashref' => { 'pkgnum' => $self->pkgnum },
482 my $error = $cust_pkg_reason->delete;
484 $dbh->rollback if $oldAutoCommit;
491 my $error = $self->SUPER::delete(@_);
493 $dbh->rollback if $oldAutoCommit;
497 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
503 =item replace [ OLD_RECORD ] [ HASHREF | OPTION => VALUE ... ]
505 Replaces the OLD_RECORD with this one in the database. If there is an error,
506 returns the error, otherwise returns false.
508 Currently, custnum, setup, bill, adjourn, susp, expire, and cancel may be changed.
510 Changing pkgpart may have disasterous effects. See the order subroutine.
512 setup and bill are normally updated by calling the bill method of a customer
513 object (see L<FS::cust_main>).
515 suspend is normally updated by the suspend and unsuspend methods.
517 cancel is normally updated by the cancel method (and also the order subroutine
520 Available options are:
526 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.
530 the access_user (see L<FS::access_user>) providing the reason
534 hashref of keys and values - cust_pkg_option records will be created, updated or removed as appopriate
543 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
548 ( ref($_[0]) eq 'HASH' )
552 #return "Can't (yet?) change pkgpart!" if $old->pkgpart != $new->pkgpart;
553 #return "Can't change otaker!" if $old->otaker ne $new->otaker;
556 #return "Can't change setup once it exists!"
557 # if $old->getfield('setup') &&
558 # $old->getfield('setup') != $new->getfield('setup');
560 #some logic for bill, susp, cancel?
562 local($disable_agentcheck) = 1 if $old->pkgpart == $new->pkgpart;
564 local $SIG{HUP} = 'IGNORE';
565 local $SIG{INT} = 'IGNORE';
566 local $SIG{QUIT} = 'IGNORE';
567 local $SIG{TERM} = 'IGNORE';
568 local $SIG{TSTP} = 'IGNORE';
569 local $SIG{PIPE} = 'IGNORE';
571 my $oldAutoCommit = $FS::UID::AutoCommit;
572 local $FS::UID::AutoCommit = 0;
575 foreach my $method ( qw(adjourn expire) ) { # How many reasons?
576 if ($options->{'reason'} && $new->$method && $old->$method ne $new->$method) {
577 my $error = $new->insert_reason(
578 'reason' => $options->{'reason'},
579 'date' => $new->$method,
581 'reason_otaker' => $options->{'reason_otaker'},
584 dbh->rollback if $oldAutoCommit;
585 return "Error inserting cust_pkg_reason: $error";
590 #save off and freeze RADIUS attributes for any associated svc_acct records
592 if ( $old->part_pkg->is_prepaid || $new->part_pkg->is_prepaid ) {
594 #also check for specific exports?
595 # to avoid spurious modify export events
596 @svc_acct = map { $_->svc_x }
597 grep { $_->part_svc->svcdb eq 'svc_acct' }
600 $_->snapshot foreach @svc_acct;
604 my $error = $new->export_pkg_change($old)
605 || $new->SUPER::replace( $old,
607 ? $options->{options}
611 $dbh->rollback if $oldAutoCommit;
615 #for prepaid packages,
616 #trigger export of new RADIUS Expiration attribute when cust_pkg.bill changes
617 foreach my $old_svc_acct ( @svc_acct ) {
618 my $new_svc_acct = new FS::svc_acct { $old_svc_acct->hash };
620 $new_svc_acct->replace( $old_svc_acct,
621 'depend_jobnum' => $options->{depend_jobnum},
624 $dbh->rollback if $oldAutoCommit;
629 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
636 Checks all fields to make sure this is a valid billing item. If there is an
637 error, returns the error, otherwise returns false. Called by the insert and
645 if ( !$self->locationnum or $self->locationnum == -1 ) {
646 $self->set('locationnum', $self->cust_main->ship_locationnum);
650 $self->ut_numbern('pkgnum')
651 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum')
652 || $self->ut_numbern('pkgpart')
653 || $self->ut_foreign_keyn('contactnum', 'contact', 'contactnum' )
654 || $self->ut_foreign_keyn('locationnum', 'cust_location', 'locationnum')
655 || $self->ut_foreign_keyn('salesnum', 'sales', 'salesnum')
656 || $self->ut_numbern('quantity')
657 || $self->ut_numbern('start_date')
658 || $self->ut_numbern('setup')
659 || $self->ut_numbern('bill')
660 || $self->ut_numbern('susp')
661 || $self->ut_numbern('cancel')
662 || $self->ut_numbern('adjourn')
663 || $self->ut_numbern('resume')
664 || $self->ut_numbern('expire')
665 || $self->ut_numbern('dundate')
666 || $self->ut_enum('no_auto', [ '', 'Y' ])
667 || $self->ut_enum('waive_setup', [ '', 'Y' ])
668 || $self->ut_numbern('agent_pkgid')
669 || $self->ut_enum('recur_show_zero', [ '', 'Y', 'N', ])
670 || $self->ut_enum('setup_show_zero', [ '', 'Y', 'N', ])
671 || $self->ut_foreign_keyn('main_pkgnum', 'cust_pkg', 'pkgnum')
672 || $self->ut_foreign_keyn('pkglinknum', 'part_pkg_link', 'pkglinknum')
673 || $self->ut_foreign_keyn('change_to_pkgnum', 'cust_pkg', 'pkgnum')
675 return $error if $error;
677 return "A package with both start date (future start) and setup date (already started) will never bill"
678 if $self->start_date && $self->setup && ! $upgrade;
680 return "A future unsuspend date can only be set for a package with a suspend date"
681 if $self->resume and !$self->susp and !$self->adjourn;
683 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
685 if ( $self->dbdef_table->column('manual_flag') ) {
686 $self->manual_flag('') if $self->manual_flag eq ' ';
687 $self->manual_flag =~ /^([01]?)$/
688 or return "Illegal manual_flag ". $self->manual_flag;
689 $self->manual_flag($1);
697 Check the pkgpart to make sure it's allowed with the reg_code and/or
698 promo_code of the package (if present) and with the customer's agent.
699 Called from C<insert>, unless we are doing a package change that doesn't
707 # my $error = $self->ut_numbern('pkgpart'); # already done
710 if ( $self->reg_code ) {
712 unless ( grep { $self->pkgpart == $_->pkgpart }
713 map { $_->reg_code_pkg }
714 qsearchs( 'reg_code', { 'code' => $self->reg_code,
715 'agentnum' => $self->cust_main->agentnum })
717 return "Unknown registration code";
720 } elsif ( $self->promo_code ) {
723 qsearchs('part_pkg', {
724 'pkgpart' => $self->pkgpart,
725 'promo_code' => { op=>'ILIKE', value=>$self->promo_code },
727 return 'Unknown promotional code' unless $promo_part_pkg;
731 unless ( $disable_agentcheck ) {
733 qsearchs( 'agent', { 'agentnum' => $self->cust_main->agentnum } );
734 return "agent ". $agent->agentnum. ':'. $agent->agent.
735 " can't purchase pkgpart ". $self->pkgpart
736 unless $agent->pkgpart_hashref->{ $self->pkgpart }
737 || $agent->agentnum == $self->part_pkg->agentnum;
740 $error = $self->ut_foreign_key('pkgpart', 'part_pkg', 'pkgpart' );
741 return $error if $error;
749 =item cancel [ OPTION => VALUE ... ]
751 Cancels and removes all services (see L<FS::cust_svc> and L<FS::part_svc>)
752 in this package, then cancels the package itself (sets the cancel field to
755 Available options are:
759 =item quiet - can be set true to supress email cancellation notices.
761 =item time - can be set to cancel the package based on a specific future or
762 historical date. Using time ensures that the remaining amount is calculated
763 correctly. Note however that this is an immediate cancel and just changes
764 the date. You are PROBABLY looking to expire the account instead of using
767 =item reason - can be set to a cancellation reason (see L<FS:reason>),
768 either a reasonnum of an existing reason, or passing a hashref will create
769 a new reason. The hashref should have the following keys: typenum - Reason
770 type (see L<FS::reason_type>, reason - Text of the new reason.
772 =item date - can be set to a unix style timestamp to specify when to
775 =item nobill - can be set true to skip billing if it might otherwise be done.
777 =item unused_credit - can be set to 1 to credit the remaining time, or 0 to
778 not credit it. This must be set (by change()) when changing the package
779 to a different pkgpart or location, and probably shouldn't be in any other
780 case. If it's not set, the 'unused_credit_cancel' part_pkg option will
785 If there is an error, returns the error, otherwise returns false.
790 my( $self, %options ) = @_;
793 # pass all suspend/cancel actions to the main package
794 if ( $self->main_pkgnum and !$options{'from_main'} ) {
795 return $self->main_pkg->cancel(%options);
798 my $conf = new FS::Conf;
800 warn "cust_pkg::cancel called with options".
801 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
804 local $SIG{HUP} = 'IGNORE';
805 local $SIG{INT} = 'IGNORE';
806 local $SIG{QUIT} = 'IGNORE';
807 local $SIG{TERM} = 'IGNORE';
808 local $SIG{TSTP} = 'IGNORE';
809 local $SIG{PIPE} = 'IGNORE';
811 my $oldAutoCommit = $FS::UID::AutoCommit;
812 local $FS::UID::AutoCommit = 0;
815 my $old = $self->select_for_update;
817 if ( $old->get('cancel') || $self->get('cancel') ) {
818 dbh->rollback if $oldAutoCommit;
819 return ""; # no error
822 # XXX possibly set cancel_time to the expire date?
823 my $cancel_time = $options{'time'} || time;
824 my $date = $options{'date'} if $options{'date'}; # expire/cancel later
825 $date = '' if ($date && $date <= $cancel_time); # complain instead?
827 #race condition: usage could be ongoing until unprovisioned
828 #resolved by performing a change package instead (which unprovisions) and
830 if ( !$options{nobill} && !$date ) {
831 # && $conf->exists('bill_usage_on_cancel') ) { #calc_cancel checks this
832 my $copy = $self->new({$self->hash});
834 $copy->cust_main->bill( 'pkg_list' => [ $copy ],
836 'time' => $cancel_time );
837 warn "Error billing during cancel, custnum ".
838 #$self->cust_main->custnum. ": $error"
843 if ( $options{'reason'} ) {
844 $error = $self->insert_reason( 'reason' => $options{'reason'},
845 'action' => $date ? 'expire' : 'cancel',
846 'date' => $date ? $date : $cancel_time,
847 'reason_otaker' => $options{'reason_otaker'},
850 dbh->rollback if $oldAutoCommit;
851 return "Error inserting cust_pkg_reason: $error";
855 my %svc_cancel_opt = ();
856 $svc_cancel_opt{'date'} = $date if $date;
857 foreach my $cust_svc (
860 sort { $a->[1] <=> $b->[1] }
861 map { [ $_, $_->svc_x ? $_->svc_x->table_info->{'cancel_weight'} : -1 ]; }
862 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
864 my $part_svc = $cust_svc->part_svc;
865 next if ( defined($part_svc) and $part_svc->preserve );
866 my $error = $cust_svc->cancel( %svc_cancel_opt );
869 $dbh->rollback if $oldAutoCommit;
870 return 'Error '. ($svc_cancel_opt{'date'} ? 'expiring' : 'canceling' ).
876 # credit remaining time if appropriate
878 if ( exists($options{'unused_credit'}) ) {
879 $do_credit = $options{'unused_credit'};
882 $do_credit = $self->part_pkg->option('unused_credit_cancel', 1);
885 my $error = $self->credit_remaining('cancel', $cancel_time);
887 $dbh->rollback if $oldAutoCommit;
894 my %hash = $self->hash;
896 $hash{'expire'} = $date;
898 $hash{'cancel'} = $cancel_time;
900 $hash{'change_custnum'} = $options{'change_custnum'};
902 my $new = new FS::cust_pkg ( \%hash );
903 $error = $new->replace( $self, options => { $self->options } );
904 if ( $self->change_to_pkgnum ) {
905 my $change_to = FS::cust_pkg->by_key($self->change_to_pkgnum);
906 $error ||= $change_to->cancel || $change_to->delete;
909 $dbh->rollback if $oldAutoCommit;
913 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
914 $error = $supp_pkg->cancel(%options, 'from_main' => 1);
916 $dbh->rollback if $oldAutoCommit;
917 return "canceling supplemental pkg#".$supp_pkg->pkgnum.": $error";
921 foreach my $usage ( $self->cust_pkg_usage ) {
922 $error = $usage->delete;
924 $dbh->rollback if $oldAutoCommit;
925 return "deleting usage pools: $error";
929 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
930 return '' if $date; #no errors
932 my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ } $self->cust_main->invoicing_list;
933 if ( !$options{'quiet'} &&
934 $conf->exists('emailcancel', $self->cust_main->agentnum) &&
936 my $msgnum = $conf->config('cancel_msgnum', $self->cust_main->agentnum);
939 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum });
940 $error = $msg_template->send( 'cust_main' => $self->cust_main,
945 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
946 'to' => \@invoicing_list,
947 'subject' => ( $conf->config('cancelsubject') || 'Cancellation Notice' ),
948 'body' => [ map "$_\n", $conf->config('cancelmessage') ],
951 #should this do something on errors?
958 =item cancel_if_expired [ NOW_TIMESTAMP ]
960 Cancels this package if its expire date has been reached.
964 sub cancel_if_expired {
966 my $time = shift || time;
967 return '' unless $self->expire && $self->expire <= $time;
968 my $error = $self->cancel;
970 return "Error cancelling expired pkg ". $self->pkgnum. " for custnum ".
971 $self->custnum. ": $error";
978 "Un-cancels" this package: Orders a new package with the same custnum, pkgpart,
979 locationnum, (other fields?). Attempts to re-provision cancelled services
980 using history information (errors at this stage are not fatal).
982 cust_pkg: pass a scalar reference, will be filled in with the new cust_pkg object
984 svc_fatal: service provisioning errors are fatal
986 svc_errors: pass an array reference, will be filled in with any provisioning errors
988 main_pkgnum: link the package as a supplemental package of this one. For
994 my( $self, %options ) = @_;
996 #in case you try do do $uncancel-date = $cust_pkg->uncacel
997 return '' unless $self->get('cancel');
999 if ( $self->main_pkgnum and !$options{'main_pkgnum'} ) {
1000 return $self->main_pkg->uncancel(%options);
1007 local $SIG{HUP} = 'IGNORE';
1008 local $SIG{INT} = 'IGNORE';
1009 local $SIG{QUIT} = 'IGNORE';
1010 local $SIG{TERM} = 'IGNORE';
1011 local $SIG{TSTP} = 'IGNORE';
1012 local $SIG{PIPE} = 'IGNORE';
1014 my $oldAutoCommit = $FS::UID::AutoCommit;
1015 local $FS::UID::AutoCommit = 0;
1019 # insert the new package
1022 my $cust_pkg = new FS::cust_pkg {
1023 last_bill => ( $options{'last_bill'} || $self->get('last_bill') ),
1024 bill => ( $options{'bill'} || $self->get('bill') ),
1026 uncancel_pkgnum => $self->pkgnum,
1027 main_pkgnum => ($options{'main_pkgnum'} || ''),
1028 map { $_ => $self->get($_) } qw(
1029 custnum pkgpart locationnum
1031 susp adjourn resume expire start_date contract_end dundate
1032 change_date change_pkgpart change_locationnum
1033 manual_flag no_auto quantity agent_pkgid recur_show_zero setup_show_zero
1037 my $error = $cust_pkg->insert(
1038 'change' => 1, #supresses any referral credit to a referring customer
1039 'allow_pkgpart' => 1, # allow this even if the package def is disabled
1042 $dbh->rollback if $oldAutoCommit;
1050 #find historical services within this timeframe before the package cancel
1051 # (incompatible with "time" option to cust_pkg->cancel?)
1052 my $fuzz = 2 * 60; #2 minutes? too much? (might catch separate unprovision)
1053 # too little? (unprovisioing export delay?)
1054 my($end, $start) = ( $self->get('cancel'), $self->get('cancel') - $fuzz );
1055 my @h_cust_svc = $self->h_cust_svc( $end, $start );
1058 foreach my $h_cust_svc (@h_cust_svc) {
1059 my $h_svc_x = $h_cust_svc->h_svc_x( $end, $start );
1060 #next unless $h_svc_x; #should this happen?
1061 (my $table = $h_svc_x->table) =~ s/^h_//;
1062 require "FS/$table.pm";
1063 my $class = "FS::$table";
1064 my $svc_x = $class->new( {
1065 'pkgnum' => $cust_pkg->pkgnum,
1066 'svcpart' => $h_cust_svc->svcpart,
1067 map { $_ => $h_svc_x->get($_) } fields($table)
1071 if ( $h_svc_x->isa('FS::h_svc_Radius_Mixin') ) {
1072 $svc_x->usergroup( [ $h_svc_x->h_usergroup($end, $start) ] );
1075 my $svc_error = $svc_x->insert;
1077 if ( $options{svc_fatal} ) {
1078 $dbh->rollback if $oldAutoCommit;
1081 # if we've failed to insert the svc_x object, svc_Common->insert
1082 # will have removed the cust_svc already. if not, then both records
1083 # were inserted but we failed for some other reason (export, most
1084 # likely). in that case, report the error and delete the records.
1085 push @svc_errors, $svc_error;
1086 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svc_x->svcnum });
1088 # except if export_insert failed, export_delete probably won't be
1090 local $FS::svc_Common::noexport_hack = 1;
1091 my $cleanup_error = $svc_x->delete; # also deletes cust_svc
1092 if ( $cleanup_error ) { # and if THAT fails, then run away
1093 $dbh->rollback if $oldAutoCommit;
1094 return $cleanup_error;
1099 } #foreach $h_cust_svc
1101 #these are pretty rare, but should handle them
1102 # - dsl_device (mac addresses)
1103 # - phone_device (mac addresses)
1104 # - dsl_note (ikano notes)
1105 # - domain_record (i.e. restore DNS information w/domains)
1106 # - inventory_item(?) (inventory w/un-cancelling service?)
1107 # - nas (svc_broaband nas stuff)
1108 #this stuff is unused in the wild afaik
1109 # - mailinglistmember
1111 # - svc_domain.parent_svcnum?
1112 # - acct_snarf (ancient mail fetching config)
1113 # - cgp_rule (communigate)
1114 # - cust_svc_option (used by our Tron stuff)
1115 # - acct_rt_transaction (used by our time worked stuff)
1118 # also move over any services that didn't unprovision at cancellation
1121 foreach my $cust_svc ( qsearch('cust_svc', { pkgnum => $self->pkgnum } ) ) {
1122 $cust_svc->pkgnum( $cust_pkg->pkgnum );
1123 my $error = $cust_svc->replace;
1125 $dbh->rollback if $oldAutoCommit;
1131 # Uncancel any supplemental packages, and make them supplemental to the
1135 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1137 $error = $supp_pkg->uncancel(%options, 'main_pkgnum' => $cust_pkg->pkgnum);
1139 $dbh->rollback if $oldAutoCommit;
1140 return "canceling supplemental pkg#".$supp_pkg->pkgnum.": $error";
1148 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1150 ${ $options{cust_pkg} } = $cust_pkg if ref($options{cust_pkg});
1151 @{ $options{svc_errors} } = @svc_errors if ref($options{svc_errors});
1158 Cancels any pending expiration (sets the expire field to null).
1160 If there is an error, returns the error, otherwise returns false.
1165 my( $self, %options ) = @_;
1168 local $SIG{HUP} = 'IGNORE';
1169 local $SIG{INT} = 'IGNORE';
1170 local $SIG{QUIT} = 'IGNORE';
1171 local $SIG{TERM} = 'IGNORE';
1172 local $SIG{TSTP} = 'IGNORE';
1173 local $SIG{PIPE} = 'IGNORE';
1175 my $oldAutoCommit = $FS::UID::AutoCommit;
1176 local $FS::UID::AutoCommit = 0;
1179 my $old = $self->select_for_update;
1181 my $pkgnum = $old->pkgnum;
1182 if ( $old->get('cancel') || $self->get('cancel') ) {
1183 dbh->rollback if $oldAutoCommit;
1184 return "Can't unexpire cancelled package $pkgnum";
1185 # or at least it's pointless
1188 unless ( $old->get('expire') && $self->get('expire') ) {
1189 dbh->rollback if $oldAutoCommit;
1190 return ""; # no error
1193 my %hash = $self->hash;
1194 $hash{'expire'} = '';
1195 my $new = new FS::cust_pkg ( \%hash );
1196 $error = $new->replace( $self, options => { $self->options } );
1198 $dbh->rollback if $oldAutoCommit;
1202 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1208 =item suspend [ OPTION => VALUE ... ]
1210 Suspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
1211 package, then suspends the package itself (sets the susp field to now).
1213 Available options are:
1217 =item reason - can be set to a cancellation reason (see L<FS:reason>),
1218 either a reasonnum of an existing reason, or passing a hashref will create
1219 a new reason. The hashref should have the following keys:
1220 - typenum - Reason type (see L<FS::reason_type>
1221 - reason - Text of the new reason.
1223 =item date - can be set to a unix style timestamp to specify when to
1226 =item time - can be set to override the current time, for calculation
1227 of final invoices or unused-time credits
1229 =item resume_date - can be set to a time when the package should be
1230 unsuspended. This may be more convenient than calling C<unsuspend()>
1233 =item from_main - allows a supplemental package to be suspended, rather
1234 than redirecting the method call to its main package. For internal use.
1238 If there is an error, returns the error, otherwise returns false.
1243 my( $self, %options ) = @_;
1246 # pass all suspend/cancel actions to the main package
1247 if ( $self->main_pkgnum and !$options{'from_main'} ) {
1248 return $self->main_pkg->suspend(%options);
1251 local $SIG{HUP} = 'IGNORE';
1252 local $SIG{INT} = 'IGNORE';
1253 local $SIG{QUIT} = 'IGNORE';
1254 local $SIG{TERM} = 'IGNORE';
1255 local $SIG{TSTP} = 'IGNORE';
1256 local $SIG{PIPE} = 'IGNORE';
1258 my $oldAutoCommit = $FS::UID::AutoCommit;
1259 local $FS::UID::AutoCommit = 0;
1262 my $old = $self->select_for_update;
1264 my $pkgnum = $old->pkgnum;
1265 if ( $old->get('cancel') || $self->get('cancel') ) {
1266 dbh->rollback if $oldAutoCommit;
1267 return "Can't suspend cancelled package $pkgnum";
1270 if ( $old->get('susp') || $self->get('susp') ) {
1271 dbh->rollback if $oldAutoCommit;
1272 return ""; # no error # complain on adjourn?
1275 my $suspend_time = $options{'time'} || time;
1276 my $date = $options{date} if $options{date}; # adjourn/suspend later
1277 $date = '' if ($date && $date <= $suspend_time); # complain instead?
1279 if ( $date && $old->get('expire') && $old->get('expire') < $date ) {
1280 dbh->rollback if $oldAutoCommit;
1281 return "Package $pkgnum expires before it would be suspended.";
1284 # some false laziness with sub cancel
1285 if ( !$options{nobill} && !$date &&
1286 $self->part_pkg->option('bill_suspend_as_cancel',1) ) {
1287 # kind of a kludge--'bill_suspend_as_cancel' to avoid having to
1288 # make the entire cust_main->bill path recognize 'suspend' and
1289 # 'cancel' separately.
1290 warn "Billing $pkgnum on suspension (at $suspend_time)\n" if $DEBUG;
1291 my $copy = $self->new({$self->hash});
1293 $copy->cust_main->bill( 'pkg_list' => [ $copy ],
1295 'time' => $suspend_time );
1296 warn "Error billing during suspend, custnum ".
1297 #$self->cust_main->custnum. ": $error"
1302 if ( $options{'reason'} ) {
1303 $error = $self->insert_reason( 'reason' => $options{'reason'},
1304 'action' => $date ? 'adjourn' : 'suspend',
1305 'date' => $date ? $date : $suspend_time,
1306 'reason_otaker' => $options{'reason_otaker'},
1309 dbh->rollback if $oldAutoCommit;
1310 return "Error inserting cust_pkg_reason: $error";
1314 my %hash = $self->hash;
1316 $hash{'adjourn'} = $date;
1318 $hash{'susp'} = $suspend_time;
1321 my $resume_date = $options{'resume_date'} || 0;
1322 if ( $resume_date > ($date || $suspend_time) ) {
1323 $hash{'resume'} = $resume_date;
1326 $options{options} ||= {};
1328 my $new = new FS::cust_pkg ( \%hash );
1329 $error = $new->replace( $self, options => { $self->options,
1330 %{ $options{options} },
1334 $dbh->rollback if $oldAutoCommit;
1339 # credit remaining time if appropriate
1340 if ( $self->part_pkg->option('unused_credit_suspend', 1) ) {
1341 my $error = $self->credit_remaining('suspend', $suspend_time);
1343 $dbh->rollback if $oldAutoCommit;
1350 foreach my $cust_svc (
1351 qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
1353 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
1355 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
1356 $dbh->rollback if $oldAutoCommit;
1357 return "Illegal svcdb value in part_svc!";
1360 require "FS/$svcdb.pm";
1362 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
1364 $error = $svc->suspend;
1366 $dbh->rollback if $oldAutoCommit;
1369 my( $label, $value ) = $cust_svc->label;
1370 push @labels, "$label: $value";
1374 my $conf = new FS::Conf;
1375 if ( $conf->config('suspend_email_admin') ) {
1377 my $error = send_email(
1378 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
1379 #invoice_from ??? well as good as any
1380 'to' => $conf->config('suspend_email_admin'),
1381 'subject' => 'FREESIDE NOTIFICATION: Customer package suspended',
1383 "This is an automatic message from your Freeside installation\n",
1384 "informing you that the following customer package has been suspended:\n",
1386 'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
1387 'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
1388 ( map { "Service : $_\n" } @labels ),
1393 warn "WARNING: can't send suspension admin email (suspending anyway): ".
1401 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1402 $error = $supp_pkg->suspend(%options, 'from_main' => 1);
1404 $dbh->rollback if $oldAutoCommit;
1405 return "suspending supplemental pkg#".$supp_pkg->pkgnum.": $error";
1409 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1414 =item credit_remaining MODE TIME
1416 Generate a credit for this package for the time remaining in the current
1417 billing period. MODE is either "suspend" or "cancel" (determines the
1418 credit type). TIME is the time of suspension/cancellation. Both arguments
1423 sub credit_remaining {
1424 # Add a credit for remaining service
1425 my ($self, $mode, $time) = @_;
1426 die 'credit_remaining requires suspend or cancel'
1427 unless $mode eq 'suspend' or $mode eq 'cancel';
1428 die 'no suspend/cancel time' unless $time > 0;
1430 my $conf = FS::Conf->new;
1431 my $reason_type = $conf->config($mode.'_credit_type');
1433 my $last_bill = $self->getfield('last_bill') || 0;
1434 my $next_bill = $self->getfield('bill') || 0;
1435 if ( $last_bill > 0 # the package has been billed
1436 and $next_bill > 0 # the package has a next bill date
1437 and $next_bill >= $time # which is in the future
1439 my $remaining_value = $self->calc_remain('time' => $time);
1440 if ( $remaining_value > 0 ) {
1441 warn "Crediting for $remaining_value on package ".$self->pkgnum."\n"
1443 my $error = $self->cust_main->credit(
1445 'Credit for unused time on '. $self->part_pkg->pkg,
1446 'reason_type' => $reason_type,
1448 return "Error crediting customer \$$remaining_value for unused time".
1449 " on ". $self->part_pkg->pkg. ": $error"
1451 } #if $remaining_value
1452 } #if $last_bill, etc.
1456 =item unsuspend [ OPTION => VALUE ... ]
1458 Unsuspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
1459 package, then unsuspends the package itself (clears the susp field and the
1460 adjourn field if it is in the past). If the suspend reason includes an
1461 unsuspension package, that package will be ordered.
1463 Available options are:
1469 Can be set to a date to unsuspend the package in the future (the 'resume'
1472 =item adjust_next_bill
1474 Can be set true to adjust the next bill date forward by
1475 the amount of time the account was inactive. This was set true by default
1476 in the past (from 1.4.2 and 1.5.0pre6 through 1.7.0), but now needs to be
1477 explicitly requested with this option or in the price plan.
1481 If there is an error, returns the error, otherwise returns false.
1486 my( $self, %opt ) = @_;
1489 # pass all suspend/cancel actions to the main package
1490 if ( $self->main_pkgnum and !$opt{'from_main'} ) {
1491 return $self->main_pkg->unsuspend(%opt);
1494 local $SIG{HUP} = 'IGNORE';
1495 local $SIG{INT} = 'IGNORE';
1496 local $SIG{QUIT} = 'IGNORE';
1497 local $SIG{TERM} = 'IGNORE';
1498 local $SIG{TSTP} = 'IGNORE';
1499 local $SIG{PIPE} = 'IGNORE';
1501 my $oldAutoCommit = $FS::UID::AutoCommit;
1502 local $FS::UID::AutoCommit = 0;
1505 my $old = $self->select_for_update;
1507 my $pkgnum = $old->pkgnum;
1508 if ( $old->get('cancel') || $self->get('cancel') ) {
1509 $dbh->rollback if $oldAutoCommit;
1510 return "Can't unsuspend cancelled package $pkgnum";
1513 unless ( $old->get('susp') && $self->get('susp') ) {
1514 $dbh->rollback if $oldAutoCommit;
1515 return ""; # no error # complain instead?
1518 my $date = $opt{'date'};
1519 if ( $date and $date > time ) { # return an error if $date <= time?
1521 if ( $old->get('expire') && $old->get('expire') < $date ) {
1522 $dbh->rollback if $oldAutoCommit;
1523 return "Package $pkgnum expires before it would be unsuspended.";
1526 my $new = new FS::cust_pkg { $self->hash };
1527 $new->set('resume', $date);
1528 $error = $new->replace($self, options => $self->options);
1531 $dbh->rollback if $oldAutoCommit;
1535 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1543 foreach my $cust_svc (
1544 qsearch('cust_svc',{'pkgnum'=> $self->pkgnum } )
1546 my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
1548 $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
1549 $dbh->rollback if $oldAutoCommit;
1550 return "Illegal svcdb value in part_svc!";
1553 require "FS/$svcdb.pm";
1555 my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
1557 $error = $svc->unsuspend;
1559 $dbh->rollback if $oldAutoCommit;
1562 my( $label, $value ) = $cust_svc->label;
1563 push @labels, "$label: $value";
1568 my $cust_pkg_reason = $self->last_cust_pkg_reason('susp');
1569 my $reason = $cust_pkg_reason ? $cust_pkg_reason->reason : '';
1571 my %hash = $self->hash;
1572 my $inactive = time - $hash{'susp'};
1574 my $conf = new FS::Conf;
1576 if ( $inactive > 0 &&
1577 ( $hash{'bill'} || $hash{'setup'} ) &&
1578 ( $opt{'adjust_next_bill'} ||
1579 $conf->exists('unsuspend-always_adjust_next_bill_date') ||
1580 $self->part_pkg->option('unsuspend_adjust_bill', 1) )
1583 $hash{'bill'} = ( $hash{'bill'} || $hash{'setup'} ) + $inactive;
1588 $hash{'adjourn'} = '' if $hash{'adjourn'} and $hash{'adjourn'} < time;
1589 $hash{'resume'} = '' if !$hash{'adjourn'};
1590 my $new = new FS::cust_pkg ( \%hash );
1591 $error = $new->replace( $self, options => { $self->options } );
1593 $dbh->rollback if $oldAutoCommit;
1599 if ( $reason && $reason->unsuspend_pkgpart ) {
1600 my $part_pkg = FS::part_pkg->by_key($reason->unsuspend_pkgpart)
1601 or $error = "Unsuspend package definition ".$reason->unsuspend_pkgpart.
1603 my $start_date = $self->cust_main->next_bill_date
1604 if $reason->unsuspend_hold;
1607 $unsusp_pkg = FS::cust_pkg->new({
1608 'custnum' => $self->custnum,
1609 'pkgpart' => $reason->unsuspend_pkgpart,
1610 'start_date' => $start_date,
1611 'locationnum' => $self->locationnum,
1612 # discount? probably not...
1615 $error ||= $self->cust_main->order_pkg( 'cust_pkg' => $unsusp_pkg );
1619 $dbh->rollback if $oldAutoCommit;
1624 if ( $conf->config('unsuspend_email_admin') ) {
1626 my $error = send_email(
1627 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
1628 #invoice_from ??? well as good as any
1629 'to' => $conf->config('unsuspend_email_admin'),
1630 'subject' => 'FREESIDE NOTIFICATION: Customer package unsuspended', 'body' => [
1631 "This is an automatic message from your Freeside installation\n",
1632 "informing you that the following customer package has been unsuspended:\n",
1634 'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
1635 'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
1636 ( map { "Service : $_\n" } @labels ),
1638 "An unsuspension fee was charged: ".
1639 $unsusp_pkg->part_pkg->pkg_comment."\n"
1646 warn "WARNING: can't send unsuspension admin email (unsuspending anyway): ".
1652 foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1653 $error = $supp_pkg->unsuspend(%opt, 'from_main' => 1);
1655 $dbh->rollback if $oldAutoCommit;
1656 return "unsuspending supplemental pkg#".$supp_pkg->pkgnum.": $error";
1660 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1667 Cancels any pending suspension (sets the adjourn field to null).
1669 If there is an error, returns the error, otherwise returns false.
1674 my( $self, %options ) = @_;
1677 local $SIG{HUP} = 'IGNORE';
1678 local $SIG{INT} = 'IGNORE';
1679 local $SIG{QUIT} = 'IGNORE';
1680 local $SIG{TERM} = 'IGNORE';
1681 local $SIG{TSTP} = 'IGNORE';
1682 local $SIG{PIPE} = 'IGNORE';
1684 my $oldAutoCommit = $FS::UID::AutoCommit;
1685 local $FS::UID::AutoCommit = 0;
1688 my $old = $self->select_for_update;
1690 my $pkgnum = $old->pkgnum;
1691 if ( $old->get('cancel') || $self->get('cancel') ) {
1692 dbh->rollback if $oldAutoCommit;
1693 return "Can't unadjourn cancelled package $pkgnum";
1694 # or at least it's pointless
1697 if ( $old->get('susp') || $self->get('susp') ) {
1698 dbh->rollback if $oldAutoCommit;
1699 return "Can't unadjourn suspended package $pkgnum";
1700 # perhaps this is arbitrary
1703 unless ( $old->get('adjourn') && $self->get('adjourn') ) {
1704 dbh->rollback if $oldAutoCommit;
1705 return ""; # no error
1708 my %hash = $self->hash;
1709 $hash{'adjourn'} = '';
1710 $hash{'resume'} = '';
1711 my $new = new FS::cust_pkg ( \%hash );
1712 $error = $new->replace( $self, options => { $self->options } );
1714 $dbh->rollback if $oldAutoCommit;
1718 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1725 =item change HASHREF | OPTION => VALUE ...
1727 Changes this package: cancels it and creates a new one, with a different
1728 pkgpart or locationnum or both. All services are transferred to the new
1729 package (no change will be made if this is not possible).
1731 Options may be passed as a list of key/value pairs or as a hash reference.
1738 New locationnum, to change the location for this package.
1742 New FS::cust_location object, to create a new location and assign it
1747 New FS::cust_main object, to create a new customer and assign the new package
1752 New pkgpart (see L<FS::part_pkg>).
1756 New refnum (see L<FS::part_referral>).
1760 New quantity; if unspecified, the new package will have the same quantity
1765 "New" (existing) FS::cust_pkg object. The package's services and other
1766 attributes will be transferred to this package.
1770 Set to true to transfer billing dates (start_date, setup, last_bill, bill,
1771 susp, adjourn, cancel, expire, and contract_end) to the new package.
1773 =item unprotect_svcs
1775 Normally, change() will rollback and return an error if some services
1776 can't be transferred (also see the I<cust_pkg-change_svcpart> config option).
1777 If unprotect_svcs is true, this method will transfer as many services as
1778 it can and then unconditionally cancel the old package.
1782 At least one of locationnum, cust_location, pkgpart, refnum, cust_main, or
1783 cust_pkg must be specified (otherwise, what's the point?)
1785 Returns either the new FS::cust_pkg object or a scalar error.
1789 my $err_or_new_cust_pkg = $old_cust_pkg->change
1793 #some false laziness w/order
1796 my $opt = ref($_[0]) ? shift : { @_ };
1798 my $conf = new FS::Conf;
1800 # Transactionize this whole mess
1801 local $SIG{HUP} = 'IGNORE';
1802 local $SIG{INT} = 'IGNORE';
1803 local $SIG{QUIT} = 'IGNORE';
1804 local $SIG{TERM} = 'IGNORE';
1805 local $SIG{TSTP} = 'IGNORE';
1806 local $SIG{PIPE} = 'IGNORE';
1808 my $oldAutoCommit = $FS::UID::AutoCommit;
1809 local $FS::UID::AutoCommit = 0;
1818 $hash{'setup'} = $time if $self->setup;
1820 $hash{'change_date'} = $time;
1821 $hash{"change_$_"} = $self->$_()
1822 foreach qw( pkgnum pkgpart locationnum );
1824 if ( $opt->{'cust_location'} ) {
1825 $error = $opt->{'cust_location'}->find_or_insert;
1827 $dbh->rollback if $oldAutoCommit;
1828 return "inserting cust_location (transaction rolled back): $error";
1830 $opt->{'locationnum'} = $opt->{'cust_location'}->locationnum;
1833 if ( $opt->{'cust_pkg'} ) {
1834 # treat changing to a package with a different pkgpart as a
1835 # pkgpart change (because it is)
1836 $opt->{'pkgpart'} = $opt->{'cust_pkg'}->pkgpart;
1839 # whether to override pkgpart checking on the new package
1840 my $same_pkgpart = 1;
1841 if ( $opt->{'pkgpart'} and ( $opt->{'pkgpart'} != $self->pkgpart ) ) {
1845 my $unused_credit = 0;
1846 my $keep_dates = $opt->{'keep_dates'};
1847 # Special case. If the pkgpart is changing, and the customer is
1848 # going to be credited for remaining time, don't keep setup, bill,
1849 # or last_bill dates, and DO pass the flag to cancel() to credit
1851 if ( $opt->{'pkgpart'}
1852 and $opt->{'pkgpart'} != $self->pkgpart
1853 and $self->part_pkg->option('unused_credit_change', 1) ) {
1856 $hash{$_} = '' foreach qw(setup bill last_bill);
1859 if ( $keep_dates ) {
1860 foreach my $date ( qw(setup bill last_bill susp adjourn cancel expire
1861 resume start_date contract_end ) ) {
1862 $hash{$date} = $self->getfield($date);
1866 # allow $opt->{'locationnum'} = '' to specifically set it to null
1867 # (i.e. customer default location)
1868 $opt->{'locationnum'} = $self->locationnum if !exists($opt->{'locationnum'});
1870 # usually this doesn't matter. the two cases where it does are:
1871 # 1. unused_credit_change + pkgpart change + setup fee on the new package
1873 # 2. (more importantly) changing a package before it's billed
1874 $hash{'waive_setup'} = $self->waive_setup;
1876 my $custnum = $self->custnum;
1877 if ( $opt->{cust_main} ) {
1878 my $cust_main = $opt->{cust_main};
1879 unless ( $cust_main->custnum ) {
1880 my $error = $cust_main->insert( @{ $opt->{cust_main_insert_args}||[] } );
1882 $dbh->rollback if $oldAutoCommit;
1883 return "inserting cust_main (transaction rolled back): $error";
1886 $custnum = $cust_main->custnum;
1889 $hash{'contactnum'} = $opt->{'contactnum'} if $opt->{'contactnum'};
1892 if ( $opt->{'cust_pkg'} ) {
1893 # The target package already exists; update it to show that it was
1894 # changed from this package.
1895 $cust_pkg = $opt->{'cust_pkg'};
1897 foreach ( qw( pkgnum pkgpart locationnum ) ) {
1898 $cust_pkg->set("change_$_", $self->get($_));
1900 $cust_pkg->set('change_date', $time);
1901 $error = $cust_pkg->replace;
1904 # Create the new package.
1905 $cust_pkg = new FS::cust_pkg {
1906 custnum => $custnum,
1907 locationnum => $opt->{'locationnum'},
1908 ( map { $_ => ( $opt->{$_} || $self->$_() ) }
1909 qw( pkgpart quantity refnum salesnum )
1913 $error = $cust_pkg->insert( 'change' => 1,
1914 'allow_pkgpart' => $same_pkgpart );
1917 $dbh->rollback if $oldAutoCommit;
1921 # Transfer services and cancel old package.
1923 $error = $self->transfer($cust_pkg);
1924 if ($error and $error == 0) {
1925 # $old_pkg->transfer failed.
1926 $dbh->rollback if $oldAutoCommit;
1930 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
1931 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
1932 $error = $self->transfer($cust_pkg, 'change_svcpart'=>1 );
1933 if ($error and $error == 0) {
1934 # $old_pkg->transfer failed.
1935 $dbh->rollback if $oldAutoCommit;
1940 # We set unprotect_svcs when executing a "future package change". It's
1941 # not a user-interactive operation, so returning an error means the
1942 # package change will just fail. Rather than have that happen, we'll
1943 # let leftover services be deleted.
1944 if ($error > 0 and !$opt->{'unprotect_svcs'}) {
1945 # Transfers were successful, but we still had services left on the old
1946 # package. We can't change the package under this circumstances, so abort.
1947 $dbh->rollback if $oldAutoCommit;
1948 return "Unable to transfer all services from package ". $self->pkgnum;
1951 #reset usage if changing pkgpart
1952 # AND usage rollover is off (otherwise adds twice, now and at package bill)
1953 if ($self->pkgpart != $cust_pkg->pkgpart) {
1954 my $part_pkg = $cust_pkg->part_pkg;
1955 $error = $part_pkg->reset_usage($cust_pkg, $part_pkg->is_prepaid
1959 if $part_pkg->can('reset_usage') && ! $part_pkg->option('usage_rollover',1);
1962 $dbh->rollback if $oldAutoCommit;
1963 return "Error setting usage values: $error";
1966 # if NOT changing pkgpart, transfer any usage pools over
1967 foreach my $usage ($self->cust_pkg_usage) {
1968 $usage->set('pkgnum', $cust_pkg->pkgnum);
1969 $error = $usage->replace;
1971 $dbh->rollback if $oldAutoCommit;
1972 return "Error transferring usage pools: $error";
1977 # transfer usage pricing add-ons, if we're not changing pkgpart
1978 if ( $same_pkgpart ) {
1979 foreach my $old_cust_pkg_usageprice ($self->cust_pkg_usageprice) {
1980 my $new_cust_pkg_usageprice = new FS::cust_pkg_usageprice {
1981 'pkgnum' => $cust_pkg->pkgnum,
1982 'usagepricepart' => $old_cust_pkg_usageprice->usagepricepart,
1983 'quantity' => $old_cust_pkg_usageprice->quantity,
1985 $error = $new_cust_pkg_usageprice->insert;
1987 $dbh->rollback if $oldAutoCommit;
1988 return "Error transferring usage pricing add-on: $error";
1993 # transfer discounts, if we're not changing pkgpart
1994 if ( $same_pkgpart ) {
1995 foreach my $old_discount ($self->cust_pkg_discount_active) {
1996 # don't remove the old discount, we may still need to bill that package.
1997 my $new_discount = new FS::cust_pkg_discount {
1998 'pkgnum' => $cust_pkg->pkgnum,
1999 'discountnum' => $old_discount->discountnum,
2000 'months_used' => $old_discount->months_used,
2002 $error = $new_discount->insert;
2004 $dbh->rollback if $oldAutoCommit;
2005 return "Error transferring discounts: $error";
2010 # transfer (copy) invoice details
2011 foreach my $detail ($self->cust_pkg_detail) {
2012 my $new_detail = FS::cust_pkg_detail->new({ $detail->hash });
2013 $new_detail->set('pkgdetailnum', '');
2014 $new_detail->set('pkgnum', $cust_pkg->pkgnum);
2015 $error = $new_detail->insert;
2017 $dbh->rollback if $oldAutoCommit;
2018 return "Error transferring package notes: $error";
2024 if ( !$opt->{'cust_pkg'} ) {
2025 # Order any supplemental packages.
2026 my $part_pkg = $cust_pkg->part_pkg;
2027 my @old_supp_pkgs = $self->supplemental_pkgs;
2028 foreach my $link ($part_pkg->supp_part_pkg_link) {
2030 foreach (@old_supp_pkgs) {
2031 if ($_->pkgpart == $link->dst_pkgpart) {
2033 $_->pkgpart(0); # so that it can't match more than once
2037 # false laziness with FS::cust_main::Packages::order_pkg
2038 my $new = FS::cust_pkg->new({
2039 pkgpart => $link->dst_pkgpart,
2040 pkglinknum => $link->pkglinknum,
2041 custnum => $custnum,
2042 main_pkgnum => $cust_pkg->pkgnum,
2043 locationnum => $cust_pkg->locationnum,
2044 start_date => $cust_pkg->start_date,
2045 order_date => $cust_pkg->order_date,
2046 expire => $cust_pkg->expire,
2047 adjourn => $cust_pkg->adjourn,
2048 contract_end => $cust_pkg->contract_end,
2049 refnum => $cust_pkg->refnum,
2050 discountnum => $cust_pkg->discountnum,
2051 waive_setup => $cust_pkg->waive_setup,
2053 if ( $old and $opt->{'keep_dates'} ) {
2054 foreach (qw(setup bill last_bill)) {
2055 $new->set($_, $old->get($_));
2058 $error = $new->insert( allow_pkgpart => $same_pkgpart );
2061 $error ||= $old->transfer($new);
2063 if ( $error and $error > 0 ) {
2064 # no reason why this should ever fail, but still...
2065 $error = "Unable to transfer all services from supplemental package ".
2069 $dbh->rollback if $oldAutoCommit;
2072 push @new_supp_pkgs, $new;
2074 } # if !$opt->{'cust_pkg'}
2075 # because if there is one, then supplemental packages would already
2076 # have been created for it.
2078 #Good to go, cancel old package. Notify 'cancel' of whether to credit
2080 #Don't allow billing the package (preceding period packages and/or
2081 #outstanding usage) if we are keeping dates (i.e. location changing),
2082 #because the new package will be billed for the same date range.
2083 #Supplemental packages are also canceled here.
2085 # during scheduled changes, avoid canceling the package we just
2087 $self->set('change_to_pkgnum' => '');
2089 $error = $self->cancel(
2091 unused_credit => $unused_credit,
2092 nobill => $keep_dates,
2093 change_custnum => ( $self->custnum != $custnum ? $custnum : '' ),
2096 $dbh->rollback if $oldAutoCommit;
2100 if ( $conf->exists('cust_pkg-change_pkgpart-bill_now') ) {
2102 my $error = $cust_pkg->cust_main->bill(
2103 'pkg_list' => [ $cust_pkg, @new_supp_pkgs ]
2106 $dbh->rollback if $oldAutoCommit;
2111 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2117 =item change_later OPTION => VALUE...
2119 Schedule a package change for a later date. This actually orders the new
2120 package immediately, but sets its start date for a future date, and sets
2121 the current package to expire on the same date.
2123 If the package is already scheduled for a change, this can be called with
2124 'start_date' to change the scheduled date, or with pkgpart and/or
2125 locationnum to modify the package change. To cancel the scheduled change
2126 entirely, see C<abort_change>.
2134 The date for the package change. Required, and must be in the future.
2142 The pkgpart. locationnum, and quantity of the new package, with the same
2143 meaning as in C<change>.
2151 my $opt = ref($_[0]) ? shift : { @_ };
2153 my $oldAutoCommit = $FS::UID::AutoCommit;
2154 local $FS::UID::AutoCommit = 0;
2157 my $cust_main = $self->cust_main;
2159 my $date = delete $opt->{'start_date'} or return 'start_date required';
2161 if ( $date <= time ) {
2162 $dbh->rollback if $oldAutoCommit;
2163 return "start_date $date is in the past";
2168 if ( $self->change_to_pkgnum ) {
2169 my $change_to = FS::cust_pkg->by_key($self->change_to_pkgnum);
2170 my $new_pkgpart = $opt->{'pkgpart'}
2171 if $opt->{'pkgpart'} and $opt->{'pkgpart'} != $change_to->pkgpart;
2172 my $new_locationnum = $opt->{'locationnum'}
2173 if $opt->{'locationnum'} and $opt->{'locationnum'} != $change_to->locationnum;
2174 my $new_quantity = $opt->{'quantity'}
2175 if $opt->{'quantity'} and $opt->{'quantity'} != $change_to->quantity;
2176 if ( $new_pkgpart or $new_locationnum or $new_quantity ) {
2177 # it hasn't been billed yet, so in principle we could just edit
2178 # it in place (w/o a package change), but that's bad form.
2179 # So change the package according to the new options...
2180 my $err_or_pkg = $change_to->change(%$opt);
2181 if ( ref $err_or_pkg ) {
2182 # Then set that package up for a future start.
2183 $self->set('change_to_pkgnum', $err_or_pkg->pkgnum);
2184 $self->set('expire', $date); # in case it's different
2185 $err_or_pkg->set('start_date', $date);
2186 $err_or_pkg->set('change_date', '');
2187 $err_or_pkg->set('change_pkgnum', '');
2189 $error = $self->replace ||
2190 $err_or_pkg->replace ||
2191 $change_to->cancel ||
2194 $error = $err_or_pkg;
2196 } else { # change the start date only.
2197 $self->set('expire', $date);
2198 $change_to->set('start_date', $date);
2199 $error = $self->replace || $change_to->replace;
2202 $dbh->rollback if $oldAutoCommit;
2205 $dbh->commit if $oldAutoCommit;
2208 } # if $self->change_to_pkgnum
2210 my $new_pkgpart = $opt->{'pkgpart'}
2211 if $opt->{'pkgpart'} and $opt->{'pkgpart'} != $self->pkgpart;
2212 my $new_locationnum = $opt->{'locationnum'}
2213 if $opt->{'locationnum'} and $opt->{'locationnum'} != $self->locationnum;
2214 my $new_quantity = $opt->{'quantity'}
2215 if $opt->{'quantity'} and $opt->{'quantity'} != $self->quantity;
2217 return '' unless $new_pkgpart or $new_locationnum or $new_quantity; # wouldn't do anything
2219 # allow $opt->{'locationnum'} = '' to specifically set it to null
2220 # (i.e. customer default location)
2221 $opt->{'locationnum'} = $self->locationnum if !exists($opt->{'locationnum'});
2223 my $new = FS::cust_pkg->new( {
2224 custnum => $self->custnum,
2225 locationnum => $opt->{'locationnum'},
2226 start_date => $date,
2227 map { $_ => ( $opt->{$_} || $self->$_() ) }
2228 qw( pkgpart quantity refnum salesnum )
2230 $error = $new->insert('change' => 1,
2231 'allow_pkgpart' => ($new_pkgpart ? 0 : 1));
2233 $self->set('change_to_pkgnum', $new->pkgnum);
2234 $self->set('expire', $date);
2235 $error = $self->replace;
2238 $dbh->rollback if $oldAutoCommit;
2240 $dbh->commit if $oldAutoCommit;
2248 Cancels a future package change scheduled by C<change_later>.
2254 my $pkgnum = $self->change_to_pkgnum;
2255 my $change_to = FS::cust_pkg->by_key($pkgnum) if $pkgnum;
2258 $error = $change_to->cancel || $change_to->delete;
2259 return $error if $error;
2261 $self->set('change_to_pkgnum', '');
2262 $self->set('expire', '');
2266 =item set_quantity QUANTITY
2268 Change the package's quantity field. This is one of the few package properties
2269 that can safely be changed without canceling and reordering the package
2270 (because it doesn't affect tax eligibility). Returns an error or an
2277 $self = $self->replace_old; # just to make sure
2278 $self->quantity(shift);
2282 =item set_salesnum SALESNUM
2284 Change the package's salesnum (sales person) field. This is one of the few
2285 package properties that can safely be changed without canceling and reordering
2286 the package (because it doesn't affect tax eligibility). Returns an error or
2293 $self = $self->replace_old; # just to make sure
2294 $self->salesnum(shift);
2296 # XXX this should probably reassign any credit that's already been given
2299 =item modify_charge OPTIONS
2301 Change the properties of a one-time charge. Currently the only properties
2302 that can be changed this way are those that have no impact on billing
2304 - pkg: the package description
2305 - classnum: the package class
2306 - additional: arrayref of additional invoice details to add to this package
2308 If you pass 'adjust_commission' => 1, and the classnum changes, and there are
2309 commission credits linked to this charge, they will be recalculated.
2316 my $part_pkg = $self->part_pkg;
2317 my $pkgnum = $self->pkgnum;
2320 my $oldAutoCommit = $FS::UID::AutoCommit;
2321 local $FS::UID::AutoCommit = 0;
2323 return "Can't use modify_charge except on one-time charges"
2324 unless $part_pkg->freq eq '0';
2326 if ( length($opt{'pkg'}) and $part_pkg->pkg ne $opt{'pkg'} ) {
2327 $part_pkg->set('pkg', $opt{'pkg'});
2330 my %pkg_opt = $part_pkg->options;
2331 if ( ref($opt{'additional'}) ) {
2332 delete $pkg_opt{$_} foreach grep /^additional/, keys %pkg_opt;
2334 for ( $i = 0; exists($opt{'additional'}->[$i]); $i++ ) {
2335 $pkg_opt{ "additional_info$i" } = $opt{'additional'}->[$i];
2337 $pkg_opt{'additional_count'} = $i if $i > 0;
2341 if ( exists($opt{'classnum'}) and $part_pkg->classnum ne $opt{'classnum'} ) {
2343 $old_classnum = $part_pkg->classnum;
2344 $part_pkg->set('classnum', $opt{'classnum'});
2347 my $error = $part_pkg->replace( options => \%pkg_opt );
2348 return $error if $error;
2350 if (defined $old_classnum) {
2351 # fix invoice grouping records
2352 my $old_catname = $old_classnum
2353 ? FS::pkg_class->by_key($old_classnum)->categoryname
2355 my $new_catname = $opt{'classnum'}
2356 ? $part_pkg->pkg_class->categoryname
2358 if ( $old_catname ne $new_catname ) {
2359 foreach my $cust_bill_pkg ($self->cust_bill_pkg) {
2360 # (there should only be one...)
2361 my @display = qsearch( 'cust_bill_pkg_display', {
2362 'billpkgnum' => $cust_bill_pkg->billpkgnum,
2363 'section' => $old_catname,
2365 foreach (@display) {
2366 $_->set('section', $new_catname);
2367 $error = $_->replace;
2369 $dbh->rollback if $oldAutoCommit;
2373 } # foreach $cust_bill_pkg
2376 if ( $opt{'adjust_commission'} ) {
2377 # fix commission credits...tricky.
2378 foreach my $cust_event ($self->cust_event) {
2379 my $part_event = $cust_event->part_event;
2380 foreach my $table (qw(sales agent)) {
2382 "FS::part_event::Action::Mixin::credit_${table}_pkg_class";
2383 my $credit = qsearchs('cust_credit', {
2384 'eventnum' => $cust_event->eventnum,
2386 if ( $part_event->isa($class) ) {
2387 # Yes, this results in current commission rates being applied
2388 # retroactively to a one-time charge. For accounting purposes
2389 # there ought to be some kind of time limit on doing this.
2390 my $amount = $part_event->_calc_credit($self);
2391 if ( $credit and $credit->amount ne $amount ) {
2392 # Void the old credit.
2393 $error = $credit->void('Package class changed');
2395 $dbh->rollback if $oldAutoCommit;
2396 return "$error (adjusting commission credit)";
2399 # redo the event action to recreate the credit.
2401 eval { $part_event->do_action( $self, $cust_event ) };
2403 $dbh->rollback if $oldAutoCommit;
2406 } # if $part_event->isa($class)
2408 } # foreach $cust_event
2409 } # if $opt{'adjust_commission'}
2410 } # if defined $old_classnum
2412 $dbh->commit if $oldAutoCommit;
2418 use Storable 'thaw';
2421 sub process_bulk_cust_pkg {
2423 my $param = thaw(decode_base64(shift));
2424 warn Dumper($param) if $DEBUG;
2426 my $old_part_pkg = qsearchs('part_pkg',
2427 { pkgpart => $param->{'old_pkgpart'} });
2428 my $new_part_pkg = qsearchs('part_pkg',
2429 { pkgpart => $param->{'new_pkgpart'} });
2430 die "Must select a new package type\n" unless $new_part_pkg;
2431 #my $keep_dates = $param->{'keep_dates'} || 0;
2432 my $keep_dates = 1; # there is no good reason to turn this off
2434 local $SIG{HUP} = 'IGNORE';
2435 local $SIG{INT} = 'IGNORE';
2436 local $SIG{QUIT} = 'IGNORE';
2437 local $SIG{TERM} = 'IGNORE';
2438 local $SIG{TSTP} = 'IGNORE';
2439 local $SIG{PIPE} = 'IGNORE';
2441 my $oldAutoCommit = $FS::UID::AutoCommit;
2442 local $FS::UID::AutoCommit = 0;
2445 my @cust_pkgs = qsearch('cust_pkg', { 'pkgpart' => $param->{'old_pkgpart'} } );
2448 foreach my $old_cust_pkg ( @cust_pkgs ) {
2450 $job->update_statustext(int(100*$i/(scalar @cust_pkgs)));
2451 if ( $old_cust_pkg->getfield('cancel') ) {
2452 warn '[process_bulk_cust_pkg ] skipping canceled pkgnum '.
2453 $old_cust_pkg->pkgnum."\n"
2457 warn '[process_bulk_cust_pkg] changing pkgnum '.$old_cust_pkg->pkgnum."\n"
2459 my $error = $old_cust_pkg->change(
2460 'pkgpart' => $param->{'new_pkgpart'},
2461 'keep_dates' => $keep_dates
2463 if ( !ref($error) ) { # change returns the cust_pkg on success
2465 die "Error changing pkgnum ".$old_cust_pkg->pkgnum.": '$error'\n";
2468 $dbh->commit if $oldAutoCommit;
2474 Returns the last bill date, or if there is no last bill date, the setup date.
2475 Useful for billing metered services.
2481 return $self->setfield('last_bill', $_[0]) if @_;
2482 return $self->getfield('last_bill') if $self->getfield('last_bill');
2483 my $cust_bill_pkg = qsearchs('cust_bill_pkg', { 'pkgnum' => $self->pkgnum,
2484 'edate' => $self->bill, } );
2485 $cust_bill_pkg ? $cust_bill_pkg->sdate : $self->setup || 0;
2488 =item last_cust_pkg_reason ACTION
2490 Returns the most recent ACTION FS::cust_pkg_reason associated with the package.
2491 Returns false if there is no reason or the package is not currenly ACTION'd
2492 ACTION is one of adjourn, susp, cancel, or expire.
2496 sub last_cust_pkg_reason {
2497 my ( $self, $action ) = ( shift, shift );
2498 my $date = $self->get($action);
2500 'table' => 'cust_pkg_reason',
2501 'hashref' => { 'pkgnum' => $self->pkgnum,
2502 'action' => substr(uc($action), 0, 1),
2505 'order_by' => 'ORDER BY num DESC LIMIT 1',
2509 =item last_reason ACTION
2511 Returns the most recent ACTION FS::reason associated with the package.
2512 Returns false if there is no reason or the package is not currenly ACTION'd
2513 ACTION is one of adjourn, susp, cancel, or expire.
2518 my $cust_pkg_reason = shift->last_cust_pkg_reason(@_);
2519 $cust_pkg_reason->reason
2520 if $cust_pkg_reason;
2525 Returns the definition for this billing item, as an FS::part_pkg object (see
2532 return $self->{'_pkgpart'} if $self->{'_pkgpart'};
2533 cluck "cust_pkg->part_pkg called" if $DEBUG > 1;
2534 qsearchs( 'part_pkg', { 'pkgpart' => $self->pkgpart } );
2539 Returns the cancelled package this package was changed from, if any.
2545 return '' unless $self->change_pkgnum;
2546 qsearchs('cust_pkg', { 'pkgnum' => $self->change_pkgnum } );
2549 =item change_cust_main
2551 Returns the customter this package was detached to, if any.
2555 sub change_cust_main {
2557 return '' unless $self->change_custnum;
2558 qsearchs('cust_main', { 'custnum' => $self->change_custnum } );
2563 Calls the I<calc_setup> of the FS::part_pkg object associated with this billing
2570 $self->part_pkg->calc_setup($self, @_);
2575 Calls the I<calc_recur> of the FS::part_pkg object associated with this billing
2582 $self->part_pkg->calc_recur($self, @_);
2587 Calls the I<base_setup> of the FS::part_pkg object associated with this billing
2594 $self->part_pkg->base_setup($self, @_);
2599 Calls the I<base_recur> of the FS::part_pkg object associated with this billing
2606 $self->part_pkg->base_recur($self, @_);
2611 Calls the I<calc_remain> of the FS::part_pkg object associated with this
2618 $self->part_pkg->calc_remain($self, @_);
2623 Calls the I<calc_cancel> of the FS::part_pkg object associated with this
2630 $self->part_pkg->calc_cancel($self, @_);
2635 Returns any invoice line items for this package (see L<FS::cust_bill_pkg>).
2641 qsearch( 'cust_bill_pkg', { 'pkgnum' => $self->pkgnum } );
2644 =item cust_pkg_detail [ DETAILTYPE ]
2646 Returns any customer package details for this package (see
2647 L<FS::cust_pkg_detail>).
2649 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
2653 sub cust_pkg_detail {
2655 my %hash = ( 'pkgnum' => $self->pkgnum );
2656 $hash{detailtype} = shift if @_;
2658 'table' => 'cust_pkg_detail',
2659 'hashref' => \%hash,
2660 'order_by' => 'ORDER BY weight, pkgdetailnum',
2664 =item set_cust_pkg_detail DETAILTYPE [ DETAIL, DETAIL, ... ]
2666 Sets customer package details for this package (see L<FS::cust_pkg_detail>).
2668 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
2670 If there is an error, returns the error, otherwise returns false.
2674 sub set_cust_pkg_detail {
2675 my( $self, $detailtype, @details ) = @_;
2677 local $SIG{HUP} = 'IGNORE';
2678 local $SIG{INT} = 'IGNORE';
2679 local $SIG{QUIT} = 'IGNORE';
2680 local $SIG{TERM} = 'IGNORE';
2681 local $SIG{TSTP} = 'IGNORE';
2682 local $SIG{PIPE} = 'IGNORE';
2684 my $oldAutoCommit = $FS::UID::AutoCommit;
2685 local $FS::UID::AutoCommit = 0;
2688 foreach my $current ( $self->cust_pkg_detail($detailtype) ) {
2689 my $error = $current->delete;
2691 $dbh->rollback if $oldAutoCommit;
2692 return "error removing old detail: $error";
2696 foreach my $detail ( @details ) {
2697 my $cust_pkg_detail = new FS::cust_pkg_detail {
2698 'pkgnum' => $self->pkgnum,
2699 'detailtype' => $detailtype,
2700 'detail' => $detail,
2702 my $error = $cust_pkg_detail->insert;
2704 $dbh->rollback if $oldAutoCommit;
2705 return "error adding new detail: $error";
2710 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2717 Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.
2721 #false laziness w/cust_bill.pm
2725 'table' => 'cust_event',
2726 'addl_from' => 'JOIN part_event USING ( eventpart )',
2727 'hashref' => { 'tablenum' => $self->pkgnum },
2728 'extra_sql' => " AND eventtable = 'cust_pkg' ",
2732 =item num_cust_event
2734 Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.
2738 #false laziness w/cust_bill.pm
2739 sub num_cust_event {
2742 "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
2743 " WHERE tablenum = ? AND eventtable = 'cust_pkg'";
2744 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
2745 $sth->execute($self->pkgnum) or die $sth->errstr. " executing $sql";
2746 $sth->fetchrow_arrayref->[0];
2749 =item part_pkg_currency_option OPTIONNAME
2751 Returns a two item list consisting of the currency of this customer, if any,
2752 and a value for the provided option. If the customer has a currency, the value
2753 is the option value the given name and the currency (see
2754 L<FS::part_pkg_currency>). Otherwise, if the customer has no currency, is the
2755 regular option value for the given name (see L<FS::part_pkg_option>).
2759 sub part_pkg_currency_option {
2760 my( $self, $optionname ) = @_;
2761 my $part_pkg = $self->part_pkg;
2762 if ( my $currency = $self->cust_main->currency ) {
2763 ($currency, $part_pkg->part_pkg_currency_option($currency, $optionname) );
2765 ('', $part_pkg->option($optionname) );
2769 =item cust_svc [ SVCPART ] (old, deprecated usage)
2771 =item cust_svc [ OPTION => VALUE ... ] (current usage)
2773 =item cust_svc_unsorted [ OPTION => VALUE ... ]
2775 Returns the services for this package, as FS::cust_svc objects (see
2776 L<FS::cust_svc>). Available options are svcpart and svcdb. If either is
2777 spcififed, returns only the matching services.
2779 As an optimization, use the cust_svc_unsorted version if you are not displaying
2786 cluck "cust_pkg->cust_svc called" if $DEBUG > 2;
2787 $self->_sort_cust_svc( $self->cust_svc_unsorted_arrayref(@_) );
2790 sub cust_svc_unsorted {
2792 @{ $self->cust_svc_unsorted_arrayref(@_) };
2795 sub cust_svc_unsorted_arrayref {
2798 return () unless $self->num_cust_svc(@_);
2801 if ( @_ && $_[0] =~ /^\d+/ ) {
2802 $opt{svcpart} = shift;
2803 } elsif ( @_ && ref($_[0]) eq 'HASH' ) {
2810 'table' => 'cust_svc',
2811 'hashref' => { 'pkgnum' => $self->pkgnum },
2813 if ( $opt{svcpart} ) {
2814 $search{hashref}->{svcpart} = $opt{'svcpart'};
2816 if ( $opt{'svcdb'} ) {
2817 $search{addl_from} = ' LEFT JOIN part_svc USING ( svcpart ) ';
2818 $search{extra_sql} = ' AND svcdb = '. dbh->quote( $opt{'svcdb'} );
2821 [ qsearch(\%search) ];
2825 =item overlimit [ SVCPART ]
2827 Returns the services for this package which have exceeded their
2828 usage limit as FS::cust_svc objects (see L<FS::cust_svc>). If a svcpart
2829 is specified, return only the matching services.
2835 return () unless $self->num_cust_svc(@_);
2836 grep { $_->overlimit } $self->cust_svc(@_);
2839 =item h_cust_svc END_TIMESTAMP [ START_TIMESTAMP ] [ MODE ]
2841 Returns historical services for this package created before END TIMESTAMP and
2842 (optionally) not cancelled before START_TIMESTAMP, as FS::h_cust_svc objects
2843 (see L<FS::h_cust_svc>). If MODE is 'I' (for 'invoice'), services with the
2844 I<pkg_svc.hidden> flag will be omitted.
2850 warn "$me _h_cust_svc called on $self\n"
2853 my ($end, $start, $mode) = @_;
2854 my @cust_svc = $self->_sort_cust_svc(
2855 [ qsearch( 'h_cust_svc',
2856 { 'pkgnum' => $self->pkgnum, },
2857 FS::h_cust_svc->sql_h_search(@_),
2860 if ( defined($mode) && $mode eq 'I' ) {
2861 my %hidden_svcpart = map { $_->svcpart => $_->hidden } $self->part_svc;
2862 return grep { !$hidden_svcpart{$_->svcpart} } @cust_svc;
2868 sub _sort_cust_svc {
2869 my( $self, $arrayref ) = @_;
2872 sub ($$) { my ($a, $b) = @_; $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] };
2874 my %pkg_svc = map { $_->svcpart => $_ }
2875 qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
2880 my $pkg_svc = $pkg_svc{ $_->svcpart } || '';
2882 $pkg_svc ? $pkg_svc->primary_svc : '',
2883 $pkg_svc ? $pkg_svc->quantity : 0,
2890 =item num_cust_svc [ SVCPART ] (old, deprecated usage)
2892 =item num_cust_svc [ OPTION => VALUE ... ] (current usage)
2894 Returns the number of services for this package. Available options are svcpart
2895 and svcdb. If either is spcififed, returns only the matching services.
2902 return $self->{'_num_cust_svc'}
2904 && exists($self->{'_num_cust_svc'})
2905 && $self->{'_num_cust_svc'} =~ /\d/;
2907 cluck "cust_pkg->num_cust_svc called, _num_cust_svc:".$self->{'_num_cust_svc'}
2911 if ( @_ && $_[0] =~ /^\d+/ ) {
2912 $opt{svcpart} = shift;
2913 } elsif ( @_ && ref($_[0]) eq 'HASH' ) {
2919 my $select = 'SELECT COUNT(*) FROM cust_svc ';
2920 my $where = ' WHERE pkgnum = ? ';
2921 my @param = ($self->pkgnum);
2923 if ( $opt{'svcpart'} ) {
2924 $where .= ' AND svcpart = ? ';
2925 push @param, $opt{'svcpart'};
2927 if ( $opt{'svcdb'} ) {
2928 $select .= ' LEFT JOIN part_svc USING ( svcpart ) ';
2929 $where .= ' AND svcdb = ? ';
2930 push @param, $opt{'svcdb'};
2933 my $sth = dbh->prepare("$select $where") or die dbh->errstr;
2934 $sth->execute(@param) or die $sth->errstr;
2935 $sth->fetchrow_arrayref->[0];
2938 =item available_part_svc
2940 Returns a list of FS::part_svc objects representing services included in this
2941 package but not yet provisioned. Each FS::part_svc object also has an extra
2942 field, I<num_avail>, which specifies the number of available services.
2946 sub available_part_svc {
2949 my $pkg_quantity = $self->quantity || 1;
2951 grep { $_->num_avail > 0 }
2953 my $part_svc = $_->part_svc;
2954 $part_svc->{'Hash'}{'num_avail'} = #evil encapsulation-breaking
2955 $pkg_quantity * $_->quantity - $self->num_cust_svc($_->svcpart);
2957 # more evil encapsulation breakage
2958 if($part_svc->{'Hash'}{'num_avail'} > 0) {
2959 my @exports = $part_svc->part_export_did;
2960 $part_svc->{'Hash'}{'can_get_dids'} = scalar(@exports);
2965 $self->part_pkg->pkg_svc;
2968 =item part_svc [ OPTION => VALUE ... ]
2970 Returns a list of FS::part_svc objects representing provisioned and available
2971 services included in this package. Each FS::part_svc object also has the
2972 following extra fields:
2976 =item num_cust_svc (count)
2978 =item num_avail (quantity - count)
2980 =item cust_pkg_svc (services) - array reference containing the provisioned services, as cust_svc objects
2984 Accepts one option: summarize_size. If specified and non-zero, will omit the
2985 extra cust_pkg_svc option for objects where num_cust_svc is this size or
2991 #label -> ($cust_svc->label)[1]
2997 my $pkg_quantity = $self->quantity || 1;
2999 #XXX some sort of sort order besides numeric by svcpart...
3000 my @part_svc = sort { $a->svcpart <=> $b->svcpart } map {
3002 my $part_svc = $pkg_svc->part_svc;
3003 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
3004 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #more evil
3005 $part_svc->{'Hash'}{'num_avail'} =
3006 max( 0, $pkg_quantity * $pkg_svc->quantity - $num_cust_svc );
3007 $part_svc->{'Hash'}{'cust_pkg_svc'} =
3008 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : []
3009 unless exists($opt{summarize_size}) && $opt{summarize_size} > 0
3010 && $num_cust_svc >= $opt{summarize_size};
3011 $part_svc->{'Hash'}{'hidden'} = $pkg_svc->hidden;
3013 } $self->part_pkg->pkg_svc;
3016 push @part_svc, map {
3018 my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
3019 $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #speak no evail
3020 $part_svc->{'Hash'}{'num_avail'} = 0; #0-$num_cust_svc ?
3021 $part_svc->{'Hash'}{'cust_pkg_svc'} =
3022 $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : [];
3024 } $self->extra_part_svc;
3030 =item extra_part_svc
3032 Returns a list of FS::part_svc objects corresponding to services in this
3033 package which are still provisioned but not (any longer) available in the
3038 sub extra_part_svc {
3041 my $pkgnum = $self->pkgnum;
3042 #my $pkgpart = $self->pkgpart;
3045 # 'table' => 'part_svc',
3048 # "WHERE 0 = ( SELECT COUNT(*) FROM pkg_svc
3049 # WHERE pkg_svc.svcpart = part_svc.svcpart
3050 # AND pkg_svc.pkgpart = ?
3053 # AND 0 < ( SELECT COUNT(*) FROM cust_svc
3054 # LEFT JOIN cust_pkg USING ( pkgnum )
3055 # WHERE cust_svc.svcpart = part_svc.svcpart
3058 # 'extra_param' => [ [$self->pkgpart=>'int'], [$self->pkgnum=>'int'] ],
3061 #seems to benchmark slightly faster... (or did?)
3063 my @pkgparts = map $_->pkgpart, $self->part_pkg->self_and_svc_linked;
3064 my $pkgparts = join(',', @pkgparts);
3067 #'select' => 'DISTINCT ON (svcpart) part_svc.*',
3068 #MySQL doesn't grok DISINCT ON
3069 'select' => 'DISTINCT part_svc.*',
3070 'table' => 'part_svc',
3072 "LEFT JOIN pkg_svc ON ( pkg_svc.svcpart = part_svc.svcpart
3073 AND pkg_svc.pkgpart IN ($pkgparts)
3076 LEFT JOIN cust_svc ON ( cust_svc.svcpart = part_svc.svcpart )
3077 LEFT JOIN cust_pkg USING ( pkgnum )
3080 'extra_sql' => "WHERE pkgsvcnum IS NULL AND cust_pkg.pkgnum = ? ",
3081 'extra_param' => [ [$self->pkgnum=>'int'] ],
3087 Returns a short status string for this package, currently:
3091 =item not yet billed
3093 =item one-time charge
3108 my $freq = length($self->freq) ? $self->freq : $self->part_pkg->freq;
3110 return 'cancelled' if $self->get('cancel');
3111 return 'suspended' if $self->susp;
3112 return 'not yet billed' unless $self->setup;
3113 return 'one-time charge' if $freq =~ /^(0|$)/;
3117 =item ucfirst_status
3119 Returns the status with the first character capitalized.
3123 sub ucfirst_status {
3124 ucfirst(shift->status);
3129 Class method that returns the list of possible status strings for packages
3130 (see L<the status method|/status>). For example:
3132 @statuses = FS::cust_pkg->statuses();
3136 tie my %statuscolor, 'Tie::IxHash',
3137 'not yet billed' => '009999', #teal? cyan?
3138 'one-time charge' => '000000',
3139 'active' => '00CC00',
3140 'suspended' => 'FF9900',
3141 'cancelled' => 'FF0000',
3145 my $self = shift; #could be class...
3146 #grep { $_ !~ /^(not yet billed)$/ } #this is a dumb status anyway
3147 # # mayble split btw one-time vs. recur
3153 Returns a hex triplet color string for this package's status.
3159 $statuscolor{$self->status};
3164 Returns a label for this package. (Currently "pkgnum: pkg - comment" or
3165 "pkg - comment" depending on user preference).
3171 my $label = $self->part_pkg->pkg_comment( 'nopkgpart' => 1 );
3172 $label = $self->pkgnum. ": $label"
3173 if $FS::CurrentUser::CurrentUser->option('show_pkgnum');
3177 =item pkg_label_long
3179 Returns a long label for this package, adding the primary service's label to
3184 sub pkg_label_long {
3186 my $label = $self->pkg_label;
3187 my $cust_svc = $self->primary_cust_svc;
3188 $label .= ' ('. ($cust_svc->label)[1]. ')' if $cust_svc;
3194 Returns a customer-localized label for this package.
3200 $self->part_pkg->pkg_locale( $self->cust_main->locale );
3203 =item primary_cust_svc
3205 Returns a primary service (as FS::cust_svc object) if one can be identified.
3209 #for labeling purposes - might not 100% match up with part_pkg->svcpart's idea
3211 sub primary_cust_svc {
3214 my @cust_svc = $self->cust_svc;
3216 return '' unless @cust_svc; #no serivces - irrelevant then
3218 return $cust_svc[0] if scalar(@cust_svc) == 1; #always return a single service
3220 # primary service as specified in the package definition
3221 # or exactly one service definition with quantity one
3222 my $svcpart = $self->part_pkg->svcpart;
3223 @cust_svc = grep { $_->svcpart == $svcpart } @cust_svc;
3224 return $cust_svc[0] if scalar(@cust_svc) == 1;
3226 #couldn't identify one thing..
3232 Returns a list of lists, calling the label method for all services
3233 (see L<FS::cust_svc>) of this billing item.
3239 map { [ $_->label ] } $self->cust_svc;
3242 =item h_labels END_TIMESTAMP [ START_TIMESTAMP ] [ MODE ]
3244 Like the labels method, but returns historical information on services that
3245 were active as of END_TIMESTAMP and (optionally) not cancelled before
3246 START_TIMESTAMP. If MODE is 'I' (for 'invoice'), services with the
3247 I<pkg_svc.hidden> flag will be omitted.
3249 Returns a list of lists, calling the label method for all (historical) services
3250 (see L<FS::h_cust_svc>) of this billing item.
3256 warn "$me _h_labels called on $self\n"
3258 map { [ $_->label(@_) ] } $self->h_cust_svc(@_);
3263 Like labels, except returns a simple flat list, and shortens long
3264 (currently >5 or the cust_bill-max_same_services configuration value) lists of
3265 identical services to one line that lists the service label and the number of
3266 individual services rather than individual items.
3271 shift->_labels_short( 'labels', @_ );
3274 =item h_labels_short END_TIMESTAMP [ START_TIMESTAMP ]
3276 Like h_labels, except returns a simple flat list, and shortens long
3277 (currently >5 or the cust_bill-max_same_services configuration value) lists of
3278 identical services to one line that lists the service label and the number of
3279 individual services rather than individual items.
3283 sub h_labels_short {
3284 shift->_labels_short( 'h_labels', @_ );
3288 my( $self, $method ) = ( shift, shift );
3290 warn "$me _labels_short called on $self with $method method\n"
3293 my $conf = new FS::Conf;
3294 my $max_same_services = $conf->config('cust_bill-max_same_services') || 5;
3296 warn "$me _labels_short populating \%labels\n"
3300 #tie %labels, 'Tie::IxHash';
3301 push @{ $labels{$_->[0]} }, $_->[1]
3302 foreach $self->$method(@_);
3304 warn "$me _labels_short populating \@labels\n"
3308 foreach my $label ( keys %labels ) {
3310 my @values = grep { ! $seen{$_}++ } @{ $labels{$label} };
3311 my $num = scalar(@values);
3312 warn "$me _labels_short $num items for $label\n"
3315 if ( $num > $max_same_services ) {
3316 warn "$me _labels_short more than $max_same_services, so summarizing\n"
3318 push @labels, "$label ($num)";
3320 if ( $conf->exists('cust_bill-consolidate_services') ) {
3321 warn "$me _labels_short consolidating services\n"
3323 # push @labels, "$label: ". join(', ', @values);
3325 my $detail = "$label: ";
3326 $detail .= shift(@values). ', '
3328 && ( length($detail.$values[0]) < 78 || $detail eq "$label: " );
3330 push @labels, $detail;
3332 warn "$me _labels_short done consolidating services\n"
3335 warn "$me _labels_short adding service data\n"
3337 push @labels, map { "$label: $_" } @values;
3348 Returns the parent customer object (see L<FS::cust_main>).
3352 Returns the balance for this specific package, when using
3353 experimental package balance.
3359 $self->cust_main->balance_pkgnum( $self->pkgnum );
3362 #these subs are in location_Mixin.pm now... unfortunately the POD doesn't mixin
3366 Returns the location object, if any (see L<FS::cust_location>).
3368 =item cust_location_or_main
3370 If this package is associated with a location, returns the locaiton (see
3371 L<FS::cust_location>), otherwise returns the customer (see L<FS::cust_main>).
3373 =item location_label [ OPTION => VALUE ... ]
3375 Returns the label of the location object (see L<FS::cust_location>).
3379 #end of subs in location_Mixin.pm now... unfortunately the POD doesn't mixin
3381 =item tax_locationnum
3383 Returns the foreign key to a L<FS::cust_location> object for calculating
3384 tax on this package, as determined by the C<tax-pkg_address> and
3385 C<tax-ship_address> configuration flags.
3389 sub tax_locationnum {
3391 my $conf = FS::Conf->new;
3392 if ( $conf->exists('tax-pkg_address') ) {
3393 return $self->locationnum;
3395 elsif ( $conf->exists('tax-ship_address') ) {
3396 return $self->cust_main->ship_locationnum;
3399 return $self->cust_main->bill_locationnum;
3405 Returns the L<FS::cust_location> object for tax_locationnum.
3411 FS::cust_location->by_key( $self->tax_locationnum )
3414 =item seconds_since TIMESTAMP
3416 Returns the number of seconds all accounts (see L<FS::svc_acct>) in this
3417 package have been online since TIMESTAMP, according to the session monitor.
3419 TIMESTAMP is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
3420 L<Time::Local> and L<Date::Parse> for conversion functions.
3425 my($self, $since) = @_;
3428 foreach my $cust_svc (
3429 grep { $_->part_svc->svcdb eq 'svc_acct' } $self->cust_svc
3431 $seconds += $cust_svc->seconds_since($since);
3438 =item seconds_since_sqlradacct TIMESTAMP_START TIMESTAMP_END
3440 Returns the numbers of seconds all accounts (see L<FS::svc_acct>) in this
3441 package have been online between TIMESTAMP_START (inclusive) and TIMESTAMP_END
3444 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
3445 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
3451 sub seconds_since_sqlradacct {
3452 my($self, $start, $end) = @_;
3456 foreach my $cust_svc (
3458 my $part_svc = $_->part_svc;
3459 $part_svc->svcdb eq 'svc_acct'
3460 && scalar($part_svc->part_export_usage);
3463 $seconds += $cust_svc->seconds_since_sqlradacct($start, $end);
3470 =item attribute_since_sqlradacct TIMESTAMP_START TIMESTAMP_END ATTRIBUTE
3472 Returns the sum of the given attribute for all accounts (see L<FS::svc_acct>)
3473 in this package for sessions ending between TIMESTAMP_START (inclusive) and
3477 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
3478 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
3483 sub attribute_since_sqlradacct {
3484 my($self, $start, $end, $attrib) = @_;
3488 foreach my $cust_svc (
3490 my $part_svc = $_->part_svc;
3491 scalar($part_svc->part_export_usage);
3494 $sum += $cust_svc->attribute_since_sqlradacct($start, $end, $attrib);
3506 my( $self, $value ) = @_;
3507 if ( defined($value) ) {
3508 $self->setfield('quantity', $value);
3510 $self->getfield('quantity') || 1;
3513 =item transfer DEST_PKGNUM | DEST_CUST_PKG, [ OPTION => VALUE ... ]
3515 Transfers as many services as possible from this package to another package.
3517 The destination package can be specified by pkgnum by passing an FS::cust_pkg
3518 object. The destination package must already exist.
3520 Services are moved only if the destination allows services with the correct
3521 I<svcpart> (not svcdb), unless the B<change_svcpart> option is set true. Use
3522 this option with caution! No provision is made for export differences
3523 between the old and new service definitions. Probably only should be used
3524 when your exports for all service definitions of a given svcdb are identical.
3525 (attempt a transfer without it first, to move all possible svcpart-matching
3528 Any services that can't be moved remain in the original package.
3530 Returns an error, if there is one; otherwise, returns the number of services
3531 that couldn't be moved.
3536 my ($self, $dest_pkgnum, %opt) = @_;
3542 if (ref ($dest_pkgnum) eq 'FS::cust_pkg') {
3543 $dest = $dest_pkgnum;
3544 $dest_pkgnum = $dest->pkgnum;
3546 $dest = qsearchs('cust_pkg', { pkgnum => $dest_pkgnum });
3549 return ('Package does not exist: '.$dest_pkgnum) unless $dest;
3551 foreach my $pkg_svc ( $dest->part_pkg->pkg_svc ) {
3552 $target{$pkg_svc->svcpart} = $pkg_svc->quantity;
3555 foreach my $cust_svc ($dest->cust_svc) {
3556 $target{$cust_svc->svcpart}--;
3559 my %svcpart2svcparts = ();
3560 if ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
3561 warn "change_svcpart option received, creating alternates list\n" if $DEBUG;
3562 foreach my $svcpart ( map { $_->svcpart } $self->cust_svc ) {
3563 next if exists $svcpart2svcparts{$svcpart};
3564 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
3565 $svcpart2svcparts{$svcpart} = [
3567 sort { $b->[1] cmp $a->[1] or $a->[2] <=> $b->[2] }
3569 my $pkg_svc = qsearchs( 'pkg_svc', { 'pkgpart' => $dest->pkgpart,
3570 'svcpart' => $_ } );
3572 $pkg_svc ? $pkg_svc->primary_svc : '',
3573 $pkg_svc ? $pkg_svc->quantity : 0,
3577 grep { $_ != $svcpart }
3579 qsearch('part_svc', { 'svcdb' => $part_svc->svcdb } )
3581 warn "alternates for svcpart $svcpart: ".
3582 join(', ', @{$svcpart2svcparts{$svcpart}}). "\n"
3587 foreach my $cust_svc ($self->cust_svc) {
3588 if($target{$cust_svc->svcpart} > 0
3589 or $FS::cust_svc::ignore_quantity) { # maybe should be a 'force' option
3590 $target{$cust_svc->svcpart}--;
3591 my $new = new FS::cust_svc { $cust_svc->hash };
3592 $new->pkgnum($dest_pkgnum);
3593 my $error = $new->replace($cust_svc);
3594 return $error if $error;
3595 } elsif ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
3597 warn "looking for alternates for svcpart ". $cust_svc->svcpart. "\n";
3598 warn "alternates to consider: ".
3599 join(', ', @{$svcpart2svcparts{$cust_svc->svcpart}}). "\n";
3601 my @alternate = grep {
3602 warn "considering alternate svcpart $_: ".
3603 "$target{$_} available in new package\n"
3606 } @{$svcpart2svcparts{$cust_svc->svcpart}};
3608 warn "alternate(s) found\n" if $DEBUG;
3609 my $change_svcpart = $alternate[0];
3610 $target{$change_svcpart}--;
3611 my $new = new FS::cust_svc { $cust_svc->hash };
3612 $new->svcpart($change_svcpart);
3613 $new->pkgnum($dest_pkgnum);
3614 my $error = $new->replace($cust_svc);
3615 return $error if $error;
3626 =item grab_svcnums SVCNUM, SVCNUM ...
3628 Change the pkgnum for the provided services to this packages. If there is an
3629 error, returns the error, otherwise returns false.
3637 local $SIG{HUP} = 'IGNORE';
3638 local $SIG{INT} = 'IGNORE';
3639 local $SIG{QUIT} = 'IGNORE';
3640 local $SIG{TERM} = 'IGNORE';
3641 local $SIG{TSTP} = 'IGNORE';
3642 local $SIG{PIPE} = 'IGNORE';
3644 my $oldAutoCommit = $FS::UID::AutoCommit;
3645 local $FS::UID::AutoCommit = 0;
3648 foreach my $svcnum (@svcnum) {
3649 my $cust_svc = qsearchs('cust_svc', { svcnum=>$svcnum } ) or do {
3650 $dbh->rollback if $oldAutoCommit;
3651 return "unknown svcnum $svcnum";
3653 $cust_svc->pkgnum( $self->pkgnum );
3654 my $error = $cust_svc->replace;
3656 $dbh->rollback if $oldAutoCommit;
3661 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3668 This method is deprecated. See the I<depend_jobnum> option to the insert and
3669 order_pkgs methods in FS::cust_main for a better way to defer provisioning.
3673 #looks like this is still used by the order_pkg and change_pkg methods in
3674 # ClientAPI/MyAccount, need to look into those before removing
3678 local $SIG{HUP} = 'IGNORE';
3679 local $SIG{INT} = 'IGNORE';
3680 local $SIG{QUIT} = 'IGNORE';
3681 local $SIG{TERM} = 'IGNORE';
3682 local $SIG{TSTP} = 'IGNORE';
3683 local $SIG{PIPE} = 'IGNORE';
3685 my $oldAutoCommit = $FS::UID::AutoCommit;
3686 local $FS::UID::AutoCommit = 0;
3689 foreach my $cust_svc ( $self->cust_svc ) {
3690 #false laziness w/svc_Common::insert
3691 my $svc_x = $cust_svc->svc_x;
3692 foreach my $part_export ( $cust_svc->part_svc->part_export ) {
3693 my $error = $part_export->export_insert($svc_x);
3695 $dbh->rollback if $oldAutoCommit;
3701 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3706 =item export_pkg_change OLD_CUST_PKG
3708 Calls the "pkg_change" export action for all services attached to this package.
3712 sub export_pkg_change {
3713 my( $self, $old ) = ( shift, shift );
3715 local $SIG{HUP} = 'IGNORE';
3716 local $SIG{INT} = 'IGNORE';
3717 local $SIG{QUIT} = 'IGNORE';
3718 local $SIG{TERM} = 'IGNORE';
3719 local $SIG{TSTP} = 'IGNORE';
3720 local $SIG{PIPE} = 'IGNORE';
3722 my $oldAutoCommit = $FS::UID::AutoCommit;
3723 local $FS::UID::AutoCommit = 0;
3726 foreach my $svc_x ( map $_->svc_x, $self->cust_svc ) {
3727 my $error = $svc_x->export('pkg_change', $self, $old);
3729 $dbh->rollback if $oldAutoCommit;
3734 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3741 Associates this package with a (suspension or cancellation) reason (see
3742 L<FS::cust_pkg_reason>, possibly inserting a new reason on the fly (see
3745 Available options are:
3751 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.
3755 the access_user (see L<FS::access_user>) providing the reason
3763 the action (cancel, susp, adjourn, expire) associated with the reason
3767 If there is an error, returns the error, otherwise returns false.
3772 my ($self, %options) = @_;
3774 my $otaker = $options{reason_otaker} ||
3775 $FS::CurrentUser::CurrentUser->username;
3778 if ( $options{'reason'} =~ /^(\d+)$/ ) {
3782 } elsif ( ref($options{'reason'}) ) {
3784 return 'Enter a new reason (or select an existing one)'
3785 unless $options{'reason'}->{'reason'} !~ /^\s*$/;
3787 my $reason = new FS::reason({
3788 'reason_type' => $options{'reason'}->{'typenum'},
3789 'reason' => $options{'reason'}->{'reason'},
3791 my $error = $reason->insert;
3792 return $error if $error;
3794 $reasonnum = $reason->reasonnum;
3797 return "Unparsable reason: ". $options{'reason'};
3800 my $cust_pkg_reason =
3801 new FS::cust_pkg_reason({ 'pkgnum' => $self->pkgnum,
3802 'reasonnum' => $reasonnum,
3803 'otaker' => $otaker,
3804 'action' => substr(uc($options{'action'}),0,1),
3805 'date' => $options{'date'}
3810 $cust_pkg_reason->insert;
3813 =item insert_discount
3815 Associates this package with a discount (see L<FS::cust_pkg_discount>, possibly
3816 inserting a new discount on the fly (see L<FS::discount>).
3818 Available options are:
3826 If there is an error, returns the error, otherwise returns false.
3830 sub insert_discount {
3831 #my ($self, %options) = @_;
3834 my $cust_pkg_discount = new FS::cust_pkg_discount {
3835 'pkgnum' => $self->pkgnum,
3836 'discountnum' => $self->discountnum,
3838 'end_date' => '', #XXX
3839 #for the create a new discount case
3840 '_type' => $self->discountnum__type,
3841 'amount' => $self->discountnum_amount,
3842 'percent' => $self->discountnum_percent,
3843 'months' => $self->discountnum_months,
3844 'setup' => $self->discountnum_setup,
3845 #'disabled' => $self->discountnum_disabled,
3848 $cust_pkg_discount->insert;
3851 =item set_usage USAGE_VALUE_HASHREF
3853 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
3854 to which they should be set (see L<FS::svc_acct>). Currently seconds,
3855 upbytes, downbytes, and totalbytes are appropriate keys.
3857 All svc_accts which are part of this package have their values reset.
3862 my ($self, $valueref, %opt) = @_;
3864 #only svc_acct can set_usage for now
3865 foreach my $cust_svc ( $self->cust_svc( 'svcdb'=>'svc_acct' ) ) {
3866 my $svc_x = $cust_svc->svc_x;
3867 $svc_x->set_usage($valueref, %opt)
3868 if $svc_x->can("set_usage");
3872 =item recharge USAGE_VALUE_HASHREF
3874 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
3875 to which they should be set (see L<FS::svc_acct>). Currently seconds,
3876 upbytes, downbytes, and totalbytes are appropriate keys.
3878 All svc_accts which are part of this package have their values incremented.
3883 my ($self, $valueref) = @_;
3885 #only svc_acct can set_usage for now
3886 foreach my $cust_svc ( $self->cust_svc( 'svcdb'=>'svc_acct' ) ) {
3887 my $svc_x = $cust_svc->svc_x;
3888 $svc_x->recharge($valueref)
3889 if $svc_x->can("recharge");
3893 =item cust_pkg_discount
3895 =item cust_pkg_discount_active
3899 sub cust_pkg_discount_active {
3901 grep { $_->status eq 'active' } $self->cust_pkg_discount;
3904 =item cust_pkg_usage
3906 Returns a list of all voice usage counters attached to this package.
3908 =item apply_usage OPTIONS
3910 Takes the following options:
3911 - cdr: a call detail record (L<FS::cdr>)
3912 - rate_detail: the rate determined for this call (L<FS::rate_detail>)
3913 - minutes: the maximum number of minutes to be charged
3915 Finds available usage minutes for a call of this class, and subtracts
3916 up to that many minutes from the usage pool. If the usage pool is empty,
3917 and the C<cdr-minutes_priority> global config option is set, minutes may
3918 be taken from other calls as well. Either way, an allocation record will
3919 be created (L<FS::cdr_cust_pkg_usage>) and this method will return the
3920 number of minutes of usage applied to the call.
3925 my ($self, %opt) = @_;
3926 my $cdr = $opt{cdr};
3927 my $rate_detail = $opt{rate_detail};
3928 my $minutes = $opt{minutes};
3929 my $classnum = $rate_detail->classnum;
3930 my $pkgnum = $self->pkgnum;
3931 my $custnum = $self->custnum;
3933 local $SIG{HUP} = 'IGNORE';
3934 local $SIG{INT} = 'IGNORE';
3935 local $SIG{QUIT} = 'IGNORE';
3936 local $SIG{TERM} = 'IGNORE';
3937 local $SIG{TSTP} = 'IGNORE';
3938 local $SIG{PIPE} = 'IGNORE';
3940 my $oldAutoCommit = $FS::UID::AutoCommit;
3941 local $FS::UID::AutoCommit = 0;
3943 my $order = FS::Conf->new->config('cdr-minutes_priority');
3947 $is_classnum = ' part_pkg_usage_class.classnum = '.$classnum;
3949 $is_classnum = ' part_pkg_usage_class.classnum IS NULL';
3951 my @usage_recs = qsearch({
3952 'table' => 'cust_pkg_usage',
3953 'addl_from' => ' JOIN part_pkg_usage USING (pkgusagepart)'.
3954 ' JOIN cust_pkg USING (pkgnum)'.
3955 ' JOIN part_pkg_usage_class USING (pkgusagepart)',
3956 'select' => 'cust_pkg_usage.*',
3957 'extra_sql' => " WHERE ( cust_pkg.pkgnum = $pkgnum OR ".
3958 " ( cust_pkg.custnum = $custnum AND ".
3959 " part_pkg_usage.shared IS NOT NULL ) ) AND ".
3960 $is_classnum . ' AND '.
3961 " cust_pkg_usage.minutes > 0",
3962 'order_by' => " ORDER BY priority ASC",
3965 my $orig_minutes = $minutes;
3967 while (!$error and $minutes > 0 and @usage_recs) {
3968 my $cust_pkg_usage = shift @usage_recs;
3969 $cust_pkg_usage->select_for_update;
3970 my $cdr_cust_pkg_usage = FS::cdr_cust_pkg_usage->new({
3971 pkgusagenum => $cust_pkg_usage->pkgusagenum,
3972 acctid => $cdr->acctid,
3973 minutes => min($cust_pkg_usage->minutes, $minutes),
3975 $cust_pkg_usage->set('minutes',
3976 sprintf('%.0f', $cust_pkg_usage->minutes - $cdr_cust_pkg_usage->minutes)
3978 $error = $cust_pkg_usage->replace || $cdr_cust_pkg_usage->insert;
3979 $minutes -= $cdr_cust_pkg_usage->minutes;
3981 if ( $order and $minutes > 0 and !$error ) {
3982 # then try to steal minutes from another call
3984 'table' => 'cdr_cust_pkg_usage',
3985 'addl_from' => ' JOIN cust_pkg_usage USING (pkgusagenum)'.
3986 ' JOIN part_pkg_usage USING (pkgusagepart)'.
3987 ' JOIN cust_pkg USING (pkgnum)'.
3988 ' JOIN part_pkg_usage_class USING (pkgusagepart)'.
3989 ' JOIN cdr USING (acctid)',
3990 'select' => 'cdr_cust_pkg_usage.*',
3991 'extra_sql' => " WHERE cdr.freesidestatus = 'rated' AND ".
3992 " ( cust_pkg.pkgnum = $pkgnum OR ".
3993 " ( cust_pkg.custnum = $custnum AND ".
3994 " part_pkg_usage.shared IS NOT NULL ) ) AND ".
3995 " part_pkg_usage_class.classnum = $classnum",
3996 'order_by' => ' ORDER BY part_pkg_usage.priority ASC',
3998 if ( $order eq 'time' ) {
3999 # find CDRs that are using minutes, but have a later startdate
4001 my $startdate = $cdr->startdate;
4002 if ($startdate !~ /^\d+$/) {
4003 die "bad cdr startdate '$startdate'";
4005 $search{'extra_sql'} .= " AND cdr.startdate > $startdate";
4006 # minimize needless reshuffling
4007 $search{'order_by'} .= ', cdr.startdate DESC';
4009 # XXX may not work correctly with rate_time schedules. Could
4010 # fix this by storing ratedetailnum in cdr_cust_pkg_usage, I
4012 $search{'addl_from'} .=
4013 ' JOIN rate_detail'.
4014 ' ON (cdr.rated_ratedetailnum = rate_detail.ratedetailnum)';
4015 if ( $order eq 'rate_high' ) {
4016 $search{'extra_sql'} .= ' AND rate_detail.min_charge < '.
4017 $rate_detail->min_charge;
4018 $search{'order_by'} .= ', rate_detail.min_charge ASC';
4019 } elsif ( $order eq 'rate_low' ) {
4020 $search{'extra_sql'} .= ' AND rate_detail.min_charge > '.
4021 $rate_detail->min_charge;
4022 $search{'order_by'} .= ', rate_detail.min_charge DESC';
4024 # this should really never happen
4025 die "invalid cdr-minutes_priority value '$order'\n";
4028 my @cdr_usage_recs = qsearch(\%search);
4030 while (!$error and @cdr_usage_recs and $minutes > 0) {
4031 my $cdr_cust_pkg_usage = shift @cdr_usage_recs;
4032 my $cust_pkg_usage = $cdr_cust_pkg_usage->cust_pkg_usage;
4033 my $old_cdr = $cdr_cust_pkg_usage->cdr;
4034 $reproc_cdrs{$old_cdr->acctid} = $old_cdr;
4035 $cdr_cust_pkg_usage->select_for_update;
4036 $old_cdr->select_for_update;
4037 $cust_pkg_usage->select_for_update;
4038 # in case someone else stole the usage from this CDR
4039 # while waiting for the lock...
4040 next if $old_cdr->acctid != $cdr_cust_pkg_usage->acctid;
4041 # steal the usage allocation and flag the old CDR for reprocessing
4042 $cdr_cust_pkg_usage->set('acctid', $cdr->acctid);
4043 # if the allocation is more minutes than we need, adjust it...
4044 my $delta = $cdr_cust_pkg_usage->minutes - $minutes;
4046 $cdr_cust_pkg_usage->set('minutes', $minutes);
4047 $cust_pkg_usage->set('minutes', $cust_pkg_usage->minutes + $delta);
4048 $error = $cust_pkg_usage->replace;
4050 #warn 'CDR '.$cdr->acctid . ' stealing allocation '.$cdr_cust_pkg_usage->cdrusagenum.' from CDR '.$old_cdr->acctid."\n";
4051 $error ||= $cdr_cust_pkg_usage->replace;
4052 # deduct the stolen minutes
4053 $minutes -= $cdr_cust_pkg_usage->minutes;
4055 # after all minute-stealing is done, reset the affected CDRs
4056 foreach (values %reproc_cdrs) {
4057 $error ||= $_->set_status('');
4058 # XXX or should we just call $cdr->rate right here?
4059 # it's not like we can create a loop this way, since the min_charge
4060 # or call time has to go monotonically in one direction.
4061 # we COULD get some very deep recursions going, though...
4063 } # if $order and $minutes
4066 die "error applying included minutes\npkgnum ".$self->pkgnum.", class $classnum, acctid ".$cdr->acctid."\n$error\n"
4068 $dbh->commit if $oldAutoCommit;
4069 return $orig_minutes - $minutes;
4073 =item supplemental_pkgs
4075 Returns a list of all packages supplemental to this one.
4079 sub supplemental_pkgs {
4081 qsearch('cust_pkg', { 'main_pkgnum' => $self->pkgnum });
4086 Returns the package that this one is supplemental to, if any.
4092 if ( $self->main_pkgnum ) {
4093 return FS::cust_pkg->by_key($self->main_pkgnum);
4100 =head1 CLASS METHODS
4106 Returns an SQL expression identifying recurring packages.
4110 sub recurring_sql { "
4111 '0' != ( select freq from part_pkg
4112 where cust_pkg.pkgpart = part_pkg.pkgpart )
4117 Returns an SQL expression identifying one-time packages.
4122 '0' = ( select freq from part_pkg
4123 where cust_pkg.pkgpart = part_pkg.pkgpart )
4128 Returns an SQL expression identifying ordered packages (recurring packages not
4134 $_[0]->recurring_sql. " AND ". $_[0]->not_yet_billed_sql;
4139 Returns an SQL expression identifying active packages.
4144 $_[0]->recurring_sql. "
4145 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
4146 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4147 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
4150 =item not_yet_billed_sql
4152 Returns an SQL expression identifying packages which have not yet been billed.
4156 sub not_yet_billed_sql { "
4157 ( cust_pkg.setup IS NULL OR cust_pkg.setup = 0 )
4158 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4159 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
4164 Returns an SQL expression identifying inactive packages (one-time packages
4165 that are otherwise unsuspended/uncancelled).
4169 sub inactive_sql { "
4170 ". $_[0]->onetime_sql(). "
4171 AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
4172 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4173 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
4179 Returns an SQL expression identifying suspended packages.
4183 sub suspended_sql { susp_sql(@_); }
4185 #$_[0]->recurring_sql(). ' AND '.
4187 ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4188 AND cust_pkg.susp IS NOT NULL AND cust_pkg.susp != 0
4195 Returns an SQL exprression identifying cancelled packages.
4199 sub cancelled_sql { cancel_sql(@_); }
4201 #$_[0]->recurring_sql(). ' AND '.
4202 "cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0";
4207 Returns an SQL expression to give the package status as a string.
4213 WHEN cust_pkg.cancel IS NOT NULL THEN 'cancelled'
4214 WHEN cust_pkg.susp IS NOT NULL THEN 'suspended'
4215 WHEN cust_pkg.setup IS NULL THEN 'not yet billed'
4216 WHEN ".onetime_sql()." THEN 'one-time charge'
4221 =item search HASHREF
4225 Returns a qsearch hash expression to search for parameters specified in HASHREF.
4226 Valid parameters are
4234 active, inactive, suspended, cancel (or cancelled)
4238 active, inactive, suspended, one-time charge, inactive, cancel (or cancelled)
4242 boolean selects custom packages
4248 pkgpart or arrayref or hashref of pkgparts
4252 arrayref of beginning and ending epoch date
4256 arrayref of beginning and ending epoch date
4260 arrayref of beginning and ending epoch date
4264 arrayref of beginning and ending epoch date
4268 arrayref of beginning and ending epoch date
4272 arrayref of beginning and ending epoch date
4276 arrayref of beginning and ending epoch date
4280 pkgnum or APKG_pkgnum
4284 a value suited to passing to FS::UI::Web::cust_header
4288 specifies the user for agent virtualization
4292 boolean; if true, returns only packages with more than 0 FCC phone lines.
4294 =item state, country
4296 Limit to packages with a service location in the specified state and country.
4297 For FCC 477 reporting, mostly.
4301 Limit to packages whose service locations are the same as the customer's
4302 default service location.
4304 =item location_nocust
4306 Limit to packages whose service locations are not the customer's default
4309 =item location_census
4311 Limit to packages whose service locations have census tracts.
4313 =item location_nocensus
4315 Limit to packages whose service locations do not have a census tract.
4317 =item location_geocode
4319 Limit to packages whose locations have geocodes.
4321 =item location_geocode
4323 Limit to packages whose locations do not have geocodes.
4330 my ($class, $params) = @_;
4337 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
4339 "cust_main.agentnum = $1";
4346 if ( $params->{'cust_status'} =~ /^([a-z]+)$/ ) {
4347 push @where, FS::cust_main->cust_status_sql . " = '$1' ";
4351 # parse customer sales person
4354 if ( $params->{'cust_main_salesnum'} =~ /^(\d+)$/ ) {
4355 push @where, ($1 > 0) ? "cust_main.salesnum = $1"
4356 : 'cust_main.salesnum IS NULL';
4361 # parse sales person
4364 if ( $params->{'salesnum'} =~ /^(\d+)$/ ) {
4365 push @where, ($1 > 0) ? "cust_pkg.salesnum = $1"
4366 : 'cust_pkg.salesnum IS NULL';
4373 if ( $params->{'custnum'} =~ /^(\d+)$/ and $1 ) {
4375 "cust_pkg.custnum = $1";
4382 if ( $params->{'pkgbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
4384 "cust_pkg.pkgbatch = '$1'";
4391 if ( $params->{'magic'} eq 'active'
4392 || $params->{'status'} eq 'active' ) {
4394 push @where, FS::cust_pkg->active_sql();
4396 } elsif ( $params->{'magic'} =~ /^not[ _]yet[ _]billed$/
4397 || $params->{'status'} =~ /^not[ _]yet[ _]billed$/ ) {
4399 push @where, FS::cust_pkg->not_yet_billed_sql();
4401 } elsif ( $params->{'magic'} =~ /^(one-time charge|inactive)/
4402 || $params->{'status'} =~ /^(one-time charge|inactive)/ ) {
4404 push @where, FS::cust_pkg->inactive_sql();
4406 } elsif ( $params->{'magic'} eq 'suspended'
4407 || $params->{'status'} eq 'suspended' ) {
4409 push @where, FS::cust_pkg->suspended_sql();
4411 } elsif ( $params->{'magic'} =~ /^cancell?ed$/
4412 || $params->{'status'} =~ /^cancell?ed$/ ) {
4414 push @where, FS::cust_pkg->cancelled_sql();
4419 # parse package class
4422 if ( exists($params->{'classnum'}) ) {
4425 if ( ref($params->{'classnum'}) ) {
4427 if ( ref($params->{'classnum'}) eq 'HASH' ) {
4428 @classnum = grep $params->{'classnum'}{$_}, keys %{ $params->{'classnum'} };
4429 } elsif ( ref($params->{'classnum'}) eq 'ARRAY' ) {
4430 @classnum = @{ $params->{'classnum'} };
4432 die 'unhandled classnum ref '. $params->{'classnum'};
4436 } elsif ( $params->{'classnum'} =~ /^(\d*)$/ && $1 ne '0' ) {
4443 my @nums = grep $_, @classnum;
4444 push @c_where, 'part_pkg.classnum IN ('. join(',',@nums). ')' if @nums;
4445 my $null = scalar( grep { $_ eq '' } @classnum );
4446 push @c_where, 'part_pkg.classnum IS NULL' if $null;
4448 if ( scalar(@c_where) == 1 ) {
4449 push @where, @c_where;
4450 } elsif ( @c_where ) {
4451 push @where, ' ( '. join(' OR ', @c_where). ' ) ';
4460 # parse package report options
4463 my @report_option = ();
4464 if ( exists($params->{'report_option'}) ) {
4465 if ( ref($params->{'report_option'}) eq 'ARRAY' ) {
4466 @report_option = @{ $params->{'report_option'} };
4467 } elsif ( $params->{'report_option'} =~ /^([,\d]*)$/ ) {
4468 @report_option = split(',', $1);
4473 if (@report_option) {
4474 # this will result in the empty set for the dangling comma case as it should
4476 map{ "0 < ( SELECT count(*) FROM part_pkg_option
4477 WHERE part_pkg_option.pkgpart = part_pkg.pkgpart
4478 AND optionname = 'report_option_$_'
4479 AND optionvalue = '1' )"
4483 foreach my $any ( grep /^report_option_any/, keys %$params ) {
4485 my @report_option_any = ();
4486 if ( ref($params->{$any}) eq 'ARRAY' ) {
4487 @report_option_any = @{ $params->{$any} };
4488 } elsif ( $params->{$any} =~ /^([,\d]*)$/ ) {
4489 @report_option_any = split(',', $1);
4492 if (@report_option_any) {
4493 # this will result in the empty set for the dangling comma case as it should
4494 push @where, ' ( '. join(' OR ',
4495 map{ "0 < ( SELECT count(*) FROM part_pkg_option
4496 WHERE part_pkg_option.pkgpart = part_pkg.pkgpart
4497 AND optionname = 'report_option_$_'
4498 AND optionvalue = '1' )"
4499 } @report_option_any
4509 push @where, "part_pkg.custom = 'Y'" if $params->{custom};
4515 push @where, "(part_pkg.fcc_ds0s > 0 OR pkg_class.fcc_ds0s > 0)"
4516 if $params->{fcc_line};
4522 if ( exists($params->{'censustract'}) ) {
4523 $params->{'censustract'} =~ /^([.\d]*)$/;
4524 my $censustract = "cust_location.censustract = '$1'";
4525 $censustract .= ' OR cust_location.censustract is NULL' unless $1;
4526 push @where, "( $censustract )";
4530 # parse censustract2
4532 if ( exists($params->{'censustract2'})
4533 && $params->{'censustract2'} =~ /^(\d*)$/
4537 push @where, "cust_location.censustract LIKE '$1%'";
4540 "( cust_location.censustract = '' OR cust_location.censustract IS NULL )";
4545 # parse country/state
4547 for (qw(state country)) { # parsing rules are the same for these
4548 if ( exists($params->{$_})
4549 && uc($params->{$_}) =~ /^([A-Z]{2})$/ )
4551 # XXX post-2.3 only--before that, state/country may be in cust_main
4552 push @where, "cust_location.$_ = '$1'";
4559 if ( $params->{location_cust} xor $params->{location_nocust} ) {
4560 my $op = $params->{location_cust} ? '=' : '!=';
4561 push @where, "cust_location.locationnum $op cust_main.ship_locationnum";
4563 if ( $params->{location_census} xor $params->{location_nocensus} ) {
4564 my $op = $params->{location_census} ? "IS NOT NULL" : "IS NULL";
4565 push @where, "cust_location.censustract $op";
4567 if ( $params->{location_geocode} xor $params->{location_nogeocode} ) {
4568 my $op = $params->{location_geocode} ? "IS NOT NULL" : "IS NULL";
4569 push @where, "cust_location.geocode $op";
4576 if ( ref($params->{'pkgpart'}) ) {
4579 if ( ref($params->{'pkgpart'}) eq 'HASH' ) {
4580 @pkgpart = grep $params->{'pkgpart'}{$_}, keys %{ $params->{'pkgpart'} };
4581 } elsif ( ref($params->{'pkgpart'}) eq 'ARRAY' ) {
4582 @pkgpart = @{ $params->{'pkgpart'} };
4584 die 'unhandled pkgpart ref '. $params->{'pkgpart'};
4587 @pkgpart = grep /^(\d+)$/, @pkgpart;
4589 push @where, 'pkgpart IN ('. join(',', @pkgpart). ')' if scalar(@pkgpart);
4591 } elsif ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
4592 push @where, "pkgpart = $1";
4601 #false laziness w/report_cust_pkg.html
4604 'one-time charge' => { 'last_bill'=>1, 'bill'=>1, 'adjourn'=>1, 'susp'=>1, 'expire'=>1, 'cancel'=>1, },
4605 'active' => { 'susp'=>1, 'cancel'=>1 },
4606 'suspended' => { 'cancel' => 1 },
4611 if( exists($params->{'active'} ) ) {
4612 # This overrides all the other date-related fields
4613 my($beginning, $ending) = @{$params->{'active'}};
4615 "cust_pkg.setup IS NOT NULL",
4616 "cust_pkg.setup <= $ending",
4617 "(cust_pkg.cancel IS NULL OR cust_pkg.cancel >= $beginning )",
4618 "NOT (".FS::cust_pkg->onetime_sql . ")";
4621 foreach my $field (qw( setup last_bill bill adjourn susp expire contract_end change_date cancel )) {
4623 next unless exists($params->{$field});
4625 my($beginning, $ending) = @{$params->{$field}};
4627 next if $beginning == 0 && $ending == 4294967295;
4630 "cust_pkg.$field IS NOT NULL",
4631 "cust_pkg.$field >= $beginning",
4632 "cust_pkg.$field <= $ending";
4634 $orderby ||= "ORDER BY cust_pkg.$field";
4639 $orderby ||= 'ORDER BY bill';
4642 # parse magic, legacy, etc.
4645 if ( $params->{'magic'} &&
4646 $params->{'magic'} =~ /^(active|inactive|suspended|cancell?ed)$/
4649 $orderby = 'ORDER BY pkgnum';
4651 if ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
4652 push @where, "pkgpart = $1";
4655 } elsif ( $params->{'query'} eq 'pkgnum' ) {
4657 $orderby = 'ORDER BY pkgnum';
4659 } elsif ( $params->{'query'} eq 'APKG_pkgnum' ) {
4661 $orderby = 'ORDER BY pkgnum';
4664 SELECT count(*) FROM pkg_svc
4665 WHERE pkg_svc.pkgpart = cust_pkg.pkgpart
4666 AND pkg_svc.quantity > ( SELECT count(*) FROM cust_svc
4667 WHERE cust_svc.pkgnum = cust_pkg.pkgnum
4668 AND cust_svc.svcpart = pkg_svc.svcpart
4675 # setup queries, links, subs, etc. for the search
4678 # here is the agent virtualization
4679 if ($params->{CurrentUser}) {
4681 qsearchs('access_user', { username => $params->{CurrentUser} });
4684 push @where, $access_user->agentnums_sql('table'=>'cust_main');
4689 push @where, $FS::CurrentUser::CurrentUser->agentnums_sql('table'=>'cust_main');
4692 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
4694 my $addl_from = 'LEFT JOIN part_pkg USING ( pkgpart ) '.
4695 'LEFT JOIN pkg_class ON ( part_pkg.classnum = pkg_class.classnum ) '.
4696 'LEFT JOIN cust_location USING ( locationnum ) '.
4697 FS::UI::Web::join_cust_main('cust_pkg', 'cust_pkg');
4701 if ( $params->{'select_zip5'} ) {
4702 my $zip = 'cust_location.zip';
4704 $select = "DISTINCT substr($zip,1,5) as zip";
4705 $orderby = "ORDER BY substr($zip,1,5)";
4706 $count_query = "SELECT COUNT( DISTINCT substr($zip,1,5) )";
4708 $select = join(', ',
4710 ( map "part_pkg.$_", qw( pkg freq ) ),
4711 'pkg_class.classname',
4712 'cust_main.custnum AS cust_main_custnum',
4713 FS::UI::Web::cust_sql_fields(
4714 $params->{'cust_fields'}
4717 $count_query = 'SELECT COUNT(*)';
4720 $count_query .= " FROM cust_pkg $addl_from $extra_sql";
4723 'table' => 'cust_pkg',
4725 'select' => $select,
4726 'extra_sql' => $extra_sql,
4727 'order_by' => $orderby,
4728 'addl_from' => $addl_from,
4729 'count_query' => $count_query,
4736 Returns a list of two package counts. The first is a count of packages
4737 based on the supplied criteria and the second is the count of residential
4738 packages with those same criteria. Criteria are specified as in the search
4744 my ($class, $params) = @_;
4746 my $sql_query = $class->search( $params );
4748 my $count_sql = delete($sql_query->{'count_query'});
4749 $count_sql =~ s/ FROM/,count(CASE WHEN cust_main.company IS NULL OR cust_main.company = '' THEN 1 END) FROM/
4750 or die "couldn't parse count_sql";
4752 my $count_sth = dbh->prepare($count_sql)
4753 or die "Error preparing $count_sql: ". dbh->errstr;
4755 or die "Error executing $count_sql: ". $count_sth->errstr;
4756 my $count_arrayref = $count_sth->fetchrow_arrayref;
4758 return ( @$count_arrayref );
4762 =item tax_locationnum_sql
4764 Returns an SQL expression for the tax location for a package, based
4765 on the settings of 'tax-pkg_address' and 'tax-ship_address'.
4769 sub tax_locationnum_sql {
4770 my $conf = FS::Conf->new;
4771 if ( $conf->exists('tax-pkg_address') ) {
4772 'cust_pkg.locationnum';
4774 elsif ( $conf->exists('tax-ship_address') ) {
4775 'cust_main.ship_locationnum';
4778 'cust_main.bill_locationnum';
4784 Returns a list: the first item is an SQL fragment identifying matching
4785 packages/customers via location (taking into account shipping and package
4786 address taxation, if enabled), and subsequent items are the parameters to
4787 substitute for the placeholders in that fragment.
4792 my($class, %opt) = @_;
4793 my $ornull = $opt{'ornull'};
4795 my $conf = new FS::Conf;
4797 # '?' placeholders in _location_sql_where
4798 my $x = $ornull ? 3 : 2;
4809 if ( $conf->exists('tax-ship_address') ) {
4812 ( ( ship_last IS NULL OR ship_last = '' )
4813 AND ". _location_sql_where('cust_main', '', $ornull ). "
4815 OR ( ship_last IS NOT NULL AND ship_last != ''
4816 AND ". _location_sql_where('cust_main', 'ship_', $ornull ). "
4819 # AND payby != 'COMP'
4821 @main_param = ( @bill_param, @bill_param );
4825 $main_where = _location_sql_where('cust_main'); # AND payby != 'COMP'
4826 @main_param = @bill_param;
4832 if ( $conf->exists('tax-pkg_address') ) {
4834 my $loc_where = _location_sql_where( 'cust_location', '', $ornull );
4837 ( cust_pkg.locationnum IS NULL AND $main_where )
4838 OR ( cust_pkg.locationnum IS NOT NULL AND $loc_where )
4841 @param = ( @main_param, @bill_param );
4845 $where = $main_where;
4846 @param = @main_param;
4854 #subroutine, helper for location_sql
4855 sub _location_sql_where {
4857 my $prefix = @_ ? shift : '';
4858 my $ornull = @_ ? shift : '';
4860 # $ornull = $ornull ? " OR ( ? IS NULL AND $table.${prefix}county IS NULL ) " : '';
4862 $ornull = $ornull ? ' OR ? IS NULL ' : '';
4864 my $or_empty_city = " OR ( ? = '' AND $table.${prefix}city IS NULL )";
4865 my $or_empty_county = " OR ( ? = '' AND $table.${prefix}county IS NULL )";
4866 my $or_empty_state = " OR ( ? = '' AND $table.${prefix}state IS NULL )";
4868 my $text = (driver_name =~ /^mysql/i) ? 'char' : 'text';
4870 # ( $table.${prefix}city = ? $or_empty_city $ornull )
4872 ( $table.district = ? OR ? = '' OR CAST(? AS $text) IS NULL )
4873 AND ( $table.${prefix}city = ? OR ? = '' OR CAST(? AS $text) IS NULL )
4874 AND ( $table.${prefix}county = ? $or_empty_county $ornull )
4875 AND ( $table.${prefix}state = ? $or_empty_state $ornull )
4876 AND $table.${prefix}country = ?
4881 my( $self, $what ) = @_;
4883 my $what_show_zero = $what. '_show_zero';
4884 length($self->$what_show_zero())
4885 ? ($self->$what_show_zero() eq 'Y')
4886 : $self->part_pkg->$what_show_zero();
4893 =item order CUSTNUM, PKGPARTS_ARYREF, [ REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF [ REFNUM ] ] ]
4895 CUSTNUM is a customer (see L<FS::cust_main>)
4897 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
4898 L<FS::part_pkg>) to order for this customer. Duplicates are of course
4901 REMOVE_PKGNUMS is an optional list of pkgnums specifying the billing items to
4902 remove for this customer. The services (see L<FS::cust_svc>) are moved to the
4903 new billing items. An error is returned if this is not possible (see
4904 L<FS::pkg_svc>). An empty arrayref is equivalent to not specifying this
4907 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
4908 newly-created cust_pkg objects.
4910 REFNUM, if specified, will specify the FS::pkg_referral record to be created
4911 and inserted. Multiple FS::pkg_referral records can be created by
4912 setting I<refnum> to an array reference of refnums or a hash reference with
4913 refnums as keys. If no I<refnum> is defined, a default FS::pkg_referral
4914 record will be created corresponding to cust_main.refnum.
4919 my ($custnum, $pkgparts, $remove_pkgnum, $return_cust_pkg, $refnum) = @_;
4921 my $conf = new FS::Conf;
4923 # Transactionize this whole mess
4924 local $SIG{HUP} = 'IGNORE';
4925 local $SIG{INT} = 'IGNORE';
4926 local $SIG{QUIT} = 'IGNORE';
4927 local $SIG{TERM} = 'IGNORE';
4928 local $SIG{TSTP} = 'IGNORE';
4929 local $SIG{PIPE} = 'IGNORE';
4931 my $oldAutoCommit = $FS::UID::AutoCommit;
4932 local $FS::UID::AutoCommit = 0;
4936 # my $cust_main = qsearchs('cust_main', { custnum => $custnum });
4937 # return "Customer not found: $custnum" unless $cust_main;
4939 warn "$me order: pkgnums to remove: ". join(',', @$remove_pkgnum). "\n"
4942 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
4945 my $change = scalar(@old_cust_pkg) != 0;
4948 if ( scalar(@old_cust_pkg) == 1 && scalar(@$pkgparts) == 1 ) {
4950 warn "$me order: changing pkgnum ". $old_cust_pkg[0]->pkgnum.
4951 " to pkgpart ". $pkgparts->[0]. "\n"
4954 my $err_or_cust_pkg =
4955 $old_cust_pkg[0]->change( 'pkgpart' => $pkgparts->[0],
4956 'refnum' => $refnum,
4959 unless (ref($err_or_cust_pkg)) {
4960 $dbh->rollback if $oldAutoCommit;
4961 return $err_or_cust_pkg;
4964 push @$return_cust_pkg, $err_or_cust_pkg;
4965 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4970 # Create the new packages.
4971 foreach my $pkgpart (@$pkgparts) {
4973 warn "$me order: inserting pkgpart $pkgpart\n" if $DEBUG;
4975 my $cust_pkg = new FS::cust_pkg { custnum => $custnum,
4976 pkgpart => $pkgpart,
4980 $error = $cust_pkg->insert( 'change' => $change );
4981 push @$return_cust_pkg, $cust_pkg;
4983 foreach my $link ($cust_pkg->part_pkg->supp_part_pkg_link) {
4984 my $supp_pkg = FS::cust_pkg->new({
4985 custnum => $custnum,
4986 pkgpart => $link->dst_pkgpart,
4988 main_pkgnum => $cust_pkg->pkgnum,
4991 $error ||= $supp_pkg->insert( 'change' => $change );
4992 push @$return_cust_pkg, $supp_pkg;
4996 $dbh->rollback if $oldAutoCommit;
5001 # $return_cust_pkg now contains refs to all of the newly
5004 # Transfer services and cancel old packages.
5005 foreach my $old_pkg (@old_cust_pkg) {
5007 warn "$me order: transferring services from pkgnum ". $old_pkg->pkgnum. "\n"
5010 foreach my $new_pkg (@$return_cust_pkg) {
5011 $error = $old_pkg->transfer($new_pkg);
5012 if ($error and $error == 0) {
5013 # $old_pkg->transfer failed.
5014 $dbh->rollback if $oldAutoCommit;
5019 if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
5020 warn "trying transfer again with change_svcpart option\n" if $DEBUG;
5021 foreach my $new_pkg (@$return_cust_pkg) {
5022 $error = $old_pkg->transfer($new_pkg, 'change_svcpart'=>1 );
5023 if ($error and $error == 0) {
5024 # $old_pkg->transfer failed.
5025 $dbh->rollback if $oldAutoCommit;
5032 # Transfers were successful, but we went through all of the
5033 # new packages and still had services left on the old package.
5034 # We can't cancel the package under the circumstances, so abort.
5035 $dbh->rollback if $oldAutoCommit;
5036 return "Unable to transfer all services from package ".$old_pkg->pkgnum;
5038 $error = $old_pkg->cancel( quiet=>1 );
5044 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5048 =item bulk_change PKGPARTS_ARYREF, REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF ]
5050 A bulk change method to change packages for multiple customers.
5052 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
5053 L<FS::part_pkg>) to order for each customer. Duplicates are of course
5056 REMOVE_PKGNUMS is an list of pkgnums specifying the billing items to
5057 replace. The services (see L<FS::cust_svc>) are moved to the
5058 new billing items. An error is returned if this is not possible (see
5061 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
5062 newly-created cust_pkg objects.
5067 my ($pkgparts, $remove_pkgnum, $return_cust_pkg) = @_;
5069 # Transactionize this whole mess
5070 local $SIG{HUP} = 'IGNORE';
5071 local $SIG{INT} = 'IGNORE';
5072 local $SIG{QUIT} = 'IGNORE';
5073 local $SIG{TERM} = 'IGNORE';
5074 local $SIG{TSTP} = 'IGNORE';
5075 local $SIG{PIPE} = 'IGNORE';
5077 my $oldAutoCommit = $FS::UID::AutoCommit;
5078 local $FS::UID::AutoCommit = 0;
5082 my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
5085 while(scalar(@old_cust_pkg)) {
5087 my $custnum = $old_cust_pkg[0]->custnum;
5088 my (@remove) = map { $_->pkgnum }
5089 grep { $_->custnum == $custnum } @old_cust_pkg;
5090 @old_cust_pkg = grep { $_->custnum != $custnum } @old_cust_pkg;
5092 my $error = order $custnum, $pkgparts, \@remove, \@return;
5094 push @errors, $error
5096 push @$return_cust_pkg, @return;
5099 if (scalar(@errors)) {
5100 $dbh->rollback if $oldAutoCommit;
5101 return join(' / ', @errors);
5104 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5108 # Used by FS::Upgrade to migrate to a new database.
5109 sub _upgrade_data { # class method
5110 my ($class, %opts) = @_;
5111 $class->_upgrade_otaker(%opts);
5113 # RT#10139, bug resulting in contract_end being set when it shouldn't
5114 'UPDATE cust_pkg SET contract_end = NULL WHERE contract_end = -1',
5115 # RT#10830, bad calculation of prorate date near end of year
5116 # the date range for bill is December 2009, and we move it forward
5117 # one year if it's before the previous bill date (which it should
5119 'UPDATE cust_pkg SET bill = bill + (365*24*60*60) WHERE bill < last_bill
5120 AND bill > 1259654400 AND bill < 1262332800 AND (SELECT plan FROM part_pkg
5121 WHERE part_pkg.pkgpart = cust_pkg.pkgpart) = \'prorate\'',
5122 # RT6628, add order_date to cust_pkg
5123 'update cust_pkg set order_date = (select history_date from h_cust_pkg
5124 where h_cust_pkg.pkgnum = cust_pkg.pkgnum and
5125 history_action = \'insert\') where order_date is null',
5127 foreach my $sql (@statements) {
5128 my $sth = dbh->prepare($sql);
5129 $sth->execute or die $sth->errstr;
5137 sub order is not OO. Perhaps it should be moved to FS::cust_main and made so?
5139 In sub order, the @pkgparts array (passed by reference) is clobbered.
5141 Also in sub order, no money is adjusted. Once FS::part_pkg defines a standard
5142 method to pass dates to the recur_prog expression, it should do so.
5144 FS::svc_acct, FS::svc_domain, FS::svc_www, FS::svc_ip and FS::svc_forward are
5145 loaded via 'use' at compile time, rather than via 'require' in sub { setup,
5146 suspend, unsuspend, cancel } because they use %FS::UID::callback to load
5147 configuration values. Probably need a subroutine which decides what to do
5148 based on whether or not we've fetched the user yet, rather than a hash. See
5149 FS::UID and the TODO.
5151 Now that things are transactional should the check in the insert method be
5156 L<FS::Record>, L<FS::cust_main>, L<FS::part_pkg>, L<FS::cust_svc>,
5157 L<FS::pkg_svc>, schema.html from the base documentation