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