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