add more debug tracing to invoice generation, RT#11452
[freeside.git] / FS / FS / cust_pkg.pm
1 package FS::cust_pkg;
2
3 use strict;
4 use base qw( FS::otaker_Mixin FS::cust_main_Mixin FS::location_Mixin
5              FS::m2m_Common FS::option_Common );
6 use vars qw($disable_agentcheck $DEBUG $me);
7 use Carp qw(cluck);
8 use Scalar::Util qw( blessed );
9 use List::Util qw(max);
10 use Tie::IxHash;
11 use Time::Local qw( timelocal_nocheck );
12 use MIME::Entity;
13 use FS::UID qw( getotaker dbh );
14 use FS::Misc qw( send_email );
15 use FS::Record qw( qsearch qsearchs );
16 use FS::CurrentUser;
17 use FS::cust_svc;
18 use FS::part_pkg;
19 use FS::cust_main;
20 use FS::cust_location;
21 use FS::pkg_svc;
22 use FS::cust_bill_pkg;
23 use FS::cust_pkg_detail;
24 use FS::cust_event;
25 use FS::h_cust_svc;
26 use FS::reg_code;
27 use FS::part_svc;
28 use FS::cust_pkg_reason;
29 use FS::reason;
30 use FS::cust_pkg_discount;
31 use FS::discount;
32 use FS::UI::Web;
33
34 # need to 'use' these instead of 'require' in sub { cancel, suspend, unsuspend,
35 # setup }
36 # because they load configuration by setting FS::UID::callback (see TODO)
37 use FS::svc_acct;
38 use FS::svc_domain;
39 use FS::svc_www;
40 use FS::svc_forward;
41
42 # for sending cancel emails in sub cancel
43 use FS::Conf;
44
45 $DEBUG = 0;
46 $me = '[FS::cust_pkg]';
47
48 $disable_agentcheck = 0;
49
50 sub _cache {
51   my $self = shift;
52   my ( $hashref, $cache ) = @_;
53   #if ( $hashref->{'pkgpart'} ) {
54   if ( $hashref->{'pkg'} ) {
55     # #@{ $self->{'_pkgnum'} } = ();
56     # my $subcache = $cache->subcache('pkgpart', 'part_pkg');
57     # $self->{'_pkgpart'} = $subcache;
58     # #push @{ $self->{'_pkgnum'} },
59     #   FS::part_pkg->new_or_cached($hashref, $subcache);
60     $self->{'_pkgpart'} = FS::part_pkg->new($hashref);
61   }
62   if ( exists $hashref->{'svcnum'} ) {
63     #@{ $self->{'_pkgnum'} } = ();
64     my $subcache = $cache->subcache('svcnum', 'cust_svc', $hashref->{pkgnum});
65     $self->{'_svcnum'} = $subcache;
66     #push @{ $self->{'_pkgnum'} },
67     FS::cust_svc->new_or_cached($hashref, $subcache) if $hashref->{svcnum};
68   }
69 }
70
71 =head1 NAME
72
73 FS::cust_pkg - Object methods for cust_pkg objects
74
75 =head1 SYNOPSIS
76
77   use FS::cust_pkg;
78
79   $record = new FS::cust_pkg \%hash;
80   $record = new FS::cust_pkg { 'column' => 'value' };
81
82   $error = $record->insert;
83
84   $error = $new_record->replace($old_record);
85
86   $error = $record->delete;
87
88   $error = $record->check;
89
90   $error = $record->cancel;
91
92   $error = $record->suspend;
93
94   $error = $record->unsuspend;
95
96   $part_pkg = $record->part_pkg;
97
98   @labels = $record->labels;
99
100   $seconds = $record->seconds_since($timestamp);
101
102   $error = FS::cust_pkg::order( $custnum, \@pkgparts );
103   $error = FS::cust_pkg::order( $custnum, \@pkgparts, \@remove_pkgnums ] );
104
105 =head1 DESCRIPTION
106
107 An FS::cust_pkg object represents a customer billing item.  FS::cust_pkg
108 inherits from FS::Record.  The following fields are currently supported:
109
110 =over 4
111
112 =item pkgnum
113
114 Primary key (assigned automatically for new billing items)
115
116 =item custnum
117
118 Customer (see L<FS::cust_main>)
119
120 =item pkgpart
121
122 Billing item definition (see L<FS::part_pkg>)
123
124 =item locationnum
125
126 Optional link to package location (see L<FS::location>)
127
128 =item order_date
129
130 date package was ordered (also remains same on changes)
131
132 =item start_date
133
134 date
135
136 =item setup
137
138 date
139
140 =item bill
141
142 date (next bill date)
143
144 =item last_bill
145
146 last bill date
147
148 =item adjourn
149
150 date
151
152 =item susp
153
154 date
155
156 =item expire
157
158 date
159
160 =item contract_end
161
162 date
163
164 =item cancel
165
166 date
167
168 =item usernum
169
170 order taker (see L<FS::access_user>)
171
172 =item manual_flag
173
174 If this field is set to 1, disables the automatic
175 unsuspension of this package when using the B<unsuspendauto> config option.
176
177 =item quantity
178
179 If not set, defaults to 1
180
181 =item change_date
182
183 Date of change from previous package
184
185 =item change_pkgnum
186
187 Previous pkgnum
188
189 =item change_pkgpart
190
191 Previous pkgpart
192
193 =item change_locationnum
194
195 Previous locationnum
196
197 =back
198
199 Note: setup, last_bill, bill, adjourn, susp, expire, cancel and change_date
200 are specified as UNIX timestamps; see L<perlfunc/"time">.  Also see
201 L<Time::Local> and L<Date::Parse> for conversion functions.
202
203 =head1 METHODS
204
205 =over 4
206
207 =item new HASHREF
208
209 Create a new billing item.  To add the item to the database, see L<"insert">.
210
211 =cut
212
213 sub table { 'cust_pkg'; }
214 sub cust_linked { $_[0]->cust_main_custnum; } 
215 sub cust_unlinked_msg {
216   my $self = shift;
217   "WARNING: can't find cust_main.custnum ". $self->custnum.
218   ' (cust_pkg.pkgnum '. $self->pkgnum. ')';
219 }
220
221 =item insert [ OPTION => VALUE ... ]
222
223 Adds this billing item to the database ("Orders" the item).  If there is an
224 error, returns the error, otherwise returns false.
225
226 If the additional field I<promo_code> is defined instead of I<pkgpart>, it
227 will be used to look up the package definition and agent restrictions will be
228 ignored.
229
230 If the additional field I<refnum> is defined, an FS::pkg_referral record will
231 be created and inserted.  Multiple FS::pkg_referral records can be created by
232 setting I<refnum> to an array reference of refnums or a hash reference with
233 refnums as keys.  If no I<refnum> is defined, a default FS::pkg_referral
234 record will be created corresponding to cust_main.refnum.
235
236 The following options are available:
237
238 =over 4
239
240 =item change
241
242 If set true, supresses any referral credit to a referring customer.
243
244 =item options
245
246 cust_pkg_option records will be created
247
248 =item ticket_subject
249
250 a ticket will be added to this customer with this subject
251
252 =item ticket_queue
253
254 an optional queue name for ticket additions
255
256 =back
257
258 =cut
259
260 sub insert {
261   my( $self, %options ) = @_;
262
263   my $error = $self->check_pkgpart;
264   return $error if $error;
265
266   if ( $self->part_pkg->option('start_1st', 1) && !$self->start_date ) {
267     my ($sec,$min,$hour,$mday,$mon,$year) = (localtime(time) )[0,1,2,3,4,5];
268     $mon += 1 unless $mday == 1;
269     until ( $mon < 12 ) { $mon -= 12; $year++; }
270     $self->start_date( timelocal_nocheck(0,0,0,1,$mon,$year) );
271   }
272
273   foreach my $action ( qw(expire adjourn contract_end) ) {
274     my $months = $self->part_pkg->option("${action}_months",1);
275     if($months and !$self->$action) {
276       my $start = $self->start_date || $self->setup || time;
277       $self->$action( $self->part_pkg->add_freq($start, $months) );
278     }
279   }
280
281   $self->order_date(time);
282
283   local $SIG{HUP} = 'IGNORE';
284   local $SIG{INT} = 'IGNORE';
285   local $SIG{QUIT} = 'IGNORE';
286   local $SIG{TERM} = 'IGNORE';
287   local $SIG{TSTP} = 'IGNORE';
288   local $SIG{PIPE} = 'IGNORE';
289
290   my $oldAutoCommit = $FS::UID::AutoCommit;
291   local $FS::UID::AutoCommit = 0;
292   my $dbh = dbh;
293
294   $error = $self->SUPER::insert($options{options} ? %{$options{options}} : ());
295   if ( $error ) {
296     $dbh->rollback if $oldAutoCommit;
297     return $error;
298   }
299
300   $self->refnum($self->cust_main->refnum) unless $self->refnum;
301   $self->refnum( [ $self->refnum ] ) unless ref($self->refnum);
302   $self->process_m2m( 'link_table'   => 'pkg_referral',
303                       'target_table' => 'part_referral',
304                       'params'       => $self->refnum,
305                     );
306
307   if ( $self->discountnum ) {
308     my $error = $self->insert_discount();
309     if ( $error ) {
310       $dbh->rollback if $oldAutoCommit;
311       return $error;
312     }
313   }
314
315   #if ( $self->reg_code ) {
316   #  my $reg_code = qsearchs('reg_code', { 'code' => $self->reg_code } );
317   #  $error = $reg_code->delete;
318   #  if ( $error ) {
319   #    $dbh->rollback if $oldAutoCommit;
320   #    return $error;
321   #  }
322   #}
323
324   my $conf = new FS::Conf;
325
326   if ( $conf->config('ticket_system') && $options{ticket_subject} ) {
327
328     #eval '
329     #  use lib ( "/opt/rt3/local/lib", "/opt/rt3/lib" );
330     #  use RT;
331     #';
332     #die $@ if $@;
333     #
334     #RT::LoadConfig();
335     #RT::Init();
336     use FS::TicketSystem;
337     FS::TicketSystem->init();
338
339     my $q = new RT::Queue($RT::SystemUser);
340     $q->Load($options{ticket_queue}) if $options{ticket_queue};
341     my $t = new RT::Ticket($RT::SystemUser);
342     my $mime = new MIME::Entity;
343     $mime->build( Type => 'text/plain', Data => $options{ticket_subject} );
344     $t->Create( $options{ticket_queue} ? (Queue => $q) : (),
345                 Subject => $options{ticket_subject},
346                 MIMEObj => $mime,
347               );
348     $t->AddLink( Type   => 'MemberOf',
349                  Target => 'freeside://freeside/cust_main/'. $self->custnum,
350                );
351   }
352
353   if ($conf->config('welcome_letter') && $self->cust_main->num_pkgs == 1) {
354     my $queue = new FS::queue {
355       'job'     => 'FS::cust_main::queueable_print',
356     };
357     $error = $queue->insert(
358       'custnum'  => $self->custnum,
359       'template' => 'welcome_letter',
360     );
361
362     if ($error) {
363       warn "can't send welcome letter: $error";
364     }
365
366   }
367
368   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
369   '';
370
371 }
372
373 =item delete
374
375 This method now works but you probably shouldn't use it.
376
377 You don't want to delete packages, because there would then be no record
378 the customer ever purchased the package.  Instead, see the cancel method and
379 hide cancelled packages.
380
381 =cut
382
383 sub delete {
384   my $self = shift;
385
386   local $SIG{HUP} = 'IGNORE';
387   local $SIG{INT} = 'IGNORE';
388   local $SIG{QUIT} = 'IGNORE';
389   local $SIG{TERM} = 'IGNORE';
390   local $SIG{TSTP} = 'IGNORE';
391   local $SIG{PIPE} = 'IGNORE';
392
393   my $oldAutoCommit = $FS::UID::AutoCommit;
394   local $FS::UID::AutoCommit = 0;
395   my $dbh = dbh;
396
397   foreach my $cust_pkg_discount ($self->cust_pkg_discount) {
398     my $error = $cust_pkg_discount->delete;
399     if ( $error ) {
400       $dbh->rollback if $oldAutoCommit;
401       return $error;
402     }
403   }
404   #cust_bill_pkg_discount?
405
406   foreach my $cust_pkg_detail ($self->cust_pkg_detail) {
407     my $error = $cust_pkg_detail->delete;
408     if ( $error ) {
409       $dbh->rollback if $oldAutoCommit;
410       return $error;
411     }
412   }
413
414   foreach my $cust_pkg_reason (
415     qsearchs( {
416                 'table' => 'cust_pkg_reason',
417                 'hashref' => { 'pkgnum' => $self->pkgnum },
418               }
419             )
420   ) {
421     my $error = $cust_pkg_reason->delete;
422     if ( $error ) {
423       $dbh->rollback if $oldAutoCommit;
424       return $error;
425     }
426   }
427
428   #pkg_referral?
429
430   my $error = $self->SUPER::delete(@_);
431   if ( $error ) {
432     $dbh->rollback if $oldAutoCommit;
433     return $error;
434   }
435
436   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
437
438   '';
439
440 }
441
442 =item replace [ OLD_RECORD ] [ HASHREF | OPTION => VALUE ... ]
443
444 Replaces the OLD_RECORD with this one in the database.  If there is an error,
445 returns the error, otherwise returns false.
446
447 Currently, custnum, setup, bill, adjourn, susp, expire, and cancel may be changed.
448
449 Changing pkgpart may have disasterous effects.  See the order subroutine.
450
451 setup and bill are normally updated by calling the bill method of a customer
452 object (see L<FS::cust_main>).
453
454 suspend is normally updated by the suspend and unsuspend methods.
455
456 cancel is normally updated by the cancel method (and also the order subroutine
457 in some cases).
458
459 Available options are:
460
461 =over 4
462
463 =item reason
464
465 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.
466
467 =item reason_otaker
468
469 the access_user (see L<FS::access_user>) providing the reason
470
471 =item options
472
473 hashref of keys and values - cust_pkg_option records will be created, updated or removed as appopriate
474
475 =back
476
477 =cut
478
479 sub replace {
480   my $new = shift;
481
482   my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
483               ? shift
484               : $new->replace_old;
485
486   my $options = 
487     ( ref($_[0]) eq 'HASH' )
488       ? shift
489       : { @_ };
490
491   #return "Can't (yet?) change pkgpart!" if $old->pkgpart != $new->pkgpart;
492   #return "Can't change otaker!" if $old->otaker ne $new->otaker;
493
494   #allow this *sigh*
495   #return "Can't change setup once it exists!"
496   #  if $old->getfield('setup') &&
497   #     $old->getfield('setup') != $new->getfield('setup');
498
499   #some logic for bill, susp, cancel?
500
501   local($disable_agentcheck) = 1 if $old->pkgpart == $new->pkgpart;
502
503   local $SIG{HUP} = 'IGNORE';
504   local $SIG{INT} = 'IGNORE';
505   local $SIG{QUIT} = 'IGNORE';
506   local $SIG{TERM} = 'IGNORE';
507   local $SIG{TSTP} = 'IGNORE';
508   local $SIG{PIPE} = 'IGNORE';
509
510   my $oldAutoCommit = $FS::UID::AutoCommit;
511   local $FS::UID::AutoCommit = 0;
512   my $dbh = dbh;
513
514   foreach my $method ( qw(adjourn expire) ) {  # How many reasons?
515     if ($options->{'reason'} && $new->$method && $old->$method ne $new->$method) {
516       my $error = $new->insert_reason(
517         'reason'        => $options->{'reason'},
518         'date'          => $new->$method,
519         'action'        => $method,
520         'reason_otaker' => $options->{'reason_otaker'},
521       );
522       if ( $error ) {
523         dbh->rollback if $oldAutoCommit;
524         return "Error inserting cust_pkg_reason: $error";
525       }
526     }
527   }
528
529   #save off and freeze RADIUS attributes for any associated svc_acct records
530   my @svc_acct = ();
531   if ( $old->part_pkg->is_prepaid || $new->part_pkg->is_prepaid ) {
532
533                 #also check for specific exports?
534                 # to avoid spurious modify export events
535     @svc_acct = map  { $_->svc_x }
536                 grep { $_->part_svc->svcdb eq 'svc_acct' }
537                      $old->cust_svc;
538
539     $_->snapshot foreach @svc_acct;
540
541   }
542
543   my $error = $new->SUPER::replace($old,
544                                    $options->{options} ? $options->{options} : ()
545                                   );
546   if ( $error ) {
547     $dbh->rollback if $oldAutoCommit;
548     return $error;
549   }
550
551   #for prepaid packages,
552   #trigger export of new RADIUS Expiration attribute when cust_pkg.bill changes
553   foreach my $old_svc_acct ( @svc_acct ) {
554     my $new_svc_acct = new FS::svc_acct { $old_svc_acct->hash };
555     my $s_error =
556       $new_svc_acct->replace( $old_svc_acct,
557                               'depend_jobnum' => $options->{depend_jobnum},
558                             );
559     if ( $s_error ) {
560       $dbh->rollback if $oldAutoCommit;
561       return $s_error;
562     }
563   }
564
565   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
566   '';
567
568 }
569
570 =item check
571
572 Checks all fields to make sure this is a valid billing item.  If there is an
573 error, returns the error, otherwise returns false.  Called by the insert and
574 replace methods.
575
576 =cut
577
578 sub check {
579   my $self = shift;
580
581   $self->locationnum('') if !$self->locationnum || $self->locationnum == -1;
582
583   my $error = 
584     $self->ut_numbern('pkgnum')
585     || $self->ut_foreign_key('custnum', 'cust_main', 'custnum')
586     || $self->ut_numbern('pkgpart')
587     || $self->check_pkgpart
588     || $self->ut_foreign_keyn('locationnum', 'cust_location', 'locationnum')
589     || $self->ut_numbern('start_date')
590     || $self->ut_numbern('setup')
591     || $self->ut_numbern('bill')
592     || $self->ut_numbern('susp')
593     || $self->ut_numbern('cancel')
594     || $self->ut_numbern('adjourn')
595     || $self->ut_numbern('expire')
596     || $self->ut_enum('no_auto', [ '', 'Y' ])
597   ;
598   return $error if $error;
599
600   $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
601
602   if ( $self->dbdef_table->column('manual_flag') ) {
603     $self->manual_flag('') if $self->manual_flag eq ' ';
604     $self->manual_flag =~ /^([01]?)$/
605       or return "Illegal manual_flag ". $self->manual_flag;
606     $self->manual_flag($1);
607   }
608
609   $self->SUPER::check;
610 }
611
612 =item check_pkgpart
613
614 =cut
615
616 sub check_pkgpart {
617   my $self = shift;
618
619   my $error = $self->ut_numbern('pkgpart');
620   return $error if $error;
621
622   if ( $self->reg_code ) {
623
624     unless ( grep { $self->pkgpart == $_->pkgpart }
625              map  { $_->reg_code_pkg }
626              qsearchs( 'reg_code', { 'code'     => $self->reg_code,
627                                      'agentnum' => $self->cust_main->agentnum })
628            ) {
629       return "Unknown registration code";
630     }
631
632   } elsif ( $self->promo_code ) {
633
634     my $promo_part_pkg =
635       qsearchs('part_pkg', {
636         'pkgpart'    => $self->pkgpart,
637         'promo_code' => { op=>'ILIKE', value=>$self->promo_code },
638       } );
639     return 'Unknown promotional code' unless $promo_part_pkg;
640
641   } else { 
642
643     unless ( $disable_agentcheck ) {
644       my $agent =
645         qsearchs( 'agent', { 'agentnum' => $self->cust_main->agentnum } );
646       return "agent ". $agent->agentnum. ':'. $agent->agent.
647              " can't purchase pkgpart ". $self->pkgpart
648         unless $agent->pkgpart_hashref->{ $self->pkgpart }
649             || $agent->agentnum == $self->part_pkg->agentnum;
650     }
651
652     $error = $self->ut_foreign_key('pkgpart', 'part_pkg', 'pkgpart' );
653     return $error if $error;
654
655   }
656
657   '';
658
659 }
660
661 =item cancel [ OPTION => VALUE ... ]
662
663 Cancels and removes all services (see L<FS::cust_svc> and L<FS::part_svc>)
664 in this package, then cancels the package itself (sets the cancel field to
665 now).
666
667 Available options are:
668
669 =over 4
670
671 =item quiet - can be set true to supress email cancellation notices.
672
673 =item time -  can be set to cancel the package based on a specific future or historical date.  Using time ensures that the remaining amount is calculated correctly.  Note however that this is an immediate cancel and just changes the date.  You are PROBABLY looking to expire the account instead of using this.
674
675 =item reason - 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.
676
677 =item date - can be set to a unix style timestamp to specify when to cancel (expire)
678
679 =item nobill - can be set true to skip billing if it might otherwise be done.
680
681 =item unused_credit - can be set to 1 to credit the remaining time, or 0 to 
682 not credit it.  This must be set (by change()) when changing the package 
683 to a different pkgpart or location, and probably shouldn't be in any other 
684 case.  If it's not set, the 'unused_credit_cancel' part_pkg option will 
685 be used.
686
687 =back
688
689 If there is an error, returns the error, otherwise returns false.
690
691 =cut
692
693 sub cancel {
694   my( $self, %options ) = @_;
695   my $error;
696
697   my $conf = new FS::Conf;
698
699   warn "cust_pkg::cancel called with options".
700        join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
701     if $DEBUG;
702
703   local $SIG{HUP} = 'IGNORE';
704   local $SIG{INT} = 'IGNORE';
705   local $SIG{QUIT} = 'IGNORE'; 
706   local $SIG{TERM} = 'IGNORE';
707   local $SIG{TSTP} = 'IGNORE';
708   local $SIG{PIPE} = 'IGNORE';
709
710   my $oldAutoCommit = $FS::UID::AutoCommit;
711   local $FS::UID::AutoCommit = 0;
712   my $dbh = dbh;
713   
714   my $old = $self->select_for_update;
715
716   if ( $old->get('cancel') || $self->get('cancel') ) {
717     dbh->rollback if $oldAutoCommit;
718     return "";  # no error
719   }
720
721   my $date = $options{date} if $options{date}; # expire/cancel later
722   $date = '' if ($date && $date <= time);      # complain instead?
723
724   #race condition: usage could be ongoing until unprovisioned
725   #resolved by performing a change package instead (which unprovisions) and
726   #later cancelling
727   if ( !$options{nobill} && !$date && $conf->exists('bill_usage_on_cancel') ) {
728       my $copy = $self->new({$self->hash});
729       my $error =
730         $copy->cust_main->bill( pkg_list => [ $copy ], cancel => 1 );
731       warn "Error billing during cancel, custnum ".
732         #$self->cust_main->custnum. ": $error"
733         ": $error"
734         if $error;
735   }
736
737   my $cancel_time = $options{'time'} || time;
738
739   if ( $options{'reason'} ) {
740     $error = $self->insert_reason( 'reason' => $options{'reason'},
741                                    'action' => $date ? 'expire' : 'cancel',
742                                    'date'   => $date ? $date : $cancel_time,
743                                    'reason_otaker' => $options{'reason_otaker'},
744                                  );
745     if ( $error ) {
746       dbh->rollback if $oldAutoCommit;
747       return "Error inserting cust_pkg_reason: $error";
748     }
749   }
750
751   unless ( $date ) {
752
753     foreach my $cust_svc (
754       #schwartz
755       map  { $_->[0] }
756       sort { $a->[1] <=> $b->[1] }
757       map  { [ $_, $_->svc_x->table_info->{'cancel_weight'} ]; }
758       qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
759     ) {
760       my $error = $cust_svc->cancel;
761
762       if ( $error ) {
763         $dbh->rollback if $oldAutoCommit;
764         return "Error cancelling cust_svc: $error";
765       }
766     }
767
768     # Add a credit for remaining service
769     my $last_bill = $self->getfield('last_bill') || 0;
770     my $next_bill = $self->getfield('bill') || 0;
771     my $do_credit;
772     if ( exists($options{'unused_credit'}) ) {
773       $do_credit = $options{'unused_credit'};
774     }
775     else {
776       $do_credit = $self->part_pkg->option('unused_credit_cancel', 1);
777     }
778     if ( $do_credit
779           and $last_bill > 0 # the package has been billed
780           and $next_bill > 0 # the package has a next bill date
781           and $next_bill >= $cancel_time # which is in the future
782     ) {
783       my $remaining_value = $self->calc_remain('time' => $cancel_time);
784       if ( $remaining_value > 0 ) {
785         my $error = $self->cust_main->credit(
786           $remaining_value,
787           'Credit for unused time on '. $self->part_pkg->pkg,
788           'reason_type' => $conf->config('cancel_credit_type'),
789         );
790         if ($error) {
791           $dbh->rollback if $oldAutoCommit;
792           return "Error crediting customer \$$remaining_value for unused time".
793                  " on ".  $self->part_pkg->pkg. ": $error";
794         }
795       } #if $remaining_value
796     } #if $do_credit
797
798   } #unless $date
799
800   my %hash = $self->hash;
801   $date ? ($hash{'expire'} = $date) : ($hash{'cancel'} = $cancel_time);
802   my $new = new FS::cust_pkg ( \%hash );
803   $error = $new->replace( $self, options => { $self->options } );
804   if ( $error ) {
805     $dbh->rollback if $oldAutoCommit;
806     return $error;
807   }
808
809   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
810   return '' if $date; #no errors
811
812   my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ } $self->cust_main->invoicing_list;
813   if ( !$options{'quiet'} && 
814         $conf->exists('emailcancel', $self->cust_main->agentnum) && 
815         @invoicing_list ) {
816     my $msgnum = $conf->config('cancel_msgnum', $self->cust_main->agentnum);
817     my $error = '';
818     if ( $msgnum ) {
819       my $msg_template = qsearchs('msg_template', { msgnum => $msgnum });
820       $error = $msg_template->send( 'cust_main' => $self->cust_main,
821                                     'object'    => $self );
822     }
823     else {
824       $error = send_email(
825         'from'    => $conf->config('invoice_from', $self->cust_main->agentnum),
826         'to'      => \@invoicing_list,
827         'subject' => ( $conf->config('cancelsubject') || 'Cancellation Notice' ),
828         'body'    => [ map "$_\n", $conf->config('cancelmessage') ],
829       );
830     }
831     #should this do something on errors?
832   }
833
834   ''; #no errors
835
836 }
837
838 =item cancel_if_expired [ NOW_TIMESTAMP ]
839
840 Cancels this package if its expire date has been reached.
841
842 =cut
843
844 sub cancel_if_expired {
845   my $self = shift;
846   my $time = shift || time;
847   return '' unless $self->expire && $self->expire <= $time;
848   my $error = $self->cancel;
849   if ( $error ) {
850     return "Error cancelling expired pkg ". $self->pkgnum. " for custnum ".
851            $self->custnum. ": $error";
852   }
853   '';
854 }
855
856 =item unexpire
857
858 Cancels any pending expiration (sets the expire field to null).
859
860 If there is an error, returns the error, otherwise returns false.
861
862 =cut
863
864 sub unexpire {
865   my( $self, %options ) = @_;
866   my $error;
867
868   local $SIG{HUP} = 'IGNORE';
869   local $SIG{INT} = 'IGNORE';
870   local $SIG{QUIT} = 'IGNORE';
871   local $SIG{TERM} = 'IGNORE';
872   local $SIG{TSTP} = 'IGNORE';
873   local $SIG{PIPE} = 'IGNORE';
874
875   my $oldAutoCommit = $FS::UID::AutoCommit;
876   local $FS::UID::AutoCommit = 0;
877   my $dbh = dbh;
878
879   my $old = $self->select_for_update;
880
881   my $pkgnum = $old->pkgnum;
882   if ( $old->get('cancel') || $self->get('cancel') ) {
883     dbh->rollback if $oldAutoCommit;
884     return "Can't unexpire cancelled package $pkgnum";
885     # or at least it's pointless
886   }
887
888   unless ( $old->get('expire') && $self->get('expire') ) {
889     dbh->rollback if $oldAutoCommit;
890     return "";  # no error
891   }
892
893   my %hash = $self->hash;
894   $hash{'expire'} = '';
895   my $new = new FS::cust_pkg ( \%hash );
896   $error = $new->replace( $self, options => { $self->options } );
897   if ( $error ) {
898     $dbh->rollback if $oldAutoCommit;
899     return $error;
900   }
901
902   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
903
904   ''; #no errors
905
906 }
907
908 =item suspend [ OPTION => VALUE ... ]
909
910 Suspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
911 package, then suspends the package itself (sets the susp field to now).
912
913 Available options are:
914
915 =over 4
916
917 =item reason - 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.
918
919 =item date - can be set to a unix style timestamp to specify when to suspend (adjourn)
920
921 =back
922
923 If there is an error, returns the error, otherwise returns false.
924
925 =cut
926
927 sub suspend {
928   my( $self, %options ) = @_;
929   my $error;
930
931   local $SIG{HUP} = 'IGNORE';
932   local $SIG{INT} = 'IGNORE';
933   local $SIG{QUIT} = 'IGNORE'; 
934   local $SIG{TERM} = 'IGNORE';
935   local $SIG{TSTP} = 'IGNORE';
936   local $SIG{PIPE} = 'IGNORE';
937
938   my $oldAutoCommit = $FS::UID::AutoCommit;
939   local $FS::UID::AutoCommit = 0;
940   my $dbh = dbh;
941
942   my $old = $self->select_for_update;
943
944   my $pkgnum = $old->pkgnum;
945   if ( $old->get('cancel') || $self->get('cancel') ) {
946     dbh->rollback if $oldAutoCommit;
947     return "Can't suspend cancelled package $pkgnum";
948   }
949
950   if ( $old->get('susp') || $self->get('susp') ) {
951     dbh->rollback if $oldAutoCommit;
952     return "";  # no error                     # complain on adjourn?
953   }
954
955   my $date = $options{date} if $options{date}; # adjourn/suspend later
956   $date = '' if ($date && $date <= time);      # complain instead?
957
958   if ( $date && $old->get('expire') && $old->get('expire') < $date ) {
959     dbh->rollback if $oldAutoCommit;
960     return "Package $pkgnum expires before it would be suspended.";
961   }
962
963   my $suspend_time = $options{'time'} || time;
964
965   if ( $options{'reason'} ) {
966     $error = $self->insert_reason( 'reason' => $options{'reason'},
967                                    'action' => $date ? 'adjourn' : 'suspend',
968                                    'date'   => $date ? $date : $suspend_time,
969                                    'reason_otaker' => $options{'reason_otaker'},
970                                  );
971     if ( $error ) {
972       dbh->rollback if $oldAutoCommit;
973       return "Error inserting cust_pkg_reason: $error";
974     }
975   }
976
977   unless ( $date ) {
978
979     my @labels = ();
980
981     foreach my $cust_svc (
982       qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } )
983     ) {
984       my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
985
986       $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
987         $dbh->rollback if $oldAutoCommit;
988         return "Illegal svcdb value in part_svc!";
989       };
990       my $svcdb = $1;
991       require "FS/$svcdb.pm";
992
993       my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
994       if ($svc) {
995         $error = $svc->suspend;
996         if ( $error ) {
997           $dbh->rollback if $oldAutoCommit;
998           return $error;
999         }
1000         my( $label, $value ) = $cust_svc->label;
1001         push @labels, "$label: $value";
1002       }
1003     }
1004
1005     my $conf = new FS::Conf;
1006     if ( $conf->config('suspend_email_admin') ) {
1007  
1008       my $error = send_email(
1009         'from'    => $conf->config('invoice_from', $self->cust_main->agentnum),
1010                                    #invoice_from ??? well as good as any
1011         'to'      => $conf->config('suspend_email_admin'),
1012         'subject' => 'FREESIDE NOTIFICATION: Customer package suspended',
1013         'body'    => [
1014           "This is an automatic message from your Freeside installation\n",
1015           "informing you that the following customer package has been suspended:\n",
1016           "\n",
1017           'Customer: #'. $self->custnum. ' '. $self->cust_main->name. "\n",
1018           'Package : #'. $self->pkgnum. " (". $self->part_pkg->pkg_comment. ")\n",
1019           ( map { "Service : $_\n" } @labels ),
1020         ],
1021       );
1022
1023       if ( $error ) {
1024         warn "WARNING: can't send suspension admin email (suspending anyway): ".
1025              "$error\n";
1026       }
1027
1028     }
1029
1030   }
1031
1032   my %hash = $self->hash;
1033   if ( $date ) {
1034     $hash{'adjourn'} = $date;
1035   } else {
1036     $hash{'susp'} = $suspend_time;
1037   }
1038   my $new = new FS::cust_pkg ( \%hash );
1039   $error = $new->replace( $self, options => { $self->options } );
1040   if ( $error ) {
1041     $dbh->rollback if $oldAutoCommit;
1042     return $error;
1043   }
1044
1045   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1046
1047   ''; #no errors
1048 }
1049
1050 =item unsuspend [ OPTION => VALUE ... ]
1051
1052 Unsuspends all services (see L<FS::cust_svc> and L<FS::part_svc>) in this
1053 package, then unsuspends the package itself (clears the susp field and the
1054 adjourn field if it is in the past).
1055
1056 Available options are:
1057
1058 =over 4
1059
1060 =item adjust_next_bill
1061
1062 Can be set true to adjust the next bill date forward by
1063 the amount of time the account was inactive.  This was set true by default
1064 since 1.4.2 and 1.5.0pre6; however, starting with 1.7.0 this needs to be
1065 explicitly requested.  Price plans for which this makes sense (anniversary-date
1066 based than prorate or subscription) could have an option to enable this
1067 behaviour?
1068
1069 =back
1070
1071 If there is an error, returns the error, otherwise returns false.
1072
1073 =cut
1074
1075 sub unsuspend {
1076   my( $self, %opt ) = @_;
1077   my $error;
1078
1079   local $SIG{HUP} = 'IGNORE';
1080   local $SIG{INT} = 'IGNORE';
1081   local $SIG{QUIT} = 'IGNORE'; 
1082   local $SIG{TERM} = 'IGNORE';
1083   local $SIG{TSTP} = 'IGNORE';
1084   local $SIG{PIPE} = 'IGNORE';
1085
1086   my $oldAutoCommit = $FS::UID::AutoCommit;
1087   local $FS::UID::AutoCommit = 0;
1088   my $dbh = dbh;
1089
1090   my $old = $self->select_for_update;
1091
1092   my $pkgnum = $old->pkgnum;
1093   if ( $old->get('cancel') || $self->get('cancel') ) {
1094     dbh->rollback if $oldAutoCommit;
1095     return "Can't unsuspend cancelled package $pkgnum";
1096   }
1097
1098   unless ( $old->get('susp') && $self->get('susp') ) {
1099     dbh->rollback if $oldAutoCommit;
1100     return "";  # no error                     # complain instead?
1101   }
1102
1103   foreach my $cust_svc (
1104     qsearch('cust_svc',{'pkgnum'=> $self->pkgnum } )
1105   ) {
1106     my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $cust_svc->svcpart } );
1107
1108     $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
1109       $dbh->rollback if $oldAutoCommit;
1110       return "Illegal svcdb value in part_svc!";
1111     };
1112     my $svcdb = $1;
1113     require "FS/$svcdb.pm";
1114
1115     my $svc = qsearchs( $svcdb, { 'svcnum' => $cust_svc->svcnum } );
1116     if ($svc) {
1117       $error = $svc->unsuspend;
1118       if ( $error ) {
1119         $dbh->rollback if $oldAutoCommit;
1120         return $error;
1121       }
1122     }
1123
1124   }
1125
1126   my %hash = $self->hash;
1127   my $inactive = time - $hash{'susp'};
1128
1129   my $conf = new FS::Conf;
1130
1131   if ( $inactive > 0 && 
1132        ( $hash{'bill'} || $hash{'setup'} ) &&
1133        ( $opt{'adjust_next_bill'} ||
1134          $conf->exists('unsuspend-always_adjust_next_bill_date') ||
1135          $self->part_pkg->option('unsuspend_adjust_bill', 1) )
1136      ) {
1137
1138     $hash{'bill'} = ( $hash{'bill'} || $hash{'setup'} ) + $inactive;
1139   
1140   }
1141
1142   $hash{'susp'} = '';
1143   $hash{'adjourn'} = '' if $hash{'adjourn'} < time;
1144   my $new = new FS::cust_pkg ( \%hash );
1145   $error = $new->replace( $self, options => { $self->options } );
1146   if ( $error ) {
1147     $dbh->rollback if $oldAutoCommit;
1148     return $error;
1149   }
1150
1151   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1152
1153   ''; #no errors
1154 }
1155
1156 =item unadjourn
1157
1158 Cancels any pending suspension (sets the adjourn field to null).
1159
1160 If there is an error, returns the error, otherwise returns false.
1161
1162 =cut
1163
1164 sub unadjourn {
1165   my( $self, %options ) = @_;
1166   my $error;
1167
1168   local $SIG{HUP} = 'IGNORE';
1169   local $SIG{INT} = 'IGNORE';
1170   local $SIG{QUIT} = 'IGNORE'; 
1171   local $SIG{TERM} = 'IGNORE';
1172   local $SIG{TSTP} = 'IGNORE';
1173   local $SIG{PIPE} = 'IGNORE';
1174
1175   my $oldAutoCommit = $FS::UID::AutoCommit;
1176   local $FS::UID::AutoCommit = 0;
1177   my $dbh = dbh;
1178
1179   my $old = $self->select_for_update;
1180
1181   my $pkgnum = $old->pkgnum;
1182   if ( $old->get('cancel') || $self->get('cancel') ) {
1183     dbh->rollback if $oldAutoCommit;
1184     return "Can't unadjourn cancelled package $pkgnum";
1185     # or at least it's pointless
1186   }
1187
1188   if ( $old->get('susp') || $self->get('susp') ) {
1189     dbh->rollback if $oldAutoCommit;
1190     return "Can't unadjourn suspended package $pkgnum";
1191     # perhaps this is arbitrary
1192   }
1193
1194   unless ( $old->get('adjourn') && $self->get('adjourn') ) {
1195     dbh->rollback if $oldAutoCommit;
1196     return "";  # no error
1197   }
1198
1199   my %hash = $self->hash;
1200   $hash{'adjourn'} = '';
1201   my $new = new FS::cust_pkg ( \%hash );
1202   $error = $new->replace( $self, options => { $self->options } );
1203   if ( $error ) {
1204     $dbh->rollback if $oldAutoCommit;
1205     return $error;
1206   }
1207
1208   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1209
1210   ''; #no errors
1211
1212 }
1213
1214
1215 =item change HASHREF | OPTION => VALUE ... 
1216
1217 Changes this package: cancels it and creates a new one, with a different
1218 pkgpart or locationnum or both.  All services are transferred to the new
1219 package (no change will be made if this is not possible).
1220
1221 Options may be passed as a list of key/value pairs or as a hash reference.
1222 Options are:
1223
1224 =over 4
1225
1226 =item locationnum
1227
1228 New locationnum, to change the location for this package.
1229
1230 =item cust_location
1231
1232 New FS::cust_location object, to create a new location and assign it
1233 to this package.
1234
1235 =item pkgpart
1236
1237 New pkgpart (see L<FS::part_pkg>).
1238
1239 =item refnum
1240
1241 New refnum (see L<FS::part_referral>).
1242
1243 =item keep_dates
1244
1245 Set to true to transfer billing dates (start_date, setup, last_bill, bill, 
1246 susp, adjourn, cancel, expire, and contract_end) to the new package.
1247
1248 =back
1249
1250 At least one of locationnum, cust_location, pkgpart, refnum must be specified 
1251 (otherwise, what's the point?)
1252
1253 Returns either the new FS::cust_pkg object or a scalar error.
1254
1255 For example:
1256
1257   my $err_or_new_cust_pkg = $old_cust_pkg->change
1258
1259 =cut
1260
1261 #some false laziness w/order
1262 sub change {
1263   my $self = shift;
1264   my $opt = ref($_[0]) ? shift : { @_ };
1265
1266 #  my ($custnum, $pkgparts, $remove_pkgnum, $return_cust_pkg, $refnum) = @_;
1267 #    
1268
1269   my $conf = new FS::Conf;
1270
1271   # Transactionize this whole mess
1272   local $SIG{HUP} = 'IGNORE';
1273   local $SIG{INT} = 'IGNORE'; 
1274   local $SIG{QUIT} = 'IGNORE';
1275   local $SIG{TERM} = 'IGNORE';
1276   local $SIG{TSTP} = 'IGNORE'; 
1277   local $SIG{PIPE} = 'IGNORE'; 
1278
1279   my $oldAutoCommit = $FS::UID::AutoCommit;
1280   local $FS::UID::AutoCommit = 0;
1281   my $dbh = dbh;
1282
1283   my $error;
1284
1285   my %hash = (); 
1286
1287   my $time = time;
1288
1289   #$hash{$_} = $self->$_() foreach qw( last_bill bill );
1290     
1291   #$hash{$_} = $self->$_() foreach qw( setup );
1292
1293   $hash{'setup'} = $time if $self->setup;
1294
1295   $hash{'change_date'} = $time;
1296   $hash{"change_$_"}  = $self->$_()
1297     foreach qw( pkgnum pkgpart locationnum );
1298
1299   if ( $opt->{'cust_location'} &&
1300        ( ! $opt->{'locationnum'} || $opt->{'locationnum'} == -1 ) ) {
1301     $error = $opt->{'cust_location'}->insert;
1302     if ( $error ) {
1303       $dbh->rollback if $oldAutoCommit;
1304       return "inserting cust_location (transaction rolled back): $error";
1305     }
1306     $opt->{'locationnum'} = $opt->{'cust_location'}->locationnum;
1307   }
1308
1309   my $unused_credit = 0;
1310   if ( $opt->{'keep_dates'} ) {
1311     foreach my $date ( qw(setup bill last_bill susp adjourn cancel expire 
1312                           start_date contract_end ) ) {
1313       $hash{$date} = $self->getfield($date);
1314     }
1315   }
1316   # Special case.  If the pkgpart is changing, and the customer is
1317   # going to be credited for remaining time, don't keep setup, bill, 
1318   # or last_bill dates, and DO pass the flag to cancel() to credit 
1319   # the customer.
1320   if ( $opt->{'pkgpart'} 
1321       and $opt->{'pkgpart'} != $self->pkgpart
1322       and $self->part_pkg->option('unused_credit_change', 1) ) {
1323     $unused_credit = 1;
1324     $hash{$_} = '' foreach qw(setup bill last_bill);
1325   }
1326
1327   # Create the new package.
1328   my $cust_pkg = new FS::cust_pkg {
1329     custnum      => $self->custnum,
1330     pkgpart      => ( $opt->{'pkgpart'}     || $self->pkgpart      ),
1331     refnum       => ( $opt->{'refnum'}      || $self->refnum       ),
1332     locationnum  => ( $opt->{'locationnum'} || $self->locationnum  ),
1333     %hash,
1334   };
1335
1336   $error = $cust_pkg->insert( 'change' => 1 );
1337   if ($error) {
1338     $dbh->rollback if $oldAutoCommit;
1339     return $error;
1340   }
1341
1342   # Transfer services and cancel old package.
1343
1344   $error = $self->transfer($cust_pkg);
1345   if ($error and $error == 0) {
1346     # $old_pkg->transfer failed.
1347     $dbh->rollback if $oldAutoCommit;
1348     return $error;
1349   }
1350
1351   if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
1352     warn "trying transfer again with change_svcpart option\n" if $DEBUG;
1353     $error = $self->transfer($cust_pkg, 'change_svcpart'=>1 );
1354     if ($error and $error == 0) {
1355       # $old_pkg->transfer failed.
1356       $dbh->rollback if $oldAutoCommit;
1357       return $error;
1358     }
1359   }
1360
1361   if ($error > 0) {
1362     # Transfers were successful, but we still had services left on the old
1363     # package.  We can't change the package under this circumstances, so abort.
1364     $dbh->rollback if $oldAutoCommit;
1365     return "Unable to transfer all services from package ". $self->pkgnum;
1366   }
1367
1368   #reset usage if changing pkgpart
1369   # AND usage rollover is off (otherwise adds twice, now and at package bill)
1370   if ($self->pkgpart != $cust_pkg->pkgpart) {
1371     my $part_pkg = $cust_pkg->part_pkg;
1372     $error = $part_pkg->reset_usage($cust_pkg, $part_pkg->is_prepaid
1373                                                  ? ()
1374                                                  : ( 'null' => 1 )
1375                                    )
1376       if $part_pkg->can('reset_usage') && ! $part_pkg->option('usage_rollover',1);
1377
1378     if ($error) {
1379       $dbh->rollback if $oldAutoCommit;
1380       return "Error setting usage values: $error";
1381     }
1382   }
1383
1384   #Good to go, cancel old package.  Notify 'cancel' of whether to credit 
1385   #remaining time.
1386   $error = $self->cancel( quiet=>1, unused_credit => $unused_credit );
1387   if ($error) {
1388     $dbh->rollback if $oldAutoCommit;
1389     return $error;
1390   }
1391
1392   if ( $conf->exists('cust_pkg-change_pkgpart-bill_now') ) {
1393     #$self->cust_main
1394     my $error = $cust_pkg->cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1395     if ( $error ) {
1396       $dbh->rollback if $oldAutoCommit;
1397       return $error;
1398     }
1399   }
1400
1401   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1402
1403   $cust_pkg;
1404
1405 }
1406
1407 use Data::Dumper;
1408 use Storable 'thaw';
1409 use MIME::Base64;
1410 sub process_bulk_cust_pkg {
1411   my $job = shift;
1412   my $param = thaw(decode_base64(shift));
1413   warn Dumper($param) if $DEBUG;
1414
1415   my $old_part_pkg = qsearchs('part_pkg', 
1416                               { pkgpart => $param->{'old_pkgpart'} });
1417   my $new_part_pkg = qsearchs('part_pkg',
1418                               { pkgpart => $param->{'new_pkgpart'} });
1419   die "Must select a new package type\n" unless $new_part_pkg;
1420   #my $keep_dates = $param->{'keep_dates'} || 0;
1421   my $keep_dates = 1; # there is no good reason to turn this off
1422
1423   local $SIG{HUP} = 'IGNORE';
1424   local $SIG{INT} = 'IGNORE';
1425   local $SIG{QUIT} = 'IGNORE';
1426   local $SIG{TERM} = 'IGNORE';
1427   local $SIG{TSTP} = 'IGNORE';
1428   local $SIG{PIPE} = 'IGNORE';
1429
1430   my $oldAutoCommit = $FS::UID::AutoCommit;
1431   local $FS::UID::AutoCommit = 0;
1432   my $dbh = dbh;
1433
1434   my @cust_pkgs = qsearch('cust_pkg', { 'pkgpart' => $param->{'old_pkgpart'} } );
1435
1436   my $i = 0;
1437   foreach my $old_cust_pkg ( @cust_pkgs ) {
1438     $i++;
1439     $job->update_statustext(int(100*$i/(scalar @cust_pkgs)));
1440     if ( $old_cust_pkg->getfield('cancel') ) {
1441       warn '[process_bulk_cust_pkg ] skipping canceled pkgnum '.
1442         $old_cust_pkg->pkgnum."\n"
1443         if $DEBUG;
1444       next;
1445     }
1446     warn '[process_bulk_cust_pkg] changing pkgnum '.$old_cust_pkg->pkgnum."\n"
1447       if $DEBUG;
1448     my $error = $old_cust_pkg->change(
1449       'pkgpart'     => $param->{'new_pkgpart'},
1450       'keep_dates'  => $keep_dates
1451     );
1452     if ( !ref($error) ) { # change returns the cust_pkg on success
1453       $dbh->rollback;
1454       die "Error changing pkgnum ".$old_cust_pkg->pkgnum.": '$error'\n";
1455     }
1456   }
1457   $dbh->commit if $oldAutoCommit;
1458   return;
1459 }
1460
1461 =item last_bill
1462
1463 Returns the last bill date, or if there is no last bill date, the setup date.
1464 Useful for billing metered services.
1465
1466 =cut
1467
1468 sub last_bill {
1469   my $self = shift;
1470   return $self->setfield('last_bill', $_[0]) if @_;
1471   return $self->getfield('last_bill') if $self->getfield('last_bill');
1472   my $cust_bill_pkg = qsearchs('cust_bill_pkg', { 'pkgnum' => $self->pkgnum,
1473                                                   'edate'  => $self->bill,  } );
1474   $cust_bill_pkg ? $cust_bill_pkg->sdate : $self->setup || 0;
1475 }
1476
1477 =item last_cust_pkg_reason ACTION
1478
1479 Returns the most recent ACTION FS::cust_pkg_reason associated with the package.
1480 Returns false if there is no reason or the package is not currenly ACTION'd
1481 ACTION is one of adjourn, susp, cancel, or expire.
1482
1483 =cut
1484
1485 sub last_cust_pkg_reason {
1486   my ( $self, $action ) = ( shift, shift );
1487   my $date = $self->get($action);
1488   qsearchs( {
1489               'table' => 'cust_pkg_reason',
1490               'hashref' => { 'pkgnum' => $self->pkgnum,
1491                              'action' => substr(uc($action), 0, 1),
1492                              'date'   => $date,
1493                            },
1494               'order_by' => 'ORDER BY num DESC LIMIT 1',
1495            } );
1496 }
1497
1498 =item last_reason ACTION
1499
1500 Returns the most recent ACTION FS::reason associated with the package.
1501 Returns false if there is no reason or the package is not currenly ACTION'd
1502 ACTION is one of adjourn, susp, cancel, or expire.
1503
1504 =cut
1505
1506 sub last_reason {
1507   my $cust_pkg_reason = shift->last_cust_pkg_reason(@_);
1508   $cust_pkg_reason->reason
1509     if $cust_pkg_reason;
1510 }
1511
1512 =item part_pkg
1513
1514 Returns the definition for this billing item, as an FS::part_pkg object (see
1515 L<FS::part_pkg>).
1516
1517 =cut
1518
1519 sub part_pkg {
1520   my $self = shift;
1521   return $self->{'_pkgpart'} if $self->{'_pkgpart'};
1522   cluck "cust_pkg->part_pkg called" if $DEBUG > 1;
1523   qsearchs( 'part_pkg', { 'pkgpart' => $self->pkgpart } );
1524 }
1525
1526 =item old_cust_pkg
1527
1528 Returns the cancelled package this package was changed from, if any.
1529
1530 =cut
1531
1532 sub old_cust_pkg {
1533   my $self = shift;
1534   return '' unless $self->change_pkgnum;
1535   qsearchs('cust_pkg', { 'pkgnum' => $self->change_pkgnum } );
1536 }
1537
1538 =item calc_setup
1539
1540 Calls the I<calc_setup> of the FS::part_pkg object associated with this billing
1541 item.
1542
1543 =cut
1544
1545 sub calc_setup {
1546   my $self = shift;
1547   $self->part_pkg->calc_setup($self, @_);
1548 }
1549
1550 =item calc_recur
1551
1552 Calls the I<calc_recur> of the FS::part_pkg object associated with this billing
1553 item.
1554
1555 =cut
1556
1557 sub calc_recur {
1558   my $self = shift;
1559   $self->part_pkg->calc_recur($self, @_);
1560 }
1561
1562 =item base_recur
1563
1564 Calls the I<base_recur> of the FS::part_pkg object associated with this billing
1565 item.
1566
1567 =cut
1568
1569 sub base_recur {
1570   my $self = shift;
1571   $self->part_pkg->base_recur($self, @_);
1572 }
1573
1574 =item calc_remain
1575
1576 Calls the I<calc_remain> of the FS::part_pkg object associated with this
1577 billing item.
1578
1579 =cut
1580
1581 sub calc_remain {
1582   my $self = shift;
1583   $self->part_pkg->calc_remain($self, @_);
1584 }
1585
1586 =item calc_cancel
1587
1588 Calls the I<calc_cancel> of the FS::part_pkg object associated with this
1589 billing item.
1590
1591 =cut
1592
1593 sub calc_cancel {
1594   my $self = shift;
1595   $self->part_pkg->calc_cancel($self, @_);
1596 }
1597
1598 =item cust_bill_pkg
1599
1600 Returns any invoice line items for this package (see L<FS::cust_bill_pkg>).
1601
1602 =cut
1603
1604 sub cust_bill_pkg {
1605   my $self = shift;
1606   qsearch( 'cust_bill_pkg', { 'pkgnum' => $self->pkgnum } );
1607 }
1608
1609 =item cust_pkg_detail [ DETAILTYPE ]
1610
1611 Returns any customer package details for this package (see
1612 L<FS::cust_pkg_detail>).
1613
1614 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
1615
1616 =cut
1617
1618 sub cust_pkg_detail {
1619   my $self = shift;
1620   my %hash = ( 'pkgnum' => $self->pkgnum );
1621   $hash{detailtype} = shift if @_;
1622   qsearch({
1623     'table'    => 'cust_pkg_detail',
1624     'hashref'  => \%hash,
1625     'order_by' => 'ORDER BY weight, pkgdetailnum',
1626   });
1627 }
1628
1629 =item set_cust_pkg_detail DETAILTYPE [ DETAIL, DETAIL, ... ]
1630
1631 Sets customer package details for this package (see L<FS::cust_pkg_detail>).
1632
1633 DETAILTYPE can be set to "I" for invoice details or "C" for comments.
1634
1635 If there is an error, returns the error, otherwise returns false.
1636
1637 =cut
1638
1639 sub set_cust_pkg_detail {
1640   my( $self, $detailtype, @details ) = @_;
1641
1642   local $SIG{HUP} = 'IGNORE';
1643   local $SIG{INT} = 'IGNORE';
1644   local $SIG{QUIT} = 'IGNORE';
1645   local $SIG{TERM} = 'IGNORE';
1646   local $SIG{TSTP} = 'IGNORE';
1647   local $SIG{PIPE} = 'IGNORE';
1648
1649   my $oldAutoCommit = $FS::UID::AutoCommit;
1650   local $FS::UID::AutoCommit = 0;
1651   my $dbh = dbh;
1652
1653   foreach my $current ( $self->cust_pkg_detail($detailtype) ) {
1654     my $error = $current->delete;
1655     if ( $error ) {
1656       $dbh->rollback if $oldAutoCommit;
1657       return "error removing old detail: $error";
1658     }
1659   }
1660
1661   foreach my $detail ( @details ) {
1662     my $cust_pkg_detail = new FS::cust_pkg_detail {
1663       'pkgnum'     => $self->pkgnum,
1664       'detailtype' => $detailtype,
1665       'detail'     => $detail,
1666     };
1667     my $error = $cust_pkg_detail->insert;
1668     if ( $error ) {
1669       $dbh->rollback if $oldAutoCommit;
1670       return "error adding new detail: $error";
1671     }
1672
1673   }
1674
1675   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1676   '';
1677
1678 }
1679
1680 =item cust_event
1681
1682 Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.
1683
1684 =cut
1685
1686 #false laziness w/cust_bill.pm
1687 sub cust_event {
1688   my $self = shift;
1689   qsearch({
1690     'table'     => 'cust_event',
1691     'addl_from' => 'JOIN part_event USING ( eventpart )',
1692     'hashref'   => { 'tablenum' => $self->pkgnum },
1693     'extra_sql' => " AND eventtable = 'cust_pkg' ",
1694   });
1695 }
1696
1697 =item num_cust_event
1698
1699 Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.
1700
1701 =cut
1702
1703 #false laziness w/cust_bill.pm
1704 sub num_cust_event {
1705   my $self = shift;
1706   my $sql =
1707     "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
1708     "  WHERE tablenum = ? AND eventtable = 'cust_pkg'";
1709   my $sth = dbh->prepare($sql) or die  dbh->errstr. " preparing $sql"; 
1710   $sth->execute($self->pkgnum) or die $sth->errstr. " executing $sql";
1711   $sth->fetchrow_arrayref->[0];
1712 }
1713
1714 =item cust_svc [ SVCPART ]
1715
1716 Returns the services for this package, as FS::cust_svc objects (see
1717 L<FS::cust_svc>).  If a svcpart is specified, return only the matching
1718 services.
1719
1720 =cut
1721
1722 sub cust_svc {
1723   my $self = shift;
1724
1725   return () unless $self->num_cust_svc(@_);
1726
1727   if ( @_ ) {
1728     return qsearch( 'cust_svc', { 'pkgnum'  => $self->pkgnum,
1729                                   'svcpart' => shift,          } );
1730   }
1731
1732   cluck "cust_pkg->cust_svc called" if $DEBUG > 2;
1733
1734   #if ( $self->{'_svcnum'} ) {
1735   #  values %{ $self->{'_svcnum'}->cache };
1736   #} else {
1737     $self->_sort_cust_svc(
1738       [ qsearch( 'cust_svc', { 'pkgnum' => $self->pkgnum } ) ]
1739     );
1740   #}
1741
1742 }
1743
1744 =item overlimit [ SVCPART ]
1745
1746 Returns the services for this package which have exceeded their
1747 usage limit as FS::cust_svc objects (see L<FS::cust_svc>).  If a svcpart
1748 is specified, return only the matching services.
1749
1750 =cut
1751
1752 sub overlimit {
1753   my $self = shift;
1754   return () unless $self->num_cust_svc(@_);
1755   grep { $_->overlimit } $self->cust_svc(@_);
1756 }
1757
1758 =item h_cust_svc END_TIMESTAMP [ START_TIMESTAMP ] [ MODE ]
1759
1760 Returns historical services for this package created before END TIMESTAMP and
1761 (optionally) not cancelled before START_TIMESTAMP, as FS::h_cust_svc objects
1762 (see L<FS::h_cust_svc>).  If MODE is 'I' (for 'invoice'), services with the 
1763 I<pkg_svc.hidden> flag will be omitted.
1764
1765 =cut
1766
1767 sub h_cust_svc {
1768   my $self = shift;
1769   warn "$me _h_cust_svc called on $self\n"
1770     if $DEBUG;
1771
1772   my ($end, $start, $mode) = @_;
1773   my @cust_svc = $self->_sort_cust_svc(
1774     [ qsearch( 'h_cust_svc',
1775       { 'pkgnum' => $self->pkgnum, },  
1776       FS::h_cust_svc->sql_h_search(@_),  
1777     ) ]
1778   );
1779   if ( $mode eq 'I' ) {
1780     my %hidden_svcpart = map { $_->svcpart => $_->hidden } $self->part_svc;
1781     return grep { !$hidden_svcpart{$_->svcpart} } @cust_svc;
1782   } else {
1783     return @cust_svc;
1784   }
1785 }
1786
1787 sub _sort_cust_svc {
1788   my( $self, $arrayref ) = @_;
1789
1790   my $sort =
1791     sub ($$) { my ($a, $b) = @_; $b->[1] cmp $a->[1]  or  $a->[2] <=> $b->[2] };
1792
1793   map  { $_->[0] }
1794   sort $sort
1795   map {
1796         my $pkg_svc = qsearchs( 'pkg_svc', { 'pkgpart' => $self->pkgpart,
1797                                              'svcpart' => $_->svcpart     } );
1798         [ $_,
1799           $pkg_svc ? $pkg_svc->primary_svc : '',
1800           $pkg_svc ? $pkg_svc->quantity : 0,
1801         ];
1802       }
1803   @$arrayref;
1804
1805 }
1806
1807 =item num_cust_svc [ SVCPART ]
1808
1809 Returns the number of provisioned services for this package.  If a svcpart is
1810 specified, counts only the matching services.
1811
1812 =cut
1813
1814 sub num_cust_svc {
1815   my $self = shift;
1816
1817   return $self->{'_num_cust_svc'}
1818     if !scalar(@_)
1819        && exists($self->{'_num_cust_svc'})
1820        && $self->{'_num_cust_svc'} =~ /\d/;
1821
1822   cluck "cust_pkg->num_cust_svc called, _num_cust_svc:".$self->{'_num_cust_svc'}
1823     if $DEBUG > 2;
1824
1825   my $sql = 'SELECT COUNT(*) FROM cust_svc WHERE pkgnum = ?';
1826   $sql .= ' AND svcpart = ?' if @_;
1827
1828   my $sth = dbh->prepare($sql)     or die  dbh->errstr;
1829   $sth->execute($self->pkgnum, @_) or die $sth->errstr;
1830   $sth->fetchrow_arrayref->[0];
1831 }
1832
1833 =item available_part_svc 
1834
1835 Returns a list of FS::part_svc objects representing services included in this
1836 package but not yet provisioned.  Each FS::part_svc object also has an extra
1837 field, I<num_avail>, which specifies the number of available services.
1838
1839 =cut
1840
1841 sub available_part_svc {
1842   my $self = shift;
1843   grep { $_->num_avail > 0 }
1844     map {
1845           my $part_svc = $_->part_svc;
1846           $part_svc->{'Hash'}{'num_avail'} = #evil encapsulation-breaking
1847             $_->quantity - $self->num_cust_svc($_->svcpart);
1848
1849           # more evil encapsulation breakage
1850           if($part_svc->{'Hash'}{'num_avail'} > 0) {
1851             my @exports = $part_svc->part_export_did;
1852             $part_svc->{'Hash'}{'can_get_dids'} = scalar(@exports);
1853           }
1854
1855           $part_svc;
1856         }
1857       $self->part_pkg->pkg_svc;
1858 }
1859
1860 =item part_svc
1861
1862 Returns a list of FS::part_svc objects representing provisioned and available
1863 services included in this package.  Each FS::part_svc object also has the
1864 following extra fields:
1865
1866 =over 4
1867
1868 =item num_cust_svc  (count)
1869
1870 =item num_avail     (quantity - count)
1871
1872 =item cust_pkg_svc (services) - array reference containing the provisioned services, as cust_svc objects
1873
1874 svcnum
1875 label -> ($cust_svc->label)[1]
1876
1877 =back
1878
1879 =cut
1880
1881 sub part_svc {
1882   my $self = shift;
1883
1884   #XXX some sort of sort order besides numeric by svcpart...
1885   my @part_svc = sort { $a->svcpart <=> $b->svcpart } map {
1886     my $pkg_svc = $_;
1887     my $part_svc = $pkg_svc->part_svc;
1888     my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
1889     $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #more evil
1890     $part_svc->{'Hash'}{'num_avail'}    =
1891       max( 0, $pkg_svc->quantity - $num_cust_svc );
1892     $part_svc->{'Hash'}{'cust_pkg_svc'} =
1893       $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : [];
1894     $part_svc->{'Hash'}{'hidden'} = $pkg_svc->hidden;
1895     $part_svc;
1896   } $self->part_pkg->pkg_svc;
1897
1898   #extras
1899   push @part_svc, map {
1900     my $part_svc = $_;
1901     my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
1902     $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #speak no evail
1903     $part_svc->{'Hash'}{'num_avail'}    = 0; #0-$num_cust_svc ?
1904     $part_svc->{'Hash'}{'cust_pkg_svc'} =
1905       $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : [];
1906     $part_svc;
1907   } $self->extra_part_svc;
1908
1909   @part_svc;
1910
1911 }
1912
1913 =item extra_part_svc
1914
1915 Returns a list of FS::part_svc objects corresponding to services in this
1916 package which are still provisioned but not (any longer) available in the
1917 package definition.
1918
1919 =cut
1920
1921 sub extra_part_svc {
1922   my $self = shift;
1923
1924   my $pkgnum  = $self->pkgnum;
1925   my $pkgpart = $self->pkgpart;
1926
1927 #  qsearch( {
1928 #    'table'     => 'part_svc',
1929 #    'hashref'   => {},
1930 #    'extra_sql' =>
1931 #      "WHERE 0 = ( SELECT COUNT(*) FROM pkg_svc 
1932 #                     WHERE pkg_svc.svcpart = part_svc.svcpart 
1933 #                       AND pkg_svc.pkgpart = ?
1934 #                       AND quantity > 0 
1935 #                 )
1936 #        AND 0 < ( SELECT COUNT(*) FROM cust_svc
1937 #                       LEFT JOIN cust_pkg USING ( pkgnum )
1938 #                     WHERE cust_svc.svcpart = part_svc.svcpart
1939 #                       AND pkgnum = ?
1940 #                 )",
1941 #    'extra_param' => [ [$self->pkgpart=>'int'], [$self->pkgnum=>'int'] ],
1942 #  } );
1943
1944 #seems to benchmark slightly faster...
1945   qsearch( {
1946     #'select'      => 'DISTINCT ON (svcpart) part_svc.*',
1947     #MySQL doesn't grok DISINCT ON
1948     'select'      => 'DISTINCT part_svc.*',
1949     'table'       => 'part_svc',
1950     'addl_from'   =>
1951       'LEFT JOIN pkg_svc  ON (     pkg_svc.svcpart   = part_svc.svcpart 
1952                                AND pkg_svc.pkgpart   = ?
1953                                AND quantity > 0
1954                              )
1955        LEFT JOIN cust_svc ON (     cust_svc.svcpart = part_svc.svcpart )
1956        LEFT JOIN cust_pkg USING ( pkgnum )
1957       ',
1958     'hashref'     => {},
1959     'extra_sql'   => "WHERE pkgsvcnum IS NULL AND cust_pkg.pkgnum = ? ",
1960     'extra_param' => [ [$self->pkgpart=>'int'], [$self->pkgnum=>'int'] ],
1961   } );
1962 }
1963
1964 =item status
1965
1966 Returns a short status string for this package, currently:
1967
1968 =over 4
1969
1970 =item not yet billed
1971
1972 =item one-time charge
1973
1974 =item active
1975
1976 =item suspended
1977
1978 =item cancelled
1979
1980 =back
1981
1982 =cut
1983
1984 sub status {
1985   my $self = shift;
1986
1987   my $freq = length($self->freq) ? $self->freq : $self->part_pkg->freq;
1988
1989   return 'cancelled' if $self->get('cancel');
1990   return 'suspended' if $self->susp;
1991   return 'not yet billed' unless $self->setup;
1992   return 'one-time charge' if $freq =~ /^(0|$)/;
1993   return 'active';
1994 }
1995
1996 =item ucfirst_status
1997
1998 Returns the status with the first character capitalized.
1999
2000 =cut
2001
2002 sub ucfirst_status {
2003   ucfirst(shift->status);
2004 }
2005
2006 =item statuses
2007
2008 Class method that returns the list of possible status strings for packages
2009 (see L<the status method|/status>).  For example:
2010
2011   @statuses = FS::cust_pkg->statuses();
2012
2013 =cut
2014
2015 tie my %statuscolor, 'Tie::IxHash', 
2016   'not yet billed'  => '009999', #teal? cyan?
2017   'one-time charge' => '000000',
2018   'active'          => '00CC00',
2019   'suspended'       => 'FF9900',
2020   'cancelled'       => 'FF0000',
2021 ;
2022
2023 sub statuses {
2024   my $self = shift; #could be class...
2025   #grep { $_ !~ /^(not yet billed)$/ } #this is a dumb status anyway
2026   #                                    # mayble split btw one-time vs. recur
2027     keys %statuscolor;
2028 }
2029
2030 =item statuscolor
2031
2032 Returns a hex triplet color string for this package's status.
2033
2034 =cut
2035
2036 sub statuscolor {
2037   my $self = shift;
2038   $statuscolor{$self->status};
2039 }
2040
2041 =item pkg_label
2042
2043 Returns a label for this package.  (Currently "pkgnum: pkg - comment" or
2044 "pkg-comment" depending on user preference).
2045
2046 =cut
2047
2048 sub pkg_label {
2049   my $self = shift;
2050   my $label = $self->part_pkg->pkg_comment( 'nopkgpart' => 1 );
2051   $label = $self->pkgnum. ": $label"
2052     if $FS::CurrentUser::CurrentUser->option('show_pkgnum');
2053   $label;
2054 }
2055
2056 =item pkg_label_long
2057
2058 Returns a long label for this package, adding the primary service's label to
2059 pkg_label.
2060
2061 =cut
2062
2063 sub pkg_label_long {
2064   my $self = shift;
2065   my $label = $self->pkg_label;
2066   my $cust_svc = $self->primary_cust_svc;
2067   $label .= ' ('. ($cust_svc->label)[1]. ')' if $cust_svc;
2068   $label;
2069 }
2070
2071 =item primary_cust_svc
2072
2073 Returns a primary service (as FS::cust_svc object) if one can be identified.
2074
2075 =cut
2076
2077 #for labeling purposes - might not 100% match up with part_pkg->svcpart's idea
2078
2079 sub primary_cust_svc {
2080   my $self = shift;
2081
2082   my @cust_svc = $self->cust_svc;
2083
2084   return '' unless @cust_svc; #no serivces - irrelevant then
2085   
2086   return $cust_svc[0] if scalar(@cust_svc) == 1; #always return a single service
2087
2088   # primary service as specified in the package definition
2089   # or exactly one service definition with quantity one
2090   my $svcpart = $self->part_pkg->svcpart;
2091   @cust_svc = grep { $_->svcpart == $svcpart } @cust_svc;
2092   return $cust_svc[0] if scalar(@cust_svc) == 1;
2093
2094   #couldn't identify one thing..
2095   return '';
2096 }
2097
2098 =item labels
2099
2100 Returns a list of lists, calling the label method for all services
2101 (see L<FS::cust_svc>) of this billing item.
2102
2103 =cut
2104
2105 sub labels {
2106   my $self = shift;
2107   map { [ $_->label ] } $self->cust_svc;
2108 }
2109
2110 =item h_labels END_TIMESTAMP [ START_TIMESTAMP ] [ MODE ]
2111
2112 Like the labels method, but returns historical information on services that
2113 were active as of END_TIMESTAMP and (optionally) not cancelled before
2114 START_TIMESTAMP.  If MODE is 'I' (for 'invoice'), services with the 
2115 I<pkg_svc.hidden> flag will be omitted.
2116
2117 Returns a list of lists, calling the label method for all (historical) services
2118 (see L<FS::h_cust_svc>) of this billing item.
2119
2120 =cut
2121
2122 sub h_labels {
2123   my $self = shift;
2124   warn "$me _h_labels called on $self\n"
2125     if $DEBUG;
2126   map { [ $_->label(@_) ] } $self->h_cust_svc(@_);
2127 }
2128
2129 =item labels_short
2130
2131 Like labels, except returns a simple flat list, and shortens long
2132 (currently >5 or the cust_bill-max_same_services configuration value) lists of
2133 identical services to one line that lists the service label and the number of
2134 individual services rather than individual items.
2135
2136 =cut
2137
2138 sub labels_short {
2139   shift->_labels_short( 'labels', @_ );
2140 }
2141
2142 =item h_labels_short END_TIMESTAMP [ START_TIMESTAMP ]
2143
2144 Like h_labels, except returns a simple flat list, and shortens long
2145 (currently >5 or the cust_bill-max_same_services configuration value) lists of
2146 identical services to one line that lists the service label and the number of
2147 individual services rather than individual items.
2148
2149 =cut
2150
2151 sub h_labels_short {
2152   shift->_labels_short( 'h_labels', @_ );
2153 }
2154
2155 sub _labels_short {
2156   my( $self, $method ) = ( shift, shift );
2157
2158   warn "$me _labels_short called on $self with $method method\n"
2159     if $DEBUG;
2160
2161   my $conf = new FS::Conf;
2162   my $max_same_services = $conf->config('cust_bill-max_same_services') || 5;
2163
2164   warn "$me _labels_short populating \%labels\n"
2165     if $DEBUG;
2166
2167   my %labels;
2168   #tie %labels, 'Tie::IxHash';
2169   push @{ $labels{$_->[0]} }, $_->[1]
2170     foreach $self->$method(@_);
2171
2172   warn "$me _labels_short populating \@labels\n"
2173     if $DEBUG;
2174
2175   my @labels;
2176   foreach my $label ( keys %labels ) {
2177     my %seen = ();
2178     my @values = grep { ! $seen{$_}++ } @{ $labels{$label} };
2179     my $num = scalar(@values);
2180     warn "$me _labels_short $num items for $label\n"
2181       if $DEBUG;
2182
2183     if ( $num > $max_same_services ) {
2184       warn "$me _labels_short   more than $max_same_services, so summarizing\n"
2185         if $DEBUG;
2186       push @labels, "$label ($num)";
2187     } else {
2188       if ( $conf->exists('cust_bill-consolidate_services') ) {
2189         warn "$me _labels_short   consolidating services\n"
2190           if $DEBUG;
2191         # push @labels, "$label: ". join(', ', @values);
2192         while ( @values ) {
2193           my $detail = "$label: ";
2194           $detail .= shift(@values). ', '
2195             while @values && length($detail.$values[0]) < 78;
2196           $detail =~ s/, $//;
2197           push @labels, $detail;
2198         }
2199       } else {
2200         warn "$me _labels_short   adding service data\n"
2201           if $DEBUG;
2202         push @labels, map { "$label: $_" } @values;
2203       }
2204     }
2205   }
2206
2207  @labels;
2208
2209 }
2210
2211 =item cust_main
2212
2213 Returns the parent customer object (see L<FS::cust_main>).
2214
2215 =cut
2216
2217 sub cust_main {
2218   my $self = shift;
2219   qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
2220 }
2221
2222 #these subs are in location_Mixin.pm now... unfortunately the POD doesn't mixin
2223
2224 =item cust_location
2225
2226 Returns the location object, if any (see L<FS::cust_location>).
2227
2228 =item cust_location_or_main
2229
2230 If this package is associated with a location, returns the locaiton (see
2231 L<FS::cust_location>), otherwise returns the customer (see L<FS::cust_main>).
2232
2233 =item location_label [ OPTION => VALUE ... ]
2234
2235 Returns the label of the location object (see L<FS::cust_location>).
2236
2237 =cut
2238
2239 #end of subs in location_Mixin.pm now... unfortunately the POD doesn't mixin
2240
2241 =item seconds_since TIMESTAMP
2242
2243 Returns the number of seconds all accounts (see L<FS::svc_acct>) in this
2244 package have been online since TIMESTAMP, according to the session monitor.
2245
2246 TIMESTAMP is specified as a UNIX timestamp; see L<perlfunc/"time">.  Also see
2247 L<Time::Local> and L<Date::Parse> for conversion functions.
2248
2249 =cut
2250
2251 sub seconds_since {
2252   my($self, $since) = @_;
2253   my $seconds = 0;
2254
2255   foreach my $cust_svc (
2256     grep { $_->part_svc->svcdb eq 'svc_acct' } $self->cust_svc
2257   ) {
2258     $seconds += $cust_svc->seconds_since($since);
2259   }
2260
2261   $seconds;
2262
2263 }
2264
2265 =item seconds_since_sqlradacct TIMESTAMP_START TIMESTAMP_END
2266
2267 Returns the numbers of seconds all accounts (see L<FS::svc_acct>) in this
2268 package have been online between TIMESTAMP_START (inclusive) and TIMESTAMP_END
2269 (exclusive).
2270
2271 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
2272 L<perlfunc/"time">.  Also see L<Time::Local> and L<Date::Parse> for conversion
2273 functions.
2274
2275
2276 =cut
2277
2278 sub seconds_since_sqlradacct {
2279   my($self, $start, $end) = @_;
2280
2281   my $seconds = 0;
2282
2283   foreach my $cust_svc (
2284     grep {
2285       my $part_svc = $_->part_svc;
2286       $part_svc->svcdb eq 'svc_acct'
2287         && scalar($part_svc->part_export('sqlradius'));
2288     } $self->cust_svc
2289   ) {
2290     $seconds += $cust_svc->seconds_since_sqlradacct($start, $end);
2291   }
2292
2293   $seconds;
2294
2295 }
2296
2297 =item attribute_since_sqlradacct TIMESTAMP_START TIMESTAMP_END ATTRIBUTE
2298
2299 Returns the sum of the given attribute for all accounts (see L<FS::svc_acct>)
2300 in this package for sessions ending between TIMESTAMP_START (inclusive) and
2301 TIMESTAMP_END
2302 (exclusive).
2303
2304 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
2305 L<perlfunc/"time">.  Also see L<Time::Local> and L<Date::Parse> for conversion
2306 functions.
2307
2308 =cut
2309
2310 sub attribute_since_sqlradacct {
2311   my($self, $start, $end, $attrib) = @_;
2312
2313   my $sum = 0;
2314
2315   foreach my $cust_svc (
2316     grep {
2317       my $part_svc = $_->part_svc;
2318       $part_svc->svcdb eq 'svc_acct'
2319         && scalar($part_svc->part_export('sqlradius'));
2320     } $self->cust_svc
2321   ) {
2322     $sum += $cust_svc->attribute_since_sqlradacct($start, $end, $attrib);
2323   }
2324
2325   $sum;
2326
2327 }
2328
2329 =item quantity
2330
2331 =cut
2332
2333 sub quantity {
2334   my( $self, $value ) = @_;
2335   if ( defined($value) ) {
2336     $self->setfield('quantity', $value);
2337   }
2338   $self->getfield('quantity') || 1;
2339 }
2340
2341 =item transfer DEST_PKGNUM | DEST_CUST_PKG, [ OPTION => VALUE ... ]
2342
2343 Transfers as many services as possible from this package to another package.
2344
2345 The destination package can be specified by pkgnum by passing an FS::cust_pkg
2346 object.  The destination package must already exist.
2347
2348 Services are moved only if the destination allows services with the correct
2349 I<svcpart> (not svcdb), unless the B<change_svcpart> option is set true.  Use
2350 this option with caution!  No provision is made for export differences
2351 between the old and new service definitions.  Probably only should be used
2352 when your exports for all service definitions of a given svcdb are identical.
2353 (attempt a transfer without it first, to move all possible svcpart-matching
2354 services)
2355
2356 Any services that can't be moved remain in the original package.
2357
2358 Returns an error, if there is one; otherwise, returns the number of services 
2359 that couldn't be moved.
2360
2361 =cut
2362
2363 sub transfer {
2364   my ($self, $dest_pkgnum, %opt) = @_;
2365
2366   my $remaining = 0;
2367   my $dest;
2368   my %target;
2369
2370   if (ref ($dest_pkgnum) eq 'FS::cust_pkg') {
2371     $dest = $dest_pkgnum;
2372     $dest_pkgnum = $dest->pkgnum;
2373   } else {
2374     $dest = qsearchs('cust_pkg', { pkgnum => $dest_pkgnum });
2375   }
2376
2377   return ('Package does not exist: '.$dest_pkgnum) unless $dest;
2378
2379   foreach my $pkg_svc ( $dest->part_pkg->pkg_svc ) {
2380     $target{$pkg_svc->svcpart} = $pkg_svc->quantity;
2381   }
2382
2383   foreach my $cust_svc ($dest->cust_svc) {
2384     $target{$cust_svc->svcpart}--;
2385   }
2386
2387   my %svcpart2svcparts = ();
2388   if ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
2389     warn "change_svcpart option received, creating alternates list\n" if $DEBUG;
2390     foreach my $svcpart ( map { $_->svcpart } $self->cust_svc ) {
2391       next if exists $svcpart2svcparts{$svcpart};
2392       my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2393       $svcpart2svcparts{$svcpart} = [
2394         map  { $_->[0] }
2395         sort { $b->[1] cmp $a->[1]  or  $a->[2] <=> $b->[2] } 
2396         map {
2397               my $pkg_svc = qsearchs( 'pkg_svc', { 'pkgpart' => $dest->pkgpart,
2398                                                    'svcpart' => $_          } );
2399               [ $_,
2400                 $pkg_svc ? $pkg_svc->primary_svc : '',
2401                 $pkg_svc ? $pkg_svc->quantity : 0,
2402               ];
2403             }
2404
2405         grep { $_ != $svcpart }
2406         map  { $_->svcpart }
2407         qsearch('part_svc', { 'svcdb' => $part_svc->svcdb } )
2408       ];
2409       warn "alternates for svcpart $svcpart: ".
2410            join(', ', @{$svcpart2svcparts{$svcpart}}). "\n"
2411         if $DEBUG;
2412     }
2413   }
2414
2415   foreach my $cust_svc ($self->cust_svc) {
2416     if($target{$cust_svc->svcpart} > 0) {
2417       $target{$cust_svc->svcpart}--;
2418       my $new = new FS::cust_svc { $cust_svc->hash };
2419       $new->pkgnum($dest_pkgnum);
2420       my $error = $new->replace($cust_svc);
2421       return $error if $error;
2422     } elsif ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
2423       if ( $DEBUG ) {
2424         warn "looking for alternates for svcpart ". $cust_svc->svcpart. "\n";
2425         warn "alternates to consider: ".
2426              join(', ', @{$svcpart2svcparts{$cust_svc->svcpart}}). "\n";
2427       }
2428       my @alternate = grep {
2429                              warn "considering alternate svcpart $_: ".
2430                                   "$target{$_} available in new package\n"
2431                                if $DEBUG;
2432                              $target{$_} > 0;
2433                            } @{$svcpart2svcparts{$cust_svc->svcpart}};
2434       if ( @alternate ) {
2435         warn "alternate(s) found\n" if $DEBUG;
2436         my $change_svcpart = $alternate[0];
2437         $target{$change_svcpart}--;
2438         my $new = new FS::cust_svc { $cust_svc->hash };
2439         $new->svcpart($change_svcpart);
2440         $new->pkgnum($dest_pkgnum);
2441         my $error = $new->replace($cust_svc);
2442         return $error if $error;
2443       } else {
2444         $remaining++;
2445       }
2446     } else {
2447       $remaining++
2448     }
2449   }
2450   return $remaining;
2451 }
2452
2453 =item reexport
2454
2455 This method is deprecated.  See the I<depend_jobnum> option to the insert and
2456 order_pkgs methods in FS::cust_main for a better way to defer provisioning.
2457
2458 =cut
2459
2460 sub reexport {
2461   my $self = shift;
2462
2463   local $SIG{HUP} = 'IGNORE';
2464   local $SIG{INT} = 'IGNORE';
2465   local $SIG{QUIT} = 'IGNORE';
2466   local $SIG{TERM} = 'IGNORE';
2467   local $SIG{TSTP} = 'IGNORE';
2468   local $SIG{PIPE} = 'IGNORE';
2469
2470   my $oldAutoCommit = $FS::UID::AutoCommit;
2471   local $FS::UID::AutoCommit = 0;
2472   my $dbh = dbh;
2473
2474   foreach my $cust_svc ( $self->cust_svc ) {
2475     #false laziness w/svc_Common::insert
2476     my $svc_x = $cust_svc->svc_x;
2477     foreach my $part_export ( $cust_svc->part_svc->part_export ) {
2478       my $error = $part_export->export_insert($svc_x);
2479       if ( $error ) {
2480         $dbh->rollback if $oldAutoCommit;
2481         return $error;
2482       }
2483     }
2484   }
2485
2486   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2487   '';
2488
2489 }
2490
2491 =item insert_reason
2492
2493 Associates this package with a (suspension or cancellation) reason (see
2494 L<FS::cust_pkg_reason>, possibly inserting a new reason on the fly (see
2495 L<FS::reason>).
2496
2497 Available options are:
2498
2499 =over 4
2500
2501 =item reason
2502
2503 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.
2504
2505 =item reason_otaker
2506
2507 the access_user (see L<FS::access_user>) providing the reason
2508
2509 =item date
2510
2511 a unix timestamp 
2512
2513 =item action
2514
2515 the action (cancel, susp, adjourn, expire) associated with the reason
2516
2517 =back
2518
2519 If there is an error, returns the error, otherwise returns false.
2520
2521 =cut
2522
2523 sub insert_reason {
2524   my ($self, %options) = @_;
2525
2526   my $otaker = $options{reason_otaker} ||
2527                $FS::CurrentUser::CurrentUser->username;
2528
2529   my $reasonnum;
2530   if ( $options{'reason'} =~ /^(\d+)$/ ) {
2531
2532     $reasonnum = $1;
2533
2534   } elsif ( ref($options{'reason'}) ) {
2535   
2536     return 'Enter a new reason (or select an existing one)'
2537       unless $options{'reason'}->{'reason'} !~ /^\s*$/;
2538
2539     my $reason = new FS::reason({
2540       'reason_type' => $options{'reason'}->{'typenum'},
2541       'reason'      => $options{'reason'}->{'reason'},
2542     });
2543     my $error = $reason->insert;
2544     return $error if $error;
2545
2546     $reasonnum = $reason->reasonnum;
2547
2548   } else {
2549     return "Unparsable reason: ". $options{'reason'};
2550   }
2551
2552   my $cust_pkg_reason =
2553     new FS::cust_pkg_reason({ 'pkgnum'    => $self->pkgnum,
2554                               'reasonnum' => $reasonnum, 
2555                               'otaker'    => $otaker,
2556                               'action'    => substr(uc($options{'action'}),0,1),
2557                               'date'      => $options{'date'}
2558                                                ? $options{'date'}
2559                                                : time,
2560                             });
2561
2562   $cust_pkg_reason->insert;
2563 }
2564
2565 =item insert_discount
2566
2567 Associates this package with a discount (see L<FS::cust_pkg_discount>, possibly
2568 inserting a new discount on the fly (see L<FS::discount>).
2569
2570 Available options are:
2571
2572 =over 4
2573
2574 =item discountnum
2575
2576 =back
2577
2578 If there is an error, returns the error, otherwise returns false.
2579
2580 =cut
2581
2582 sub insert_discount {
2583   #my ($self, %options) = @_;
2584   my $self = shift;
2585
2586   my $cust_pkg_discount = new FS::cust_pkg_discount {
2587     'pkgnum'      => $self->pkgnum,
2588     'discountnum' => $self->discountnum,
2589     'months_used' => 0,
2590     'end_date'    => '', #XXX
2591     #for the create a new discount case
2592     '_type'       => $self->discountnum__type,
2593     'amount'      => $self->discountnum_amount,
2594     'percent'     => $self->discountnum_percent,
2595     'months'      => $self->discountnum_months,
2596     #'disabled'    => $self->discountnum_disabled,
2597   };
2598
2599   $cust_pkg_discount->insert;
2600 }
2601
2602 =item set_usage USAGE_VALUE_HASHREF 
2603
2604 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
2605 to which they should be set (see L<FS::svc_acct>).  Currently seconds,
2606 upbytes, downbytes, and totalbytes are appropriate keys.
2607
2608 All svc_accts which are part of this package have their values reset.
2609
2610 =cut
2611
2612 sub set_usage {
2613   my ($self, $valueref, %opt) = @_;
2614
2615   foreach my $cust_svc ($self->cust_svc){
2616     my $svc_x = $cust_svc->svc_x;
2617     $svc_x->set_usage($valueref, %opt)
2618       if $svc_x->can("set_usage");
2619   }
2620 }
2621
2622 =item recharge USAGE_VALUE_HASHREF 
2623
2624 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
2625 to which they should be set (see L<FS::svc_acct>).  Currently seconds,
2626 upbytes, downbytes, and totalbytes are appropriate keys.
2627
2628 All svc_accts which are part of this package have their values incremented.
2629
2630 =cut
2631
2632 sub recharge {
2633   my ($self, $valueref) = @_;
2634
2635   foreach my $cust_svc ($self->cust_svc){
2636     my $svc_x = $cust_svc->svc_x;
2637     $svc_x->recharge($valueref)
2638       if $svc_x->can("recharge");
2639   }
2640 }
2641
2642 =item cust_pkg_discount
2643
2644 =cut
2645
2646 sub cust_pkg_discount {
2647   my $self = shift;
2648   qsearch('cust_pkg_discount', { 'pkgnum' => $self->pkgnum } );
2649 }
2650
2651 =item cust_pkg_discount_active
2652
2653 =cut
2654
2655 sub cust_pkg_discount_active {
2656   my $self = shift;
2657   grep { $_->status eq 'active' } $self->cust_pkg_discount;
2658 }
2659
2660 =back
2661
2662 =head1 CLASS METHODS
2663
2664 =over 4
2665
2666 =item recurring_sql
2667
2668 Returns an SQL expression identifying recurring packages.
2669
2670 =cut
2671
2672 sub recurring_sql { "
2673   '0' != ( select freq from part_pkg
2674              where cust_pkg.pkgpart = part_pkg.pkgpart )
2675 "; }
2676
2677 =item onetime_sql
2678
2679 Returns an SQL expression identifying one-time packages.
2680
2681 =cut
2682
2683 sub onetime_sql { "
2684   '0' = ( select freq from part_pkg
2685             where cust_pkg.pkgpart = part_pkg.pkgpart )
2686 "; }
2687
2688 =item ordered_sql
2689
2690 Returns an SQL expression identifying ordered packages (recurring packages not
2691 yet billed).
2692
2693 =cut
2694
2695 sub ordered_sql {
2696    $_[0]->recurring_sql. " AND ". $_[0]->not_yet_billed_sql;
2697 }
2698
2699 =item active_sql
2700
2701 Returns an SQL expression identifying active packages.
2702
2703 =cut
2704
2705 sub active_sql {
2706   $_[0]->recurring_sql. "
2707   AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
2708   AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
2709   AND ( cust_pkg.susp   IS NULL OR cust_pkg.susp   = 0 )
2710 "; }
2711
2712 =item not_yet_billed_sql
2713
2714 Returns an SQL expression identifying packages which have not yet been billed.
2715
2716 =cut
2717
2718 sub not_yet_billed_sql { "
2719       ( cust_pkg.setup  IS NULL OR cust_pkg.setup  = 0 )
2720   AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
2721   AND ( cust_pkg.susp   IS NULL OR cust_pkg.susp   = 0 )
2722 "; }
2723
2724 =item inactive_sql
2725
2726 Returns an SQL expression identifying inactive packages (one-time packages
2727 that are otherwise unsuspended/uncancelled).
2728
2729 =cut
2730
2731 sub inactive_sql { "
2732   ". $_[0]->onetime_sql(). "
2733   AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
2734   AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
2735   AND ( cust_pkg.susp   IS NULL OR cust_pkg.susp   = 0 )
2736 "; }
2737
2738 =item susp_sql
2739 =item suspended_sql
2740
2741 Returns an SQL expression identifying suspended packages.
2742
2743 =cut
2744
2745 sub suspended_sql { susp_sql(@_); }
2746 sub susp_sql {
2747   #$_[0]->recurring_sql(). ' AND '.
2748   "
2749         ( cust_pkg.cancel IS     NULL  OR cust_pkg.cancel = 0 )
2750     AND   cust_pkg.susp   IS NOT NULL AND cust_pkg.susp  != 0
2751   ";
2752 }
2753
2754 =item cancel_sql
2755 =item cancelled_sql
2756
2757 Returns an SQL exprression identifying cancelled packages.
2758
2759 =cut
2760
2761 sub cancelled_sql { cancel_sql(@_); }
2762 sub cancel_sql { 
2763   #$_[0]->recurring_sql(). ' AND '.
2764   "cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0";
2765 }
2766
2767 =item status_sql
2768
2769 Returns an SQL expression to give the package status as a string.
2770
2771 =cut
2772
2773 sub status_sql {
2774 "CASE
2775   WHEN cust_pkg.cancel IS NOT NULL THEN 'cancelled'
2776   WHEN cust_pkg.susp IS NOT NULL THEN 'suspended'
2777   WHEN cust_pkg.setup IS NULL THEN 'not yet billed'
2778   WHEN ".onetime_sql()." THEN 'one-time charge'
2779   ELSE 'active'
2780 END"
2781 }
2782
2783 =item search HASHREF
2784
2785 (Class method)
2786
2787 Returns a qsearch hash expression to search for parameters specified in HASHREF.
2788 Valid parameters are
2789
2790 =over 4
2791
2792 =item agentnum
2793
2794 =item magic
2795
2796 active, inactive, suspended, cancel (or cancelled)
2797
2798 =item status
2799
2800 active, inactive, suspended, one-time charge, inactive, cancel (or cancelled)
2801
2802 =item custom
2803
2804  boolean selects custom packages
2805
2806 =item classnum
2807
2808 =item pkgpart
2809
2810 pkgpart or arrayref or hashref of pkgparts
2811
2812 =item setup
2813
2814 arrayref of beginning and ending epoch date
2815
2816 =item last_bill
2817
2818 arrayref of beginning and ending epoch date
2819
2820 =item bill
2821
2822 arrayref of beginning and ending epoch date
2823
2824 =item adjourn
2825
2826 arrayref of beginning and ending epoch date
2827
2828 =item susp
2829
2830 arrayref of beginning and ending epoch date
2831
2832 =item expire
2833
2834 arrayref of beginning and ending epoch date
2835
2836 =item cancel
2837
2838 arrayref of beginning and ending epoch date
2839
2840 =item query
2841
2842 pkgnum or APKG_pkgnum
2843
2844 =item cust_fields
2845
2846 a value suited to passing to FS::UI::Web::cust_header
2847
2848 =item CurrentUser
2849
2850 specifies the user for agent virtualization
2851
2852 =item fcc_line
2853
2854  boolean selects packages containing fcc form 477 telco lines
2855
2856 =back
2857
2858 =cut
2859
2860 sub search {
2861   my ($class, $params) = @_;
2862   my @where = ();
2863
2864   ##
2865   # parse agent
2866   ##
2867
2868   if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
2869     push @where,
2870       "cust_main.agentnum = $1";
2871   }
2872
2873   ##
2874   # parse custnum
2875   ##
2876
2877   if ( $params->{'custnum'} =~ /^(\d+)$/ and $1 ) {
2878     push @where,
2879       "cust_pkg.custnum = $1";
2880   }
2881
2882   ##
2883   # custbatch
2884   ##
2885
2886   if ( $params->{'pkgbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
2887     push @where,
2888       "cust_pkg.pkgbatch = '$1'";
2889   }
2890
2891   ##
2892   # parse status
2893   ##
2894
2895   if (    $params->{'magic'}  eq 'active'
2896        || $params->{'status'} eq 'active' ) {
2897
2898     push @where, FS::cust_pkg->active_sql();
2899
2900   } elsif (    $params->{'magic'}  =~ /^not[ _]yet[ _]billed$/
2901             || $params->{'status'} =~ /^not[ _]yet[ _]billed$/ ) {
2902
2903     push @where, FS::cust_pkg->not_yet_billed_sql();
2904
2905   } elsif (    $params->{'magic'}  =~ /^(one-time charge|inactive)/
2906             || $params->{'status'} =~ /^(one-time charge|inactive)/ ) {
2907
2908     push @where, FS::cust_pkg->inactive_sql();
2909
2910   } elsif (    $params->{'magic'}  eq 'suspended'
2911             || $params->{'status'} eq 'suspended'  ) {
2912
2913     push @where, FS::cust_pkg->suspended_sql();
2914
2915   } elsif (    $params->{'magic'}  =~ /^cancell?ed$/
2916             || $params->{'status'} =~ /^cancell?ed$/ ) {
2917
2918     push @where, FS::cust_pkg->cancelled_sql();
2919
2920   }
2921
2922   ###
2923   # parse package class
2924   ###
2925
2926   #false lazinessish w/graph/cust_bill_pkg.cgi
2927   my $classnum = 0;
2928   my @pkg_class = ();
2929   if ( exists($params->{'classnum'})
2930        && $params->{'classnum'} =~ /^(\d*)$/
2931      )
2932   {
2933     $classnum = $1;
2934     if ( $classnum ) { #a specific class
2935       push @where, "part_pkg.classnum = $classnum";
2936
2937       #@pkg_class = ( qsearchs('pkg_class', { 'classnum' => $classnum } ) );
2938       #die "classnum $classnum not found!" unless $pkg_class[0];
2939       #$title .= $pkg_class[0]->classname.' ';
2940
2941     } elsif ( $classnum eq '' ) { #the empty class
2942
2943       push @where, "part_pkg.classnum IS NULL";
2944       #$title .= 'Empty class ';
2945       #@pkg_class = ( '(empty class)' );
2946     } elsif ( $classnum eq '0' ) {
2947       #@pkg_class = qsearch('pkg_class', {} ); # { 'disabled' => '' } );
2948       #push @pkg_class, '(empty class)';
2949     } else {
2950       die "illegal classnum";
2951     }
2952   }
2953   #eslaf
2954
2955   ###
2956   # parse package report options
2957   ###
2958
2959   my @report_option = ();
2960   if ( exists($params->{'report_option'})
2961        && $params->{'report_option'} =~ /^([,\d]*)$/
2962      )
2963   {
2964     @report_option = split(',', $1);
2965   }
2966
2967   if (@report_option) {
2968     # this will result in the empty set for the dangling comma case as it should
2969     push @where, 
2970       map{ "0 < ( SELECT count(*) FROM part_pkg_option
2971                     WHERE part_pkg_option.pkgpart = part_pkg.pkgpart
2972                     AND optionname = 'report_option_$_'
2973                     AND optionvalue = '1' )"
2974          } @report_option;
2975   }
2976
2977   #eslaf
2978
2979   ###
2980   # parse custom
2981   ###
2982
2983   push @where,  "part_pkg.custom = 'Y'" if $params->{custom};
2984
2985   ###
2986   # parse fcc_line
2987   ###
2988
2989   push @where,  "part_pkg.fcc_ds0s > 0" if $params->{fcc_line};
2990
2991   ###
2992   # parse censustract
2993   ###
2994
2995   if ( exists($params->{'censustract'}) ) {
2996     $params->{'censustract'} =~ /^([.\d]*)$/;
2997     my $censustract = "cust_main.censustract = '$1'";
2998     $censustract .= ' OR cust_main.censustract is NULL' unless $1;
2999     push @where,  "( $censustract )";
3000   }
3001
3002   ###
3003   # parse part_pkg
3004   ###
3005
3006   if ( ref($params->{'pkgpart'}) ) {
3007
3008     my @pkgpart = ();
3009     if ( ref($params->{'pkgpart'}) eq 'HASH' ) {
3010       @pkgpart = grep $params->{'pkgpart'}{$_}, keys %{ $params->{'pkgpart'} };
3011     } elsif ( ref($params->{'pkgpart'}) eq 'ARRAY' ) {
3012       @pkgpart = @{ $params->{'pkgpart'} };
3013     } else {
3014       die 'unhandled pkgpart ref '. $params->{'pkgpart'};
3015     }
3016
3017     @pkgpart = grep /^(\d+)$/, @pkgpart;
3018
3019     push @where, 'pkgpart IN ('. join(',', @pkgpart). ')' if scalar(@pkgpart);
3020
3021   } elsif ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
3022     push @where, "pkgpart = $1";
3023   } 
3024
3025   ###
3026   # parse dates
3027   ###
3028
3029   my $orderby = '';
3030
3031   #false laziness w/report_cust_pkg.html
3032   my %disable = (
3033     'all'             => {},
3034     'one-time charge' => { 'last_bill'=>1, 'bill'=>1, 'adjourn'=>1, 'susp'=>1, 'expire'=>1, 'cancel'=>1, },
3035     'active'          => { 'susp'=>1, 'cancel'=>1 },
3036     'suspended'       => { 'cancel' => 1 },
3037     'cancelled'       => {},
3038     ''                => {},
3039   );
3040
3041   if( exists($params->{'active'} ) ) {
3042     # This overrides all the other date-related fields
3043     my($beginning, $ending) = @{$params->{'active'}};
3044     push @where,
3045       "cust_pkg.setup IS NOT NULL",
3046       "cust_pkg.setup <= $ending",
3047       "(cust_pkg.cancel IS NULL OR cust_pkg.cancel >= $beginning )",
3048       "NOT (".FS::cust_pkg->onetime_sql . ")";
3049   }
3050   else {
3051     foreach my $field (qw( setup last_bill bill adjourn susp expire contract_end cancel )) {
3052
3053       next unless exists($params->{$field});
3054
3055       my($beginning, $ending) = @{$params->{$field}};
3056
3057       next if $beginning == 0 && $ending == 4294967295;
3058
3059       push @where,
3060         "cust_pkg.$field IS NOT NULL",
3061         "cust_pkg.$field >= $beginning",
3062         "cust_pkg.$field <= $ending";
3063
3064       $orderby ||= "ORDER BY cust_pkg.$field";
3065
3066     }
3067   }
3068
3069   $orderby ||= 'ORDER BY bill';
3070
3071   ###
3072   # parse magic, legacy, etc.
3073   ###
3074
3075   if ( $params->{'magic'} &&
3076        $params->{'magic'} =~ /^(active|inactive|suspended|cancell?ed)$/
3077   ) {
3078
3079     $orderby = 'ORDER BY pkgnum';
3080
3081     if ( $params->{'pkgpart'} =~ /^(\d+)$/ ) {
3082       push @where, "pkgpart = $1";
3083     }
3084
3085   } elsif ( $params->{'query'} eq 'pkgnum' ) {
3086
3087     $orderby = 'ORDER BY pkgnum';
3088
3089   } elsif ( $params->{'query'} eq 'APKG_pkgnum' ) {
3090
3091     $orderby = 'ORDER BY pkgnum';
3092
3093     push @where, '0 < (
3094       SELECT count(*) FROM pkg_svc
3095        WHERE pkg_svc.pkgpart =  cust_pkg.pkgpart
3096          AND pkg_svc.quantity > ( SELECT count(*) FROM cust_svc
3097                                    WHERE cust_svc.pkgnum  = cust_pkg.pkgnum
3098                                      AND cust_svc.svcpart = pkg_svc.svcpart
3099                                 )
3100     )';
3101   
3102   }
3103
3104   ##
3105   # setup queries, links, subs, etc. for the search
3106   ##
3107
3108   # here is the agent virtualization
3109   if ($params->{CurrentUser}) {
3110     my $access_user =
3111       qsearchs('access_user', { username => $params->{CurrentUser} });
3112
3113     if ($access_user) {
3114       push @where, $access_user->agentnums_sql('table'=>'cust_main');
3115     } else {
3116       push @where, "1=0";
3117     }
3118   } else {
3119     push @where, $FS::CurrentUser::CurrentUser->agentnums_sql('table'=>'cust_main');
3120   }
3121
3122   my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
3123
3124   my $addl_from = 'LEFT JOIN cust_main USING ( custnum  ) '.
3125                   'LEFT JOIN part_pkg  USING ( pkgpart  ) '.
3126                   'LEFT JOIN pkg_class ON ( part_pkg.classnum = pkg_class.classnum ) ';
3127
3128   my $count_query = "SELECT COUNT(*) FROM cust_pkg $addl_from $extra_sql";
3129
3130   my $sql_query = {
3131     'table'       => 'cust_pkg',
3132     'hashref'     => {},
3133     'select'      => join(', ',
3134                                 'cust_pkg.*',
3135                                 ( map "part_pkg.$_", qw( pkg freq ) ),
3136                                 'pkg_class.classname',
3137                                 'cust_main.custnum AS cust_main_custnum',
3138                                 FS::UI::Web::cust_sql_fields(
3139                                   $params->{'cust_fields'}
3140                                 ),
3141                      ),
3142     'extra_sql'   => "$extra_sql $orderby",
3143     'addl_from'   => $addl_from,
3144     'count_query' => $count_query,
3145   };
3146
3147 }
3148
3149 =item fcc_477_count
3150
3151 Returns a list of two package counts.  The first is a count of packages
3152 based on the supplied criteria and the second is the count of residential
3153 packages with those same criteria.  Criteria are specified as in the search
3154 method.
3155
3156 =cut
3157
3158 sub fcc_477_count {
3159   my ($class, $params) = @_;
3160
3161   my $sql_query = $class->search( $params );
3162
3163   my $count_sql = delete($sql_query->{'count_query'});
3164   $count_sql =~ s/ FROM/,count(CASE WHEN cust_main.company IS NULL OR cust_main.company = '' THEN 1 END) FROM/
3165     or die "couldn't parse count_sql";
3166
3167   my $count_sth = dbh->prepare($count_sql)
3168     or die "Error preparing $count_sql: ". dbh->errstr;
3169   $count_sth->execute
3170     or die "Error executing $count_sql: ". $count_sth->errstr;
3171   my $count_arrayref = $count_sth->fetchrow_arrayref;
3172
3173   return ( @$count_arrayref );
3174
3175 }
3176
3177
3178 =item location_sql
3179
3180 Returns a list: the first item is an SQL fragment identifying matching 
3181 packages/customers via location (taking into account shipping and package
3182 address taxation, if enabled), and subsequent items are the parameters to
3183 substitute for the placeholders in that fragment.
3184
3185 =cut
3186
3187 sub location_sql {
3188   my($class, %opt) = @_;
3189   my $ornull = $opt{'ornull'};
3190
3191   my $conf = new FS::Conf;
3192
3193   # '?' placeholders in _location_sql_where
3194   my $x = $ornull ? 3 : 2;
3195   my @bill_param = ( ('city')x3, ('county')x$x, ('state')x$x, 'country' );
3196
3197   my $main_where;
3198   my @main_param;
3199   if ( $conf->exists('tax-ship_address') ) {
3200
3201     $main_where = "(
3202          (     ( ship_last IS NULL     OR  ship_last  = '' )
3203            AND ". _location_sql_where('cust_main', '', $ornull ). "
3204          )
3205       OR (       ship_last IS NOT NULL AND ship_last != ''
3206            AND ". _location_sql_where('cust_main', 'ship_', $ornull ). "
3207          )
3208     )";
3209     #    AND payby != 'COMP'
3210
3211     @main_param = ( @bill_param, @bill_param );
3212
3213   } else {
3214
3215     $main_where = _location_sql_where('cust_main'); # AND payby != 'COMP'
3216     @main_param = @bill_param;
3217
3218   }
3219
3220   my $where;
3221   my @param;
3222   if ( $conf->exists('tax-pkg_address') ) {
3223
3224     my $loc_where = _location_sql_where( 'cust_location', '', $ornull );
3225
3226     $where = " (
3227                     ( cust_pkg.locationnum IS     NULL AND $main_where )
3228                  OR ( cust_pkg.locationnum IS NOT NULL AND $loc_where  )
3229                )
3230              ";
3231     @param = ( @main_param, @bill_param );
3232   
3233   } else {
3234
3235     $where = $main_where;
3236     @param = @main_param;
3237
3238   }
3239
3240   ( $where, @param );
3241
3242 }
3243
3244 #subroutine, helper for location_sql
3245 sub _location_sql_where {
3246   my $table  = shift;
3247   my $prefix = @_ ? shift : '';
3248   my $ornull = @_ ? shift : '';
3249
3250 #  $ornull             = $ornull          ? " OR ( ? IS NULL AND $table.${prefix}county IS NULL ) " : '';
3251
3252   $ornull = $ornull ? ' OR ? IS NULL ' : '';
3253
3254   my $or_empty_city   = " OR ( ? = '' AND $table.${prefix}city   IS NULL ) ";
3255   my $or_empty_county = " OR ( ? = '' AND $table.${prefix}county IS NULL ) ";
3256   my $or_empty_state =  " OR ( ? = '' AND $table.${prefix}state  IS NULL ) ";
3257
3258 #        ( $table.${prefix}city    = ? $or_empty_city   $ornull )
3259   "
3260         ( $table.${prefix}city    = ? OR ? = '' OR CAST(? AS text) IS NULL )
3261     AND ( $table.${prefix}county  = ? $or_empty_county $ornull )
3262     AND ( $table.${prefix}state   = ? $or_empty_state  $ornull )
3263     AND   $table.${prefix}country = ?
3264   ";
3265 }
3266
3267 =head1 SUBROUTINES
3268
3269 =over 4
3270
3271 =item order CUSTNUM, PKGPARTS_ARYREF, [ REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF [ REFNUM ] ] ]
3272
3273 CUSTNUM is a customer (see L<FS::cust_main>)
3274
3275 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
3276 L<FS::part_pkg>) to order for this customer.  Duplicates are of course
3277 permitted.
3278
3279 REMOVE_PKGNUMS is an optional list of pkgnums specifying the billing items to
3280 remove for this customer.  The services (see L<FS::cust_svc>) are moved to the
3281 new billing items.  An error is returned if this is not possible (see
3282 L<FS::pkg_svc>).  An empty arrayref is equivalent to not specifying this
3283 parameter.
3284
3285 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
3286 newly-created cust_pkg objects.
3287
3288 REFNUM, if specified, will specify the FS::pkg_referral record to be created
3289 and inserted.  Multiple FS::pkg_referral records can be created by
3290 setting I<refnum> to an array reference of refnums or a hash reference with
3291 refnums as keys.  If no I<refnum> is defined, a default FS::pkg_referral
3292 record will be created corresponding to cust_main.refnum.
3293
3294 =cut
3295
3296 sub order {
3297   my ($custnum, $pkgparts, $remove_pkgnum, $return_cust_pkg, $refnum) = @_;
3298
3299   my $conf = new FS::Conf;
3300
3301   # Transactionize this whole mess
3302   local $SIG{HUP} = 'IGNORE';
3303   local $SIG{INT} = 'IGNORE'; 
3304   local $SIG{QUIT} = 'IGNORE';
3305   local $SIG{TERM} = 'IGNORE';
3306   local $SIG{TSTP} = 'IGNORE'; 
3307   local $SIG{PIPE} = 'IGNORE'; 
3308
3309   my $oldAutoCommit = $FS::UID::AutoCommit;
3310   local $FS::UID::AutoCommit = 0;
3311   my $dbh = dbh;
3312
3313   my $error;
3314 #  my $cust_main = qsearchs('cust_main', { custnum => $custnum });
3315 #  return "Customer not found: $custnum" unless $cust_main;
3316
3317   warn "$me order: pkgnums to remove: ". join(',', @$remove_pkgnum). "\n"
3318     if $DEBUG;
3319
3320   my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
3321                          @$remove_pkgnum;
3322
3323   my $change = scalar(@old_cust_pkg) != 0;
3324
3325   my %hash = (); 
3326   if ( scalar(@old_cust_pkg) == 1 && scalar(@$pkgparts) == 1 ) {
3327
3328     warn "$me order: changing pkgnum ". $old_cust_pkg[0]->pkgnum.
3329          " to pkgpart ". $pkgparts->[0]. "\n"
3330       if $DEBUG;
3331
3332     my $err_or_cust_pkg =
3333       $old_cust_pkg[0]->change( 'pkgpart' => $pkgparts->[0],
3334                                 'refnum'  => $refnum,
3335                               );
3336
3337     unless (ref($err_or_cust_pkg)) {
3338       $dbh->rollback if $oldAutoCommit;
3339       return $err_or_cust_pkg;
3340     }
3341
3342     push @$return_cust_pkg, $err_or_cust_pkg;
3343     $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3344     return '';
3345
3346   }
3347
3348   # Create the new packages.
3349   foreach my $pkgpart (@$pkgparts) {
3350
3351     warn "$me order: inserting pkgpart $pkgpart\n" if $DEBUG;
3352
3353     my $cust_pkg = new FS::cust_pkg { custnum => $custnum,
3354                                       pkgpart => $pkgpart,
3355                                       refnum  => $refnum,
3356                                       %hash,
3357                                     };
3358     $error = $cust_pkg->insert( 'change' => $change );
3359     if ($error) {
3360       $dbh->rollback if $oldAutoCommit;
3361       return $error;
3362     }
3363     push @$return_cust_pkg, $cust_pkg;
3364   }
3365   # $return_cust_pkg now contains refs to all of the newly 
3366   # created packages.
3367
3368   # Transfer services and cancel old packages.
3369   foreach my $old_pkg (@old_cust_pkg) {
3370
3371     warn "$me order: transferring services from pkgnum ". $old_pkg->pkgnum. "\n"
3372       if $DEBUG;
3373
3374     foreach my $new_pkg (@$return_cust_pkg) {
3375       $error = $old_pkg->transfer($new_pkg);
3376       if ($error and $error == 0) {
3377         # $old_pkg->transfer failed.
3378         $dbh->rollback if $oldAutoCommit;
3379         return $error;
3380       }
3381     }
3382
3383     if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
3384       warn "trying transfer again with change_svcpart option\n" if $DEBUG;
3385       foreach my $new_pkg (@$return_cust_pkg) {
3386         $error = $old_pkg->transfer($new_pkg, 'change_svcpart'=>1 );
3387         if ($error and $error == 0) {
3388           # $old_pkg->transfer failed.
3389         $dbh->rollback if $oldAutoCommit;
3390         return $error;
3391         }
3392       }
3393     }
3394
3395     if ($error > 0) {
3396       # Transfers were successful, but we went through all of the 
3397       # new packages and still had services left on the old package.
3398       # We can't cancel the package under the circumstances, so abort.
3399       $dbh->rollback if $oldAutoCommit;
3400       return "Unable to transfer all services from package ".$old_pkg->pkgnum;
3401     }
3402     $error = $old_pkg->cancel( quiet=>1 );
3403     if ($error) {
3404       $dbh->rollback;
3405       return $error;
3406     }
3407   }
3408   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3409   '';
3410 }
3411
3412 =item bulk_change PKGPARTS_ARYREF, REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF ]
3413
3414 A bulk change method to change packages for multiple customers.
3415
3416 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
3417 L<FS::part_pkg>) to order for each customer.  Duplicates are of course
3418 permitted.
3419
3420 REMOVE_PKGNUMS is an list of pkgnums specifying the billing items to
3421 replace.  The services (see L<FS::cust_svc>) are moved to the
3422 new billing items.  An error is returned if this is not possible (see
3423 L<FS::pkg_svc>).
3424
3425 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
3426 newly-created cust_pkg objects.
3427
3428 =cut
3429
3430 sub bulk_change {
3431   my ($pkgparts, $remove_pkgnum, $return_cust_pkg) = @_;
3432
3433   # Transactionize this whole mess
3434   local $SIG{HUP} = 'IGNORE';
3435   local $SIG{INT} = 'IGNORE'; 
3436   local $SIG{QUIT} = 'IGNORE';
3437   local $SIG{TERM} = 'IGNORE';
3438   local $SIG{TSTP} = 'IGNORE'; 
3439   local $SIG{PIPE} = 'IGNORE'; 
3440
3441   my $oldAutoCommit = $FS::UID::AutoCommit;
3442   local $FS::UID::AutoCommit = 0;
3443   my $dbh = dbh;
3444
3445   my @errors;
3446   my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
3447                          @$remove_pkgnum;
3448
3449   while(scalar(@old_cust_pkg)) {
3450     my @return = ();
3451     my $custnum = $old_cust_pkg[0]->custnum;
3452     my (@remove) = map { $_->pkgnum }
3453                    grep { $_->custnum == $custnum } @old_cust_pkg;
3454     @old_cust_pkg = grep { $_->custnum != $custnum } @old_cust_pkg;
3455
3456     my $error = order $custnum, $pkgparts, \@remove, \@return;
3457
3458     push @errors, $error
3459       if $error;
3460     push @$return_cust_pkg, @return;
3461   }
3462
3463   if (scalar(@errors)) {
3464     $dbh->rollback if $oldAutoCommit;
3465     return join(' / ', @errors);
3466   }
3467
3468   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3469   '';
3470 }
3471
3472 # Used by FS::Upgrade to migrate to a new database.
3473 sub _upgrade_data {  # class method
3474   my ($class, %opts) = @_;
3475   $class->_upgrade_otaker(%opts);
3476   my @statements = (
3477     # RT#10139, bug resulting in contract_end being set when it shouldn't
3478   'UPDATE cust_pkg SET contract_end = NULL WHERE contract_end = -1',
3479     # RT#10830, bad calculation of prorate date near end of year
3480     # the date range for bill is December 2009, and we move it forward
3481     # one year if it's before the previous bill date (which it should 
3482     # never be)
3483   'UPDATE cust_pkg SET bill = bill + (365*24*60*60) WHERE bill < last_bill
3484   AND bill > 1259654400 AND bill < 1262332800 AND (SELECT plan FROM part_pkg 
3485   WHERE part_pkg.pkgpart = cust_pkg.pkgpart) = \'prorate\'',
3486     # RT6628, add order_date to cust_pkg
3487     'update cust_pkg set order_date = (select history_date from h_cust_pkg 
3488         where h_cust_pkg.pkgnum = cust_pkg.pkgnum and 
3489         history_action = \'insert\') where order_date is null',
3490   );
3491   foreach my $sql (@statements) {
3492     my $sth = dbh->prepare($sql);
3493     $sth->execute or die $sth->errstr;
3494   }
3495 }
3496
3497 =back
3498
3499 =head1 BUGS
3500
3501 sub order is not OO.  Perhaps it should be moved to FS::cust_main and made so?
3502
3503 In sub order, the @pkgparts array (passed by reference) is clobbered.
3504
3505 Also in sub order, no money is adjusted.  Once FS::part_pkg defines a standard
3506 method to pass dates to the recur_prog expression, it should do so.
3507
3508 FS::svc_acct, FS::svc_domain, FS::svc_www, FS::svc_ip and FS::svc_forward are
3509 loaded via 'use' at compile time, rather than via 'require' in sub { setup,
3510 suspend, unsuspend, cancel } because they use %FS::UID::callback to load
3511 configuration values.  Probably need a subroutine which decides what to do
3512 based on whether or not we've fetched the user yet, rather than a hash.  See
3513 FS::UID and the TODO.
3514
3515 Now that things are transactional should the check in the insert method be
3516 moved to check ?
3517
3518 =head1 SEE ALSO
3519
3520 L<FS::Record>, L<FS::cust_main>, L<FS::part_pkg>, L<FS::cust_svc>,
3521 L<FS::pkg_svc>, schema.html from the base documentation
3522
3523 =cut
3524
3525 1;
3526