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