backport cust_svc_unsorted method from master, RT#26097
[freeside.git] / FS / FS / cust_pkg.pm
1 package FS::cust_pkg;
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 );
5
6 use strict;
7 use vars qw( $disable_agentcheck $DEBUG $me $upgrade );
8 use Carp qw(cluck);
9 use Scalar::Util qw( blessed );
10 use List::Util qw(min max);
11 use Tie::IxHash;
12 use Time::Local qw( timelocal timelocal_nocheck );
13 use MIME::Entity;
14 use FS::UID qw( getotaker dbh driver_name );
15 use FS::Misc qw( send_email );
16 use FS::Record qw( qsearch qsearchs fields );
17 use FS::CurrentUser;
18 use FS::cust_svc;
19 use FS::part_pkg;
20 use FS::cust_main;
21 use FS::contact;
22 use FS::cust_location;
23 use FS::pkg_svc;
24 use FS::cust_bill_pkg;
25 use FS::cust_pkg_detail;
26 use FS::cust_pkg_usage;
27 use FS::cdr_cust_pkg_usage;
28 use FS::cust_event;
29 use FS::h_cust_svc;
30 use FS::reg_code;
31 use FS::part_svc;
32 use FS::cust_pkg_reason;
33 use FS::reason;
34 use FS::cust_pkg_discount;
35 use FS::discount;
36 use FS::UI::Web;
37 use FS::sales;
38 # for modify_charge
39 use FS::cust_credit;
40
41 # need to 'use' these instead of 'require' in sub { cancel, suspend, unsuspend,
42 # setup }
43 # because they load configuration by setting FS::UID::callback (see TODO)
44 use FS::svc_acct;
45 use FS::svc_domain;
46 use FS::svc_www;
47 use FS::svc_forward;
48
49 # for sending cancel emails in sub cancel
50 use FS::Conf;
51
52 $DEBUG = 0;
53 $me = '[FS::cust_pkg]';
54
55 $disable_agentcheck = 0;
56
57 $upgrade = 0; #go away after setup+start dates cleaned up for old customers
58
59 sub _cache {
60   my $self = shift;
61   my ( $hashref, $cache ) = @_;
62   #if ( $hashref->{'pkgpart'} ) {
63   if ( $hashref->{'pkg'} ) {
64     # #@{ $self->{'_pkgnum'} } = ();
65     # my $subcache = $cache->subcache('pkgpart', 'part_pkg');
66     # $self->{'_pkgpart'} = $subcache;
67     # #push @{ $self->{'_pkgnum'} },
68     #   FS::part_pkg->new_or_cached($hashref, $subcache);
69     $self->{'_pkgpart'} = FS::part_pkg->new($hashref);
70   }
71   if ( exists $hashref->{'svcnum'} ) {
72     #@{ $self->{'_pkgnum'} } = ();
73     my $subcache = $cache->subcache('svcnum', 'cust_svc', $hashref->{pkgnum});
74     $self->{'_svcnum'} = $subcache;
75     #push @{ $self->{'_pkgnum'} },
76     FS::cust_svc->new_or_cached($hashref, $subcache) if $hashref->{svcnum};
77   }
78 }
79
80 =head1 NAME
81
82 FS::cust_pkg - Object methods for cust_pkg objects
83
84 =head1 SYNOPSIS
85
86   use FS::cust_pkg;
87
88   $record = new FS::cust_pkg \%hash;
89   $record = new FS::cust_pkg { 'column' => 'value' };
90
91   $error = $record->insert;
92
93   $error = $new_record->replace($old_record);
94
95   $error = $record->delete;
96
97   $error = $record->check;
98
99   $error = $record->cancel;
100
101   $error = $record->suspend;
102
103   $error = $record->unsuspend;
104
105   $part_pkg = $record->part_pkg;
106
107   @labels = $record->labels;
108
109   $seconds = $record->seconds_since($timestamp);
110
111   $error = FS::cust_pkg::order( $custnum, \@pkgparts );
112   $error = FS::cust_pkg::order( $custnum, \@pkgparts, \@remove_pkgnums ] );
113
114 =head1 DESCRIPTION
115
116 An FS::cust_pkg object represents a customer billing item.  FS::cust_pkg
117 inherits from FS::Record.  The following fields are currently supported:
118
119 =over 4
120
121 =item pkgnum
122
123 Primary key (assigned automatically for new billing items)
124
125 =item custnum
126
127 Customer (see L<FS::cust_main>)
128
129 =item pkgpart
130
131 Billing item definition (see L<FS::part_pkg>)
132
133 =item locationnum
134
135 Optional link to package location (see L<FS::location>)
136
137 =item order_date
138
139 date package was ordered (also remains same on changes)
140
141 =item start_date
142
143 date
144
145 =item setup
146
147 date
148
149 =item bill
150
151 date (next bill date)
152
153 =item last_bill
154
155 last bill date
156
157 =item adjourn
158
159 date
160
161 =item susp
162
163 date
164
165 =item expire
166
167 date
168
169 =item contract_end
170
171 date
172
173 =item cancel
174
175 date
176
177 =item usernum
178
179 order taker (see L<FS::access_user>)
180
181 =item manual_flag
182
183 If this field is set to 1, disables the automatic
184 unsuspension of this package when using the B<unsuspendauto> config option.
185
186 =item quantity
187
188 If not set, defaults to 1
189
190 =item change_date
191
192 Date of change from previous package
193
194 =item change_pkgnum
195
196 Previous pkgnum
197
198 =item change_pkgpart
199
200 Previous pkgpart
201
202 =item change_locationnum
203
204 Previous locationnum
205
206 =item waive_setup
207
208 =item main_pkgnum
209
210 The pkgnum of the package that this package is supplemental to, if any.
211
212 =item pkglinknum
213
214 The package link (L<FS::part_pkg_link>) that defines this supplemental
215 package, if it is one.
216
217 =item change_to_pkgnum
218
219 The pkgnum of the package this one will be "changed to" in the future
220 (on its expiration date).
221
222 =back
223
224 Note: setup, last_bill, bill, adjourn, susp, expire, cancel and change_date
225 are specified as UNIX timestamps; see L<perlfunc/"time">.  Also see
226 L<Time::Local> and L<Date::Parse> for conversion functions.
227
228 =head1 METHODS
229
230 =over 4
231
232 =item new HASHREF
233
234 Create a new billing item.  To add the item to the database, see L<"insert">.
235
236 =cut
237
238 sub table { 'cust_pkg'; }
239 sub cust_linked { $_[0]->cust_main_custnum || $_[0]->custnum } 
240 sub cust_unlinked_msg {
241   my $self = shift;
242   "WARNING: can't find cust_main.custnum ". $self->custnum.
243   ' (cust_pkg.pkgnum '. $self->pkgnum. ')';
244 }
245
246 =item insert [ OPTION => VALUE ... ]
247
248 Adds this billing item to the database ("Orders" the item).  If there is an
249 error, returns the error, otherwise returns false.
250
251 If the additional field I<promo_code> is defined instead of I<pkgpart>, it
252 will be used to look up the package definition and agent restrictions will be
253 ignored.
254
255 If the additional field I<refnum> is defined, an FS::pkg_referral record will
256 be created and inserted.  Multiple FS::pkg_referral records can be created by
257 setting I<refnum> to an array reference of refnums or a hash reference with
258 refnums as keys.  If no I<refnum> is defined, a default FS::pkg_referral
259 record will be created corresponding to cust_main.refnum.
260
261 The following options are available:
262
263 =over 4
264
265 =item change
266
267 If set true, supresses actions that should only be taken for new package
268 orders.  (Currently this includes: intro periods when delay_setup is on.)
269
270 =item options
271
272 cust_pkg_option records will be created
273
274 =item ticket_subject
275
276 a ticket will be added to this customer with this subject
277
278 =item ticket_queue
279
280 an optional queue name for ticket additions
281
282 =item allow_pkgpart
283
284 Don't check the legality of the package definition.  This should be used
285 when performing a package change that doesn't change the pkgpart (i.e. 
286 a location change).
287
288 =back
289
290 =cut
291
292 sub insert {
293   my( $self, %options ) = @_;
294
295   my $error;
296   $error = $self->check_pkgpart unless $options{'allow_pkgpart'};
297   return $error if $error;
298
299   my $part_pkg = $self->part_pkg;
300
301   # if the package def says to start only on the first of the month:
302   if ( $part_pkg->option('start_1st', 1) && !$self->start_date ) {
303     my ($sec,$min,$hour,$mday,$mon,$year) = (localtime(time) )[0,1,2,3,4,5];
304     $mon += 1 unless $mday == 1;
305     until ( $mon < 12 ) { $mon -= 12; $year++; }
306     $self->start_date( timelocal_nocheck(0,0,0,1,$mon,$year) );
307   }
308
309   # set up any automatic expire/adjourn/contract_end timers
310   # based on the start date
311   foreach my $action ( qw(expire adjourn contract_end) ) {
312     my $months = $part_pkg->option("${action}_months",1);
313     if($months and !$self->$action) {
314       my $start = $self->start_date || $self->setup || time;
315       $self->$action( $part_pkg->add_freq($start, $months) );
316     }
317   }
318
319   # if this package has "free days" and delayed setup fee, tehn 
320   # set start date that many days in the future.
321   # (this should have been set in the UI, but enforce it here)
322   if (    ! $options{'change'}
323        && ( my $free_days = $part_pkg->option('free_days',1) )
324        && $part_pkg->option('delay_setup',1)
325        #&& ! $self->start_date
326      )
327   {
328     $self->start_date( $part_pkg->default_start_date );
329   }
330
331   $self->order_date(time);
332
333   local $SIG{HUP} = 'IGNORE';
334   local $SIG{INT} = 'IGNORE';
335   local $SIG{QUIT} = 'IGNORE';
336   local $SIG{TERM} = 'IGNORE';
337   local $SIG{TSTP} = 'IGNORE';
338   local $SIG{PIPE} = 'IGNORE';
339
340   my $oldAutoCommit = $FS::UID::AutoCommit;
341   local $FS::UID::AutoCommit = 0;
342   my $dbh = dbh;
343
344   $error = $self->SUPER::insert($options{options} ? %{$options{options}} : ());
345   if ( $error ) {
346     $dbh->rollback if $oldAutoCommit;
347     return $error;
348   }
349
350   $self->refnum($self->cust_main->refnum) unless $self->refnum;
351   $self->refnum( [ $self->refnum ] ) unless ref($self->refnum);
352   $self->process_m2m( 'link_table'   => 'pkg_referral',
353                       'target_table' => 'part_referral',
354                       'params'       => $self->refnum,
355                     );
356
357   if ( $self->discountnum ) {
358     my $error = $self->insert_discount();
359     if ( $error ) {
360       $dbh->rollback if $oldAutoCommit;
361       return $error;
362     }
363   }
364
365   my $conf = new FS::Conf;
366
367   if ( $conf->config('ticket_system') && $options{ticket_subject} ) {
368
369     #this init stuff is still inefficient, but at least its limited to 
370     # the small number (any?) folks using ticket emailing on pkg order
371
372     #eval '
373     #  use lib ( "/opt/rt3/local/lib", "/opt/rt3/lib" );
374     #  use RT;
375     #';
376     #die $@ if $@;
377     #
378     #RT::LoadConfig();
379     #RT::Init();
380     use FS::TicketSystem;
381     FS::TicketSystem->init();
382
383     my $q = new RT::Queue($RT::SystemUser);
384     $q->Load($options{ticket_queue}) if $options{ticket_queue};
385     my $t = new RT::Ticket($RT::SystemUser);
386     my $mime = new MIME::Entity;
387     $mime->build( Type => 'text/plain', Data => $options{ticket_subject} );
388     $t->Create( $options{ticket_queue} ? (Queue => $q) : (),
389                 Subject => $options{ticket_subject},
390                 MIMEObj => $mime,
391               );
392     $t->AddLink( Type   => 'MemberOf',
393                  Target => 'freeside://freeside/cust_main/'. $self->custnum,
394                );
395   }
396
397   if ($conf->config('welcome_letter') && $self->cust_main->num_pkgs == 1) {
398     my $queue = new FS::queue {
399       'job'     => 'FS::cust_main::queueable_print',
400     };
401     $error = $queue->insert(
402       'custnum'  => $self->custnum,
403       'template' => 'welcome_letter',
404     );
405
406     if ($error) {
407       warn "can't send welcome letter: $error";
408     }
409
410   }
411
412   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
413   '';
414
415 }
416
417 =item delete
418
419 This method now works but you probably shouldn't use it.
420
421 You don't want to delete packages, because there would then be no record
422 the customer ever purchased the package.  Instead, see the cancel method and
423 hide cancelled packages.
424
425 =cut
426
427 sub delete {
428   my $self = shift;
429
430   local $SIG{HUP} = 'IGNORE';
431   local $SIG{INT} = 'IGNORE';
432   local $SIG{QUIT} = 'IGNORE';
433   local $SIG{TERM} = 'IGNORE';
434   local $SIG{TSTP} = 'IGNORE';
435   local $SIG{PIPE} = 'IGNORE';
436
437   my $oldAutoCommit = $FS::UID::AutoCommit;
438   local $FS::UID::AutoCommit = 0;
439   my $dbh = dbh;
440
441   foreach my $cust_pkg_discount ($self->cust_pkg_discount) {
442     my $error = $cust_pkg_discount->delete;
443     if ( $error ) {
444       $dbh->rollback if $oldAutoCommit;
445       return $error;
446     }
447   }
448   #cust_bill_pkg_discount?
449
450   foreach my $cust_pkg_detail ($self->cust_pkg_detail) {
451     my $error = $cust_pkg_detail->delete;
452     if ( $error ) {
453       $dbh->rollback if $oldAutoCommit;
454       return $error;
455     }
456   }
457
458   foreach my $cust_pkg_reason (
459     qsearchs( {
460                 'table' => 'cust_pkg_reason',
461                 'hashref' => { 'pkgnum' => $self->pkgnum },
462               }
463             )
464   ) {
465     my $error = $cust_pkg_reason->delete;
466     if ( $error ) {
467       $dbh->rollback if $oldAutoCommit;
468       return $error;
469     }
470   }
471
472   #pkg_referral?
473
474   my $error = $self->SUPER::delete(@_);
475   if ( $error ) {
476     $dbh->rollback if $oldAutoCommit;
477     return $error;
478   }
479
480   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
481
482   '';
483
484 }
485
486 =item replace [ OLD_RECORD ] [ HASHREF | OPTION => VALUE ... ]
487
488 Replaces the OLD_RECORD with this one in the database.  If there is an error,
489 returns the error, otherwise returns false.
490
491 Currently, custnum, setup, bill, adjourn, susp, expire, and cancel may be changed.
492
493 Changing pkgpart may have disasterous effects.  See the order subroutine.
494
495 setup and bill are normally updated by calling the bill method of a customer
496 object (see L<FS::cust_main>).
497
498 suspend is normally updated by the suspend and unsuspend methods.
499
500 cancel is normally updated by the cancel method (and also the order subroutine
501 in some cases).
502
503 Available options are:
504
505 =over 4
506
507 =item reason
508
509 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.
510
511 =item reason_otaker
512
513 the access_user (see L<FS::access_user>) providing the reason
514
515 =item options
516
517 hashref of keys and values - cust_pkg_option records will be created, updated or removed as appopriate
518
519 =back
520
521 =cut
522
523 sub replace {
524   my $new = shift;
525
526   my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
527               ? shift
528               : $new->replace_old;
529
530   my $options = 
531     ( ref($_[0]) eq 'HASH' )
532       ? shift
533       : { @_ };
534
535   #return "Can't (yet?) change pkgpart!" if $old->pkgpart != $new->pkgpart;
536   #return "Can't change otaker!" if $old->otaker ne $new->otaker;
537
538   #allow this *sigh*
539   #return "Can't change setup once it exists!"
540   #  if $old->getfield('setup') &&
541   #     $old->getfield('setup') != $new->getfield('setup');
542
543   #some logic for bill, susp, cancel?
544
545   local($disable_agentcheck) = 1 if $old->pkgpart == $new->pkgpart;
546
547   local $SIG{HUP} = 'IGNORE';
548   local $SIG{INT} = 'IGNORE';
549   local $SIG{QUIT} = 'IGNORE';
550   local $SIG{TERM} = 'IGNORE';
551   local $SIG{TSTP} = 'IGNORE';
552   local $SIG{PIPE} = 'IGNORE';
553
554   my $oldAutoCommit = $FS::UID::AutoCommit;
555   local $FS::UID::AutoCommit = 0;
556   my $dbh = dbh;
557
558   foreach my $method ( qw(adjourn expire) ) {  # How many reasons?
559     if ($options->{'reason'} && $new->$method && $old->$method ne $new->$method) {
560       my $error = $new->insert_reason(
561         'reason'        => $options->{'reason'},
562         'date'          => $new->$method,
563         'action'        => $method,
564         'reason_otaker' => $options->{'reason_otaker'},
565       );
566       if ( $error ) {
567         dbh->rollback if $oldAutoCommit;
568         return "Error inserting cust_pkg_reason: $error";
569       }
570     }
571   }
572
573   #save off and freeze RADIUS attributes for any associated svc_acct records
574   my @svc_acct = ();
575   if ( $old->part_pkg->is_prepaid || $new->part_pkg->is_prepaid ) {
576
577                 #also check for specific exports?
578                 # to avoid spurious modify export events
579     @svc_acct = map  { $_->svc_x }
580                 grep { $_->part_svc->svcdb eq 'svc_acct' }
581                      $old->cust_svc;
582
583     $_->snapshot foreach @svc_acct;
584
585   }
586
587   my $error =  $new->export_pkg_change($old)
588             || $new->SUPER::replace( $old,
589                                      $options->{options}
590                                        ? $options->{options}
591                                        : ()
592                                    );
593   if ( $error ) {
594     $dbh->rollback if $oldAutoCommit;
595     return $error;
596   }
597
598   #for prepaid packages,
599   #trigger export of new RADIUS Expiration attribute when cust_pkg.bill changes
600   foreach my $old_svc_acct ( @svc_acct ) {
601     my $new_svc_acct = new FS::svc_acct { $old_svc_acct->hash };
602     my $s_error =
603       $new_svc_acct->replace( $old_svc_acct,
604                               'depend_jobnum' => $options->{depend_jobnum},
605                             );
606     if ( $s_error ) {
607       $dbh->rollback if $oldAutoCommit;
608       return $s_error;
609     }
610   }
611
612   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
613   '';
614
615 }
616
617 =item check
618
619 Checks all fields to make sure this is a valid billing item.  If there is an
620 error, returns the error, otherwise returns false.  Called by the insert and
621 replace methods.
622
623 =cut
624
625 sub check {
626   my $self = shift;
627
628   if ( !$self->locationnum or $self->locationnum == -1 ) {
629     $self->set('locationnum', $self->cust_main->ship_locationnum);
630   }
631
632   my $error = 
633     $self->ut_numbern('pkgnum')
634     || $self->ut_foreign_key('custnum', 'cust_main', 'custnum')
635     || $self->ut_numbern('pkgpart')
636     || $self->ut_foreign_keyn('contactnum',  'contact',       'contactnum' )
637     || $self->ut_foreign_keyn('locationnum', 'cust_location', 'locationnum')
638     || $self->ut_foreign_keyn('salesnum', 'sales', 'salesnum')
639     || $self->ut_numbern('quantity')
640     || $self->ut_numbern('start_date')
641     || $self->ut_numbern('setup')
642     || $self->ut_numbern('bill')
643     || $self->ut_numbern('susp')
644     || $self->ut_numbern('cancel')
645     || $self->ut_numbern('adjourn')
646     || $self->ut_numbern('resume')
647     || $self->ut_numbern('expire')
648     || $self->ut_numbern('dundate')
649     || $self->ut_enum('no_auto', [ '', 'Y' ])
650     || $self->ut_enum('waive_setup', [ '', 'Y' ])
651     || $self->ut_numbern('agent_pkgid')
652     || $self->ut_enum('recur_show_zero', [ '', 'Y', 'N', ])
653     || $self->ut_enum('setup_show_zero', [ '', 'Y', 'N', ])
654     || $self->ut_foreign_keyn('main_pkgnum', 'cust_pkg', 'pkgnum')
655     || $self->ut_foreign_keyn('pkglinknum', 'part_pkg_link', 'pkglinknum')
656     || $self->ut_foreign_keyn('change_to_pkgnum', 'cust_pkg', 'pkgnum')
657   ;
658   return $error if $error;
659
660   return "A package with both start date (future start) and setup date (already started) will never bill"
661     if $self->start_date && $self->setup && ! $upgrade;
662
663   return "A future unsuspend date can only be set for a package with a suspend date"
664     if $self->resume and !$self->susp and !$self->adjourn;
665
666   $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
667
668   if ( $self->dbdef_table->column('manual_flag') ) {
669     $self->manual_flag('') if $self->manual_flag eq ' ';
670     $self->manual_flag =~ /^([01]?)$/
671       or return "Illegal manual_flag ". $self->manual_flag;
672     $self->manual_flag($1);
673   }
674
675   $self->SUPER::check;
676 }
677
678 =item check_pkgpart
679
680 Check the pkgpart to make sure it's allowed with the reg_code and/or
681 promo_code of the package (if present) and with the customer's agent.
682 Called from C<insert>, unless we are doing a package change that doesn't
683 affect pkgpart.
684
685 =cut
686
687 sub check_pkgpart {
688   my $self = shift;
689
690   # my $error = $self->ut_numbern('pkgpart'); # already done
691
692   my $error;
693   if ( $self->reg_code ) {
694
695     unless ( grep { $self->pkgpart == $_->pkgpart }
696              map  { $_->reg_code_pkg }
697              qsearchs( 'reg_code', { 'code'     => $self->reg_code,
698                                      'agentnum' => $self->cust_main->agentnum })
699            ) {
700       return "Unknown registration code";
701     }
702
703   } elsif ( $self->promo_code ) {
704
705     my $promo_part_pkg =
706       qsearchs('part_pkg', {
707         'pkgpart'    => $self->pkgpart,
708         'promo_code' => { op=>'ILIKE', value=>$self->promo_code },
709       } );
710     return 'Unknown promotional code' unless $promo_part_pkg;
711
712   } else { 
713
714     unless ( $disable_agentcheck ) {
715       my $agent =
716         qsearchs( 'agent', { 'agentnum' => $self->cust_main->agentnum } );
717       return "agent ". $agent->agentnum. ':'. $agent->agent.
718              " can't purchase pkgpart ". $self->pkgpart
719         unless $agent->pkgpart_hashref->{ $self->pkgpart }
720             || $agent->agentnum == $self->part_pkg->agentnum;
721     }
722
723     $error = $self->ut_foreign_key('pkgpart', 'part_pkg', 'pkgpart' );
724     return $error if $error;
725
726   }
727
728   '';
729
730 }
731
732 =item cancel [ OPTION => VALUE ... ]
733
734 Cancels and removes all services (see L<FS::cust_svc> and L<FS::part_svc>)
735 in this package, then cancels the package itself (sets the cancel field to
736 now).
737
738 Available options are:
739
740 =over 4
741
742 =item quiet - can be set true to supress email cancellation notices.
743
744 =item time -  can be set to cancel the package based on a specific future or 
745 historical date.  Using time ensures that the remaining amount is calculated 
746 correctly.  Note however that this is an immediate cancel and just changes 
747 the date.  You are PROBABLY looking to expire the account instead of using 
748 this.
749
750 =item reason - can be set to a cancellation reason (see L<FS:reason>), 
751 either a reasonnum of an existing reason, or passing a hashref will create 
752 a new reason.  The hashref should have the following keys: typenum - Reason 
753 type (see L<FS::reason_type>, reason - Text of the new reason.
754
755 =item date - can be set to a unix style timestamp to specify when to 
756 cancel (expire)
757
758 =item nobill - can be set true to skip billing if it might otherwise be done.
759
760 =item unused_credit - can be set to 1 to credit the remaining time, or 0 to 
761 not credit it.  This must be set (by change()) when changing the package 
762 to a different pkgpart or location, and probably shouldn't be in any other 
763 case.  If it's not set, the 'unused_credit_cancel' part_pkg option will 
764 be used.
765
766 =back
767
768 If there is an error, returns the error, otherwise returns false.
769
770 =cut
771
772 sub cancel {
773   my( $self, %options ) = @_;
774   my $error;
775
776   # pass all suspend/cancel actions to the main package
777   if ( $self->main_pkgnum and !$options{'from_main'} ) {
778     return $self->main_pkg->cancel(%options);
779   }
780
781   my $conf = new FS::Conf;
782
783   warn "cust_pkg::cancel called with options".
784        join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
785     if $DEBUG;
786
787   local $SIG{HUP} = 'IGNORE';
788   local $SIG{INT} = 'IGNORE';
789   local $SIG{QUIT} = 'IGNORE'; 
790   local $SIG{TERM} = 'IGNORE';
791   local $SIG{TSTP} = 'IGNORE';
792   local $SIG{PIPE} = 'IGNORE';
793
794   my $oldAutoCommit = $FS::UID::AutoCommit;
795   local $FS::UID::AutoCommit = 0;
796   my $dbh = dbh;
797   
798   my $old = $self->select_for_update;
799
800   if ( $old->get('cancel') || $self->get('cancel') ) {
801     dbh->rollback if $oldAutoCommit;
802     return "";  # no error
803   }
804
805   # XXX possibly set cancel_time to the expire date?
806   my $cancel_time = $options{'time'} || time;
807   my $date = $options{'date'} if $options{'date'}; # expire/cancel later
808   $date = '' if ($date && $date <= $cancel_time);      # complain instead?
809
810   #race condition: usage could be ongoing until unprovisioned
811   #resolved by performing a change package instead (which unprovisions) and
812   #later cancelling
813   if ( !$options{nobill} && !$date ) {
814     # && $conf->exists('bill_usage_on_cancel') ) { #calc_cancel checks this
815       my $copy = $self->new({$self->hash});
816       my $error =
817         $copy->cust_main->bill( 'pkg_list' => [ $copy ], 
818                                 'cancel'   => 1,
819                                 'time'     => $cancel_time );
820       warn "Error billing during cancel, custnum ".
821         #$self->cust_main->custnum. ": $error"
822         ": $error"
823         if $error;
824   }
825
826   if ( $options{'reason'} ) {
827     $error = $self->insert_reason( 'reason' => $options{'reason'},
828                                    'action' => $date ? 'expire' : 'cancel',
829                                    'date'   => $date ? $date : $cancel_time,
830                                    'reason_otaker' => $options{'reason_otaker'},
831                                  );
832     if ( $error ) {
833       dbh->rollback if $oldAutoCommit;
834       return "Error inserting cust_pkg_reason: $error";
835     }
836   }
837
838   my %svc_cancel_opt = ();
839   $svc_cancel_opt{'date'} = $date if $date;
840   foreach my $cust_svc (
841     #schwartz
842     map  { $_->[0] }
843     sort { $a->[1] <=> $b->[1] }
844     map  { [ $_, $_->svc_x ? $_->svc_x->table_info->{'cancel_weight'} : -1 ]; }
845     qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
846   ) {
847     my $part_svc = $cust_svc->part_svc;
848     next if ( defined($part_svc) and $part_svc->preserve );
849     my $error = $cust_svc->cancel( %svc_cancel_opt );
850
851     if ( $error ) {
852       $dbh->rollback if $oldAutoCommit;
853       return 'Error '. ($svc_cancel_opt{'date'} ? 'expiring' : 'canceling' ).
854              " cust_svc: $error";
855     }
856   }
857
858   unless ($date) {
859     # credit remaining time if appropriate
860     my $do_credit;
861     if ( exists($options{'unused_credit'}) ) {
862       $do_credit = $options{'unused_credit'};
863     }
864     else {
865       $do_credit = $self->part_pkg->option('unused_credit_cancel', 1);
866     }
867     if ( $do_credit ) {
868       my $error = $self->credit_remaining('cancel', $cancel_time);
869       if ($error) {
870         $dbh->rollback if $oldAutoCommit;
871         return $error;
872       }
873     }
874
875   } #unless $date
876
877   my %hash = $self->hash;
878   if ( $date ) {
879     $hash{'expire'} = $date;
880   } else {
881     $hash{'cancel'} = $cancel_time;
882   }
883   $hash{'change_custnum'} = $options{'change_custnum'};
884
885   my $new = new FS::cust_pkg ( \%hash );
886   $error = $new->replace( $self, options => { $self->options } );
887   if ( $self->change_to_pkgnum ) {
888     my $change_to = FS::cust_pkg->by_key($self->change_to_pkgnum);
889     $error ||= $change_to->cancel || $change_to->delete;
890   }
891   if ( $error ) {
892     $dbh->rollback if $oldAutoCommit;
893     return $error;
894   }
895
896   foreach my $supp_pkg ( $self->supplemental_pkgs ) {
897     $error = $supp_pkg->cancel(%options, 'from_main' => 1);
898     if ( $error ) {
899       $dbh->rollback if $oldAutoCommit;
900       return "canceling supplemental pkg#".$supp_pkg->pkgnum.": $error";
901     }
902   }
903
904   foreach my $usage ( $self->cust_pkg_usage ) {
905     $error = $usage->delete;
906     if ( $error ) {
907       $dbh->rollback if $oldAutoCommit;
908       return "deleting usage pools: $error";
909     }
910   }
911
912   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
913   return '' if $date; #no errors
914
915   my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ } $self->cust_main->invoicing_list;
916   if ( !$options{'quiet'} && 
917         $conf->exists('emailcancel', $self->cust_main->agentnum) && 
918         @invoicing_list ) {
919     my $msgnum = $conf->config('cancel_msgnum', $self->cust_main->agentnum);
920     my $error = '';
921     if ( $msgnum ) {
922       my $msg_template = qsearchs('msg_template', { msgnum => $msgnum });
923       $error = $msg_template->send( 'cust_main' => $self->cust_main,
924                                     'object'    => $self );
925     }
926     else {
927       $error = send_email(
928         'from'    => $conf->config('invoice_from', $self->cust_main->agentnum),
929         'to'      => \@invoicing_list,
930         'subject' => ( $conf->config('cancelsubject') || 'Cancellation Notice' ),
931         'body'    => [ map "$_\n", $conf->config('cancelmessage') ],
932       );
933     }
934     #should this do something on errors?
935   }
936
937   ''; #no errors
938
939 }
940
941 =item cancel_if_expired [ NOW_TIMESTAMP ]
942
943 Cancels this package if its expire date has been reached.
944
945 =cut
946
947 sub cancel_if_expired {
948   my $self = shift;
949   my $time = shift || time;
950   return '' unless $self->expire && $self->expire <= $time;
951   my $error = $self->cancel;
952   if ( $error ) {
953     return "Error cancelling expired pkg ". $self->pkgnum. " for custnum ".
954            $self->custnum. ": $error";
955   }
956   '';
957 }
958
959 =item uncancel
960
961 "Un-cancels" this package: Orders a new package with the same custnum, pkgpart,
962 locationnum, (other fields?).  Attempts to re-provision cancelled services
963 using history information (errors at this stage are not fatal).
964
965 cust_pkg: pass a scalar reference, will be filled in with the new cust_pkg object
966
967 svc_fatal: service provisioning errors are fatal
968
969 svc_errors: pass an array reference, will be filled in with any provisioning errors
970
971 main_pkgnum: link the package as a supplemental package of this one.  For 
972 internal use only.
973
974 =cut
975
976 sub uncancel {
977   my( $self, %options ) = @_;
978
979   #in case you try do do $uncancel-date = $cust_pkg->uncacel 
980   return '' unless $self->get('cancel');
981
982   if ( $self->main_pkgnum and !$options{'main_pkgnum'} ) {
983     return $self->main_pkg->uncancel(%options);
984   }
985
986   ##
987   # Transaction-alize
988   ##
989
990   local $SIG{HUP} = 'IGNORE';
991   local $SIG{INT} = 'IGNORE'; 
992   local $SIG{QUIT} = 'IGNORE';
993   local $SIG{TERM} = 'IGNORE';
994   local $SIG{TSTP} = 'IGNORE'; 
995   local $SIG{PIPE} = 'IGNORE'; 
996
997   my $oldAutoCommit = $FS::UID::AutoCommit;
998   local $FS::UID::AutoCommit = 0;
999   my $dbh = dbh;
1000
1001   ##
1002   # insert the new package
1003   ##
1004
1005   my $cust_pkg = new FS::cust_pkg {
1006     last_bill       => ( $options{'last_bill'} || $self->get('last_bill') ),
1007     bill            => ( $options{'bill'}      || $self->get('bill')      ),
1008     uncancel        => time,
1009     uncancel_pkgnum => $self->pkgnum,
1010     main_pkgnum     => ($options{'main_pkgnum'} || ''),
1011     map { $_ => $self->get($_) } qw(
1012       custnum pkgpart locationnum
1013       setup
1014       susp adjourn resume expire start_date contract_end dundate
1015       change_date change_pkgpart change_locationnum
1016       manual_flag no_auto quantity agent_pkgid recur_show_zero setup_show_zero
1017     ),
1018   };
1019
1020   my $error = $cust_pkg->insert(
1021     'change' => 1, #supresses any referral credit to a referring customer
1022     'allow_pkgpart' => 1, # allow this even if the package def is disabled
1023   );
1024   if ($error) {
1025     $dbh->rollback if $oldAutoCommit;
1026     return $error;
1027   }
1028
1029   ##
1030   # insert services
1031   ##
1032
1033   #find historical services within this timeframe before the package cancel
1034   # (incompatible with "time" option to cust_pkg->cancel?)
1035   my $fuzz = 2 * 60; #2 minutes?  too much?   (might catch separate unprovision)
1036                      #            too little? (unprovisioing export delay?)
1037   my($end, $start) = ( $self->get('cancel'), $self->get('cancel') - $fuzz );
1038   my @h_cust_svc = $self->h_cust_svc( $end, $start );
1039
1040   my @svc_errors;
1041   foreach my $h_cust_svc (@h_cust_svc) {
1042     my $h_svc_x = $h_cust_svc->h_svc_x( $end, $start );
1043     #next unless $h_svc_x; #should this happen?
1044     (my $table = $h_svc_x->table) =~ s/^h_//;
1045     require "FS/$table.pm";
1046     my $class = "FS::$table";
1047     my $svc_x = $class->new( {
1048       'pkgnum'  => $cust_pkg->pkgnum,
1049       'svcpart' => $h_cust_svc->svcpart,
1050       map { $_ => $h_svc_x->get($_) } fields($table)
1051     } );
1052
1053     # radius_usergroup
1054     if ( $h_svc_x->isa('FS::h_svc_Radius_Mixin') ) {
1055       $svc_x->usergroup( [ $h_svc_x->h_usergroup($end, $start) ] );
1056     }
1057
1058     my $svc_error = $svc_x->insert;
1059     if ( $svc_error ) {
1060       if ( $options{svc_fatal} ) {
1061         $dbh->rollback if $oldAutoCommit;
1062         return $svc_error;
1063       } else {
1064         # if we've failed to insert the svc_x object, svc_Common->insert 
1065         # will have removed the cust_svc already.  if not, then both records
1066         # were inserted but we failed for some other reason (export, most 
1067         # likely).  in that case, report the error and delete the records.
1068         push @svc_errors, $svc_error;
1069         my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svc_x->svcnum });
1070         if ( $cust_svc ) {
1071           # except if export_insert failed, export_delete probably won't be
1072           # much better
1073           local $FS::svc_Common::noexport_hack = 1;
1074           my $cleanup_error = $svc_x->delete; # also deletes cust_svc
1075           if ( $cleanup_error ) { # and if THAT fails, then run away
1076             $dbh->rollback if $oldAutoCommit;
1077             return $cleanup_error;
1078           }
1079         }
1080       } # svc_fatal
1081     } # svc_error
1082   } #foreach $h_cust_svc
1083
1084   #these are pretty rare, but should handle them
1085   # - dsl_device (mac addresses)
1086   # - phone_device (mac addresses)
1087   # - dsl_note (ikano notes)
1088   # - domain_record (i.e. restore DNS information w/domains)
1089   # - inventory_item(?) (inventory w/un-cancelling service?)
1090   # - nas (svc_broaband nas stuff)
1091   #this stuff is unused in the wild afaik
1092   # - mailinglistmember
1093   # - router.svcnum?
1094   # - svc_domain.parent_svcnum?
1095   # - acct_snarf (ancient mail fetching config)
1096   # - cgp_rule (communigate)
1097   # - cust_svc_option (used by our Tron stuff)
1098   # - acct_rt_transaction (used by our time worked stuff)
1099
1100   ##
1101   # also move over any services that didn't unprovision at cancellation
1102   ## 
1103
1104   foreach my $cust_svc ( qsearch('cust_svc', { pkgnum => $self->pkgnum } ) ) {
1105     $cust_svc->pkgnum( $cust_pkg->pkgnum );
1106     my $error = $cust_svc->replace;
1107     if ( $error ) {
1108       $dbh->rollback if $oldAutoCommit;
1109       return $error;
1110     }
1111   }
1112
1113   ##
1114   # Uncancel any supplemental packages, and make them supplemental to the 
1115   # new one.
1116   ##
1117
1118   foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1119     my $new_pkg;
1120     $error = $supp_pkg->uncancel(%options, 'main_pkgnum' => $cust_pkg->pkgnum);
1121     if ( $error ) {
1122       $dbh->rollback if $oldAutoCommit;
1123       return "canceling supplemental pkg#".$supp_pkg->pkgnum.": $error";
1124     }
1125   }
1126
1127   ##
1128   # Finish
1129   ##
1130
1131   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1132
1133   ${ $options{cust_pkg} }   = $cust_pkg   if ref($options{cust_pkg});
1134   @{ $options{svc_errors} } = @svc_errors if ref($options{svc_errors});
1135
1136   '';
1137 }
1138
1139 =item unexpire
1140
1141 Cancels any pending expiration (sets the expire field to null).
1142
1143 If there is an error, returns the error, otherwise returns false.
1144
1145 =cut
1146
1147 sub unexpire {
1148   my( $self, %options ) = @_;
1149   my $error;
1150
1151   local $SIG{HUP} = 'IGNORE';
1152   local $SIG{INT} = 'IGNORE';
1153   local $SIG{QUIT} = 'IGNORE';
1154   local $SIG{TERM} = 'IGNORE';
1155   local $SIG{TSTP} = 'IGNORE';
1156   local $SIG{PIPE} = 'IGNORE';
1157
1158   my $oldAutoCommit = $FS::UID::AutoCommit;
1159   local $FS::UID::AutoCommit = 0;
1160   my $dbh = dbh;
1161
1162   my $old = $self->select_for_update;
1163
1164   my $pkgnum = $old->pkgnum;
1165   if ( $old->get('cancel') || $self->get('cancel') ) {
1166     dbh->rollback if $oldAutoCommit;
1167     return "Can't unexpire cancelled package $pkgnum";
1168     # or at least it's pointless
1169   }
1170
1171   unless ( $old->get('expire') && $self->get('expire') ) {
1172     dbh->rollback if $oldAutoCommit;
1173     return "";  # no error
1174   }
1175
1176   my %hash = $self->hash;
1177   $hash{'expire'} = '';
1178   my $new = new FS::cust_pkg ( \%hash );
1179   $error = $new->replace( $self, options => { $self->options } );
1180   if ( $error ) {
1181     $dbh->rollback if $oldAutoCommit;
1182     return $error;
1183   }
1184
1185   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1186
1187   ''; #no errors
1188
1189 }
1190
1191 =item suspend [ OPTION => VALUE ... ]
1192
1193 Suspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
1194 package, then suspends the package itself (sets the susp field to now).
1195
1196 Available options are:
1197
1198 =over 4
1199
1200 =item reason - can be set to a cancellation reason (see L<FS:reason>), 
1201 either a reasonnum of an existing reason, or passing a hashref will create 
1202 a new reason.  The hashref should have the following keys: 
1203 - typenum - Reason type (see L<FS::reason_type>
1204 - reason - Text of the new reason.
1205
1206 =item date - can be set to a unix style timestamp to specify when to 
1207 suspend (adjourn)
1208
1209 =item time - can be set to override the current time, for calculation 
1210 of final invoices or unused-time credits
1211
1212 =item resume_date - can be set to a time when the package should be 
1213 unsuspended.  This may be more convenient than calling C<unsuspend()>
1214 separately.
1215
1216 =item from_main - allows a supplemental package to be suspended, rather
1217 than redirecting the method call to its main package.  For internal use.
1218
1219 =back
1220
1221 If there is an error, returns the error, otherwise returns false.
1222
1223 =cut
1224
1225 sub suspend {
1226   my( $self, %options ) = @_;
1227   my $error;
1228
1229   # pass all suspend/cancel actions to the main package
1230   if ( $self->main_pkgnum and !$options{'from_main'} ) {
1231     return $self->main_pkg->suspend(%options);
1232   }
1233
1234   local $SIG{HUP} = 'IGNORE';
1235   local $SIG{INT} = 'IGNORE';
1236   local $SIG{QUIT} = 'IGNORE'; 
1237   local $SIG{TERM} = 'IGNORE';
1238   local $SIG{TSTP} = 'IGNORE';
1239   local $SIG{PIPE} = 'IGNORE';
1240
1241   my $oldAutoCommit = $FS::UID::AutoCommit;
1242   local $FS::UID::AutoCommit = 0;
1243   my $dbh = dbh;
1244
1245   my $old = $self->select_for_update;
1246
1247   my $pkgnum = $old->pkgnum;
1248   if ( $old->get('cancel') || $self->get('cancel') ) {
1249     dbh->rollback if $oldAutoCommit;
1250     return "Can't suspend cancelled package $pkgnum";
1251   }
1252
1253   if ( $old->get('susp') || $self->get('susp') ) {
1254     dbh->rollback if $oldAutoCommit;
1255     return "";  # no error                     # complain on adjourn?
1256   }
1257
1258   my $suspend_time = $options{'time'} || time;
1259   my $date = $options{date} if $options{date}; # adjourn/suspend later
1260   $date = '' if ($date && $date <= $suspend_time); # complain instead?
1261
1262   if ( $date && $old->get('expire') && $old->get('expire') < $date ) {
1263     dbh->rollback if $oldAutoCommit;
1264     return "Package $pkgnum expires before it would be suspended.";
1265   }
1266
1267   # some false laziness with sub cancel
1268   if ( !$options{nobill} && !$date &&
1269        $self->part_pkg->option('bill_suspend_as_cancel',1) ) {
1270     # kind of a kludge--'bill_suspend_as_cancel' to avoid having to 
1271     # make the entire cust_main->bill path recognize 'suspend' and 
1272     # 'cancel' separately.
1273     warn "Billing $pkgnum on suspension (at $suspend_time)\n" if $DEBUG;
1274     my $copy = $self->new({$self->hash});
1275     my $error =
1276       $copy->cust_main->bill( 'pkg_list' => [ $copy ], 
1277                               'cancel'   => 1,
1278                               'time'     => $suspend_time );
1279     warn "Error billing during suspend, custnum ".
1280       #$self->cust_main->custnum. ": $error"
1281       ": $error"
1282       if $error;
1283   }
1284
1285   if ( $options{'reason'} ) {
1286     $error = $self->insert_reason( 'reason' => $options{'reason'},
1287                                    'action' => $date ? 'adjourn' : 'suspend',
1288                                    'date'   => $date ? $date : $suspend_time,
1289                                    'reason_otaker' => $options{'reason_otaker'},
1290                                  );
1291     if ( $error ) {
1292       dbh->rollback if $oldAutoCommit;
1293       return "Error inserting cust_pkg_reason: $error";
1294     }
1295   }
1296
1297   my %hash = $self->hash;
1298   if ( $date ) {
1299     $hash{'adjourn'} = $date;
1300   } else {
1301     $hash{'susp'} = $suspend_time;
1302   }
1303
1304   my $resume_date = $options{'resume_date'} || 0;
1305   if ( $resume_date > ($date || $suspend_time) ) {
1306     $hash{'resume'} = $resume_date;
1307   }
1308
1309   $options{options} ||= {};
1310
1311   my $new = new FS::cust_pkg ( \%hash );
1312   $error = $new->replace( $self, options => { $self->options,
1313                                               %{ $options{options} },
1314                                             }
1315                         );
1316   if ( $error ) {
1317     $dbh->rollback if $oldAutoCommit;
1318     return $error;
1319   }
1320
1321   unless ( $date ) {
1322     # credit remaining time if appropriate
1323     if ( $self->part_pkg->option('unused_credit_suspend', 1) ) {
1324       my $error = $self->credit_remaining('suspend', $suspend_time);
1325       if ($error) {
1326         $dbh->rollback if $oldAutoCommit;
1327         return $error;
1328       }
1329     }
1330
1331     my @labels = ();
1332
1333     foreach my $cust_svc (
1334       qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
1335     ) {
1336       my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
1337
1338       $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
1339         $dbh->rollback if $oldAutoCommit;
1340         return "Illegal svcdb value in part_svc!";
1341       };
1342       my $svcdb = $1;
1343       require "FS/$svcdb.pm";
1344
1345       my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
1346       if ($svc) {
1347         $error = $svc->suspend;
1348         if ( $error ) {
1349           $dbh->rollback if $oldAutoCommit;
1350           return $error;
1351         }
1352         my( $label, $value ) = $cust_svc->label;
1353         push @labels, "$label: $value";
1354       }
1355     }
1356
1357     my $conf = new FS::Conf;
1358     if ( $conf->config('suspend_email_admin') ) {
1359  
1360       my $error = send_email(
1361         'from'    => $conf->config('invoice_from', $self->cust_main->agentnum),
1362                                    #invoice_from ??? well as good as any
1363         'to'      => $conf->config('suspend_email_admin'),
1364         'subject' => 'FREESIDE NOTIFICATION: Customer package suspended',
1365         'body'    => [
1366           "This is an automatic message from your Freeside installation\n",
1367           "informing you that the following customer package has been suspended:\n",
1368           "\n",
1369           'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
1370           'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
1371           ( map { "Service : $_\n" } @labels ),
1372         ],
1373       );
1374
1375       if ( $error ) {
1376         warn "WARNING: can't send suspension admin email (suspending anyway): ".
1377              "$error\n";
1378       }
1379
1380     }
1381
1382   }
1383
1384   foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1385     $error = $supp_pkg->suspend(%options, 'from_main' => 1);
1386     if ( $error ) {
1387       $dbh->rollback if $oldAutoCommit;
1388       return "suspending supplemental pkg#".$supp_pkg->pkgnum.": $error";
1389     }
1390   }
1391
1392   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1393
1394   ''; #no errors
1395 }
1396
1397 =item credit_remaining MODE TIME
1398
1399 Generate a credit for this package for the time remaining in the current 
1400 billing period.  MODE is either "suspend" or "cancel" (determines the 
1401 credit type).  TIME is the time of suspension/cancellation.  Both arguments
1402 are mandatory.
1403
1404 =cut
1405
1406 sub credit_remaining {
1407   # Add a credit for remaining service
1408   my ($self, $mode, $time) = @_;
1409   die 'credit_remaining requires suspend or cancel' 
1410     unless $mode eq 'suspend' or $mode eq 'cancel';
1411   die 'no suspend/cancel time' unless $time > 0;
1412
1413   my $conf = FS::Conf->new;
1414   my $reason_type = $conf->config($mode.'_credit_type');
1415
1416   my $last_bill = $self->getfield('last_bill') || 0;
1417   my $next_bill = $self->getfield('bill') || 0;
1418   if ( $last_bill > 0         # the package has been billed
1419       and $next_bill > 0      # the package has a next bill date
1420       and $next_bill >= $time # which is in the future
1421   ) {
1422     my $remaining_value = $self->calc_remain('time' => $time);
1423     if ( $remaining_value > 0 ) {
1424       warn "Crediting for $remaining_value on package ".$self->pkgnum."\n"
1425         if $DEBUG;
1426       my $error = $self->cust_main->credit(
1427         $remaining_value,
1428         'Credit for unused time on '. $self->part_pkg->pkg,
1429         'reason_type' => $reason_type,
1430       );
1431       return "Error crediting customer \$$remaining_value for unused time".
1432         " on ". $self->part_pkg->pkg. ": $error"
1433         if $error;
1434     } #if $remaining_value
1435   } #if $last_bill, etc.
1436   '';
1437 }
1438
1439 =item unsuspend [ OPTION => VALUE ... ]
1440
1441 Unsuspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
1442 package, then unsuspends the package itself (clears the susp field and the
1443 adjourn field if it is in the past).  If the suspend reason includes an 
1444 unsuspension package, that package will be ordered.
1445
1446 Available options are:
1447
1448 =over 4
1449
1450 =item date
1451
1452 Can be set to a date to unsuspend the package in the future (the 'resume' 
1453 field).
1454
1455 =item adjust_next_bill
1456
1457 Can be set true to adjust the next bill date forward by
1458 the amount of time the account was inactive.  This was set true by default
1459 in the past (from 1.4.2 and 1.5.0pre6 through 1.7.0), but now needs to be
1460 explicitly requested with this option or in the price plan.
1461
1462 =back
1463
1464 If there is an error, returns the error, otherwise returns false.
1465
1466 =cut
1467
1468 sub unsuspend {
1469   my( $self, %opt ) = @_;
1470   my $error;
1471
1472   # pass all suspend/cancel actions to the main package
1473   if ( $self->main_pkgnum and !$opt{'from_main'} ) {
1474     return $self->main_pkg->unsuspend(%opt);
1475   }
1476
1477   local $SIG{HUP} = 'IGNORE';
1478   local $SIG{INT} = 'IGNORE';
1479   local $SIG{QUIT} = 'IGNORE'; 
1480   local $SIG{TERM} = 'IGNORE';
1481   local $SIG{TSTP} = 'IGNORE';
1482   local $SIG{PIPE} = 'IGNORE';
1483
1484   my $oldAutoCommit = $FS::UID::AutoCommit;
1485   local $FS::UID::AutoCommit = 0;
1486   my $dbh = dbh;
1487
1488   my $old = $self->select_for_update;
1489
1490   my $pkgnum = $old->pkgnum;
1491   if ( $old->get('cancel') || $self->get('cancel') ) {
1492     $dbh->rollback if $oldAutoCommit;
1493     return "Can't unsuspend cancelled package $pkgnum";
1494   }
1495
1496   unless ( $old->get('susp') && $self->get('susp') ) {
1497     $dbh->rollback if $oldAutoCommit;
1498     return "";  # no error                     # complain instead?
1499   }
1500
1501   my $date = $opt{'date'};
1502   if ( $date and $date > time ) { # return an error if $date <= time?
1503
1504     if ( $old->get('expire') && $old->get('expire') < $date ) {
1505       $dbh->rollback if $oldAutoCommit;
1506       return "Package $pkgnum expires before it would be unsuspended.";
1507     }
1508
1509     my $new = new FS::cust_pkg { $self->hash };
1510     $new->set('resume', $date);
1511     $error = $new->replace($self, options => $self->options);
1512
1513     if ( $error ) {
1514       $dbh->rollback if $oldAutoCommit;
1515       return $error;
1516     }
1517     else {
1518       $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1519       return '';
1520     }
1521   
1522   } #if $date 
1523
1524   my @labels = ();
1525
1526   foreach my $cust_svc (
1527     qsearch('cust_svc',{'pkgnum'=> $self->pkgnum } )
1528   ) {
1529     my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
1530
1531     $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
1532       $dbh->rollback if $oldAutoCommit;
1533       return "Illegal svcdb value in part_svc!";
1534     };
1535     my $svcdb = $1;
1536     require "FS/$svcdb.pm";
1537
1538     my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
1539     if ($svc) {
1540       $error = $svc->unsuspend;
1541       if ( $error ) {
1542         $dbh->rollback if $oldAutoCommit;
1543         return $error;
1544       }
1545       my( $label, $value ) = $cust_svc->label;
1546       push @labels, "$label: $value";
1547     }
1548
1549   }
1550
1551   my $cust_pkg_reason = $self->last_cust_pkg_reason('susp');
1552   my $reason = $cust_pkg_reason ? $cust_pkg_reason->reason : '';
1553
1554   my %hash = $self->hash;
1555   my $inactive = time - $hash{'susp'};
1556
1557   my $conf = new FS::Conf;
1558
1559   if ( $inactive > 0 && 
1560        ( $hash{'bill'} || $hash{'setup'} ) &&
1561        ( $opt{'adjust_next_bill'} ||
1562          $conf->exists('unsuspend-always_adjust_next_bill_date') ||
1563          $self->part_pkg->option('unsuspend_adjust_bill', 1) )
1564      ) {
1565
1566     $hash{'bill'} = ( $hash{'bill'} || $hash{'setup'} ) + $inactive;
1567   
1568   }
1569
1570   $hash{'susp'} = '';
1571   $hash{'adjourn'} = '' if $hash{'adjourn'} and $hash{'adjourn'} < time;
1572   $hash{'resume'} = '' if !$hash{'adjourn'};
1573   my $new = new FS::cust_pkg ( \%hash );
1574   $error = $new->replace( $self, options => { $self->options } );
1575   if ( $error ) {
1576     $dbh->rollback if $oldAutoCommit;
1577     return $error;
1578   }
1579
1580   my $unsusp_pkg;
1581
1582   if ( $reason && $reason->unsuspend_pkgpart ) {
1583     my $part_pkg = FS::part_pkg->by_key($reason->unsuspend_pkgpart)
1584       or $error = "Unsuspend package definition ".$reason->unsuspend_pkgpart.
1585                   " not found.";
1586     my $start_date = $self->cust_main->next_bill_date 
1587       if $reason->unsuspend_hold;
1588
1589     if ( $part_pkg ) {
1590       $unsusp_pkg = FS::cust_pkg->new({
1591           'custnum'     => $self->custnum,
1592           'pkgpart'     => $reason->unsuspend_pkgpart,
1593           'start_date'  => $start_date,
1594           'locationnum' => $self->locationnum,
1595           # discount? probably not...
1596       });
1597       
1598       $error ||= $self->cust_main->order_pkg( 'cust_pkg' => $unsusp_pkg );
1599     }
1600
1601     if ( $error ) {
1602       $dbh->rollback if $oldAutoCommit;
1603       return $error;
1604     }
1605   }
1606
1607   if ( $conf->config('unsuspend_email_admin') ) {
1608  
1609     my $error = send_email(
1610       'from'    => $conf->config('invoice_from', $self->cust_main->agentnum),
1611                                  #invoice_from ??? well as good as any
1612       'to'      => $conf->config('unsuspend_email_admin'),
1613       'subject' => 'FREESIDE NOTIFICATION: Customer package unsuspended',       'body'    => [
1614         "This is an automatic message from your Freeside installation\n",
1615         "informing you that the following customer package has been unsuspended:\n",
1616         "\n",
1617         'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
1618         'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
1619         ( map { "Service : $_\n" } @labels ),
1620         ($unsusp_pkg ?
1621           "An unsuspension fee was charged: ".
1622             $unsusp_pkg->part_pkg->pkg_comment."\n"
1623           : ''
1624         ),
1625       ],
1626     );
1627
1628     if ( $error ) {
1629       warn "WARNING: can't send unsuspension admin email (unsuspending anyway): ".
1630            "$error\n";
1631     }
1632
1633   }
1634
1635   foreach my $supp_pkg ( $self->supplemental_pkgs ) {
1636     $error = $supp_pkg->unsuspend(%opt, 'from_main' => 1);
1637     if ( $error ) {
1638       $dbh->rollback if $oldAutoCommit;
1639       return "unsuspending supplemental pkg#".$supp_pkg->pkgnum.": $error";
1640     }
1641   }
1642
1643   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1644
1645   ''; #no errors
1646 }
1647
1648 =item unadjourn
1649
1650 Cancels any pending suspension (sets the adjourn field to null).
1651
1652 If there is an error, returns the error, otherwise returns false.
1653
1654 =cut
1655
1656 sub unadjourn {
1657   my( $self, %options ) = @_;
1658   my $error;
1659
1660   local $SIG{HUP} = 'IGNORE';
1661   local $SIG{INT} = 'IGNORE';
1662   local $SIG{QUIT} = 'IGNORE'; 
1663   local $SIG{TERM} = 'IGNORE';
1664   local $SIG{TSTP} = 'IGNORE';
1665   local $SIG{PIPE} = 'IGNORE';
1666
1667   my $oldAutoCommit = $FS::UID::AutoCommit;
1668   local $FS::UID::AutoCommit = 0;
1669   my $dbh = dbh;
1670
1671   my $old = $self->select_for_update;
1672
1673   my $pkgnum = $old->pkgnum;
1674   if ( $old->get('cancel') || $self->get('cancel') ) {
1675     dbh->rollback if $oldAutoCommit;
1676     return "Can't unadjourn cancelled package $pkgnum";
1677     # or at least it's pointless
1678   }
1679
1680   if ( $old->get('susp') || $self->get('susp') ) {
1681     dbh->rollback if $oldAutoCommit;
1682     return "Can't unadjourn suspended package $pkgnum";
1683     # perhaps this is arbitrary
1684   }
1685
1686   unless ( $old->get('adjourn') && $self->get('adjourn') ) {
1687     dbh->rollback if $oldAutoCommit;
1688     return "";  # no error
1689   }
1690
1691   my %hash = $self->hash;
1692   $hash{'adjourn'} = '';
1693   $hash{'resume'}  = '';
1694   my $new = new FS::cust_pkg ( \%hash );
1695   $error = $new->replace( $self, options => { $self->options } );
1696   if ( $error ) {
1697     $dbh->rollback if $oldAutoCommit;
1698     return $error;
1699   }
1700
1701   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1702
1703   ''; #no errors
1704
1705 }
1706
1707
1708 =item change HASHREF | OPTION => VALUE ... 
1709
1710 Changes this package: cancels it and creates a new one, with a different
1711 pkgpart or locationnum or both.  All services are transferred to the new
1712 package (no change will be made if this is not possible).
1713
1714 Options may be passed as a list of key/value pairs or as a hash reference.
1715 Options are:
1716
1717 =over 4
1718
1719 =item locationnum
1720
1721 New locationnum, to change the location for this package.
1722
1723 =item cust_location
1724
1725 New FS::cust_location object, to create a new location and assign it
1726 to this package.
1727
1728 =item cust_main
1729
1730 New FS::cust_main object, to create a new customer and assign the new package
1731 to it.
1732
1733 =item pkgpart
1734
1735 New pkgpart (see L<FS::part_pkg>).
1736
1737 =item refnum
1738
1739 New refnum (see L<FS::part_referral>).
1740
1741 =item quantity
1742
1743 New quantity; if unspecified, the new package will have the same quantity
1744 as the old.
1745
1746 =item cust_pkg
1747
1748 "New" (existing) FS::cust_pkg object.  The package's services and other 
1749 attributes will be transferred to this package.
1750
1751 =item keep_dates
1752
1753 Set to true to transfer billing dates (start_date, setup, last_bill, bill, 
1754 susp, adjourn, cancel, expire, and contract_end) to the new package.
1755
1756 =item unprotect_svcs
1757
1758 Normally, change() will rollback and return an error if some services 
1759 can't be transferred (also see the I<cust_pkg-change_svcpart> config option).
1760 If unprotect_svcs is true, this method will transfer as many services as 
1761 it can and then unconditionally cancel the old package.
1762
1763 =back
1764
1765 At least one of locationnum, cust_location, pkgpart, refnum, cust_main, or
1766 cust_pkg must be specified (otherwise, what's the point?)
1767
1768 Returns either the new FS::cust_pkg object or a scalar error.
1769
1770 For example:
1771
1772   my $err_or_new_cust_pkg = $old_cust_pkg->change
1773
1774 =cut
1775
1776 #some false laziness w/order
1777 sub change {
1778   my $self = shift;
1779   my $opt = ref($_[0]) ? shift : { @_ };
1780
1781   my $conf = new FS::Conf;
1782
1783   # Transactionize this whole mess
1784   local $SIG{HUP} = 'IGNORE';
1785   local $SIG{INT} = 'IGNORE'; 
1786   local $SIG{QUIT} = 'IGNORE';
1787   local $SIG{TERM} = 'IGNORE';
1788   local $SIG{TSTP} = 'IGNORE'; 
1789   local $SIG{PIPE} = 'IGNORE'; 
1790
1791   my $oldAutoCommit = $FS::UID::AutoCommit;
1792   local $FS::UID::AutoCommit = 0;
1793   my $dbh = dbh;
1794
1795   my $error;
1796
1797   my %hash = (); 
1798
1799   my $time = time;
1800
1801   $hash{'setup'} = $time if $self->setup;
1802
1803   $hash{'change_date'} = $time;
1804   $hash{"change_$_"}  = $self->$_()
1805     foreach qw( pkgnum pkgpart locationnum );
1806
1807   if ( $opt->{'cust_location'} ) {
1808     $error = $opt->{'cust_location'}->find_or_insert;
1809     if ( $error ) {
1810       $dbh->rollback if $oldAutoCommit;
1811       return "inserting cust_location (transaction rolled back): $error";
1812     }
1813     $opt->{'locationnum'} = $opt->{'cust_location'}->locationnum;
1814   }
1815
1816   if ( $opt->{'cust_pkg'} ) {
1817     # treat changing to a package with a different pkgpart as a 
1818     # pkgpart change (because it is)
1819     $opt->{'pkgpart'} = $opt->{'cust_pkg'}->pkgpart;
1820   }
1821
1822   # whether to override pkgpart checking on the new package
1823   my $same_pkgpart = 1;
1824   if ( $opt->{'pkgpart'} and ( $opt->{'pkgpart'} != $self->pkgpart ) ) {
1825     $same_pkgpart = 0;
1826   }
1827
1828   my $unused_credit = 0;
1829   my $keep_dates = $opt->{'keep_dates'};
1830   # Special case.  If the pkgpart is changing, and the customer is
1831   # going to be credited for remaining time, don't keep setup, bill, 
1832   # or last_bill dates, and DO pass the flag to cancel() to credit 
1833   # the customer.
1834   if ( $opt->{'pkgpart'} 
1835        and $opt->{'pkgpart'} != $self->pkgpart
1836        and $self->part_pkg->option('unused_credit_change', 1) ) {
1837     $unused_credit = 1;
1838     $keep_dates = 0;
1839     $hash{$_} = '' foreach qw(setup bill last_bill);
1840   }
1841
1842   if ( $keep_dates ) {
1843     foreach my $date ( qw(setup bill last_bill susp adjourn cancel expire 
1844                           resume start_date contract_end ) ) {
1845       $hash{$date} = $self->getfield($date);
1846     }
1847   }
1848
1849   # allow $opt->{'locationnum'} = '' to specifically set it to null
1850   # (i.e. customer default location)
1851   $opt->{'locationnum'} = $self->locationnum if !exists($opt->{'locationnum'});
1852
1853   # usually this doesn't matter.  the two cases where it does are:
1854   # 1. unused_credit_change + pkgpart change + setup fee on the new package
1855   # and
1856   # 2. (more importantly) changing a package before it's billed
1857   $hash{'waive_setup'} = $self->waive_setup;
1858
1859   my $custnum = $self->custnum;
1860   if ( $opt->{cust_main} ) {
1861     my $cust_main = $opt->{cust_main};
1862     unless ( $cust_main->custnum ) { 
1863       my $error = $cust_main->insert( @{ $opt->{cust_main_insert_args}||[] } );
1864       if ( $error ) {
1865         $dbh->rollback if $oldAutoCommit;
1866         return "inserting cust_main (transaction rolled back): $error";
1867       }
1868     }
1869     $custnum = $cust_main->custnum;
1870   }
1871
1872   $hash{'contactnum'} = $opt->{'contactnum'} if $opt->{'contactnum'};
1873
1874   my $cust_pkg;
1875   if ( $opt->{'cust_pkg'} ) {
1876     # The target package already exists; update it to show that it was 
1877     # changed from this package.
1878     $cust_pkg = $opt->{'cust_pkg'};
1879
1880     foreach ( qw( pkgnum pkgpart locationnum ) ) {
1881       $cust_pkg->set("change_$_", $self->get($_));
1882     }
1883     $cust_pkg->set('change_date', $time);
1884     $error = $cust_pkg->replace;
1885
1886   } else {
1887     # Create the new package.
1888     $cust_pkg = new FS::cust_pkg {
1889       custnum     => $custnum,
1890       locationnum => $opt->{'locationnum'},
1891       ( map {  $_ => ( $opt->{$_} || $self->$_() )  }
1892           qw( pkgpart quantity refnum salesnum )
1893       ),
1894       %hash,
1895     };
1896     $error = $cust_pkg->insert( 'change' => 1,
1897                                 'allow_pkgpart' => $same_pkgpart );
1898   }
1899   if ($error) {
1900     $dbh->rollback if $oldAutoCommit;
1901     return $error;
1902   }
1903
1904   # Transfer services and cancel old package.
1905
1906   $error = $self->transfer($cust_pkg);
1907   if ($error and $error == 0) {
1908     # $old_pkg->transfer failed.
1909     $dbh->rollback if $oldAutoCommit;
1910     return $error;
1911   }
1912
1913   if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
1914     warn "trying transfer again with change_svcpart option\n" if $DEBUG;
1915     $error = $self->transfer($cust_pkg, 'change_svcpart'=>1 );
1916     if ($error and $error == 0) {
1917       # $old_pkg->transfer failed.
1918       $dbh->rollback if $oldAutoCommit;
1919       return $error;
1920     }
1921   }
1922
1923   # We set unprotect_svcs when executing a "future package change".  It's 
1924   # not a user-interactive operation, so returning an error means the 
1925   # package change will just fail.  Rather than have that happen, we'll 
1926   # let leftover services be deleted.
1927   if ($error > 0 and !$opt->{'unprotect_svcs'}) {
1928     # Transfers were successful, but we still had services left on the old
1929     # package.  We can't change the package under this circumstances, so abort.
1930     $dbh->rollback if $oldAutoCommit;
1931     return "Unable to transfer all services from package ". $self->pkgnum;
1932   }
1933
1934   #reset usage if changing pkgpart
1935   # AND usage rollover is off (otherwise adds twice, now and at package bill)
1936   if ($self->pkgpart != $cust_pkg->pkgpart) {
1937     my $part_pkg = $cust_pkg->part_pkg;
1938     $error = $part_pkg->reset_usage($cust_pkg, $part_pkg->is_prepaid
1939                                                  ? ()
1940                                                  : ( 'null' => 1 )
1941                                    )
1942       if $part_pkg->can('reset_usage') && ! $part_pkg->option('usage_rollover',1);
1943
1944     if ($error) {
1945       $dbh->rollback if $oldAutoCommit;
1946       return "Error setting usage values: $error";
1947     }
1948   } else {
1949     # if NOT changing pkgpart, transfer any usage pools over
1950     foreach my $usage ($self->cust_pkg_usage) {
1951       $usage->set('pkgnum', $cust_pkg->pkgnum);
1952       $error = $usage->replace;
1953       if ( $error ) {
1954         $dbh->rollback if $oldAutoCommit;
1955         return "Error transferring usage pools: $error";
1956       }
1957     }
1958   }
1959
1960   # transfer discounts, if we're not changing pkgpart
1961   if ( $same_pkgpart ) {
1962     foreach my $old_discount ($self->cust_pkg_discount_active) {
1963       # don't remove the old discount, we may still need to bill that package.
1964       my $new_discount = new FS::cust_pkg_discount {
1965         'pkgnum'      => $cust_pkg->pkgnum,
1966         'discountnum' => $old_discount->discountnum,
1967         'months_used' => $old_discount->months_used,
1968       };
1969       $error = $new_discount->insert;
1970       if ( $error ) {
1971         $dbh->rollback if $oldAutoCommit;
1972         return "Error transferring discounts: $error";
1973       }
1974     }
1975   }
1976
1977   # transfer (copy) invoice details
1978   foreach my $detail ($self->cust_pkg_detail) {
1979     my $new_detail = FS::cust_pkg_detail->new({ $detail->hash });
1980     $new_detail->set('pkgdetailnum', '');
1981     $new_detail->set('pkgnum', $cust_pkg->pkgnum);
1982     $error = $new_detail->insert;
1983     if ( $error ) {
1984       $dbh->rollback if $oldAutoCommit;
1985       return "Error transferring package notes: $error";
1986     }
1987   }
1988   
1989   my @new_supp_pkgs;
1990
1991   if ( !$opt->{'cust_pkg'} ) {
1992     # Order any supplemental packages.
1993     my $part_pkg = $cust_pkg->part_pkg;
1994     my @old_supp_pkgs = $self->supplemental_pkgs;
1995     foreach my $link ($part_pkg->supp_part_pkg_link) {
1996       my $old;
1997       foreach (@old_supp_pkgs) {
1998         if ($_->pkgpart == $link->dst_pkgpart) {
1999           $old = $_;
2000           $_->pkgpart(0); # so that it can't match more than once
2001         }
2002         last if $old;
2003       }
2004       # false laziness with FS::cust_main::Packages::order_pkg
2005       my $new = FS::cust_pkg->new({
2006           pkgpart       => $link->dst_pkgpart,
2007           pkglinknum    => $link->pkglinknum,
2008           custnum       => $custnum,
2009           main_pkgnum   => $cust_pkg->pkgnum,
2010           locationnum   => $cust_pkg->locationnum,
2011           start_date    => $cust_pkg->start_date,
2012           order_date    => $cust_pkg->order_date,
2013           expire        => $cust_pkg->expire,
2014           adjourn       => $cust_pkg->adjourn,
2015           contract_end  => $cust_pkg->contract_end,
2016           refnum        => $cust_pkg->refnum,
2017           discountnum   => $cust_pkg->discountnum,
2018           waive_setup   => $cust_pkg->waive_setup,
2019       });
2020       if ( $old and $opt->{'keep_dates'} ) {
2021         foreach (qw(setup bill last_bill)) {
2022           $new->set($_, $old->get($_));
2023         }
2024       }
2025       $error = $new->insert( allow_pkgpart => $same_pkgpart );
2026       # transfer services
2027       if ( $old ) {
2028         $error ||= $old->transfer($new);
2029       }
2030       if ( $error and $error > 0 ) {
2031         # no reason why this should ever fail, but still...
2032         $error = "Unable to transfer all services from supplemental package ".
2033           $old->pkgnum;
2034       }
2035       if ( $error ) {
2036         $dbh->rollback if $oldAutoCommit;
2037         return $error;
2038       }
2039       push @new_supp_pkgs, $new;
2040     }
2041   } # if !$opt->{'cust_pkg'}
2042     # because if there is one, then supplemental packages would already
2043     # have been created for it.
2044
2045   #Good to go, cancel old package.  Notify 'cancel' of whether to credit 
2046   #remaining time.
2047   #Don't allow billing the package (preceding period packages and/or 
2048   #outstanding usage) if we are keeping dates (i.e. location changing), 
2049   #because the new package will be billed for the same date range.
2050   #Supplemental packages are also canceled here.
2051
2052   # during scheduled changes, avoid canceling the package we just
2053   # changed to (duh)
2054   $self->set('change_to_pkgnum' => '');
2055
2056   $error = $self->cancel(
2057     quiet          => 1, 
2058     unused_credit  => $unused_credit,
2059     nobill         => $keep_dates,
2060     change_custnum => ( $self->custnum != $custnum ? $custnum : '' ),
2061   );
2062   if ($error) {
2063     $dbh->rollback if $oldAutoCommit;
2064     return $error;
2065   }
2066
2067   if ( $conf->exists('cust_pkg-change_pkgpart-bill_now') ) {
2068     #$self->cust_main
2069     my $error = $cust_pkg->cust_main->bill( 
2070       'pkg_list' => [ $cust_pkg, @new_supp_pkgs ]
2071     );
2072     if ( $error ) {
2073       $dbh->rollback if $oldAutoCommit;
2074       return $error;
2075     }
2076   }
2077
2078   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2079
2080   $cust_pkg;
2081
2082 }
2083
2084 =item change_later OPTION => VALUE...
2085
2086 Schedule a package change for a later date.  This actually orders the new
2087 package immediately, but sets its start date for a future date, and sets
2088 the current package to expire on the same date.
2089
2090 If the package is already scheduled for a change, this can be called with 
2091 'start_date' to change the scheduled date, or with pkgpart and/or 
2092 locationnum to modify the package change.  To cancel the scheduled change 
2093 entirely, see C<abort_change>.
2094
2095 Options include:
2096
2097 =over 4
2098
2099 =item start_date
2100
2101 The date for the package change.  Required, and must be in the future.
2102
2103 =item pkgpart
2104
2105 =item locationnum
2106
2107 =item quantity
2108
2109 The pkgpart. locationnum, and quantity of the new package, with the same 
2110 meaning as in C<change>.
2111
2112 =back
2113
2114 =cut
2115
2116 sub change_later {
2117   my $self = shift;
2118   my $opt = ref($_[0]) ? shift : { @_ };
2119
2120   my $oldAutoCommit = $FS::UID::AutoCommit;
2121   local $FS::UID::AutoCommit = 0;
2122   my $dbh = dbh;
2123
2124   my $cust_main = $self->cust_main;
2125
2126   my $date = delete $opt->{'start_date'} or return 'start_date required';
2127  
2128   if ( $date <= time ) {
2129     $dbh->rollback if $oldAutoCommit;
2130     return "start_date $date is in the past";
2131   }
2132
2133   my $error;
2134
2135   if ( $self->change_to_pkgnum ) {
2136     my $change_to = FS::cust_pkg->by_key($self->change_to_pkgnum);
2137     my $new_pkgpart = $opt->{'pkgpart'}
2138         if $opt->{'pkgpart'} and $opt->{'pkgpart'} != $change_to->pkgpart;
2139     my $new_locationnum = $opt->{'locationnum'}
2140         if $opt->{'locationnum'} and $opt->{'locationnum'} != $change_to->locationnum;
2141     my $new_quantity = $opt->{'quantity'}
2142         if $opt->{'quantity'} and $opt->{'quantity'} != $change_to->quantity;
2143     if ( $new_pkgpart or $new_locationnum or $new_quantity ) {
2144       # it hasn't been billed yet, so in principle we could just edit
2145       # it in place (w/o a package change), but that's bad form.
2146       # So change the package according to the new options...
2147       my $err_or_pkg = $change_to->change(%$opt);
2148       if ( ref $err_or_pkg ) {
2149         # Then set that package up for a future start.
2150         $self->set('change_to_pkgnum', $err_or_pkg->pkgnum);
2151         $self->set('expire', $date); # in case it's different
2152         $err_or_pkg->set('start_date', $date);
2153         $err_or_pkg->set('change_date', '');
2154         $err_or_pkg->set('change_pkgnum', '');
2155
2156         $error = $self->replace       ||
2157                  $err_or_pkg->replace ||
2158                  $change_to->cancel   ||
2159                  $change_to->delete;
2160       } else {
2161         $error = $err_or_pkg;
2162       }
2163     } else { # change the start date only.
2164       $self->set('expire', $date);
2165       $change_to->set('start_date', $date);
2166       $error = $self->replace || $change_to->replace;
2167     }
2168     if ( $error ) {
2169       $dbh->rollback if $oldAutoCommit;
2170       return $error;
2171     } else {
2172       $dbh->commit if $oldAutoCommit;
2173       return '';
2174     }
2175   } # if $self->change_to_pkgnum
2176
2177   my $new_pkgpart = $opt->{'pkgpart'}
2178       if $opt->{'pkgpart'} and $opt->{'pkgpart'} != $self->pkgpart;
2179   my $new_locationnum = $opt->{'locationnum'}
2180       if $opt->{'locationnum'} and $opt->{'locationnum'} != $self->locationnum;
2181   my $new_quantity = $opt->{'quantity'}
2182       if $opt->{'quantity'} and $opt->{'quantity'} != $self->quantity;
2183
2184   return '' unless $new_pkgpart or $new_locationnum or $new_quantity; # wouldn't do anything
2185
2186   # allow $opt->{'locationnum'} = '' to specifically set it to null
2187   # (i.e. customer default location)
2188   $opt->{'locationnum'} = $self->locationnum if !exists($opt->{'locationnum'});
2189
2190   my $new = FS::cust_pkg->new( {
2191     custnum     => $self->custnum,
2192     locationnum => $opt->{'locationnum'},
2193     start_date  => $date,
2194     map   {  $_ => ( $opt->{$_} || $self->$_() )  }
2195       qw( pkgpart quantity refnum salesnum )
2196   } );
2197   $error = $new->insert('change' => 1, 
2198                         'allow_pkgpart' => ($new_pkgpart ? 0 : 1));
2199   if ( !$error ) {
2200     $self->set('change_to_pkgnum', $new->pkgnum);
2201     $self->set('expire', $date);
2202     $error = $self->replace;
2203   }
2204   if ( $error ) {
2205     $dbh->rollback if $oldAutoCommit;
2206   } else {
2207     $dbh->commit if $oldAutoCommit;
2208   }
2209
2210   $error;
2211 }
2212
2213 =item abort_change
2214
2215 Cancels a future package change scheduled by C<change_later>.
2216
2217 =cut
2218
2219 sub abort_change {
2220   my $self = shift;
2221   my $pkgnum = $self->change_to_pkgnum;
2222   my $change_to = FS::cust_pkg->by_key($pkgnum) if $pkgnum;
2223   my $error;
2224   if ( $change_to ) {
2225     $error = $change_to->cancel || $change_to->delete;
2226     return $error if $error;
2227   }
2228   $self->set('change_to_pkgnum', '');
2229   $self->set('expire', '');
2230   $self->replace;
2231 }
2232
2233 =item set_quantity QUANTITY
2234
2235 Change the package's quantity field.  This is one of the few package properties
2236 that can safely be changed without canceling and reordering the package
2237 (because it doesn't affect tax eligibility).  Returns an error or an 
2238 empty string.
2239
2240 =cut
2241
2242 sub set_quantity {
2243   my $self = shift;
2244   $self = $self->replace_old; # just to make sure
2245   $self->quantity(shift);
2246   $self->replace;
2247 }
2248
2249 =item set_salesnum SALESNUM
2250
2251 Change the package's salesnum (sales person) field.  This is one of the few
2252 package properties that can safely be changed without canceling and reordering
2253 the package (because it doesn't affect tax eligibility).  Returns an error or
2254 an empty string.
2255
2256 =cut
2257
2258 sub set_salesnum {
2259   my $self = shift;
2260   $self = $self->replace_old; # just to make sure
2261   $self->salesnum(shift);
2262   $self->replace;
2263   # XXX this should probably reassign any credit that's already been given
2264 }
2265
2266 =item modify_charge OPTIONS
2267
2268 Change the properties of a one-time charge.  Currently the only properties
2269 that can be changed this way are those that have no impact on billing 
2270 calculations:
2271 - pkg: the package description
2272 - classnum: the package class
2273 - additional: arrayref of additional invoice details to add to this package
2274
2275 If you pass 'adjust_commission' => 1, and the classnum changes, and there are
2276 commission credits linked to this charge, they will be recalculated.
2277
2278 =cut
2279
2280 sub modify_charge {
2281   my $self = shift;
2282   my %opt = @_;
2283   my $part_pkg = $self->part_pkg;
2284   my $pkgnum = $self->pkgnum;
2285
2286   my $dbh = dbh;
2287   my $oldAutoCommit = $FS::UID::AutoCommit;
2288   local $FS::UID::AutoCommit = 0;
2289
2290   return "Can't use modify_charge except on one-time charges"
2291     unless $part_pkg->freq eq '0';
2292
2293   if ( length($opt{'pkg'}) and $part_pkg->pkg ne $opt{'pkg'} ) {
2294     $part_pkg->set('pkg', $opt{'pkg'});
2295   }
2296
2297   my %pkg_opt = $part_pkg->options;
2298   if ( ref($opt{'additional'}) ) {
2299     delete $pkg_opt{$_} foreach grep /^additional/, keys %pkg_opt;
2300     my $i;
2301     for ( $i = 0; exists($opt{'additional'}->[$i]); $i++ ) {
2302       $pkg_opt{ "additional_info$i" } = $opt{'additional'}->[$i];
2303     }
2304     $pkg_opt{'additional_count'} = $i if $i > 0;
2305   }
2306
2307   my $old_classnum;
2308   if ( exists($opt{'classnum'}) and $part_pkg->classnum ne $opt{'classnum'} ) {
2309     # remember it
2310     $old_classnum = $part_pkg->classnum;
2311     $part_pkg->set('classnum', $opt{'classnum'});
2312   }
2313
2314   my $error = $part_pkg->replace( options => \%pkg_opt );
2315   return $error if $error;
2316
2317   if (defined $old_classnum) {
2318     # fix invoice grouping records
2319     my $old_catname = $old_classnum
2320                       ? FS::pkg_class->by_key($old_classnum)->categoryname
2321                       : '';
2322     my $new_catname = $opt{'classnum'}
2323                       ? $part_pkg->pkg_class->categoryname
2324                       : '';
2325     if ( $old_catname ne $new_catname ) {
2326       foreach my $cust_bill_pkg ($self->cust_bill_pkg) {
2327         # (there should only be one...)
2328         my @display = qsearch( 'cust_bill_pkg_display', {
2329             'billpkgnum'  => $cust_bill_pkg->billpkgnum,
2330             'section'     => $old_catname,
2331         });
2332         foreach (@display) {
2333           $_->set('section', $new_catname);
2334           $error = $_->replace;
2335           if ( $error ) {
2336             $dbh->rollback if $oldAutoCommit;
2337             return $error;
2338           }
2339         }
2340       } # foreach $cust_bill_pkg
2341     }
2342
2343     if ( $opt{'adjust_commission'} ) {
2344       # fix commission credits...tricky.
2345       foreach my $cust_event ($self->cust_event) {
2346         my $part_event = $cust_event->part_event;
2347         foreach my $table (qw(sales agent)) {
2348           my $class =
2349             "FS::part_event::Action::Mixin::credit_${table}_pkg_class";
2350           my $credit = qsearchs('cust_credit', {
2351               'eventnum' => $cust_event->eventnum,
2352           });
2353           if ( $part_event->isa($class) ) {
2354             # Yes, this results in current commission rates being applied 
2355             # retroactively to a one-time charge.  For accounting purposes 
2356             # there ought to be some kind of time limit on doing this.
2357             my $amount = $part_event->_calc_credit($self);
2358             if ( $credit and $credit->amount ne $amount ) {
2359               # Void the old credit.
2360               $error = $credit->void('Package class changed');
2361               if ( $error ) {
2362                 $dbh->rollback if $oldAutoCommit;
2363                 return "$error (adjusting commission credit)";
2364               }
2365             }
2366             # redo the event action to recreate the credit.
2367             local $@ = '';
2368             eval { $part_event->do_action( $self, $cust_event ) };
2369             if ( $@ ) {
2370               $dbh->rollback if $oldAutoCommit;
2371               return $@;
2372             }
2373           } # if $part_event->isa($class)
2374         } # foreach $table
2375       } # foreach $cust_event
2376     } # if $opt{'adjust_commission'}
2377   } # if defined $old_classnum
2378
2379   $dbh->commit if $oldAutoCommit;
2380   '';
2381 }
2382
2383
2384
2385 use Storable 'thaw';
2386 use MIME::Base64;
2387 use Data::Dumper;
2388 sub process_bulk_cust_pkg {
2389   my $job = shift;
2390   my $param = thaw(decode_base64(shift));
2391   warn Dumper($param) if $DEBUG;
2392
2393   my $old_part_pkg = qsearchs('part_pkg', 
2394                               { pkgpart => $param->{'old_pkgpart'} });
2395   my $new_part_pkg = qsearchs('part_pkg',
2396                               { pkgpart => $param->{'new_pkgpart'} });
2397   die "Must select a new package type\n" unless $new_part_pkg;
2398   #my $keep_dates = $param->{'keep_dates'} || 0;
2399   my $keep_dates = 1; # there is no good reason to turn this off
2400
2401   local $SIG{HUP} = 'IGNORE';
2402   local $SIG{INT} = 'IGNORE';
2403   local $SIG{QUIT} = 'IGNORE';
2404   local $SIG{TERM} = 'IGNORE';
2405   local $SIG{TSTP} = 'IGNORE';
2406   local $SIG{PIPE} = 'IGNORE';
2407
2408   my $oldAutoCommit = $FS::UID::AutoCommit;
2409   local $FS::UID::AutoCommit = 0;
2410   my $dbh = dbh;
2411
2412   my @cust_pkgs = qsearch('cust_pkg', { 'pkgpart' => $param->{'old_pkgpart'} } );
2413
2414   my $i = 0;
2415   foreach my $old_cust_pkg ( @cust_pkgs ) {
2416     $i++;
2417     $job->update_statustext(int(100*$i/(scalar @cust_pkgs)));
2418     if ( $old_cust_pkg->getfield('cancel') ) {
2419       warn '[process_bulk_cust_pkg ] skipping canceled pkgnum '.
2420         $old_cust_pkg->pkgnum."\n"
2421         if $DEBUG;
2422       next;
2423     }
2424     warn '[process_bulk_cust_pkg] changing pkgnum '.$old_cust_pkg->pkgnum."\n"
2425       if $DEBUG;
2426     my $error = $old_cust_pkg->change(
2427       'pkgpart'     => $param->{'new_pkgpart'},
2428       'keep_dates'  => $keep_dates
2429     );
2430     if ( !ref($error) ) { # change returns the cust_pkg on success
2431       $dbh->rollback;
2432       die "Error changing pkgnum ".$old_cust_pkg->pkgnum.": '$error'\n";
2433     }
2434   }
2435   $dbh->commit if $oldAutoCommit;
2436   return;
2437 }
2438
2439 =item last_bill
2440
2441 Returns the last bill date, or if there is no last bill date, the setup date.
2442 Useful for billing metered services.
2443
2444 =cut
2445
2446 sub last_bill {
2447   my $self = shift;
2448   return $self->setfield('last_bill', $_[0]) if @_;
2449   return $self->getfield('last_bill') if $self->getfield('last_bill');
2450   my $cust_bill_pkg = qsearchs('cust_bill_pkg', { 'pkgnum' => $self->pkgnum,
2451                                                   'edate'  => $self->bill,  } );
2452   $cust_bill_pkg ? $cust_bill_pkg->sdate : $self->setup || 0;
2453 }
2454
2455 =item last_cust_pkg_reason ACTION
2456
2457 Returns the most recent ACTION FS::cust_pkg_reason associated with the package.
2458 Returns false if there is no reason or the package is not currenly ACTION'd
2459 ACTION is one of adjourn, susp, cancel, or expire.
2460
2461 =cut
2462
2463 sub last_cust_pkg_reason {
2464   my ( $self, $action ) = ( shift, shift );
2465   my $date = $self->get($action);
2466   qsearchs( {
2467               'table' => 'cust_pkg_reason',
2468               'hashref' => { 'pkgnum' => $self->pkgnum,
2469                              'action' => substr(uc($action), 0, 1),
2470                              'date'   => $date,
2471                            },
2472               'order_by' => 'ORDER BY num DESC LIMIT 1',
2473            } );
2474 }
2475
2476 =item last_reason ACTION
2477
2478 Returns the most recent ACTION FS::reason associated with the package.
2479 Returns false if there is no reason or the package is not currenly ACTION'd
2480 ACTION is one of adjourn, susp, cancel, or expire.
2481
2482 =cut
2483
2484 sub last_reason {
2485   my $cust_pkg_reason = shift->last_cust_pkg_reason(@_);
2486   $cust_pkg_reason->reason
2487     if $cust_pkg_reason;
2488 }
2489
2490 =item part_pkg
2491
2492 Returns the definition for this billing item, as an FS::part_pkg object (see
2493 L<FS::part_pkg>).
2494
2495 =cut
2496
2497 sub part_pkg {
2498   my $self = shift;
2499   return $self->{'_pkgpart'} if $self->{'_pkgpart'};
2500   cluck "cust_pkg->part_pkg called" if $DEBUG > 1;
2501   qsearchs( 'part_pkg', { 'pkgpart' => $self->pkgpart } );
2502 }
2503
2504 =item old_cust_pkg
2505
2506 Returns the cancelled package this package was changed from, if any.
2507
2508 =cut
2509
2510 sub old_cust_pkg {
2511   my $self = shift;
2512   return '' unless $self->change_pkgnum;
2513   qsearchs('cust_pkg', { 'pkgnum' => $self->change_pkgnum } );
2514 }
2515
2516 =item change_cust_main
2517
2518 Returns the customter this package was detached to, if any.
2519
2520 =cut
2521
2522 sub change_cust_main {
2523   my $self = shift;
2524   return '' unless $self->change_custnum;
2525   qsearchs('cust_main', { 'custnum' => $self->change_custnum } );
2526 }
2527
2528 =item calc_setup
2529
2530 Calls the I<calc_setup> of the FS::part_pkg object associated with this billing
2531 item.
2532
2533 =cut
2534
2535 sub calc_setup {
2536   my $self = shift;
2537   $self->part_pkg->calc_setup($self, @_);
2538 }
2539
2540 =item calc_recur
2541
2542 Calls the I<calc_recur> of the FS::part_pkg object associated with this billing
2543 item.
2544
2545 =cut
2546
2547 sub calc_recur {
2548   my $self = shift;
2549   $self->part_pkg->calc_recur($self, @_);
2550 }
2551
2552 =item base_recur
2553
2554 Calls the I<base_recur> of the FS::part_pkg object associated with this billing
2555 item.
2556
2557 =cut
2558
2559 sub base_recur {
2560   my $self = shift;
2561   $self->part_pkg->base_recur($self, @_);
2562 }
2563
2564 =item calc_remain
2565
2566 Calls the I<calc_remain> of the FS::part_pkg object associated with this
2567 billing item.
2568
2569 =cut
2570
2571 sub calc_remain {
2572   my $self = shift;
2573   $self->part_pkg->calc_remain($self, @_);
2574 }
2575
2576 =item calc_cancel
2577
2578 Calls the I<calc_cancel> of the FS::part_pkg object associated with this
2579 billing item.
2580
2581 =cut
2582
2583 sub calc_cancel {
2584   my $self = shift;
2585   $self->part_pkg->calc_cancel($self, @_);
2586 }
2587
2588 =item cust_bill_pkg
2589
2590 Returns any invoice line items for this package (see L<FS::cust_bill_pkg>).
2591
2592 =cut
2593
2594 sub cust_bill_pkg {
2595   my $self = shift;
2596   qsearch( 'cust_bill_pkg', { 'pkgnum' => $self->pkgnum } );
2597 }
2598
2599 =item cust_pkg_detail [ DETAILTYPE ]
2600
2601 Returns any customer package details for this package (see
2602 L<FS::cust_pkg_detail>).
2603
2604 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
2605
2606 =cut
2607
2608 sub cust_pkg_detail {
2609   my $self = shift;
2610   my %hash = ( 'pkgnum' => $self->pkgnum );
2611   $hash{detailtype} = shift if @_;
2612   qsearch({
2613     'table'    => 'cust_pkg_detail',
2614     'hashref'  => \%hash,
2615     'order_by' => 'ORDER BY weight, pkgdetailnum',
2616   });
2617 }
2618
2619 =item set_cust_pkg_detail DETAILTYPE [ DETAIL, DETAIL, ... ]
2620
2621 Sets customer package details for this package (see L<FS::cust_pkg_detail>).
2622
2623 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
2624
2625 If there is an error, returns the error, otherwise returns false.
2626
2627 =cut
2628
2629 sub set_cust_pkg_detail {
2630   my( $self, $detailtype, @details ) = @_;
2631
2632   local $SIG{HUP} = 'IGNORE';
2633   local $SIG{INT} = 'IGNORE';
2634   local $SIG{QUIT} = 'IGNORE';
2635   local $SIG{TERM} = 'IGNORE';
2636   local $SIG{TSTP} = 'IGNORE';
2637   local $SIG{PIPE} = 'IGNORE';
2638
2639   my $oldAutoCommit = $FS::UID::AutoCommit;
2640   local $FS::UID::AutoCommit = 0;
2641   my $dbh = dbh;
2642
2643   foreach my $current ( $self->cust_pkg_detail($detailtype) ) {
2644     my $error = $current->delete;
2645     if ( $error ) {
2646       $dbh->rollback if $oldAutoCommit;
2647       return "error removing old detail: $error";
2648     }
2649   }
2650
2651   foreach my $detail ( @details ) {
2652     my $cust_pkg_detail = new FS::cust_pkg_detail {
2653       'pkgnum'     => $self->pkgnum,
2654       'detailtype' => $detailtype,
2655       'detail'     => $detail,
2656     };
2657     my $error = $cust_pkg_detail->insert;
2658     if ( $error ) {
2659       $dbh->rollback if $oldAutoCommit;
2660       return "error adding new detail: $error";
2661     }
2662
2663   }
2664
2665   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2666   '';
2667
2668 }
2669
2670 =item cust_event
2671
2672 Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.
2673
2674 =cut
2675
2676 #false laziness w/cust_bill.pm
2677 sub cust_event {
2678   my $self = shift;
2679   qsearch({
2680     'table'     => 'cust_event',
2681     'addl_from' => 'JOIN part_event USING ( eventpart )',
2682     'hashref'   => { 'tablenum' => $self->pkgnum },
2683     'extra_sql' => " AND eventtable = 'cust_pkg' ",
2684   });
2685 }
2686
2687 =item num_cust_event
2688
2689 Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.
2690
2691 =cut
2692
2693 #false laziness w/cust_bill.pm
2694 sub num_cust_event {
2695   my $self = shift;
2696   my $sql =
2697     "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
2698     "  WHERE tablenum = ? AND eventtable = 'cust_pkg'";
2699   my $sth = dbh->prepare($sql) or die  dbh->errstr. " preparing $sql"; 
2700   $sth->execute($self->pkgnum) or die $sth->errstr. " executing $sql";
2701   $sth->fetchrow_arrayref->[0];
2702 }
2703
2704 =item cust_svc [ SVCPART ] (old, deprecated usage)
2705
2706 =item cust_svc [ OPTION => VALUE ... ] (current usage)
2707
2708 =item cust_svc_unsorted [ OPTION => VALUE ... ] 
2709
2710 Returns the services for this package, as FS::cust_svc objects (see
2711 L<FS::cust_svc>).  Available options are svcpart and svcdb.  If either is
2712 spcififed, returns only the matching services.
2713
2714 As an optimization, use the cust_svc_unsorted version if you are not displaying
2715 the results.
2716
2717 =cut
2718
2719 sub cust_svc {
2720   my $self = shift;
2721   cluck "cust_pkg->cust_svc called" if $DEBUG > 2;
2722   $self->_sort_cust_svc( $self->cust_svc_unsorted_arrayref(@_) );
2723 }
2724
2725 sub cust_svc_unsorted {
2726   my $self = shift;
2727   @{ $self->cust_svc_unsorted_arrayref(@_) };
2728 }
2729
2730 sub cust_svc_unsorted_arrayref {
2731   my $self = shift;
2732
2733   return () unless $self->num_cust_svc(@_);
2734
2735   my %opt = ();
2736   if ( @_ && $_[0] =~ /^\d+/ ) {
2737     $opt{svcpart} = shift;
2738   } elsif ( @_ && ref($_[0]) eq 'HASH' ) {
2739     %opt = %{ $_[0] };
2740   } elsif ( @_ ) {
2741     %opt = @_;
2742   }
2743
2744   my %search = (
2745     'table'   => 'cust_svc',
2746     'hashref' => { 'pkgnum' => $self->pkgnum },
2747   );
2748   if ( $opt{svcpart} ) {
2749     $search{hashref}->{svcpart} = $opt{'svcpart'};
2750   }
2751   if ( $opt{'svcdb'} ) {
2752     $search{addl_from} = ' LEFT JOIN part_svc USING ( svcpart ) ';
2753     $search{extra_sql} = ' AND svcdb = '. dbh->quote( $opt{'svcdb'} );
2754   }
2755
2756   [ qsearch(\%search) ];
2757
2758 }
2759
2760 =item overlimit [ SVCPART ]
2761
2762 Returns the services for this package which have exceeded their
2763 usage limit as FS::cust_svc objects (see L<FS::cust_svc>).  If a svcpart
2764 is specified, return only the matching services.
2765
2766 =cut
2767
2768 sub overlimit {
2769   my $self = shift;
2770   return () unless $self->num_cust_svc(@_);
2771   grep { $_->overlimit } $self->cust_svc(@_);
2772 }
2773
2774 =item h_cust_svc END_TIMESTAMP [ START_TIMESTAMP ] [ MODE ]
2775
2776 Returns historical services for this package created before END TIMESTAMP and
2777 (optionally) not cancelled before START_TIMESTAMP, as FS::h_cust_svc objects
2778 (see L<FS::h_cust_svc>).  If MODE is 'I' (for 'invoice'), services with the 
2779 I<pkg_svc.hidden> flag will be omitted.
2780
2781 =cut
2782
2783 sub h_cust_svc {
2784   my $self = shift;
2785   warn "$me _h_cust_svc called on $self\n"
2786     if $DEBUG;
2787
2788   my ($end, $start, $mode) = @_;
2789   my @cust_svc = $self->_sort_cust_svc(
2790     [ qsearch( 'h_cust_svc',
2791       { 'pkgnum' => $self->pkgnum, },  
2792       FS::h_cust_svc->sql_h_search(@_),  
2793     ) ]
2794   );
2795   if ( defined($mode) && $mode eq 'I' ) {
2796     my %hidden_svcpart = map { $_->svcpart => $_->hidden } $self->part_svc;
2797     return grep { !$hidden_svcpart{$_->svcpart} } @cust_svc;
2798   } else {
2799     return @cust_svc;
2800   }
2801 }
2802
2803 sub _sort_cust_svc {
2804   my( $self, $arrayref ) = @_;
2805
2806   my $sort =
2807     sub ($$) { my ($a, $b) = @_; $b->[1] cmp $a->[1]  or  $a->[2] <=> $b->[2] };
2808
2809   my %pkg_svc = map { $_->svcpart => $_ }
2810                 qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
2811
2812   map  { $_->[0] }
2813   sort $sort
2814   map {
2815         my $pkg_svc = $pkg_svc{ $_->svcpart } || '';
2816         [ $_,
2817           $pkg_svc ? $pkg_svc->primary_svc : '',
2818           $pkg_svc ? $pkg_svc->quantity : 0,
2819         ];
2820       }
2821   @$arrayref;
2822
2823 }
2824
2825 =item num_cust_svc [ SVCPART ] (old, deprecated usage)
2826
2827 =item num_cust_svc [ OPTION => VALUE ... ] (current usage)
2828
2829 Returns the number of services for this package.  Available options are svcpart
2830 and svcdb.  If either is spcififed, returns only the matching services.
2831
2832 =cut
2833
2834 sub num_cust_svc {
2835   my $self = shift;
2836
2837   return $self->{'_num_cust_svc'}
2838     if !scalar(@_)
2839        && exists($self->{'_num_cust_svc'})
2840        && $self->{'_num_cust_svc'} =~ /\d/;
2841
2842   cluck "cust_pkg->num_cust_svc called, _num_cust_svc:".$self->{'_num_cust_svc'}
2843     if $DEBUG > 2;
2844
2845   my %opt = ();
2846   if ( @_ && $_[0] =~ /^\d+/ ) {
2847     $opt{svcpart} = shift;
2848   } elsif ( @_ && ref($_[0]) eq 'HASH' ) {
2849     %opt = %{ $_[0] };
2850   } elsif ( @_ ) {
2851     %opt = @_;
2852   }
2853
2854   my $select = 'SELECT COUNT(*) FROM cust_svc ';
2855   my $where = ' WHERE pkgnum = ? ';
2856   my @param = ($self->pkgnum);
2857
2858   if ( $opt{'svcpart'} ) {
2859     $where .= ' AND svcpart = ? ';
2860     push @param, $opt{'svcpart'};
2861   }
2862   if ( $opt{'svcdb'} ) {
2863     $select .= ' LEFT JOIN part_svc USING ( svcpart ) ';
2864     $where .= ' AND svcdb = ? ';
2865     push @param, $opt{'svcdb'};
2866   }
2867
2868   my $sth = dbh->prepare("$select $where") or die  dbh->errstr;
2869   $sth->execute(@param) or die $sth->errstr;
2870   $sth->fetchrow_arrayref->[0];
2871 }
2872
2873 =item available_part_svc 
2874
2875 Returns a list of FS::part_svc objects representing services included in this
2876 package but not yet provisioned.  Each FS::part_svc object also has an extra
2877 field, I<num_avail>, which specifies the number of available services.
2878
2879 =cut
2880
2881 sub available_part_svc {
2882   my $self = shift;
2883
2884   my $pkg_quantity = $self->quantity || 1;
2885
2886   grep { $_->num_avail > 0 }
2887     map {
2888           my $part_svc = $_->part_svc;
2889           $part_svc->{'Hash'}{'num_avail'} = #evil encapsulation-breaking
2890             $pkg_quantity * $_->quantity - $self->num_cust_svc($_->svcpart);
2891
2892           # more evil encapsulation breakage
2893           if($part_svc->{'Hash'}{'num_avail'} > 0) {
2894             my @exports = $part_svc->part_export_did;
2895             $part_svc->{'Hash'}{'can_get_dids'} = scalar(@exports);
2896           }
2897
2898           $part_svc;
2899         }
2900       $self->part_pkg->pkg_svc;
2901 }
2902
2903 =item part_svc [ OPTION => VALUE ... ]
2904
2905 Returns a list of FS::part_svc objects representing provisioned and available
2906 services included in this package.  Each FS::part_svc object also has the
2907 following extra fields:
2908
2909 =over 4
2910
2911 =item num_cust_svc  (count)
2912
2913 =item num_avail     (quantity - count)
2914
2915 =item cust_pkg_svc (services) - array reference containing the provisioned services, as cust_svc objects
2916
2917 =back
2918
2919 Accepts one option: summarize_size.  If specified and non-zero, will omit the
2920 extra cust_pkg_svc option for objects where num_cust_svc is this size or
2921 greater.
2922
2923 =cut
2924
2925 #svcnum
2926 #label -> ($cust_svc->label)[1]
2927
2928 sub part_svc {
2929   my $self = shift;
2930   my %opt = @_;
2931
2932   my $pkg_quantity = $self->quantity || 1;
2933
2934   #XXX some sort of sort order besides numeric by svcpart...
2935   my @part_svc = sort { $a->svcpart <=> $b->svcpart } map {
2936     my $pkg_svc = $_;
2937     my $part_svc = $pkg_svc->part_svc;
2938     my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
2939     $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #more evil
2940     $part_svc->{'Hash'}{'num_avail'}    =
2941       max( 0, $pkg_quantity * $pkg_svc->quantity - $num_cust_svc );
2942     $part_svc->{'Hash'}{'cust_pkg_svc'} =
2943         $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : []
2944       unless exists($opt{summarize_size}) && $opt{summarize_size} > 0
2945           && $num_cust_svc >= $opt{summarize_size};
2946     $part_svc->{'Hash'}{'hidden'} = $pkg_svc->hidden;
2947     $part_svc;
2948   } $self->part_pkg->pkg_svc;
2949
2950   #extras
2951   push @part_svc, map {
2952     my $part_svc = $_;
2953     my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
2954     $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #speak no evail
2955     $part_svc->{'Hash'}{'num_avail'}    = 0; #0-$num_cust_svc ?
2956     $part_svc->{'Hash'}{'cust_pkg_svc'} =
2957       $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : [];
2958     $part_svc;
2959   } $self->extra_part_svc;
2960
2961   @part_svc;
2962
2963 }
2964
2965 =item extra_part_svc
2966
2967 Returns a list of FS::part_svc objects corresponding to services in this
2968 package which are still provisioned but not (any longer) available in the
2969 package definition.
2970
2971 =cut
2972
2973 sub extra_part_svc {
2974   my $self = shift;
2975
2976   my $pkgnum  = $self->pkgnum;
2977   #my $pkgpart = $self->pkgpart;
2978
2979 #  qsearch( {
2980 #    'table'     => 'part_svc',
2981 #    'hashref'   => {},
2982 #    'extra_sql' =>
2983 #      "WHERE 0 = ( SELECT COUNT(*) FROM pkg_svc 
2984 #                     WHERE pkg_svc.svcpart = part_svc.svcpart 
2985 #                       AND pkg_svc.pkgpart = ?
2986 #                       AND quantity > 0 
2987 #                 )
2988 #        AND 0 < ( SELECT COUNT(*) FROM cust_svc
2989 #                       LEFT JOIN cust_pkg USING ( pkgnum )
2990 #                     WHERE cust_svc.svcpart = part_svc.svcpart
2991 #                       AND pkgnum = ?
2992 #                 )",
2993 #    'extra_param' => [ [$self->pkgpart=>'int'], [$self->pkgnum=>'int'] ],
2994 #  } );
2995
2996 #seems to benchmark slightly faster... (or did?)
2997
2998   my @pkgparts = map $_->pkgpart, $self->part_pkg->self_and_svc_linked;
2999   my $pkgparts = join(',', @pkgparts);
3000
3001   qsearch( {
3002     #'select'      => 'DISTINCT ON (svcpart) part_svc.*',
3003     #MySQL doesn't grok DISINCT ON
3004     'select'      => 'DISTINCT part_svc.*',
3005     'table'       => 'part_svc',
3006     'addl_from'   =>
3007       "LEFT JOIN pkg_svc  ON (     pkg_svc.svcpart   = part_svc.svcpart 
3008                                AND pkg_svc.pkgpart IN ($pkgparts)
3009                                AND quantity > 0
3010                              )
3011        LEFT JOIN cust_svc ON (     cust_svc.svcpart = part_svc.svcpart )
3012        LEFT JOIN cust_pkg USING ( pkgnum )
3013       ",
3014     'hashref'     => {},
3015     'extra_sql'   => "WHERE pkgsvcnum IS NULL AND cust_pkg.pkgnum = ? ",
3016     'extra_param' => [ [$self->pkgnum=>'int'] ],
3017   } );
3018 }
3019
3020 =item status
3021
3022 Returns a short status string for this package, currently:
3023
3024 =over 4
3025
3026 =item not yet billed
3027
3028 =item one-time charge
3029
3030 =item active
3031
3032 =item suspended
3033
3034 =item cancelled
3035
3036 =back
3037
3038 =cut
3039
3040 sub status {
3041   my $self = shift;
3042
3043   my $freq = length($self->freq) ? $self->freq : $self->part_pkg->freq;
3044
3045   return 'cancelled' if $self->get('cancel');
3046   return 'suspended' if $self->susp;
3047   return 'not yet billed' unless $self->setup;
3048   return 'one-time charge' if $freq =~ /^(0|$)/;
3049   return 'active';
3050 }
3051
3052 =item ucfirst_status
3053
3054 Returns the status with the first character capitalized.
3055
3056 =cut
3057
3058 sub ucfirst_status {
3059   ucfirst(shift->status);
3060 }
3061
3062 =item statuses
3063
3064 Class method that returns the list of possible status strings for packages
3065 (see L<the status method|/status>).  For example:
3066
3067   @statuses = FS::cust_pkg->statuses();
3068
3069 =cut
3070
3071 tie my %statuscolor, 'Tie::IxHash', 
3072   'not yet billed'  => '009999', #teal? cyan?
3073   'one-time charge' => '000000',
3074   'active'          => '00CC00',
3075   'suspended'       => 'FF9900',
3076   'cancelled'       => 'FF0000',
3077 ;
3078
3079 sub statuses {
3080   my $self = shift; #could be class...
3081   #grep { $_ !~ /^(not yet billed)$/ } #this is a dumb status anyway
3082   #                                    # mayble split btw one-time vs. recur
3083     keys %statuscolor;
3084 }
3085
3086 =item statuscolor
3087
3088 Returns a hex triplet color string for this package's status.
3089
3090 =cut
3091
3092 sub statuscolor {
3093   my $self = shift;
3094   $statuscolor{$self->status};
3095 }
3096
3097 =item pkg_label
3098
3099 Returns a label for this package.  (Currently "pkgnum: pkg - comment" or
3100 "pkg - comment" depending on user preference).
3101
3102 =cut
3103
3104 sub pkg_label {
3105   my $self = shift;
3106   my $label = $self->part_pkg->pkg_comment( 'nopkgpart' => 1 );
3107   $label = $self->pkgnum. ": $label"
3108     if $FS::CurrentUser::CurrentUser->option('show_pkgnum');
3109   $label;
3110 }
3111
3112 =item pkg_label_long
3113
3114 Returns a long label for this package, adding the primary service's label to
3115 pkg_label.
3116
3117 =cut
3118
3119 sub pkg_label_long {
3120   my $self = shift;
3121   my $label = $self->pkg_label;
3122   my $cust_svc = $self->primary_cust_svc;
3123   $label .= ' ('. ($cust_svc->label)[1]. ')' if $cust_svc;
3124   $label;
3125 }
3126
3127 =item pkg_locale
3128
3129 Returns a customer-localized label for this package.
3130
3131 =cut
3132
3133 sub pkg_locale {
3134   my $self = shift;
3135   $self->part_pkg->pkg_locale( $self->cust_main->locale );
3136 }
3137
3138 =item primary_cust_svc
3139
3140 Returns a primary service (as FS::cust_svc object) if one can be identified.
3141
3142 =cut
3143
3144 #for labeling purposes - might not 100% match up with part_pkg->svcpart's idea
3145
3146 sub primary_cust_svc {
3147   my $self = shift;
3148
3149   my @cust_svc = $self->cust_svc;
3150
3151   return '' unless @cust_svc; #no serivces - irrelevant then
3152   
3153   return $cust_svc[0] if scalar(@cust_svc) == 1; #always return a single service
3154
3155   # primary service as specified in the package definition
3156   # or exactly one service definition with quantity one
3157   my $svcpart = $self->part_pkg->svcpart;
3158   @cust_svc = grep { $_->svcpart == $svcpart } @cust_svc;
3159   return $cust_svc[0] if scalar(@cust_svc) == 1;
3160
3161   #couldn't identify one thing..
3162   return '';
3163 }
3164
3165 =item labels
3166
3167 Returns a list of lists, calling the label method for all services
3168 (see L<FS::cust_svc>) of this billing item.
3169
3170 =cut
3171
3172 sub labels {
3173   my $self = shift;
3174   map { [ $_->label ] } $self->cust_svc;
3175 }
3176
3177 =item h_labels END_TIMESTAMP [ START_TIMESTAMP ] [ MODE ]
3178
3179 Like the labels method, but returns historical information on services that
3180 were active as of END_TIMESTAMP and (optionally) not cancelled before
3181 START_TIMESTAMP.  If MODE is 'I' (for 'invoice'), services with the 
3182 I<pkg_svc.hidden> flag will be omitted.
3183
3184 Returns a list of lists, calling the label method for all (historical) services
3185 (see L<FS::h_cust_svc>) of this billing item.
3186
3187 =cut
3188
3189 sub h_labels {
3190   my $self = shift;
3191   warn "$me _h_labels called on $self\n"
3192     if $DEBUG;
3193   map { [ $_->label(@_) ] } $self->h_cust_svc(@_);
3194 }
3195
3196 =item labels_short
3197
3198 Like labels, except returns a simple flat list, and shortens long
3199 (currently >5 or the cust_bill-max_same_services configuration value) lists of
3200 identical services to one line that lists the service label and the number of
3201 individual services rather than individual items.
3202
3203 =cut
3204
3205 sub labels_short {
3206   shift->_labels_short( 'labels', @_ );
3207 }
3208
3209 =item h_labels_short END_TIMESTAMP [ START_TIMESTAMP ]
3210
3211 Like h_labels, except returns a simple flat list, and shortens long
3212 (currently >5 or the cust_bill-max_same_services configuration value) lists of
3213 identical services to one line that lists the service label and the number of
3214 individual services rather than individual items.
3215
3216 =cut
3217
3218 sub h_labels_short {
3219   shift->_labels_short( 'h_labels', @_ );
3220 }
3221
3222 sub _labels_short {
3223   my( $self, $method ) = ( shift, shift );
3224
3225   warn "$me _labels_short called on $self with $method method\n"
3226     if $DEBUG;
3227
3228   my $conf = new FS::Conf;
3229   my $max_same_services = $conf->config('cust_bill-max_same_services') || 5;
3230
3231   warn "$me _labels_short populating \%labels\n"
3232     if $DEBUG;
3233
3234   my %labels;
3235   #tie %labels, 'Tie::IxHash';
3236   push @{ $labels{$_->[0]} }, $_->[1]
3237     foreach $self->$method(@_);
3238
3239   warn "$me _labels_short populating \@labels\n"
3240     if $DEBUG;
3241
3242   my @labels;
3243   foreach my $label ( keys %labels ) {
3244     my %seen = ();
3245     my @values = grep { ! $seen{$_}++ } @{ $labels{$label} };
3246     my $num = scalar(@values);
3247     warn "$me _labels_short $num items for $label\n"
3248       if $DEBUG;
3249
3250     if ( $num > $max_same_services ) {
3251       warn "$me _labels_short   more than $max_same_services, so summarizing\n"
3252         if $DEBUG;
3253       push @labels, "$label ($num)";
3254     } else {
3255       if ( $conf->exists('cust_bill-consolidate_services') ) {
3256         warn "$me _labels_short   consolidating services\n"
3257           if $DEBUG;
3258         # push @labels, "$label: ". join(', ', @values);
3259         while ( @values ) {
3260           my $detail = "$label: ";
3261           $detail .= shift(@values). ', '
3262             while @values
3263                && ( length($detail.$values[0]) < 78 || $detail eq "$label: " );
3264           $detail =~ s/, $//;
3265           push @labels, $detail;
3266         }
3267         warn "$me _labels_short   done consolidating services\n"
3268           if $DEBUG;
3269       } else {
3270         warn "$me _labels_short   adding service data\n"
3271           if $DEBUG;
3272         push @labels, map { "$label: $_" } @values;
3273       }
3274     }
3275   }
3276
3277  @labels;
3278
3279 }
3280
3281 =item cust_main
3282
3283 Returns the parent customer object (see L<FS::cust_main>).
3284
3285 =cut
3286
3287 sub cust_main {
3288   my $self = shift;
3289   qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
3290 }
3291
3292 =item balance
3293
3294 Returns the balance for this specific package, when using
3295 experimental package balance.
3296
3297 =cut
3298
3299 sub balance {
3300   my $self = shift;
3301   $self->cust_main->balance_pkgnum( $self->pkgnum );
3302 }
3303
3304 #these subs are in location_Mixin.pm now... unfortunately the POD doesn't mixin
3305
3306 =item cust_location
3307
3308 Returns the location object, if any (see L<FS::cust_location>).
3309
3310 =item cust_location_or_main
3311
3312 If this package is associated with a location, returns the locaiton (see
3313 L<FS::cust_location>), otherwise returns the customer (see L<FS::cust_main>).
3314
3315 =item location_label [ OPTION => VALUE ... ]
3316
3317 Returns the label of the location object (see L<FS::cust_location>).
3318
3319 =cut
3320
3321 #end of subs in location_Mixin.pm now... unfortunately the POD doesn't mixin
3322
3323 =item tax_locationnum
3324
3325 Returns the foreign key to a L<FS::cust_location> object for calculating  
3326 tax on this package, as determined by the C<tax-pkg_address> and 
3327 C<tax-ship_address> configuration flags.
3328
3329 =cut
3330
3331 sub tax_locationnum {
3332   my $self = shift;
3333   my $conf = FS::Conf->new;
3334   if ( $conf->exists('tax-pkg_address') ) {
3335     return $self->locationnum;
3336   }
3337   elsif ( $conf->exists('tax-ship_address') ) {
3338     return $self->cust_main->ship_locationnum;
3339   }
3340   else {
3341     return $self->cust_main->bill_locationnum;
3342   }
3343 }
3344
3345 =item tax_location
3346
3347 Returns the L<FS::cust_location> object for tax_locationnum.
3348
3349 =cut
3350
3351 sub tax_location {
3352   my $self = shift;
3353   FS::cust_location->by_key( $self->tax_locationnum )
3354 }
3355
3356 =item seconds_since TIMESTAMP
3357
3358 Returns the number of seconds all accounts (see L<FS::svc_acct>) in this
3359 package have been online since TIMESTAMP, according to the session monitor.
3360
3361 TIMESTAMP is specified as a UNIX timestamp; see L<perlfunc/"time">.  Also see
3362 L<Time::Local> and L<Date::Parse> for conversion functions.
3363
3364 =cut
3365
3366 sub seconds_since {
3367   my($self, $since) = @_;
3368   my $seconds = 0;
3369
3370   foreach my $cust_svc (
3371     grep { $_->part_svc->svcdb eq 'svc_acct' } $self->cust_svc
3372   ) {
3373     $seconds += $cust_svc->seconds_since($since);
3374   }
3375
3376   $seconds;
3377
3378 }
3379
3380 =item seconds_since_sqlradacct TIMESTAMP_START TIMESTAMP_END
3381
3382 Returns the numbers of seconds all accounts (see L<FS::svc_acct>) in this
3383 package have been online between TIMESTAMP_START (inclusive) and TIMESTAMP_END
3384 (exclusive).
3385
3386 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
3387 L<perlfunc/"time">.  Also see L<Time::Local> and L<Date::Parse> for conversion
3388 functions.
3389
3390
3391 =cut
3392
3393 sub seconds_since_sqlradacct {
3394   my($self, $start, $end) = @_;
3395
3396   my $seconds = 0;
3397
3398   foreach my $cust_svc (
3399     grep {
3400       my $part_svc = $_->part_svc;
3401       $part_svc->svcdb eq 'svc_acct'
3402         && scalar($part_svc->part_export_usage);
3403     } $self->cust_svc
3404   ) {
3405     $seconds += $cust_svc->seconds_since_sqlradacct($start, $end);
3406   }
3407
3408   $seconds;
3409
3410 }
3411
3412 =item attribute_since_sqlradacct TIMESTAMP_START TIMESTAMP_END ATTRIBUTE
3413
3414 Returns the sum of the given attribute for all accounts (see L<FS::svc_acct>)
3415 in this package for sessions ending between TIMESTAMP_START (inclusive) and
3416 TIMESTAMP_END
3417 (exclusive).
3418
3419 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
3420 L<perlfunc/"time">.  Also see L<Time::Local> and L<Date::Parse> for conversion
3421 functions.
3422
3423 =cut
3424
3425 sub attribute_since_sqlradacct {
3426   my($self, $start, $end, $attrib) = @_;
3427
3428   my $sum = 0;
3429
3430   foreach my $cust_svc (
3431     grep {
3432       my $part_svc = $_->part_svc;
3433       scalar($part_svc->part_export_usage);
3434     } $self->cust_svc
3435   ) {
3436     $sum += $cust_svc->attribute_since_sqlradacct($start, $end, $attrib);
3437   }
3438
3439   $sum;
3440
3441 }
3442
3443 =item quantity
3444
3445 =cut
3446
3447 sub quantity {
3448   my( $self, $value ) = @_;
3449   if ( defined($value) ) {
3450     $self->setfield('quantity', $value);
3451   }
3452   $self->getfield('quantity') || 1;
3453 }
3454
3455 =item transfer DEST_PKGNUM | DEST_CUST_PKG, [ OPTION => VALUE ... ]
3456
3457 Transfers as many services as possible from this package to another package.
3458
3459 The destination package can be specified by pkgnum by passing an FS::cust_pkg
3460 object.  The destination package must already exist.
3461
3462 Services are moved only if the destination allows services with the correct
3463 I<svcpart> (not svcdb), unless the B<change_svcpart> option is set true.  Use
3464 this option with caution!  No provision is made for export differences
3465 between the old and new service definitions.  Probably only should be used
3466 when your exports for all service definitions of a given svcdb are identical.
3467 (attempt a transfer without it first, to move all possible svcpart-matching
3468 services)
3469
3470 Any services that can't be moved remain in the original package.
3471
3472 Returns an error, if there is one; otherwise, returns the number of services 
3473 that couldn't be moved.
3474
3475 =cut
3476
3477 sub transfer {
3478   my ($self, $dest_pkgnum, %opt) = @_;
3479
3480   my $remaining = 0;
3481   my $dest;
3482   my %target;
3483
3484   if (ref ($dest_pkgnum) eq 'FS::cust_pkg') {
3485     $dest = $dest_pkgnum;
3486     $dest_pkgnum = $dest->pkgnum;
3487   } else {
3488     $dest = qsearchs('cust_pkg', { pkgnum => $dest_pkgnum });
3489   }
3490
3491   return ('Package does not exist: '.$dest_pkgnum) unless $dest;
3492
3493   foreach my $pkg_svc ( $dest->part_pkg->pkg_svc ) {
3494     $target{$pkg_svc->svcpart} = $pkg_svc->quantity;
3495   }
3496
3497   foreach my $cust_svc ($dest->cust_svc) {
3498     $target{$cust_svc->svcpart}--;
3499   }
3500
3501   my %svcpart2svcparts = ();
3502   if ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
3503     warn "change_svcpart option received, creating alternates list\n" if $DEBUG;
3504     foreach my $svcpart ( map { $_->svcpart } $self->cust_svc ) {
3505       next if exists $svcpart2svcparts{$svcpart};
3506       my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
3507       $svcpart2svcparts{$svcpart} = [
3508         map  { $_->[0] }
3509         sort { $b->[1] cmp $a->[1]  or  $a->[2] <=> $b->[2] } 
3510         map {
3511               my $pkg_svc = qsearchs( 'pkg_svc', { 'pkgpart' => $dest->pkgpart,
3512                                                    'svcpart' => $_          } );
3513               [ $_,
3514                 $pkg_svc ? $pkg_svc->primary_svc : '',
3515                 $pkg_svc ? $pkg_svc->quantity : 0,
3516               ];
3517             }
3518
3519         grep { $_ != $svcpart }
3520         map  { $_->svcpart }
3521         qsearch('part_svc', { 'svcdb' => $part_svc->svcdb } )
3522       ];
3523       warn "alternates for svcpart $svcpart: ".
3524            join(', ', @{$svcpart2svcparts{$svcpart}}). "\n"
3525         if $DEBUG;
3526     }
3527   }
3528
3529   foreach my $cust_svc ($self->cust_svc) {
3530     if($target{$cust_svc->svcpart} > 0
3531        or $FS::cust_svc::ignore_quantity) { # maybe should be a 'force' option
3532       $target{$cust_svc->svcpart}--;
3533       my $new = new FS::cust_svc { $cust_svc->hash };
3534       $new->pkgnum($dest_pkgnum);
3535       my $error = $new->replace($cust_svc);
3536       return $error if $error;
3537     } elsif ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
3538       if ( $DEBUG ) {
3539         warn "looking for alternates for svcpart ". $cust_svc->svcpart. "\n";
3540         warn "alternates to consider: ".
3541              join(', ', @{$svcpart2svcparts{$cust_svc->svcpart}}). "\n";
3542       }
3543       my @alternate = grep {
3544                              warn "considering alternate svcpart $_: ".
3545                                   "$target{$_} available in new package\n"
3546                                if $DEBUG;
3547                              $target{$_} > 0;
3548                            } @{$svcpart2svcparts{$cust_svc->svcpart}};
3549       if ( @alternate ) {
3550         warn "alternate(s) found\n" if $DEBUG;
3551         my $change_svcpart = $alternate[0];
3552         $target{$change_svcpart}--;
3553         my $new = new FS::cust_svc { $cust_svc->hash };
3554         $new->svcpart($change_svcpart);
3555         $new->pkgnum($dest_pkgnum);
3556         my $error = $new->replace($cust_svc);
3557         return $error if $error;
3558       } else {
3559         $remaining++;
3560       }
3561     } else {
3562       $remaining++
3563     }
3564   }
3565   return $remaining;
3566 }
3567
3568 =item grab_svcnums SVCNUM, SVCNUM ...
3569
3570 Change the pkgnum for the provided services to this packages.  If there is an
3571 error, returns the error, otherwise returns false.
3572
3573 =cut
3574
3575 sub grab_svcnums {
3576   my $self = shift;
3577   my @svcnum = @_;
3578
3579   local $SIG{HUP} = 'IGNORE';
3580   local $SIG{INT} = 'IGNORE';
3581   local $SIG{QUIT} = 'IGNORE';
3582   local $SIG{TERM} = 'IGNORE';
3583   local $SIG{TSTP} = 'IGNORE';
3584   local $SIG{PIPE} = 'IGNORE';
3585
3586   my $oldAutoCommit = $FS::UID::AutoCommit;
3587   local $FS::UID::AutoCommit = 0;
3588   my $dbh = dbh;
3589
3590   foreach my $svcnum (@svcnum) {
3591     my $cust_svc = qsearchs('cust_svc', { svcnum=>$svcnum } ) or do {
3592       $dbh->rollback if $oldAutoCommit;
3593       return "unknown svcnum $svcnum";
3594     };
3595     $cust_svc->pkgnum( $self->pkgnum );
3596     my $error = $cust_svc->replace;
3597     if ( $error ) {
3598       $dbh->rollback if $oldAutoCommit;
3599       return $error;
3600     }
3601   }
3602
3603   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3604   '';
3605
3606 }
3607
3608 =item reexport
3609
3610 This method is deprecated.  See the I<depend_jobnum> option to the insert and
3611 order_pkgs methods in FS::cust_main for a better way to defer provisioning.
3612
3613 =cut
3614
3615 sub reexport {
3616   my $self = shift;
3617
3618   local $SIG{HUP} = 'IGNORE';
3619   local $SIG{INT} = 'IGNORE';
3620   local $SIG{QUIT} = 'IGNORE';
3621   local $SIG{TERM} = 'IGNORE';
3622   local $SIG{TSTP} = 'IGNORE';
3623   local $SIG{PIPE} = 'IGNORE';
3624
3625   my $oldAutoCommit = $FS::UID::AutoCommit;
3626   local $FS::UID::AutoCommit = 0;
3627   my $dbh = dbh;
3628
3629   foreach my $cust_svc ( $self->cust_svc ) {
3630     #false laziness w/svc_Common::insert
3631     my $svc_x = $cust_svc->svc_x;
3632     foreach my $part_export ( $cust_svc->part_svc->part_export ) {
3633       my $error = $part_export->export_insert($svc_x);
3634       if ( $error ) {
3635         $dbh->rollback if $oldAutoCommit;
3636         return $error;
3637       }
3638     }
3639   }
3640
3641   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3642   '';
3643
3644 }
3645
3646 =item export_pkg_change OLD_CUST_PKG
3647
3648 Calls the "pkg_change" export action for all services attached to this package.
3649
3650 =cut
3651
3652 sub export_pkg_change {
3653   my( $self, $old )  = ( shift, shift );
3654
3655   local $SIG{HUP} = 'IGNORE';
3656   local $SIG{INT} = 'IGNORE';
3657   local $SIG{QUIT} = 'IGNORE';
3658   local $SIG{TERM} = 'IGNORE';
3659   local $SIG{TSTP} = 'IGNORE';
3660   local $SIG{PIPE} = 'IGNORE';
3661
3662   my $oldAutoCommit = $FS::UID::AutoCommit;
3663   local $FS::UID::AutoCommit = 0;
3664   my $dbh = dbh;
3665
3666   foreach my $svc_x ( map $_->svc_x, $self->cust_svc ) {
3667     my $error = $svc_x->export('pkg_change', $self, $old);
3668     if ( $error ) {
3669       $dbh->rollback if $oldAutoCommit;
3670       return $error;
3671     }
3672   }
3673
3674   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3675   '';
3676
3677 }
3678
3679 =item insert_reason
3680
3681 Associates this package with a (suspension or cancellation) reason (see
3682 L<FS::cust_pkg_reason>, possibly inserting a new reason on the fly (see
3683 L<FS::reason>).
3684
3685 Available options are:
3686
3687 =over 4
3688
3689 =item reason
3690
3691 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.
3692
3693 =item reason_otaker
3694
3695 the access_user (see L<FS::access_user>) providing the reason
3696
3697 =item date
3698
3699 a unix timestamp 
3700
3701 =item action
3702
3703 the action (cancel, susp, adjourn, expire) associated with the reason
3704
3705 =back
3706
3707 If there is an error, returns the error, otherwise returns false.
3708
3709 =cut
3710
3711 sub insert_reason {
3712   my ($self, %options) = @_;
3713
3714   my $otaker = $options{reason_otaker} ||
3715                $FS::CurrentUser::CurrentUser->username;
3716
3717   my $reasonnum;
3718   if ( $options{'reason'} =~ /^(\d+)$/ ) {
3719
3720     $reasonnum = $1;
3721
3722   } elsif ( ref($options{'reason'}) ) {
3723   
3724     return 'Enter a new reason (or select an existing one)'
3725       unless $options{'reason'}->{'reason'} !~ /^\s*$/;
3726
3727     my $reason = new FS::reason({
3728       'reason_type' => $options{'reason'}->{'typenum'},
3729       'reason'      => $options{'reason'}->{'reason'},
3730     });
3731     my $error = $reason->insert;
3732     return $error if $error;
3733
3734     $reasonnum = $reason->reasonnum;
3735
3736   } else {
3737     return "Unparsable reason: ". $options{'reason'};
3738   }
3739
3740   my $cust_pkg_reason =
3741     new FS::cust_pkg_reason({ 'pkgnum'    => $self->pkgnum,
3742                               'reasonnum' => $reasonnum, 
3743                               'otaker'    => $otaker,
3744                               'action'    => substr(uc($options{'action'}),0,1),
3745                               'date'      => $options{'date'}
3746                                                ? $options{'date'}
3747                                                : time,
3748                             });
3749
3750   $cust_pkg_reason->insert;
3751 }
3752
3753 =item insert_discount
3754
3755 Associates this package with a discount (see L<FS::cust_pkg_discount>, possibly
3756 inserting a new discount on the fly (see L<FS::discount>).
3757
3758 Available options are:
3759
3760 =over 4
3761
3762 =item discountnum
3763
3764 =back
3765
3766 If there is an error, returns the error, otherwise returns false.
3767
3768 =cut
3769
3770 sub insert_discount {
3771   #my ($self, %options) = @_;
3772   my $self = shift;
3773
3774   my $cust_pkg_discount = new FS::cust_pkg_discount {
3775     'pkgnum'      => $self->pkgnum,
3776     'discountnum' => $self->discountnum,
3777     'months_used' => 0,
3778     'end_date'    => '', #XXX
3779     #for the create a new discount case
3780     '_type'       => $self->discountnum__type,
3781     'amount'      => $self->discountnum_amount,
3782     'percent'     => $self->discountnum_percent,
3783     'months'      => $self->discountnum_months,
3784     'setup'      => $self->discountnum_setup,
3785     #'disabled'    => $self->discountnum_disabled,
3786   };
3787
3788   $cust_pkg_discount->insert;
3789 }
3790
3791 =item set_usage USAGE_VALUE_HASHREF 
3792
3793 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
3794 to which they should be set (see L<FS::svc_acct>).  Currently seconds,
3795 upbytes, downbytes, and totalbytes are appropriate keys.
3796
3797 All svc_accts which are part of this package have their values reset.
3798
3799 =cut
3800
3801 sub set_usage {
3802   my ($self, $valueref, %opt) = @_;
3803
3804   #only svc_acct can set_usage for now
3805   foreach my $cust_svc ( $self->cust_svc( 'svcdb'=>'svc_acct' ) ) {
3806     my $svc_x = $cust_svc->svc_x;
3807     $svc_x->set_usage($valueref, %opt)
3808       if $svc_x->can("set_usage");
3809   }
3810 }
3811
3812 =item recharge USAGE_VALUE_HASHREF 
3813
3814 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
3815 to which they should be set (see L<FS::svc_acct>).  Currently seconds,
3816 upbytes, downbytes, and totalbytes are appropriate keys.
3817
3818 All svc_accts which are part of this package have their values incremented.
3819
3820 =cut
3821
3822 sub recharge {
3823   my ($self, $valueref) = @_;
3824
3825   #only svc_acct can set_usage for now
3826   foreach my $cust_svc ( $self->cust_svc( 'svcdb'=>'svc_acct' ) ) {
3827     my $svc_x = $cust_svc->svc_x;
3828     $svc_x->recharge($valueref)
3829       if $svc_x->can("recharge");
3830   }
3831 }
3832
3833 =item cust_pkg_discount
3834
3835 =cut
3836
3837 sub cust_pkg_discount {
3838   my $self = shift;
3839   qsearch('cust_pkg_discount', { 'pkgnum' => $self->pkgnum } );
3840 }
3841
3842 =item cust_pkg_discount_active
3843
3844 =cut
3845
3846 sub cust_pkg_discount_active {
3847   my $self = shift;
3848   grep { $_->status eq 'active' } $self->cust_pkg_discount;
3849 }
3850
3851 =item cust_pkg_usage
3852
3853 Returns a list of all voice usage counters attached to this package.
3854
3855 =cut
3856
3857 sub cust_pkg_usage {
3858   my $self = shift;
3859   qsearch('cust_pkg_usage', { pkgnum => $self->pkgnum });
3860 }
3861
3862 =item apply_usage OPTIONS
3863
3864 Takes the following options:
3865 - cdr: a call detail record (L<FS::cdr>)
3866 - rate_detail: the rate determined for this call (L<FS::rate_detail>)
3867 - minutes: the maximum number of minutes to be charged
3868
3869 Finds available usage minutes for a call of this class, and subtracts
3870 up to that many minutes from the usage pool.  If the usage pool is empty,
3871 and the C<cdr-minutes_priority> global config option is set, minutes may
3872 be taken from other calls as well.  Either way, an allocation record will
3873 be created (L<FS::cdr_cust_pkg_usage>) and this method will return the 
3874 number of minutes of usage applied to the call.
3875
3876 =cut
3877
3878 sub apply_usage {
3879   my ($self, %opt) = @_;
3880   my $cdr = $opt{cdr};
3881   my $rate_detail = $opt{rate_detail};
3882   my $minutes = $opt{minutes};
3883   my $classnum = $rate_detail->classnum;
3884   my $pkgnum = $self->pkgnum;
3885   my $custnum = $self->custnum;
3886
3887   local $SIG{HUP} = 'IGNORE';
3888   local $SIG{INT} = 'IGNORE'; 
3889   local $SIG{QUIT} = 'IGNORE';
3890   local $SIG{TERM} = 'IGNORE';
3891   local $SIG{TSTP} = 'IGNORE'; 
3892   local $SIG{PIPE} = 'IGNORE'; 
3893
3894   my $oldAutoCommit = $FS::UID::AutoCommit;
3895   local $FS::UID::AutoCommit = 0;
3896   my $dbh = dbh;
3897   my $order = FS::Conf->new->config('cdr-minutes_priority');
3898
3899   my $is_classnum;
3900   if ( $classnum ) {
3901     $is_classnum = ' part_pkg_usage_class.classnum = '.$classnum;
3902   } else {
3903     $is_classnum = ' part_pkg_usage_class.classnum IS NULL';
3904   }
3905   my @usage_recs = qsearch({
3906       'table'     => 'cust_pkg_usage',
3907       'addl_from' => ' JOIN part_pkg_usage       USING (pkgusagepart)'.
3908                      ' JOIN cust_pkg             USING (pkgnum)'.
3909                      ' JOIN part_pkg_usage_class USING (pkgusagepart)',
3910       'select'    => 'cust_pkg_usage.*',
3911       'extra_sql' => " WHERE ( cust_pkg.pkgnum = $pkgnum OR ".
3912                      " ( cust_pkg.custnum = $custnum AND ".
3913                      " part_pkg_usage.shared IS NOT NULL ) ) AND ".
3914                      $is_classnum . ' AND '.
3915                      " cust_pkg_usage.minutes > 0",
3916       'order_by'  => " ORDER BY priority ASC",
3917   });
3918
3919   my $orig_minutes = $minutes;
3920   my $error;
3921   while (!$error and $minutes > 0 and @usage_recs) {
3922     my $cust_pkg_usage = shift @usage_recs;
3923     $cust_pkg_usage->select_for_update;
3924     my $cdr_cust_pkg_usage = FS::cdr_cust_pkg_usage->new({
3925         pkgusagenum => $cust_pkg_usage->pkgusagenum,
3926         acctid      => $cdr->acctid,
3927         minutes     => min($cust_pkg_usage->minutes, $minutes),
3928     });
3929     $cust_pkg_usage->set('minutes',
3930       sprintf('%.0f', $cust_pkg_usage->minutes - $cdr_cust_pkg_usage->minutes)
3931     );
3932     $error = $cust_pkg_usage->replace || $cdr_cust_pkg_usage->insert;
3933     $minutes -= $cdr_cust_pkg_usage->minutes;
3934   }
3935   if ( $order and $minutes > 0 and !$error ) {
3936     # then try to steal minutes from another call
3937     my %search = (
3938         'table'     => 'cdr_cust_pkg_usage',
3939         'addl_from' => ' JOIN cust_pkg_usage        USING (pkgusagenum)'.
3940                        ' JOIN part_pkg_usage        USING (pkgusagepart)'.
3941                        ' JOIN cust_pkg              USING (pkgnum)'.
3942                        ' JOIN part_pkg_usage_class  USING (pkgusagepart)'.
3943                        ' JOIN cdr                   USING (acctid)',
3944         'select'    => 'cdr_cust_pkg_usage.*',
3945         'extra_sql' => " WHERE cdr.freesidestatus = 'rated' AND ".
3946                        " ( cust_pkg.pkgnum = $pkgnum OR ".
3947                        " ( cust_pkg.custnum = $custnum AND ".
3948                        " part_pkg_usage.shared IS NOT NULL ) ) AND ".
3949                        " part_pkg_usage_class.classnum = $classnum",
3950         'order_by'  => ' ORDER BY part_pkg_usage.priority ASC',
3951     );
3952     if ( $order eq 'time' ) {
3953       # find CDRs that are using minutes, but have a later startdate
3954       # than this call
3955       my $startdate = $cdr->startdate;
3956       if ($startdate !~ /^\d+$/) {
3957         die "bad cdr startdate '$startdate'";
3958       }
3959       $search{'extra_sql'} .= " AND cdr.startdate > $startdate";
3960       # minimize needless reshuffling
3961       $search{'order_by'} .= ', cdr.startdate DESC';
3962     } else {
3963       # XXX may not work correctly with rate_time schedules.  Could 
3964       # fix this by storing ratedetailnum in cdr_cust_pkg_usage, I 
3965       # think...
3966       $search{'addl_from'} .=
3967         ' JOIN rate_detail'.
3968         ' ON (cdr.rated_ratedetailnum = rate_detail.ratedetailnum)';
3969       if ( $order eq 'rate_high' ) {
3970         $search{'extra_sql'} .= ' AND rate_detail.min_charge < '.
3971                                 $rate_detail->min_charge;
3972         $search{'order_by'} .= ', rate_detail.min_charge ASC';
3973       } elsif ( $order eq 'rate_low' ) {
3974         $search{'extra_sql'} .= ' AND rate_detail.min_charge > '.
3975                                 $rate_detail->min_charge;
3976         $search{'order_by'} .= ', rate_detail.min_charge DESC';
3977       } else {
3978         #  this should really never happen
3979         die "invalid cdr-minutes_priority value '$order'\n";
3980       }
3981     }
3982     my @cdr_usage_recs = qsearch(\%search);
3983     my %reproc_cdrs;
3984     while (!$error and @cdr_usage_recs and $minutes > 0) {
3985       my $cdr_cust_pkg_usage = shift @cdr_usage_recs;
3986       my $cust_pkg_usage = $cdr_cust_pkg_usage->cust_pkg_usage;
3987       my $old_cdr = $cdr_cust_pkg_usage->cdr;
3988       $reproc_cdrs{$old_cdr->acctid} = $old_cdr;
3989       $cdr_cust_pkg_usage->select_for_update;
3990       $old_cdr->select_for_update;
3991       $cust_pkg_usage->select_for_update;
3992       # in case someone else stole the usage from this CDR
3993       # while waiting for the lock...
3994       next if $old_cdr->acctid != $cdr_cust_pkg_usage->acctid;
3995       # steal the usage allocation and flag the old CDR for reprocessing
3996       $cdr_cust_pkg_usage->set('acctid', $cdr->acctid);
3997       # if the allocation is more minutes than we need, adjust it...
3998       my $delta = $cdr_cust_pkg_usage->minutes - $minutes;
3999       if ( $delta > 0 ) {
4000         $cdr_cust_pkg_usage->set('minutes', $minutes);
4001         $cust_pkg_usage->set('minutes', $cust_pkg_usage->minutes + $delta);
4002         $error = $cust_pkg_usage->replace;
4003       }
4004       #warn 'CDR '.$cdr->acctid . ' stealing allocation '.$cdr_cust_pkg_usage->cdrusagenum.' from CDR '.$old_cdr->acctid."\n";
4005       $error ||= $cdr_cust_pkg_usage->replace;
4006       # deduct the stolen minutes
4007       $minutes -= $cdr_cust_pkg_usage->minutes;
4008     }
4009     # after all minute-stealing is done, reset the affected CDRs
4010     foreach (values %reproc_cdrs) {
4011       $error ||= $_->set_status('');
4012       # XXX or should we just call $cdr->rate right here?
4013       # it's not like we can create a loop this way, since the min_charge
4014       # or call time has to go monotonically in one direction.
4015       # we COULD get some very deep recursions going, though...
4016     }
4017   } # if $order and $minutes
4018   if ( $error ) {
4019     $dbh->rollback;
4020     die "error applying included minutes\npkgnum ".$self->pkgnum.", class $classnum, acctid ".$cdr->acctid."\n$error\n"
4021   } else {
4022     $dbh->commit if $oldAutoCommit;
4023     return $orig_minutes - $minutes;
4024   }
4025 }
4026
4027 =item supplemental_pkgs
4028
4029 Returns a list of all packages supplemental to this one.
4030
4031 =cut
4032
4033 sub supplemental_pkgs {
4034   my $self = shift;
4035   qsearch('cust_pkg', { 'main_pkgnum' => $self->pkgnum });
4036 }
4037
4038 =item main_pkg
4039
4040 Returns the package that this one is supplemental to, if any.
4041
4042 =cut
4043
4044 sub main_pkg {
4045   my $self = shift;
4046   if ( $self->main_pkgnum ) {
4047     return FS::cust_pkg->by_key($self->main_pkgnum);
4048   }
4049   return;
4050 }
4051
4052 =back
4053
4054 =head1 CLASS METHODS
4055
4056 =over 4
4057
4058 =item recurring_sql
4059
4060 Returns an SQL expression identifying recurring packages.
4061
4062 =cut
4063
4064 sub recurring_sql { "
4065   '0' != ( select freq from part_pkg
4066              where cust_pkg.pkgpart = part_pkg.pkgpart )
4067 "; }
4068
4069 =item onetime_sql
4070
4071 Returns an SQL expression identifying one-time packages.
4072
4073 =cut
4074
4075 sub onetime_sql { "
4076   '0' = ( select freq from part_pkg
4077             where cust_pkg.pkgpart = part_pkg.pkgpart )
4078 "; }
4079
4080 =item ordered_sql
4081
4082 Returns an SQL expression identifying ordered packages (recurring packages not
4083 yet billed).
4084
4085 =cut
4086
4087 sub ordered_sql {
4088    $_[0]->recurring_sql. " AND ". $_[0]->not_yet_billed_sql;
4089 }
4090
4091 =item active_sql
4092
4093 Returns an SQL expression identifying active packages.
4094
4095 =cut
4096
4097 sub active_sql {
4098   $_[0]->recurring_sql. "
4099   AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
4100   AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4101   AND ( cust_pkg.susp   IS NULL OR cust_pkg.susp   = 0 )
4102 "; }
4103
4104 =item not_yet_billed_sql
4105
4106 Returns an SQL expression identifying packages which have not yet been billed.
4107
4108 =cut
4109
4110 sub not_yet_billed_sql { "
4111       ( cust_pkg.setup  IS NULL OR cust_pkg.setup  = 0 )
4112   AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4113   AND ( cust_pkg.susp   IS NULL OR cust_pkg.susp   = 0 )
4114 "; }
4115
4116 =item inactive_sql
4117
4118 Returns an SQL expression identifying inactive packages (one-time packages
4119 that are otherwise unsuspended/uncancelled).
4120
4121 =cut
4122
4123 sub inactive_sql { "
4124   ". $_[0]->onetime_sql(). "
4125   AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
4126   AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4127   AND ( cust_pkg.susp   IS NULL OR cust_pkg.susp   = 0 )
4128 "; }
4129
4130 =item susp_sql
4131 =item suspended_sql
4132
4133 Returns an SQL expression identifying suspended packages.
4134
4135 =cut
4136
4137 sub suspended_sql { susp_sql(@_); }
4138 sub susp_sql {
4139   #$_[0]->recurring_sql(). ' AND '.
4140   "
4141         ( cust_pkg.cancel IS     NULL  OR cust_pkg.cancel = 0 )
4142     AND   cust_pkg.susp   IS NOT NULL AND cust_pkg.susp  != 0
4143   ";
4144 }
4145
4146 =item cancel_sql
4147 =item cancelled_sql
4148
4149 Returns an SQL exprression identifying cancelled packages.
4150
4151 =cut
4152
4153 sub cancelled_sql { cancel_sql(@_); }
4154 sub cancel_sql { 
4155   #$_[0]->recurring_sql(). ' AND '.
4156   "cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0";
4157 }
4158
4159 =item status_sql
4160
4161 Returns an SQL expression to give the package status as a string.
4162
4163 =cut
4164
4165 sub status_sql {
4166 "CASE
4167   WHEN cust_pkg.cancel IS NOT NULL THEN 'cancelled'
4168   WHEN cust_pkg.susp IS NOT NULL THEN 'suspended'
4169   WHEN cust_pkg.setup IS NULL THEN 'not yet billed'
4170   WHEN ".onetime_sql()." THEN 'one-time charge'
4171   ELSE 'active'
4172 END"
4173 }
4174
4175 =item search HASHREF
4176
4177 (Class method)
4178
4179 Returns a qsearch hash expression to search for parameters specified in HASHREF.
4180 Valid parameters are
4181
4182 =over 4
4183
4184 =item agentnum
4185
4186 =item magic
4187
4188 active, inactive, suspended, cancel (or cancelled)
4189
4190 =item status
4191
4192 active, inactive, suspended, one-time charge, inactive, cancel (or cancelled)
4193
4194 =item custom
4195
4196  boolean selects custom packages
4197
4198 =item classnum
4199
4200 =item pkgpart
4201
4202 pkgpart or arrayref or hashref of pkgparts
4203
4204 =item setup
4205
4206 arrayref of beginning and ending epoch date
4207
4208 =item last_bill
4209
4210 arrayref of beginning and ending epoch date
4211
4212 =item bill
4213
4214 arrayref of beginning and ending epoch date
4215
4216 =item adjourn
4217
4218 arrayref of beginning and ending epoch date
4219
4220 =item susp
4221
4222 arrayref of beginning and ending epoch date
4223
4224 =item expire
4225
4226 arrayref of beginning and ending epoch date
4227
4228 =item cancel
4229
4230 arrayref of beginning and ending epoch date
4231
4232 =item query
4233
4234 pkgnum or APKG_pkgnum
4235
4236 =item cust_fields
4237
4238 a value suited to passing to FS::UI::Web::cust_header
4239
4240 =item CurrentUser
4241
4242 specifies the user for agent virtualization
4243
4244 =item fcc_line
4245
4246 boolean; if true, returns only packages with more than 0 FCC phone lines.
4247
4248 =item state, country
4249
4250 Limit to packages with a service location in the specified state and country.
4251 For FCC 477 reporting, mostly.
4252
4253 =item location_cust
4254
4255 Limit to packages whose service locations are the same as the customer's 
4256 default service location.
4257
4258 =item location_nocust
4259
4260 Limit to packages whose service locations are not the customer's default 
4261 service location.
4262
4263 =item location_census
4264
4265 Limit to packages whose service locations have census tracts.
4266
4267 =item location_nocensus
4268
4269 Limit to packages whose service locations do not have a census tract.
4270
4271 =item location_geocode
4272
4273 Limit to packages whose locations have geocodes.
4274
4275 =item location_geocode
4276
4277 Limit to packages whose locations do not have geocodes.
4278
4279 =back
4280
4281 =cut
4282
4283 sub search {
4284   my ($class, $params) = @_;
4285   my @where = ();
4286
4287   ##
4288   # parse agent
4289   ##
4290
4291   if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
4292     push @where,
4293       "cust_main.agentnum = $1";
4294   }
4295
4296   ##
4297   # parse cust_status
4298   ##
4299
4300   if ( $params->{'cust_status'} =~ /^([a-z]+)$/ ) {
4301     push @where, FS::cust_main->cust_status_sql . " = '$1' ";
4302   }
4303
4304   ##
4305   # parse customer sales person
4306   ##
4307
4308   if ( $params->{'cust_main_salesnum'} =~ /^(\d+)$/ ) {
4309     push @where, ($1 > 0) ? "cust_main.salesnum = $1"
4310                           : 'cust_main.salesnum IS NULL';
4311   }
4312
4313
4314   ##
4315   # parse sales person
4316   ##
4317
4318   if ( $params->{'salesnum'} =~ /^(\d+)$/ ) {
4319     push @where, ($1 > 0) ? "cust_pkg.salesnum = $1"
4320                           : 'cust_pkg.salesnum IS NULL';
4321   }
4322
4323   ##
4324   # parse custnum
4325   ##
4326
4327   if ( $params->{'custnum'} =~ /^(\d+)$/ and $1 ) {
4328     push @where,
4329       "cust_pkg.custnum = $1";
4330   }
4331
4332   ##
4333   # custbatch
4334   ##
4335
4336   if ( $params->{'pkgbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
4337     push @where,
4338       "cust_pkg.pkgbatch = '$1'";
4339   }
4340
4341   ##
4342   # parse status
4343   ##
4344
4345   if (    $params->{'magic'}  eq 'active'
4346        || $params->{'status'} eq 'active' ) {
4347
4348     push @where, FS::cust_pkg->active_sql();
4349
4350   } elsif (    $params->{'magic'}  =~ /^not[ _]yet[ _]billed$/
4351             || $params->{'status'} =~ /^not[ _]yet[ _]billed$/ ) {
4352
4353     push @where, FS::cust_pkg->not_yet_billed_sql();
4354
4355   } elsif (    $params->{'magic'}  =~ /^(one-time charge|inactive)/
4356             || $params->{'status'} =~ /^(one-time charge|inactive)/ ) {
4357
4358     push @where, FS::cust_pkg->inactive_sql();
4359
4360   } elsif (    $params->{'magic'}  eq 'suspended'
4361             || $params->{'status'} eq 'suspended'  ) {
4362
4363     push @where, FS::cust_pkg->suspended_sql();
4364
4365   } elsif (    $params->{'magic'}  =~ /^cancell?ed$/
4366             || $params->{'status'} =~ /^cancell?ed$/ ) {
4367
4368     push @where, FS::cust_pkg->cancelled_sql();
4369
4370   }
4371
4372   ###
4373   # parse package class
4374   ###
4375
4376   if ( exists($params->{'classnum'}) ) {
4377
4378     my @classnum = ();
4379     if ( ref($params->{'classnum'}) ) {
4380
4381       if ( ref($params->{'classnum'}) eq 'HASH' ) {
4382         @classnum = grep $params->{'classnum'}{$_}, keys %{ $params->{'classnum'} };
4383       } elsif ( ref($params->{'classnum'}) eq 'ARRAY' ) {
4384         @classnum = @{ $params->{'classnum'} };
4385       } else {
4386         die 'unhandled classnum ref '. $params->{'classnum'};
4387       }
4388
4389
4390     } elsif ( $params->{'classnum'} =~ /^(\d*)$/ && $1 ne '0' ) {
4391       @classnum = ( $1 );
4392     }
4393
4394     if ( @classnum ) {
4395
4396       my @c_where = ();
4397       my @nums = grep $_, @classnum;
4398       push @c_where, 'part_pkg.classnum IN ('. join(',',@nums). ')' if @nums;
4399       my $null = scalar( grep { $_ eq '' } @classnum );
4400       push @c_where, 'part_pkg.classnum IS NULL' if $null;
4401
4402       if ( scalar(@c_where) == 1 ) {
4403         push @where, @c_where;
4404       } elsif ( @c_where ) {
4405         push @where, ' ( '. join(' OR ', @c_where). ' ) ';
4406       }
4407
4408     }
4409     
4410
4411   }
4412
4413   ###
4414   # parse package report options
4415   ###
4416
4417   my @report_option = ();
4418   if ( exists($params->{'report_option'}) ) {
4419     if ( ref($params->{'report_option'}) eq 'ARRAY' ) {
4420       @report_option = @{ $params->{'report_option'} };
4421     } elsif ( $params->{'report_option'} =~ /^([,\d]*)$/ ) {
4422       @report_option = split(',', $1);
4423     }
4424
4425   }
4426
4427   if (@report_option) {
4428     # this will result in the empty set for the dangling comma case as it should
4429     push @where, 
4430       map{ "0 < ( SELECT count(*) FROM part_pkg_option
4431                     WHERE part_pkg_option.pkgpart = part_pkg.pkgpart
4432                     AND optionname = 'report_option_$_'
4433                     AND optionvalue = '1' )"
4434          } @report_option;
4435   }
4436
4437   foreach my $any ( grep /^report_option_any/, keys %$params ) {
4438
4439     my @report_option_any = ();
4440     if ( ref($params->{$any}) eq 'ARRAY' ) {
4441       @report_option_any = @{ $params->{$any} };
4442     } elsif ( $params->{$any} =~ /^([,\d]*)$/ ) {
4443       @report_option_any = split(',', $1);
4444     }
4445
4446     if (@report_option_any) {
4447       # this will result in the empty set for the dangling comma case as it should
4448       push @where, ' ( '. join(' OR ',
4449         map{ "0 < ( SELECT count(*) FROM part_pkg_option
4450                       WHERE part_pkg_option.pkgpart = part_pkg.pkgpart
4451                       AND optionname = 'report_option_$_'
4452                       AND optionvalue = '1' )"
4453            } @report_option_any
4454       ). ' ) ';
4455     }
4456
4457   }
4458
4459   ###
4460   # parse custom
4461   ###
4462
4463   push @where,  "part_pkg.custom = 'Y'" if $params->{custom};
4464
4465   ###
4466   # parse fcc_line
4467   ###
4468
4469   push @where,  "(part_pkg.fcc_ds0s > 0 OR pkg_class.fcc_ds0s > 0)" 
4470                                                         if $params->{fcc_line};
4471
4472   ###
4473   # parse censustract
4474   ###
4475
4476   if ( exists($params->{'censustract'}) ) {
4477     $params->{'censustract'} =~ /^([.\d]*)$/;
4478     my $censustract = "cust_location.censustract = '$1'";
4479     $censustract .= ' OR cust_location.censustract is NULL' unless $1;
4480     push @where,  "( $censustract )";
4481   }
4482
4483   ###
4484   # parse censustract2
4485   ###
4486   if ( exists($params->{'censustract2'})
4487        && $params->{'censustract2'} =~ /^(\d*)$/
4488      )
4489   {
4490     if ($1) {
4491       push @where, "cust_location.censustract LIKE '$1%'";
4492     } else {
4493       push @where,
4494         "( cust_location.censustract = '' OR cust_location.censustract IS NULL )";
4495     }
4496   }
4497
4498   ###
4499   # parse country/state
4500   ###
4501   for (qw(state country)) { # parsing rules are the same for these
4502   if ( exists($params->{$_}) 
4503     && uc($params->{$_}) =~ /^([A-Z]{2})$/ )
4504     {
4505       # XXX post-2.3 only--before that, state/country may be in cust_main
4506       push @where, "cust_location.$_ = '$1'";
4507     }
4508   }
4509
4510   ###
4511   # location_* flags
4512   ###
4513   if ( $params->{location_cust} xor $params->{location_nocust} ) {
4514     my $op = $params->{location_cust} ? '=' : '!=';
4515     push @where, "cust_location.locationnum $op cust_main.ship_locationnum";
4516   }
4517   if ( $params->{location_census} xor $params->{location_nocensus} ) {
4518     my $op = $params->{location_census} ? "IS NOT NULL" : "IS NULL";
4519     push @where, "cust_location.censustract $op";
4520   }
4521   if ( $params->{location_geocode} xor $params->{location_nogeocode} ) {
4522     my $op = $params->{location_geocode} ? "IS NOT NULL" : "IS NULL";
4523     push @where, "cust_location.geocode $op";
4524   }
4525
4526   ###
4527   # parse part_pkg
4528   ###
4529
4530   if ( ref($params->{'pkgpart'}) ) {
4531
4532     my @pkgpart = ();
4533     if ( ref($params->{'pkgpart'}) eq 'HASH' ) {
4534       @pkgpart = grep $params->{'pkgpart'}{$_}, keys %{ $params->{'pkgpart'} };
4535     } elsif ( ref($params->{'pkgpart'}) eq 'ARRAY' ) {
4536       @pkgpart = @{ $params->{'pkgpart'} };
4537     } else {
4538       die 'unhandled pkgpart ref '. $params->{'pkgpart'};
4539     }
4540
4541     @pkgpart = grep /^(\d+)$/, @pkgpart;
4542
4543     push @where, 'pkgpart IN ('. join(',', @pkgpart). ')' if scalar(@pkgpart);
4544
4545   } elsif ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
4546     push @where, "pkgpart = $1";
4547   } 
4548
4549   ###
4550   # parse dates
4551   ###
4552
4553   my $orderby = '';
4554
4555   #false laziness w/report_cust_pkg.html
4556   my %disable = (
4557     'all'             => {},
4558     'one-time charge' => { 'last_bill'=>1, 'bill'=>1, 'adjourn'=>1, 'susp'=>1, 'expire'=>1, 'cancel'=>1, },
4559     'active'          => { 'susp'=>1, 'cancel'=>1 },
4560     'suspended'       => { 'cancel' => 1 },
4561     'cancelled'       => {},
4562     ''                => {},
4563   );
4564
4565   if( exists($params->{'active'} ) ) {
4566     # This overrides all the other date-related fields
4567     my($beginning, $ending) = @{$params->{'active'}};
4568     push @where,
4569       "cust_pkg.setup IS NOT NULL",
4570       "cust_pkg.setup <= $ending",
4571       "(cust_pkg.cancel IS NULL OR cust_pkg.cancel >= $beginning )",
4572       "NOT (".FS::cust_pkg->onetime_sql . ")";
4573   }
4574   else {
4575     foreach my $field (qw( setup last_bill bill adjourn susp expire contract_end change_date cancel )) {
4576
4577       next unless exists($params->{$field});
4578
4579       my($beginning, $ending) = @{$params->{$field}};
4580
4581       next if $beginning == 0 && $ending == 4294967295;
4582
4583       push @where,
4584         "cust_pkg.$field IS NOT NULL",
4585         "cust_pkg.$field >= $beginning",
4586         "cust_pkg.$field <= $ending";
4587
4588       $orderby ||= "ORDER BY cust_pkg.$field";
4589
4590     }
4591   }
4592
4593   $orderby ||= 'ORDER BY bill';
4594
4595   ###
4596   # parse magic, legacy, etc.
4597   ###
4598
4599   if ( $params->{'magic'} &&
4600        $params->{'magic'} =~ /^(active|inactive|suspended|cancell?ed)$/
4601   ) {
4602
4603     $orderby = 'ORDER BY pkgnum';
4604
4605     if ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
4606       push @where, "pkgpart = $1";
4607     }
4608
4609   } elsif ( $params->{'query'} eq 'pkgnum' ) {
4610
4611     $orderby = 'ORDER BY pkgnum';
4612
4613   } elsif ( $params->{'query'} eq 'APKG_pkgnum' ) {
4614
4615     $orderby = 'ORDER BY pkgnum';
4616
4617     push @where, '0 < (
4618       SELECT count(*) FROM pkg_svc
4619        WHERE pkg_svc.pkgpart =  cust_pkg.pkgpart
4620          AND pkg_svc.quantity > ( SELECT count(*) FROM cust_svc
4621                                    WHERE cust_svc.pkgnum  = cust_pkg.pkgnum
4622                                      AND cust_svc.svcpart = pkg_svc.svcpart
4623                                 )
4624     )';
4625   
4626   }
4627
4628   ##
4629   # setup queries, links, subs, etc. for the search
4630   ##
4631
4632   # here is the agent virtualization
4633   if ($params->{CurrentUser}) {
4634     my $access_user =
4635       qsearchs('access_user', { username => $params->{CurrentUser} });
4636
4637     if ($access_user) {
4638       push @where, $access_user->agentnums_sql('table'=>'cust_main');
4639     } else {
4640       push @where, "1=0";
4641     }
4642   } else {
4643     push @where, $FS::CurrentUser::CurrentUser->agentnums_sql('table'=>'cust_main');
4644   }
4645
4646   my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
4647
4648   my $addl_from = 'LEFT JOIN part_pkg  USING ( pkgpart  ) '.
4649                   'LEFT JOIN pkg_class ON ( part_pkg.classnum = pkg_class.classnum ) '.
4650                   'LEFT JOIN cust_location USING ( locationnum ) '.
4651                   FS::UI::Web::join_cust_main('cust_pkg', 'cust_pkg');
4652
4653   my $select;
4654   my $count_query;
4655   if ( $params->{'select_zip5'} ) {
4656     my $zip = 'cust_location.zip';
4657
4658     $select = "DISTINCT substr($zip,1,5) as zip";
4659     $orderby = "ORDER BY substr($zip,1,5)";
4660     $count_query = "SELECT COUNT( DISTINCT substr($zip,1,5) )";
4661   } else {
4662     $select = join(', ',
4663                          'cust_pkg.*',
4664                          ( map "part_pkg.$_", qw( pkg freq ) ),
4665                          'pkg_class.classname',
4666                          'cust_main.custnum AS cust_main_custnum',
4667                          FS::UI::Web::cust_sql_fields(
4668                            $params->{'cust_fields'}
4669                          ),
4670                   );
4671     $count_query = 'SELECT COUNT(*)';
4672   }
4673
4674   $count_query .= " FROM cust_pkg $addl_from $extra_sql";
4675
4676   my $sql_query = {
4677     'table'       => 'cust_pkg',
4678     'hashref'     => {},
4679     'select'      => $select,
4680     'extra_sql'   => $extra_sql,
4681     'order_by'    => $orderby,
4682     'addl_from'   => $addl_from,
4683     'count_query' => $count_query,
4684   };
4685
4686 }
4687
4688 =item fcc_477_count
4689
4690 Returns a list of two package counts.  The first is a count of packages
4691 based on the supplied criteria and the second is the count of residential
4692 packages with those same criteria.  Criteria are specified as in the search
4693 method.
4694
4695 =cut
4696
4697 sub fcc_477_count {
4698   my ($class, $params) = @_;
4699
4700   my $sql_query = $class->search( $params );
4701
4702   my $count_sql = delete($sql_query->{'count_query'});
4703   $count_sql =~ s/ FROM/,count(CASE WHEN cust_main.company IS NULL OR cust_main.company = '' THEN 1 END) FROM/
4704     or die "couldn't parse count_sql";
4705
4706   my $count_sth = dbh->prepare($count_sql)
4707     or die "Error preparing $count_sql: ". dbh->errstr;
4708   $count_sth->execute
4709     or die "Error executing $count_sql: ". $count_sth->errstr;
4710   my $count_arrayref = $count_sth->fetchrow_arrayref;
4711
4712   return ( @$count_arrayref );
4713
4714 }
4715
4716 =item tax_locationnum_sql
4717
4718 Returns an SQL expression for the tax location for a package, based
4719 on the settings of 'tax-pkg_address' and 'tax-ship_address'.
4720
4721 =cut
4722
4723 sub tax_locationnum_sql {
4724   my $conf = FS::Conf->new;
4725   if ( $conf->exists('tax-pkg_address') ) {
4726     'cust_pkg.locationnum';
4727   }
4728   elsif ( $conf->exists('tax-ship_address') ) {
4729     'cust_main.ship_locationnum';
4730   }
4731   else {
4732     'cust_main.bill_locationnum';
4733   }
4734 }
4735
4736 =item location_sql
4737
4738 Returns a list: the first item is an SQL fragment identifying matching 
4739 packages/customers via location (taking into account shipping and package
4740 address taxation, if enabled), and subsequent items are the parameters to
4741 substitute for the placeholders in that fragment.
4742
4743 =cut
4744
4745 sub location_sql {
4746   my($class, %opt) = @_;
4747   my $ornull = $opt{'ornull'};
4748
4749   my $conf = new FS::Conf;
4750
4751   # '?' placeholders in _location_sql_where
4752   my $x = $ornull ? 3 : 2;
4753   my @bill_param = ( 
4754     ('district')x3,
4755     ('city')x3, 
4756     ('county')x$x,
4757     ('state')x$x,
4758     'country'
4759   );
4760
4761   my $main_where;
4762   my @main_param;
4763   if ( $conf->exists('tax-ship_address') ) {
4764
4765     $main_where = "(
4766          (     ( ship_last IS NULL     OR  ship_last  = '' )
4767            AND ". _location_sql_where('cust_main', '', $ornull ). "
4768          )
4769       OR (       ship_last IS NOT NULL AND ship_last != ''
4770            AND ". _location_sql_where('cust_main', 'ship_', $ornull ). "
4771          )
4772     )";
4773     #    AND payby != 'COMP'
4774
4775     @main_param = ( @bill_param, @bill_param );
4776
4777   } else {
4778
4779     $main_where = _location_sql_where('cust_main'); # AND payby != 'COMP'
4780     @main_param = @bill_param;
4781
4782   }
4783
4784   my $where;
4785   my @param;
4786   if ( $conf->exists('tax-pkg_address') ) {
4787
4788     my $loc_where = _location_sql_where( 'cust_location', '', $ornull );
4789
4790     $where = " (
4791                     ( cust_pkg.locationnum IS     NULL AND $main_where )
4792                  OR ( cust_pkg.locationnum IS NOT NULL AND $loc_where  )
4793                )
4794              ";
4795     @param = ( @main_param, @bill_param );
4796   
4797   } else {
4798
4799     $where = $main_where;
4800     @param = @main_param;
4801
4802   }
4803
4804   ( $where, @param );
4805
4806 }
4807
4808 #subroutine, helper for location_sql
4809 sub _location_sql_where {
4810   my $table  = shift;
4811   my $prefix = @_ ? shift : '';
4812   my $ornull = @_ ? shift : '';
4813
4814 #  $ornull             = $ornull          ? " OR ( ? IS NULL AND $table.${prefix}county IS NULL ) " : '';
4815
4816   $ornull = $ornull ? ' OR ? IS NULL ' : '';
4817
4818   my $or_empty_city     = " OR ( ? = '' AND $table.${prefix}city     IS NULL )";
4819   my $or_empty_county   = " OR ( ? = '' AND $table.${prefix}county   IS NULL )";
4820   my $or_empty_state    = " OR ( ? = '' AND $table.${prefix}state    IS NULL )";
4821
4822   my $text = (driver_name =~ /^mysql/i) ? 'char' : 'text';
4823
4824 #        ( $table.${prefix}city    = ? $or_empty_city   $ornull )
4825   "
4826         ( $table.district = ? OR ? = '' OR CAST(? AS $text) IS NULL )
4827     AND ( $table.${prefix}city     = ? OR ? = '' OR CAST(? AS $text) IS NULL )
4828     AND ( $table.${prefix}county   = ? $or_empty_county $ornull )
4829     AND ( $table.${prefix}state    = ? $or_empty_state  $ornull )
4830     AND   $table.${prefix}country  = ?
4831   ";
4832 }
4833
4834 sub _X_show_zero {
4835   my( $self, $what ) = @_;
4836
4837   my $what_show_zero = $what. '_show_zero';
4838   length($self->$what_show_zero())
4839     ? ($self->$what_show_zero() eq 'Y')
4840     : $self->part_pkg->$what_show_zero();
4841 }
4842
4843 =head1 SUBROUTINES
4844
4845 =over 4
4846
4847 =item order CUSTNUM, PKGPARTS_ARYREF, [ REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF [ REFNUM ] ] ]
4848
4849 CUSTNUM is a customer (see L<FS::cust_main>)
4850
4851 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
4852 L<FS::part_pkg>) to order for this customer.  Duplicates are of course
4853 permitted.
4854
4855 REMOVE_PKGNUMS is an optional list of pkgnums specifying the billing items to
4856 remove for this customer.  The services (see L<FS::cust_svc>) are moved to the
4857 new billing items.  An error is returned if this is not possible (see
4858 L<FS::pkg_svc>).  An empty arrayref is equivalent to not specifying this
4859 parameter.
4860
4861 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
4862 newly-created cust_pkg objects.
4863
4864 REFNUM, if specified, will specify the FS::pkg_referral record to be created
4865 and inserted.  Multiple FS::pkg_referral records can be created by
4866 setting I<refnum> to an array reference of refnums or a hash reference with
4867 refnums as keys.  If no I<refnum> is defined, a default FS::pkg_referral
4868 record will be created corresponding to cust_main.refnum.
4869
4870 =cut
4871
4872 sub order {
4873   my ($custnum, $pkgparts, $remove_pkgnum, $return_cust_pkg, $refnum) = @_;
4874
4875   my $conf = new FS::Conf;
4876
4877   # Transactionize this whole mess
4878   local $SIG{HUP} = 'IGNORE';
4879   local $SIG{INT} = 'IGNORE'; 
4880   local $SIG{QUIT} = 'IGNORE';
4881   local $SIG{TERM} = 'IGNORE';
4882   local $SIG{TSTP} = 'IGNORE'; 
4883   local $SIG{PIPE} = 'IGNORE'; 
4884
4885   my $oldAutoCommit = $FS::UID::AutoCommit;
4886   local $FS::UID::AutoCommit = 0;
4887   my $dbh = dbh;
4888
4889   my $error;
4890 #  my $cust_main = qsearchs('cust_main', { custnum => $custnum });
4891 #  return "Customer not found: $custnum" unless $cust_main;
4892
4893   warn "$me order: pkgnums to remove: ". join(',', @$remove_pkgnum). "\n"
4894     if $DEBUG;
4895
4896   my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
4897                          @$remove_pkgnum;
4898
4899   my $change = scalar(@old_cust_pkg) != 0;
4900
4901   my %hash = (); 
4902   if ( scalar(@old_cust_pkg) == 1 && scalar(@$pkgparts) == 1 ) {
4903
4904     warn "$me order: changing pkgnum ". $old_cust_pkg[0]->pkgnum.
4905          " to pkgpart ". $pkgparts->[0]. "\n"
4906       if $DEBUG;
4907
4908     my $err_or_cust_pkg =
4909       $old_cust_pkg[0]->change( 'pkgpart' => $pkgparts->[0],
4910                                 'refnum'  => $refnum,
4911                               );
4912
4913     unless (ref($err_or_cust_pkg)) {
4914       $dbh->rollback if $oldAutoCommit;
4915       return $err_or_cust_pkg;
4916     }
4917
4918     push @$return_cust_pkg, $err_or_cust_pkg;
4919     $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4920     return '';
4921
4922   }
4923
4924   # Create the new packages.
4925   foreach my $pkgpart (@$pkgparts) {
4926
4927     warn "$me order: inserting pkgpart $pkgpart\n" if $DEBUG;
4928
4929     my $cust_pkg = new FS::cust_pkg { custnum => $custnum,
4930                                       pkgpart => $pkgpart,
4931                                       refnum  => $refnum,
4932                                       %hash,
4933                                     };
4934     $error = $cust_pkg->insert( 'change' => $change );
4935     push @$return_cust_pkg, $cust_pkg;
4936
4937     foreach my $link ($cust_pkg->part_pkg->supp_part_pkg_link) {
4938       my $supp_pkg = FS::cust_pkg->new({
4939           custnum => $custnum,
4940           pkgpart => $link->dst_pkgpart,
4941           refnum  => $refnum,
4942           main_pkgnum => $cust_pkg->pkgnum,
4943           %hash,
4944       });
4945       $error ||= $supp_pkg->insert( 'change' => $change );
4946       push @$return_cust_pkg, $supp_pkg;
4947     }
4948
4949     if ($error) {
4950       $dbh->rollback if $oldAutoCommit;
4951       return $error;
4952     }
4953
4954   }
4955   # $return_cust_pkg now contains refs to all of the newly 
4956   # created packages.
4957
4958   # Transfer services and cancel old packages.
4959   foreach my $old_pkg (@old_cust_pkg) {
4960
4961     warn "$me order: transferring services from pkgnum ". $old_pkg->pkgnum. "\n"
4962       if $DEBUG;
4963
4964     foreach my $new_pkg (@$return_cust_pkg) {
4965       $error = $old_pkg->transfer($new_pkg);
4966       if ($error and $error == 0) {
4967         # $old_pkg->transfer failed.
4968         $dbh->rollback if $oldAutoCommit;
4969         return $error;
4970       }
4971     }
4972
4973     if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
4974       warn "trying transfer again with change_svcpart option\n" if $DEBUG;
4975       foreach my $new_pkg (@$return_cust_pkg) {
4976         $error = $old_pkg->transfer($new_pkg, 'change_svcpart'=>1 );
4977         if ($error and $error == 0) {
4978           # $old_pkg->transfer failed.
4979         $dbh->rollback if $oldAutoCommit;
4980         return $error;
4981         }
4982       }
4983     }
4984
4985     if ($error > 0) {
4986       # Transfers were successful, but we went through all of the 
4987       # new packages and still had services left on the old package.
4988       # We can't cancel the package under the circumstances, so abort.
4989       $dbh->rollback if $oldAutoCommit;
4990       return "Unable to transfer all services from package ".$old_pkg->pkgnum;
4991     }
4992     $error = $old_pkg->cancel( quiet=>1 );
4993     if ($error) {
4994       $dbh->rollback;
4995       return $error;
4996     }
4997   }
4998   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4999   '';
5000 }
5001
5002 =item bulk_change PKGPARTS_ARYREF, REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF ]
5003
5004 A bulk change method to change packages for multiple customers.
5005
5006 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
5007 L<FS::part_pkg>) to order for each customer.  Duplicates are of course
5008 permitted.
5009
5010 REMOVE_PKGNUMS is an list of pkgnums specifying the billing items to
5011 replace.  The services (see L<FS::cust_svc>) are moved to the
5012 new billing items.  An error is returned if this is not possible (see
5013 L<FS::pkg_svc>).
5014
5015 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
5016 newly-created cust_pkg objects.
5017
5018 =cut
5019
5020 sub bulk_change {
5021   my ($pkgparts, $remove_pkgnum, $return_cust_pkg) = @_;
5022
5023   # Transactionize this whole mess
5024   local $SIG{HUP} = 'IGNORE';
5025   local $SIG{INT} = 'IGNORE'; 
5026   local $SIG{QUIT} = 'IGNORE';
5027   local $SIG{TERM} = 'IGNORE';
5028   local $SIG{TSTP} = 'IGNORE'; 
5029   local $SIG{PIPE} = 'IGNORE'; 
5030
5031   my $oldAutoCommit = $FS::UID::AutoCommit;
5032   local $FS::UID::AutoCommit = 0;
5033   my $dbh = dbh;
5034
5035   my @errors;
5036   my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
5037                          @$remove_pkgnum;
5038
5039   while(scalar(@old_cust_pkg)) {
5040     my @return = ();
5041     my $custnum = $old_cust_pkg[0]->custnum;
5042     my (@remove) = map { $_->pkgnum }
5043                    grep { $_->custnum == $custnum } @old_cust_pkg;
5044     @old_cust_pkg = grep { $_->custnum != $custnum } @old_cust_pkg;
5045
5046     my $error = order $custnum, $pkgparts, \@remove, \@return;
5047
5048     push @errors, $error
5049       if $error;
5050     push @$return_cust_pkg, @return;
5051   }
5052
5053   if (scalar(@errors)) {
5054     $dbh->rollback if $oldAutoCommit;
5055     return join(' / ', @errors);
5056   }
5057
5058   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5059   '';
5060 }
5061
5062 # Used by FS::Upgrade to migrate to a new database.
5063 sub _upgrade_data {  # class method
5064   my ($class, %opts) = @_;
5065   $class->_upgrade_otaker(%opts);
5066   my @statements = (
5067     # RT#10139, bug resulting in contract_end being set when it shouldn't
5068   'UPDATE cust_pkg SET contract_end = NULL WHERE contract_end = -1',
5069     # RT#10830, bad calculation of prorate date near end of year
5070     # the date range for bill is December 2009, and we move it forward
5071     # one year if it's before the previous bill date (which it should 
5072     # never be)
5073   'UPDATE cust_pkg SET bill = bill + (365*24*60*60) WHERE bill < last_bill
5074   AND bill > 1259654400 AND bill < 1262332800 AND (SELECT plan FROM part_pkg 
5075   WHERE part_pkg.pkgpart = cust_pkg.pkgpart) = \'prorate\'',
5076     # RT6628, add order_date to cust_pkg
5077     'update cust_pkg set order_date = (select history_date from h_cust_pkg 
5078         where h_cust_pkg.pkgnum = cust_pkg.pkgnum and 
5079         history_action = \'insert\') where order_date is null',
5080   );
5081   foreach my $sql (@statements) {
5082     my $sth = dbh->prepare($sql);
5083     $sth->execute or die $sth->errstr;
5084   }
5085 }
5086
5087 =back
5088
5089 =head1 BUGS
5090
5091 sub order is not OO.  Perhaps it should be moved to FS::cust_main and made so?
5092
5093 In sub order, the @pkgparts array (passed by reference) is clobbered.
5094
5095 Also in sub order, no money is adjusted.  Once FS::part_pkg defines a standard
5096 method to pass dates to the recur_prog expression, it should do so.
5097
5098 FS::svc_acct, FS::svc_domain, FS::svc_www, FS::svc_ip and FS::svc_forward are
5099 loaded via 'use' at compile time, rather than via 'require' in sub { setup,
5100 suspend, unsuspend, cancel } because they use %FS::UID::callback to load
5101 configuration values.  Probably need a subroutine which decides what to do
5102 based on whether or not we've fetched the user yet, rather than a hash.  See
5103 FS::UID and the TODO.
5104
5105 Now that things are transactional should the check in the insert method be
5106 moved to check ?
5107
5108 =head1 SEE ALSO
5109
5110 L<FS::Record>, L<FS::cust_main>, L<FS::part_pkg>, L<FS::cust_svc>,
5111 L<FS::pkg_svc>, schema.html from the base documentation
5112
5113 =cut
5114
5115 1;
5116