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