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