1 package FS::cust_main::Packages;
4 use vars qw( $DEBUG $me );
5 use List::Util qw( min );
7 use FS::Record qw( qsearch qsearchs );
10 use FS::contact; # for attach_pkgs
11 use FS::cust_location; #
14 $me = '[FS::cust_main::Packages]';
18 FS::cust_main::Packages - Packages mixin for cust_main
24 These methods are available on FS::cust_main objects;
30 =item order_pkg HASHREF | OPTION => VALUE ...
32 Orders a single package.
34 Note that if the package definition has supplemental packages, those will
37 Options may be passed as a list of key/value pairs or as a hash reference.
48 Optional FS::cust_location object. If not specified, the customer's
49 ship_location will be used.
53 Optional arryaref of FS::svc_* service objects.
57 If this option is set to a job queue jobnum (see L<FS::queue>), all provisioning
58 jobs will have a dependancy on the supplied job (they will not run until the
59 specific job completes). This can be used to defer provisioning until some
60 action completes (such as running the customer's credit card successfully).
64 This option is option is deprecated but still works for now (use
65 I<depend_jobnum> instead for new code). If I<noexport> is set true, no
66 provisioning jobs (exports) are scheduled. (You can schedule them later with
67 the B<reexport> method for each cust_pkg object. Using the B<reexport> method
68 on the cust_main object is not recommended, as existing services will also be
73 Optional subject for a ticket created and attached to this customer
77 Optional queue name for ticket additions
85 my $opt = ref($_[0]) ? shift : { @_ };
87 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
89 warn "$me order_pkg called with options ".
90 join(', ', map { "$_: $opt->{$_}" } keys %$opt ). "\n"
93 local $FS::svc_Common::noexport_hack = 1 if $opt->{'noexport'};
95 my $cust_pkg = $opt->{'cust_pkg'};
96 my $svcs = $opt->{'svcs'} || [];
99 $svc_options{'depend_jobnum'} = $opt->{'depend_jobnum'}
100 if exists($opt->{'depend_jobnum'}) && $opt->{'depend_jobnum'};
102 my %insert_params = map { $opt->{$_} ? ( $_ => $opt->{$_} ) : () }
103 qw( ticket_subject ticket_queue allow_pkgpart );
105 local $SIG{HUP} = 'IGNORE';
106 local $SIG{INT} = 'IGNORE';
107 local $SIG{QUIT} = 'IGNORE';
108 local $SIG{TERM} = 'IGNORE';
109 local $SIG{TSTP} = 'IGNORE';
110 local $SIG{PIPE} = 'IGNORE';
112 my $oldAutoCommit = $FS::UID::AutoCommit;
113 local $FS::UID::AutoCommit = 0;
116 if ( $opt->{'contactnum'} and $opt->{'contactnum'} != -1 ) {
118 $cust_pkg->contactnum($opt->{'contactnum'});
120 } elsif ( $opt->{'contact'} ) {
122 if ( ! $opt->{'contact'}->contactnum ) {
124 my $error = $opt->{'contact'}->insert;
126 $dbh->rollback if $oldAutoCommit;
127 return "inserting contact (transaction rolled back): $error";
130 $cust_pkg->contactnum($opt->{'contact'}->contactnum);
134 # $cust_pkg->contactnum();
138 if ( $opt->{'locationnum'} and $opt->{'locationnum'} != -1 ) {
140 $cust_pkg->locationnum($opt->{'locationnum'});
142 } elsif ( $opt->{'cust_location'} ) {
144 my $error = $opt->{'cust_location'}->find_or_insert;
146 $dbh->rollback if $oldAutoCommit;
147 return "inserting cust_location (transaction rolled back): $error";
149 $cust_pkg->locationnum($opt->{'cust_location'}->locationnum);
153 $cust_pkg->locationnum($self->ship_locationnum);
157 $cust_pkg->custnum( $self->custnum );
159 my $error = $cust_pkg->insert( %insert_params );
161 $dbh->rollback if $oldAutoCommit;
162 return "inserting cust_pkg (transaction rolled back): $error";
165 foreach my $svc_something ( @{ $opt->{'svcs'} } ) {
166 if ( $svc_something->svcnum ) {
167 my $old_cust_svc = $svc_something->cust_svc;
168 my $new_cust_svc = new FS::cust_svc { $old_cust_svc->hash };
169 $new_cust_svc->pkgnum( $cust_pkg->pkgnum);
170 $error = $new_cust_svc->replace($old_cust_svc);
172 $svc_something->pkgnum( $cust_pkg->pkgnum );
173 if ( $svc_something->isa('FS::svc_acct') ) {
174 foreach ( grep { $opt->{$_.'_ref'} && ${ $opt->{$_.'_ref'} } }
175 qw( seconds upbytes downbytes totalbytes ) ) {
176 $svc_something->$_( $svc_something->$_() + ${ $opt->{$_.'_ref'} } );
177 ${ $opt->{$_.'_ref'} } = 0;
180 $error = $svc_something->insert(%svc_options);
183 $dbh->rollback if $oldAutoCommit;
184 return "inserting svc_ (transaction rolled back): $error";
188 # add supplemental packages, if any are needed
189 my $part_pkg = FS::part_pkg->by_key($cust_pkg->pkgpart);
190 foreach my $link ($part_pkg->supp_part_pkg_link) {
191 #warn "inserting supplemental package ".$link->dst_pkgpart;
192 my $pkg = FS::cust_pkg->new({
193 'pkgpart' => $link->dst_pkgpart,
194 'pkglinknum' => $link->pkglinknum,
195 'custnum' => $self->custnum,
196 'main_pkgnum' => $cust_pkg->pkgnum,
197 # try to prevent as many surprises as possible
198 'allow_pkgpart' => $opt->{'allow_pkgpart'},
199 map { $_ => $cust_pkg->$_() }
201 start_date order_date expire adjourn contract_end
202 refnum discountnum waive_setup
205 $error = $self->order_pkg('cust_pkg' => $pkg,
206 'locationnum' => $cust_pkg->locationnum);
208 $dbh->rollback if $oldAutoCommit;
209 return "inserting supplemental package: $error";
213 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
218 =item order_pkgs HASHREF [ , OPTION => VALUE ... ]
220 Like the insert method on an existing record, this method orders multiple
221 packages and included services atomicaly. Pass a Tie::RefHash data structure
222 to this method containing FS::cust_pkg and FS::svc_I<tablename> objects.
223 There should be a better explanation of this, but until then, here's an
227 tie %hash, 'Tie::RefHash'; #this part is important
229 $cust_pkg => [ $svc_acct ],
232 $cust_main->order_pkgs( \%hash, 'noexport'=>1 );
234 Services can be new, in which case they are inserted, or existing unaudited
235 services, in which case they are linked to the newly-created package.
237 Currently available options are: I<depend_jobnum>, I<noexport>, I<seconds_ref>,
238 I<upbytes_ref>, I<downbytes_ref>, and I<totalbytes_ref>.
240 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
241 on the supplied jobnum (they will not run until the specific job completes).
242 This can be used to defer provisioning until some action completes (such
243 as running the customer's credit card successfully).
245 The I<noexport> option is deprecated but still works for now (use
246 I<depend_jobnum> instead for new code). If I<noexport> is set true, no
247 provisioning jobs (exports) are scheduled. (You can schedule them later with
248 the B<reexport> method for each cust_pkg object. Using the B<reexport> method
249 on the cust_main object is not recommended, as existing services will also be
252 If I<seconds_ref>, I<upbytes_ref>, I<downbytes_ref>, or I<totalbytes_ref> is
253 provided, the scalars (provided by references) will be incremented by the
254 values of the prepaid card.`
260 my $cust_pkgs = shift;
263 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
265 warn "$me order_pkgs called with options ".
266 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
269 local $SIG{HUP} = 'IGNORE';
270 local $SIG{INT} = 'IGNORE';
271 local $SIG{QUIT} = 'IGNORE';
272 local $SIG{TERM} = 'IGNORE';
273 local $SIG{TSTP} = 'IGNORE';
274 local $SIG{PIPE} = 'IGNORE';
276 my $oldAutoCommit = $FS::UID::AutoCommit;
277 local $FS::UID::AutoCommit = 0;
280 local $FS::svc_Common::noexport_hack = 1 if $options{'noexport'};
282 foreach my $cust_pkg ( keys %$cust_pkgs ) {
284 my $error = $self->order_pkg(
285 'cust_pkg' => $cust_pkg,
286 'svcs' => $cust_pkgs->{$cust_pkg},
287 map { $_ => $options{$_} }
288 qw( seconds_ref upbytes_ref downbytes_ref totalbytes_ref depend_jobnum )
291 $dbh->rollback if $oldAutoCommit;
297 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
303 Merges this customer's package's into the target customer and then cancels them.
308 my( $self, $new_custnum ) = @_;
310 #mostly false laziness w/ merge
312 return "Can't attach packages to self" if $self->custnum == $new_custnum;
314 my $new_cust_main = qsearchs( 'cust_main', { 'custnum' => $new_custnum } )
315 or return "Invalid new customer number: $new_custnum";
317 return 'Access denied: "Merge customer across agents" access right required to merge into a customer of a different agent'
318 if $self->agentnum != $new_cust_main->agentnum
319 && ! $FS::CurrentUser::CurrentUser->access_right('Merge customer across agents');
321 local $SIG{HUP} = 'IGNORE';
322 local $SIG{INT} = 'IGNORE';
323 local $SIG{QUIT} = 'IGNORE';
324 local $SIG{TERM} = 'IGNORE';
325 local $SIG{TSTP} = 'IGNORE';
326 local $SIG{PIPE} = 'IGNORE';
328 my $oldAutoCommit = $FS::UID::AutoCommit;
329 local $FS::UID::AutoCommit = 0;
332 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
333 $dbh->rollback if $oldAutoCommit;
334 return "Can't merge a master agent customer";
338 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
339 $dbh->rollback if $oldAutoCommit;
340 return "Can't merge a master employee customer";
343 if ( qsearch('cust_pay_pending', { 'custnum' => $self->custnum,
344 'status' => { op=>'!=', value=>'done' },
348 $dbh->rollback if $oldAutoCommit;
349 return "Can't merge a customer with pending payments";
352 #end of false laziness
356 my %contact_hash = ( 'first' => $self->first,
357 'last' => $self->get('last'),
358 'custnum' => $new_custnum,
362 my $contact = qsearchs( 'contact', \%contact_hash)
363 || new FS::contact \%contact_hash;
364 unless ( $contact->contactnum ) {
365 my $error = $contact->insert;
367 $dbh->rollback if $oldAutoCommit;
372 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
374 my $cust_location = $cust_pkg->cust_location || $self->ship_location;
375 my %loc_hash = $cust_location->hash;
376 $loc_hash{'locationnum'} = '';
377 $loc_hash{'custnum'} = $new_custnum;
378 $loc_hash{'disabled'} = '';
379 my $new_cust_location = qsearchs( 'cust_location', \%loc_hash)
380 || new FS::cust_location \%loc_hash;
382 my $pkg_or_error = $cust_pkg->change( {
384 'cust_main' => $new_cust_main,
385 'contactnum' => $contact->contactnum,
386 'cust_location' => $new_cust_location,
389 my $error = ref($pkg_or_error) ? '' : $pkg_or_error;
392 $dbh->rollback if $oldAutoCommit;
398 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
403 =item all_pkgs [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
405 Returns all packages (see L<FS::cust_pkg>) for this customer.
411 my $extra_qsearch = ref($_[0]) ? shift : { @_ };
413 return $self->num_pkgs unless wantarray || keys %$extra_qsearch;
416 if ( $self->{'_pkgnum'} && ! keys %$extra_qsearch ) {
417 @cust_pkg = values %{ $self->{'_pkgnum'}->cache };
419 @cust_pkg = $self->_cust_pkg($extra_qsearch);
422 map { $_ } sort sort_packages @cust_pkg;
427 Synonym for B<all_pkgs>.
435 =item ncancelled_pkgs [ EXTRA_QSEARCH_PARAMS_HASHREF ]
437 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
441 sub ncancelled_pkgs {
443 my $extra_qsearch = ref($_[0]) ? shift : {};
445 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
447 return $self->num_ncancelled_pkgs unless wantarray;
450 if ( $self->{'_pkgnum'} ) {
452 warn "$me ncancelled_pkgs: returning cached objects"
455 @cust_pkg = grep { ! $_->getfield('cancel') }
456 values %{ $self->{'_pkgnum'}->cache };
460 warn "$me ncancelled_pkgs: searching for packages with custnum ".
464 $extra_qsearch->{'extra_sql'} .= ' AND ( cancel IS NULL OR cancel = 0 ) ';
466 @cust_pkg = $self->_cust_pkg($extra_qsearch);
470 sort sort_packages @cust_pkg;
476 my $extra_qsearch = ref($_[0]) ? shift : {};
478 $extra_qsearch->{'select'} ||= '*';
479 $extra_qsearch->{'select'} .=
480 ',( SELECT COUNT(*) FROM cust_svc WHERE cust_pkg.pkgnum = cust_svc.pkgnum )
484 $_->{'_num_cust_svc'} = $_->get('_num_cust_svc');
489 'table' => 'cust_pkg',
490 'hashref' => { 'custnum' => $self->custnum },
495 # This should be generalized to use config options to determine order.
498 my $locationsort = ( $a->locationnum || 0 ) <=> ( $b->locationnum || 0 );
499 return $locationsort if $locationsort;
501 if ( $a->get('cancel') xor $b->get('cancel') ) {
502 return -1 if $b->get('cancel');
503 return 1 if $a->get('cancel');
504 #shouldn't get here...
507 my $a_num_cust_svc = $a->num_cust_svc;
508 my $b_num_cust_svc = $b->num_cust_svc;
509 return 0 if !$a_num_cust_svc && !$b_num_cust_svc;
510 return -1 if $a_num_cust_svc && !$b_num_cust_svc;
511 return 1 if !$a_num_cust_svc && $b_num_cust_svc;
512 return 0 if $a_num_cust_svc + $b_num_cust_svc > 20; #for perf, just give up
513 my @a_cust_svc = $a->cust_svc_unsorted;
514 my @b_cust_svc = $b->cust_svc_unsorted;
515 return 0 if !scalar(@a_cust_svc) && !scalar(@b_cust_svc);
516 return -1 if scalar(@a_cust_svc) && !scalar(@b_cust_svc);
517 return 1 if !scalar(@a_cust_svc) && scalar(@b_cust_svc);
518 $a_cust_svc[0]->svc_x->label cmp $b_cust_svc[0]->svc_x->label;
525 Returns all suspended packages (see L<FS::cust_pkg>) for this customer.
531 return $self->num_suspended_pkgs unless wantarray;
532 grep { $_->susp } $self->ncancelled_pkgs;
535 ### This appears to be unused, will be going away
537 #=item unflagged_suspended_pkgs
539 #Returns all unflagged suspended packages (see L<FS::cust_pkg>) for this
540 #customer (thouse packages without the `manual_flag' set).
544 sub unflagged_suspended_pkgs {
546 return $self->suspended_pkgs
547 unless dbdef->table('cust_pkg')->column('manual_flag');
548 grep { ! $_->manual_flag } $self->suspended_pkgs;
551 =item unsuspended_pkgs
553 Returns all unsuspended (and uncancelled) packages (see L<FS::cust_pkg>) for
558 sub unsuspended_pkgs {
560 return $self->num_unsuspended_pkgs unless wantarray;
561 grep { ! $_->susp } $self->ncancelled_pkgs;
566 Returns all unsuspended (and uncancelled) packages (see L<FS::cust_pkg>) for
567 this customer that are active (recurring).
573 grep { my $part_pkg = $_->part_pkg;
574 $part_pkg->freq ne '' && $part_pkg->freq ne '0';
576 $self->unsuspended_pkgs;
579 =item ncancelled_active_pkgs
581 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer that
582 are active (recurring).
586 sub ncancelled_active_pkgs {
588 grep { my $part_pkg = $_->part_pkg;
589 $part_pkg->freq ne '' && $part_pkg->freq ne '0';
591 $self->ncancelled_pkgs;
596 Returns active packages, and also any suspended packages which are set to
597 continue billing while suspended.
603 grep { my $part_pkg = $_->part_pkg;
604 $part_pkg->freq ne '' && $part_pkg->freq ne '0'
605 && ( ! $_->susp || $_->option('suspend_bill',1)
606 || ( $part_pkg->option('suspend_bill', 1)
607 && ! $_->option('no_suspend_bill',1)
611 $self->ncancelled_pkgs;
616 Returns the next date this customer will be billed, as a UNIX timestamp, or
617 undef if no billing package has a next bill date.
623 min( map $_->get('bill'), grep $_->get('bill'), $self->billing_pkgs );
626 =item num_cancelled_pkgs
628 Returns the number of cancelled packages (see L<FS::cust_pkg>) for this
633 sub num_cancelled_pkgs {
634 shift->num_pkgs("cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0");
637 sub num_ncancelled_pkgs {
638 shift->num_pkgs("( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )");
641 sub num_suspended_pkgs {
642 shift->num_pkgs(" ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
643 AND cust_pkg.susp IS NOT NULL AND cust_pkg.susp != 0 ");
646 sub num_unsuspended_pkgs {
647 shift->num_pkgs(" ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
648 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 ) ");
653 my $sql = scalar(@_) ? shift : '';
654 $sql = "AND $sql" if $sql && $sql !~ /^\s*$/ && $sql !~ /^\s*AND/i;
655 my $sth = dbh->prepare(
656 "SELECT COUNT(*) FROM cust_pkg WHERE custnum = ? $sql"
657 ) or die dbh->errstr;
658 $sth->execute($self->custnum) or die $sth->errstr;
659 $sth->fetchrow_arrayref->[0];
668 L<FS::cust_main>, L<FS::cust_pkg>