"on hold" package ordering and status, RT#28508
[freeside.git] / FS / FS / cust_pkg.pm
1 package FS::cust_pkg;
2 use base qw( FS::cust_pkg::Search
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  (count)
2981
2982 =item num_avail     (quantity - count)
2983
2984 =item cust_pkg_svc (services) - array reference containing the provisioned services, as cust_svc objects
2985
2986 =back
2987
2988 Accepts one option: summarize_size.  If specified and non-zero, will omit the
2989 extra cust_pkg_svc option for objects where num_cust_svc is this size or
2990 greater.
2991
2992 =cut
2993
2994 #svcnum
2995 #label -> ($cust_svc->label)[1]
2996
2997 sub part_svc {
2998   my $self = shift;
2999   my %opt = @_;
3000
3001   my $pkg_quantity = $self->quantity || 1;
3002
3003   #XXX some sort of sort order besides numeric by svcpart...
3004   my @part_svc = sort { $a->svcpart <=> $b->svcpart } map {
3005     my $pkg_svc = $_;
3006     my $part_svc = $pkg_svc->part_svc;
3007     my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
3008     $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #more evil
3009     $part_svc->{'Hash'}{'num_avail'}    =
3010       max( 0, $pkg_quantity * $pkg_svc->quantity - $num_cust_svc );
3011     $part_svc->{'Hash'}{'cust_pkg_svc'} =
3012         $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : []
3013       unless exists($opt{summarize_size}) && $opt{summarize_size} > 0
3014           && $num_cust_svc >= $opt{summarize_size};
3015     $part_svc->{'Hash'}{'hidden'} = $pkg_svc->hidden;
3016     $part_svc;
3017   } $self->part_pkg->pkg_svc;
3018
3019   #extras
3020   push @part_svc, map {
3021     my $part_svc = $_;
3022     my $num_cust_svc = $self->num_cust_svc($part_svc->svcpart);
3023     $part_svc->{'Hash'}{'num_cust_svc'} = $num_cust_svc; #speak no evail
3024     $part_svc->{'Hash'}{'num_avail'}    = 0; #0-$num_cust_svc ?
3025     $part_svc->{'Hash'}{'cust_pkg_svc'} =
3026       $num_cust_svc ? [ $self->cust_svc($part_svc->svcpart) ] : [];
3027     $part_svc;
3028   } $self->extra_part_svc;
3029
3030   @part_svc;
3031
3032 }
3033
3034 =item extra_part_svc
3035
3036 Returns a list of FS::part_svc objects corresponding to services in this
3037 package which are still provisioned but not (any longer) available in the
3038 package definition.
3039
3040 =cut
3041
3042 sub extra_part_svc {
3043   my $self = shift;
3044
3045   my $pkgnum  = $self->pkgnum;
3046   #my $pkgpart = $self->pkgpart;
3047
3048 #  qsearch( {
3049 #    'table'     => 'part_svc',
3050 #    'hashref'   => {},
3051 #    'extra_sql' =>
3052 #      "WHERE 0 = ( SELECT COUNT(*) FROM pkg_svc 
3053 #                     WHERE pkg_svc.svcpart = part_svc.svcpart 
3054 #                       AND pkg_svc.pkgpart = ?
3055 #                       AND quantity > 0 
3056 #                 )
3057 #        AND 0 < ( SELECT COUNT(*) FROM cust_svc
3058 #                       LEFT JOIN cust_pkg USING ( pkgnum )
3059 #                     WHERE cust_svc.svcpart = part_svc.svcpart
3060 #                       AND pkgnum = ?
3061 #                 )",
3062 #    'extra_param' => [ [$self->pkgpart=>'int'], [$self->pkgnum=>'int'] ],
3063 #  } );
3064
3065 #seems to benchmark slightly faster... (or did?)
3066
3067   my @pkgparts = map $_->pkgpart, $self->part_pkg->self_and_svc_linked;
3068   my $pkgparts = join(',', @pkgparts);
3069
3070   qsearch( {
3071     #'select'      => 'DISTINCT ON (svcpart) part_svc.*',
3072     #MySQL doesn't grok DISINCT ON
3073     'select'      => 'DISTINCT part_svc.*',
3074     'table'       => 'part_svc',
3075     'addl_from'   =>
3076       "LEFT JOIN pkg_svc  ON (     pkg_svc.svcpart   = part_svc.svcpart 
3077                                AND pkg_svc.pkgpart IN ($pkgparts)
3078                                AND quantity > 0
3079                              )
3080        LEFT JOIN cust_svc ON (     cust_svc.svcpart = part_svc.svcpart )
3081        LEFT JOIN cust_pkg USING ( pkgnum )
3082       ",
3083     'hashref'     => {},
3084     'extra_sql'   => "WHERE pkgsvcnum IS NULL AND cust_pkg.pkgnum = ? ",
3085     'extra_param' => [ [$self->pkgnum=>'int'] ],
3086   } );
3087 }
3088
3089 =item status
3090
3091 Returns a short status string for this package, currently:
3092
3093 =over 4
3094
3095 =item on hold
3096
3097 =item not yet billed
3098
3099 =item one-time charge
3100
3101 =item active
3102
3103 =item suspended
3104
3105 =item cancelled
3106
3107 =back
3108
3109 =cut
3110
3111 sub status {
3112   my $self = shift;
3113
3114   my $freq = length($self->freq) ? $self->freq : $self->part_pkg->freq;
3115
3116   return 'cancelled' if $self->get('cancel');
3117   return 'on hold' if $self->susp && ! $self->setup;
3118   return 'suspended' if $self->susp;
3119   return 'not yet billed' unless $self->setup;
3120   return 'one-time charge' if $freq =~ /^(0|$)/;
3121   return 'active';
3122 }
3123
3124 =item ucfirst_status
3125
3126 Returns the status with the first character capitalized.
3127
3128 =cut
3129
3130 sub ucfirst_status {
3131   ucfirst(shift->status);
3132 }
3133
3134 =item statuses
3135
3136 Class method that returns the list of possible status strings for packages
3137 (see L<the status method|/status>).  For example:
3138
3139   @statuses = FS::cust_pkg->statuses();
3140
3141 =cut
3142
3143 tie my %statuscolor, 'Tie::IxHash', 
3144   'on hold'         => '7E0079', #purple!
3145   'not yet billed'  => '009999', #teal? cyan?
3146   'one-time charge' => '000000',
3147   'active'          => '00CC00',
3148   'suspended'       => 'FF9900',
3149   'cancelled'       => 'FF0000',
3150 ;
3151
3152 sub statuses {
3153   my $self = shift; #could be class...
3154   #grep { $_ !~ /^(not yet billed)$/ } #this is a dumb status anyway
3155   #                                    # mayble split btw one-time vs. recur
3156     keys %statuscolor;
3157 }
3158
3159 =item statuscolor
3160
3161 Returns a hex triplet color string for this package's status.
3162
3163 =cut
3164
3165 sub statuscolor {
3166   my $self = shift;
3167   $statuscolor{$self->status};
3168 }
3169
3170 =item pkg_label
3171
3172 Returns a label for this package.  (Currently "pkgnum: pkg - comment" or
3173 "pkg - comment" depending on user preference).
3174
3175 =cut
3176
3177 sub pkg_label {
3178   my $self = shift;
3179   my $label = $self->part_pkg->pkg_comment( cust_pkg=>$self, nopkgpart=>1 );
3180   $label = $self->pkgnum. ": $label"
3181     if $FS::CurrentUser::CurrentUser->option('show_pkgnum');
3182   $label;
3183 }
3184
3185 =item pkg_label_long
3186
3187 Returns a long label for this package, adding the primary service's label to
3188 pkg_label.
3189
3190 =cut
3191
3192 sub pkg_label_long {
3193   my $self = shift;
3194   my $label = $self->pkg_label;
3195   my $cust_svc = $self->primary_cust_svc;
3196   $label .= ' ('. ($cust_svc->label)[1]. ')' if $cust_svc;
3197   $label;
3198 }
3199
3200 =item pkg_locale
3201
3202 Returns a customer-localized label for this package.
3203
3204 =cut
3205
3206 sub pkg_locale {
3207   my $self = shift;
3208   $self->part_pkg->pkg_locale( $self->cust_main->locale );
3209 }
3210
3211 =item primary_cust_svc
3212
3213 Returns a primary service (as FS::cust_svc object) if one can be identified.
3214
3215 =cut
3216
3217 #for labeling purposes - might not 100% match up with part_pkg->svcpart's idea
3218
3219 sub primary_cust_svc {
3220   my $self = shift;
3221
3222   my @cust_svc = $self->cust_svc;
3223
3224   return '' unless @cust_svc; #no serivces - irrelevant then
3225   
3226   return $cust_svc[0] if scalar(@cust_svc) == 1; #always return a single service
3227
3228   # primary service as specified in the package definition
3229   # or exactly one service definition with quantity one
3230   my $svcpart = $self->part_pkg->svcpart;
3231   @cust_svc = grep { $_->svcpart == $svcpart } @cust_svc;
3232   return $cust_svc[0] if scalar(@cust_svc) == 1;
3233
3234   #couldn't identify one thing..
3235   return '';
3236 }
3237
3238 =item labels
3239
3240 Returns a list of lists, calling the label method for all services
3241 (see L<FS::cust_svc>) of this billing item.
3242
3243 =cut
3244
3245 sub labels {
3246   my $self = shift;
3247   map { [ $_->label ] } $self->cust_svc;
3248 }
3249
3250 =item h_labels END_TIMESTAMP [ START_TIMESTAMP ] [ MODE ]
3251
3252 Like the labels method, but returns historical information on services that
3253 were active as of END_TIMESTAMP and (optionally) not cancelled before
3254 START_TIMESTAMP.  If MODE is 'I' (for 'invoice'), services with the 
3255 I<pkg_svc.hidden> flag will be omitted.
3256
3257 Returns a list of lists, calling the label method for all (historical) services
3258 (see L<FS::h_cust_svc>) of this billing item.
3259
3260 =cut
3261
3262 sub h_labels {
3263   my $self = shift;
3264   warn "$me _h_labels called on $self\n"
3265     if $DEBUG;
3266   map { [ $_->label(@_) ] } $self->h_cust_svc(@_);
3267 }
3268
3269 =item labels_short
3270
3271 Like labels, except returns a simple flat list, and shortens long
3272 (currently >5 or the cust_bill-max_same_services configuration value) lists of
3273 identical services to one line that lists the service label and the number of
3274 individual services rather than individual items.
3275
3276 =cut
3277
3278 sub labels_short {
3279   shift->_labels_short( 'labels', @_ );
3280 }
3281
3282 =item h_labels_short END_TIMESTAMP [ START_TIMESTAMP ]
3283
3284 Like h_labels, except returns a simple flat list, and shortens long
3285 (currently >5 or the cust_bill-max_same_services configuration value) lists of
3286 identical services to one line that lists the service label and the number of
3287 individual services rather than individual items.
3288
3289 =cut
3290
3291 sub h_labels_short {
3292   shift->_labels_short( 'h_labels', @_ );
3293 }
3294
3295 sub _labels_short {
3296   my( $self, $method ) = ( shift, shift );
3297
3298   warn "$me _labels_short called on $self with $method method\n"
3299     if $DEBUG;
3300
3301   my $conf = new FS::Conf;
3302   my $max_same_services = $conf->config('cust_bill-max_same_services') || 5;
3303
3304   warn "$me _labels_short populating \%labels\n"
3305     if $DEBUG;
3306
3307   my %labels;
3308   #tie %labels, 'Tie::IxHash';
3309   push @{ $labels{$_->[0]} }, $_->[1]
3310     foreach $self->$method(@_);
3311
3312   warn "$me _labels_short populating \@labels\n"
3313     if $DEBUG;
3314
3315   my @labels;
3316   foreach my $label ( keys %labels ) {
3317     my %seen = ();
3318     my @values = grep { ! $seen{$_}++ } @{ $labels{$label} };
3319     my $num = scalar(@values);
3320     warn "$me _labels_short $num items for $label\n"
3321       if $DEBUG;
3322
3323     if ( $num > $max_same_services ) {
3324       warn "$me _labels_short   more than $max_same_services, so summarizing\n"
3325         if $DEBUG;
3326       push @labels, "$label ($num)";
3327     } else {
3328       if ( $conf->exists('cust_bill-consolidate_services') ) {
3329         warn "$me _labels_short   consolidating services\n"
3330           if $DEBUG;
3331         # push @labels, "$label: ". join(', ', @values);
3332         while ( @values ) {
3333           my $detail = "$label: ";
3334           $detail .= shift(@values). ', '
3335             while @values
3336                && ( length($detail.$values[0]) < 78 || $detail eq "$label: " );
3337           $detail =~ s/, $//;
3338           push @labels, $detail;
3339         }
3340         warn "$me _labels_short   done consolidating services\n"
3341           if $DEBUG;
3342       } else {
3343         warn "$me _labels_short   adding service data\n"
3344           if $DEBUG;
3345         push @labels, map { "$label: $_" } @values;
3346       }
3347     }
3348   }
3349
3350  @labels;
3351
3352 }
3353
3354 =item cust_main
3355
3356 Returns the parent customer object (see L<FS::cust_main>).
3357
3358 =item balance
3359
3360 Returns the balance for this specific package, when using
3361 experimental package balance.
3362
3363 =cut
3364
3365 sub balance {
3366   my $self = shift;
3367   $self->cust_main->balance_pkgnum( $self->pkgnum );
3368 }
3369
3370 #these subs are in location_Mixin.pm now... unfortunately the POD doesn't mixin
3371
3372 =item cust_location
3373
3374 Returns the location object, if any (see L<FS::cust_location>).
3375
3376 =item cust_location_or_main
3377
3378 If this package is associated with a location, returns the locaiton (see
3379 L<FS::cust_location>), otherwise returns the customer (see L<FS::cust_main>).
3380
3381 =item location_label [ OPTION => VALUE ... ]
3382
3383 Returns the label of the location object (see L<FS::cust_location>).
3384
3385 =cut
3386
3387 #end of subs in location_Mixin.pm now... unfortunately the POD doesn't mixin
3388
3389 =item tax_locationnum
3390
3391 Returns the foreign key to a L<FS::cust_location> object for calculating  
3392 tax on this package, as determined by the C<tax-pkg_address> and 
3393 C<tax-ship_address> configuration flags.
3394
3395 =cut
3396
3397 sub tax_locationnum {
3398   my $self = shift;
3399   my $conf = FS::Conf->new;
3400   if ( $conf->exists('tax-pkg_address') ) {
3401     return $self->locationnum;
3402   }
3403   elsif ( $conf->exists('tax-ship_address') ) {
3404     return $self->cust_main->ship_locationnum;
3405   }
3406   else {
3407     return $self->cust_main->bill_locationnum;
3408   }
3409 }
3410
3411 =item tax_location
3412
3413 Returns the L<FS::cust_location> object for tax_locationnum.
3414
3415 =cut
3416
3417 sub tax_location {
3418   my $self = shift;
3419   FS::cust_location->by_key( $self->tax_locationnum )
3420 }
3421
3422 =item seconds_since TIMESTAMP
3423
3424 Returns the number of seconds all accounts (see L<FS::svc_acct>) in this
3425 package have been online since TIMESTAMP, according to the session monitor.
3426
3427 TIMESTAMP is specified as a UNIX timestamp; see L<perlfunc/"time">.  Also see
3428 L<Time::Local> and L<Date::Parse> for conversion functions.
3429
3430 =cut
3431
3432 sub seconds_since {
3433   my($self, $since) = @_;
3434   my $seconds = 0;
3435
3436   foreach my $cust_svc (
3437     grep { $_->part_svc->svcdb eq 'svc_acct' } $self->cust_svc
3438   ) {
3439     $seconds += $cust_svc->seconds_since($since);
3440   }
3441
3442   $seconds;
3443
3444 }
3445
3446 =item seconds_since_sqlradacct TIMESTAMP_START TIMESTAMP_END
3447
3448 Returns the numbers of seconds all accounts (see L<FS::svc_acct>) in this
3449 package have been online between TIMESTAMP_START (inclusive) and TIMESTAMP_END
3450 (exclusive).
3451
3452 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
3453 L<perlfunc/"time">.  Also see L<Time::Local> and L<Date::Parse> for conversion
3454 functions.
3455
3456
3457 =cut
3458
3459 sub seconds_since_sqlradacct {
3460   my($self, $start, $end) = @_;
3461
3462   my $seconds = 0;
3463
3464   foreach my $cust_svc (
3465     grep {
3466       my $part_svc = $_->part_svc;
3467       $part_svc->svcdb eq 'svc_acct'
3468         && scalar($part_svc->part_export_usage);
3469     } $self->cust_svc
3470   ) {
3471     $seconds += $cust_svc->seconds_since_sqlradacct($start, $end);
3472   }
3473
3474   $seconds;
3475
3476 }
3477
3478 =item attribute_since_sqlradacct TIMESTAMP_START TIMESTAMP_END ATTRIBUTE
3479
3480 Returns the sum of the given attribute for all accounts (see L<FS::svc_acct>)
3481 in this package for sessions ending between TIMESTAMP_START (inclusive) and
3482 TIMESTAMP_END
3483 (exclusive).
3484
3485 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
3486 L<perlfunc/"time">.  Also see L<Time::Local> and L<Date::Parse> for conversion
3487 functions.
3488
3489 =cut
3490
3491 sub attribute_since_sqlradacct {
3492   my($self, $start, $end, $attrib) = @_;
3493
3494   my $sum = 0;
3495
3496   foreach my $cust_svc (
3497     grep {
3498       my $part_svc = $_->part_svc;
3499       scalar($part_svc->part_export_usage);
3500     } $self->cust_svc
3501   ) {
3502     $sum += $cust_svc->attribute_since_sqlradacct($start, $end, $attrib);
3503   }
3504
3505   $sum;
3506
3507 }
3508
3509 =item quantity
3510
3511 =cut
3512
3513 sub quantity {
3514   my( $self, $value ) = @_;
3515   if ( defined($value) ) {
3516     $self->setfield('quantity', $value);
3517   }
3518   $self->getfield('quantity') || 1;
3519 }
3520
3521 =item transfer DEST_PKGNUM | DEST_CUST_PKG, [ OPTION => VALUE ... ]
3522
3523 Transfers as many services as possible from this package to another package.
3524
3525 The destination package can be specified by pkgnum by passing an FS::cust_pkg
3526 object.  The destination package must already exist.
3527
3528 Services are moved only if the destination allows services with the correct
3529 I<svcpart> (not svcdb), unless the B<change_svcpart> option is set true.  Use
3530 this option with caution!  No provision is made for export differences
3531 between the old and new service definitions.  Probably only should be used
3532 when your exports for all service definitions of a given svcdb are identical.
3533 (attempt a transfer without it first, to move all possible svcpart-matching
3534 services)
3535
3536 Any services that can't be moved remain in the original package.
3537
3538 Returns an error, if there is one; otherwise, returns the number of services 
3539 that couldn't be moved.
3540
3541 =cut
3542
3543 sub transfer {
3544   my ($self, $dest_pkgnum, %opt) = @_;
3545
3546   my $remaining = 0;
3547   my $dest;
3548   my %target;
3549
3550   if (ref ($dest_pkgnum) eq 'FS::cust_pkg') {
3551     $dest = $dest_pkgnum;
3552     $dest_pkgnum = $dest->pkgnum;
3553   } else {
3554     $dest = qsearchs('cust_pkg', { pkgnum => $dest_pkgnum });
3555   }
3556
3557   return ('Package does not exist: '.$dest_pkgnum) unless $dest;
3558
3559   foreach my $pkg_svc ( $dest->part_pkg->pkg_svc ) {
3560     $target{$pkg_svc->svcpart} = $pkg_svc->quantity;
3561   }
3562
3563   foreach my $cust_svc ($dest->cust_svc) {
3564     $target{$cust_svc->svcpart}--;
3565   }
3566
3567   my %svcpart2svcparts = ();
3568   if ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
3569     warn "change_svcpart option received, creating alternates list\n" if $DEBUG;
3570     foreach my $svcpart ( map { $_->svcpart } $self->cust_svc ) {
3571       next if exists $svcpart2svcparts{$svcpart};
3572       my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
3573       $svcpart2svcparts{$svcpart} = [
3574         map  { $_->[0] }
3575         sort { $b->[1] cmp $a->[1]  or  $a->[2] <=> $b->[2] } 
3576         map {
3577               my $pkg_svc = qsearchs( 'pkg_svc', { 'pkgpart' => $dest->pkgpart,
3578                                                    'svcpart' => $_          } );
3579               [ $_,
3580                 $pkg_svc ? $pkg_svc->primary_svc : '',
3581                 $pkg_svc ? $pkg_svc->quantity : 0,
3582               ];
3583             }
3584
3585         grep { $_ != $svcpart }
3586         map  { $_->svcpart }
3587         qsearch('part_svc', { 'svcdb' => $part_svc->svcdb } )
3588       ];
3589       warn "alternates for svcpart $svcpart: ".
3590            join(', ', @{$svcpart2svcparts{$svcpart}}). "\n"
3591         if $DEBUG;
3592     }
3593   }
3594
3595   my $error;
3596   foreach my $cust_svc ($self->cust_svc) {
3597     my $svcnum = $cust_svc->svcnum;
3598     if($target{$cust_svc->svcpart} > 0
3599        or $FS::cust_svc::ignore_quantity) { # maybe should be a 'force' option
3600       $target{$cust_svc->svcpart}--;
3601       my $new = new FS::cust_svc { $cust_svc->hash };
3602       $new->pkgnum($dest_pkgnum);
3603       $error = $new->replace($cust_svc);
3604     } elsif ( exists $opt{'change_svcpart'} && $opt{'change_svcpart'} ) {
3605       if ( $DEBUG ) {
3606         warn "looking for alternates for svcpart ". $cust_svc->svcpart. "\n";
3607         warn "alternates to consider: ".
3608              join(', ', @{$svcpart2svcparts{$cust_svc->svcpart}}). "\n";
3609       }
3610       my @alternate = grep {
3611                              warn "considering alternate svcpart $_: ".
3612                                   "$target{$_} available in new package\n"
3613                                if $DEBUG;
3614                              $target{$_} > 0;
3615                            } @{$svcpart2svcparts{$cust_svc->svcpart}};
3616       if ( @alternate ) {
3617         warn "alternate(s) found\n" if $DEBUG;
3618         my $change_svcpart = $alternate[0];
3619         $target{$change_svcpart}--;
3620         my $new = new FS::cust_svc { $cust_svc->hash };
3621         $new->svcpart($change_svcpart);
3622         $new->pkgnum($dest_pkgnum);
3623         $error = $new->replace($cust_svc);
3624       } else {
3625         $remaining++;
3626       }
3627     } else {
3628       $remaining++
3629     }
3630     if ( $error ) {
3631       my @label = $cust_svc->label;
3632       return "$label[0] $label[1]: $error";
3633     }
3634   }
3635   return $remaining;
3636 }
3637
3638 =item grab_svcnums SVCNUM, SVCNUM ...
3639
3640 Change the pkgnum for the provided services to this packages.  If there is an
3641 error, returns the error, otherwise returns false.
3642
3643 =cut
3644
3645 sub grab_svcnums {
3646   my $self = shift;
3647   my @svcnum = @_;
3648
3649   my $oldAutoCommit = $FS::UID::AutoCommit;
3650   local $FS::UID::AutoCommit = 0;
3651   my $dbh = dbh;
3652
3653   foreach my $svcnum (@svcnum) {
3654     my $cust_svc = qsearchs('cust_svc', { svcnum=>$svcnum } ) or do {
3655       $dbh->rollback if $oldAutoCommit;
3656       return "unknown svcnum $svcnum";
3657     };
3658     $cust_svc->pkgnum( $self->pkgnum );
3659     my $error = $cust_svc->replace;
3660     if ( $error ) {
3661       $dbh->rollback if $oldAutoCommit;
3662       return $error;
3663     }
3664   }
3665
3666   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3667   '';
3668
3669 }
3670
3671 =item reexport
3672
3673 This method is deprecated.  See the I<depend_jobnum> option to the insert and
3674 order_pkgs methods in FS::cust_main for a better way to defer provisioning.
3675
3676 =cut
3677
3678 #looks like this is still used by the order_pkg and change_pkg methods in
3679 # ClientAPI/MyAccount, need to look into those before removing
3680 sub reexport {
3681   my $self = shift;
3682
3683   my $oldAutoCommit = $FS::UID::AutoCommit;
3684   local $FS::UID::AutoCommit = 0;
3685   my $dbh = dbh;
3686
3687   foreach my $cust_svc ( $self->cust_svc ) {
3688     #false laziness w/svc_Common::insert
3689     my $svc_x = $cust_svc->svc_x;
3690     foreach my $part_export ( $cust_svc->part_svc->part_export ) {
3691       my $error = $part_export->export_insert($svc_x);
3692       if ( $error ) {
3693         $dbh->rollback if $oldAutoCommit;
3694         return $error;
3695       }
3696     }
3697   }
3698
3699   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3700   '';
3701
3702 }
3703
3704 =item export_pkg_change OLD_CUST_PKG
3705
3706 Calls the "pkg_change" export action for all services attached to this package.
3707
3708 =cut
3709
3710 sub export_pkg_change {
3711   my( $self, $old )  = ( shift, shift );
3712
3713   my $oldAutoCommit = $FS::UID::AutoCommit;
3714   local $FS::UID::AutoCommit = 0;
3715   my $dbh = dbh;
3716
3717   foreach my $svc_x ( map $_->svc_x, $self->cust_svc ) {
3718     my $error = $svc_x->export('pkg_change', $self, $old);
3719     if ( $error ) {
3720       $dbh->rollback if $oldAutoCommit;
3721       return $error;
3722     }
3723   }
3724
3725   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3726   '';
3727
3728 }
3729
3730 =item insert_reason
3731
3732 Associates this package with a (suspension or cancellation) reason (see
3733 L<FS::cust_pkg_reason>, possibly inserting a new reason on the fly (see
3734 L<FS::reason>).
3735
3736 Available options are:
3737
3738 =over 4
3739
3740 =item reason
3741
3742 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.
3743
3744 =item reason_otaker
3745
3746 the access_user (see L<FS::access_user>) providing the reason
3747
3748 =item date
3749
3750 a unix timestamp 
3751
3752 =item action
3753
3754 the action (cancel, susp, adjourn, expire) associated with the reason
3755
3756 =back
3757
3758 If there is an error, returns the error, otherwise returns false.
3759
3760 =cut
3761
3762 sub insert_reason {
3763   my ($self, %options) = @_;
3764
3765   my $otaker = $options{reason_otaker} ||
3766                $FS::CurrentUser::CurrentUser->username;
3767
3768   my $reasonnum;
3769   if ( $options{'reason'} =~ /^(\d+)$/ ) {
3770
3771     $reasonnum = $1;
3772
3773   } elsif ( ref($options{'reason'}) ) {
3774   
3775     return 'Enter a new reason (or select an existing one)'
3776       unless $options{'reason'}->{'reason'} !~ /^\s*$/;
3777
3778     my $reason = new FS::reason({
3779       'reason_type' => $options{'reason'}->{'typenum'},
3780       'reason'      => $options{'reason'}->{'reason'},
3781     });
3782     my $error = $reason->insert;
3783     return $error if $error;
3784
3785     $reasonnum = $reason->reasonnum;
3786
3787   } else {
3788     return "Unparsable reason: ". $options{'reason'};
3789   }
3790
3791   my $cust_pkg_reason =
3792     new FS::cust_pkg_reason({ 'pkgnum'    => $self->pkgnum,
3793                               'reasonnum' => $reasonnum, 
3794                               'otaker'    => $otaker,
3795                               'action'    => substr(uc($options{'action'}),0,1),
3796                               'date'      => $options{'date'}
3797                                                ? $options{'date'}
3798                                                : time,
3799                             });
3800
3801   $cust_pkg_reason->insert;
3802 }
3803
3804 =item insert_discount
3805
3806 Associates this package with a discount (see L<FS::cust_pkg_discount>, possibly
3807 inserting a new discount on the fly (see L<FS::discount>).
3808
3809 Available options are:
3810
3811 =over 4
3812
3813 =item discountnum
3814
3815 =back
3816
3817 If there is an error, returns the error, otherwise returns false.
3818
3819 =cut
3820
3821 sub insert_discount {
3822   #my ($self, %options) = @_;
3823   my $self = shift;
3824
3825   my $cust_pkg_discount = new FS::cust_pkg_discount {
3826     'pkgnum'      => $self->pkgnum,
3827     'discountnum' => $self->discountnum,
3828     'months_used' => 0,
3829     'end_date'    => '', #XXX
3830     #for the create a new discount case
3831     '_type'       => $self->discountnum__type,
3832     'amount'      => $self->discountnum_amount,
3833     'percent'     => $self->discountnum_percent,
3834     'months'      => $self->discountnum_months,
3835     'setup'      => $self->discountnum_setup,
3836     #'disabled'    => $self->discountnum_disabled,
3837   };
3838
3839   $cust_pkg_discount->insert;
3840 }
3841
3842 =item set_usage USAGE_VALUE_HASHREF 
3843
3844 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
3845 to which they should be set (see L<FS::svc_acct>).  Currently seconds,
3846 upbytes, downbytes, and totalbytes are appropriate keys.
3847
3848 All svc_accts which are part of this package have their values reset.
3849
3850 =cut
3851
3852 sub set_usage {
3853   my ($self, $valueref, %opt) = @_;
3854
3855   #only svc_acct can set_usage for now
3856   foreach my $cust_svc ( $self->cust_svc( 'svcdb'=>'svc_acct' ) ) {
3857     my $svc_x = $cust_svc->svc_x;
3858     $svc_x->set_usage($valueref, %opt)
3859       if $svc_x->can("set_usage");
3860   }
3861 }
3862
3863 =item recharge USAGE_VALUE_HASHREF 
3864
3865 USAGE_VALUE_HASHREF is a hashref of svc_acct usage columns and the amounts
3866 to which they should be set (see L<FS::svc_acct>).  Currently seconds,
3867 upbytes, downbytes, and totalbytes are appropriate keys.
3868
3869 All svc_accts which are part of this package have their values incremented.
3870
3871 =cut
3872
3873 sub recharge {
3874   my ($self, $valueref) = @_;
3875
3876   #only svc_acct can set_usage for now
3877   foreach my $cust_svc ( $self->cust_svc( 'svcdb'=>'svc_acct' ) ) {
3878     my $svc_x = $cust_svc->svc_x;
3879     $svc_x->recharge($valueref)
3880       if $svc_x->can("recharge");
3881   }
3882 }
3883
3884 =item apply_usageprice 
3885
3886 =cut
3887
3888 sub apply_usageprice {
3889   my $self = shift;
3890
3891   my $oldAutoCommit = $FS::UID::AutoCommit;
3892   local $FS::UID::AutoCommit = 0;
3893   my $dbh = dbh;
3894
3895   my $error = '';
3896
3897   foreach my $cust_pkg_usageprice ( $self->cust_pkg_usageprice ) {
3898     $error ||= $cust_pkg_usageprice->apply;
3899   }
3900
3901   if ( $error ) {
3902     $dbh->rollback if $oldAutoCommit;
3903     die "error applying part_pkg_usageprice add-ons, pkgnum ". $self->pkgnum.
3904         ": $error\n";
3905   } else {
3906     $dbh->commit if $oldAutoCommit;
3907   }
3908
3909
3910 }
3911
3912 =item cust_pkg_discount
3913
3914 =item cust_pkg_discount_active
3915
3916 =cut
3917
3918 sub cust_pkg_discount_active {
3919   my $self = shift;
3920   grep { $_->status eq 'active' } $self->cust_pkg_discount;
3921 }
3922
3923 =item cust_pkg_usage
3924
3925 Returns a list of all voice usage counters attached to this package.
3926
3927 =item apply_usage OPTIONS
3928
3929 Takes the following options:
3930 - cdr: a call detail record (L<FS::cdr>)
3931 - rate_detail: the rate determined for this call (L<FS::rate_detail>)
3932 - minutes: the maximum number of minutes to be charged
3933
3934 Finds available usage minutes for a call of this class, and subtracts
3935 up to that many minutes from the usage pool.  If the usage pool is empty,
3936 and the C<cdr-minutes_priority> global config option is set, minutes may
3937 be taken from other calls as well.  Either way, an allocation record will
3938 be created (L<FS::cdr_cust_pkg_usage>) and this method will return the 
3939 number of minutes of usage applied to the call.
3940
3941 =cut
3942
3943 sub apply_usage {
3944   my ($self, %opt) = @_;
3945   my $cdr = $opt{cdr};
3946   my $rate_detail = $opt{rate_detail};
3947   my $minutes = $opt{minutes};
3948   my $classnum = $rate_detail->classnum;
3949   my $pkgnum = $self->pkgnum;
3950   my $custnum = $self->custnum;
3951
3952   my $oldAutoCommit = $FS::UID::AutoCommit;
3953   local $FS::UID::AutoCommit = 0;
3954   my $dbh = dbh;
3955
3956   my $order = FS::Conf->new->config('cdr-minutes_priority');
3957
3958   my $is_classnum;
3959   if ( $classnum ) {
3960     $is_classnum = ' part_pkg_usage_class.classnum = '.$classnum;
3961   } else {
3962     $is_classnum = ' part_pkg_usage_class.classnum IS NULL';
3963   }
3964   my @usage_recs = qsearch({
3965       'table'     => 'cust_pkg_usage',
3966       'addl_from' => ' JOIN part_pkg_usage       USING (pkgusagepart)'.
3967                      ' JOIN cust_pkg             USING (pkgnum)'.
3968                      ' JOIN part_pkg_usage_class USING (pkgusagepart)',
3969       'select'    => 'cust_pkg_usage.*',
3970       'extra_sql' => " WHERE ( cust_pkg.pkgnum = $pkgnum OR ".
3971                      " ( cust_pkg.custnum = $custnum AND ".
3972                      " part_pkg_usage.shared IS NOT NULL ) ) AND ".
3973                      $is_classnum . ' AND '.
3974                      " cust_pkg_usage.minutes > 0",
3975       'order_by'  => " ORDER BY priority ASC",
3976   });
3977
3978   my $orig_minutes = $minutes;
3979   my $error;
3980   while (!$error and $minutes > 0 and @usage_recs) {
3981     my $cust_pkg_usage = shift @usage_recs;
3982     $cust_pkg_usage->select_for_update;
3983     my $cdr_cust_pkg_usage = FS::cdr_cust_pkg_usage->new({
3984         pkgusagenum => $cust_pkg_usage->pkgusagenum,
3985         acctid      => $cdr->acctid,
3986         minutes     => min($cust_pkg_usage->minutes, $minutes),
3987     });
3988     $cust_pkg_usage->set('minutes',
3989       sprintf('%.0f', $cust_pkg_usage->minutes - $cdr_cust_pkg_usage->minutes)
3990     );
3991     $error = $cust_pkg_usage->replace || $cdr_cust_pkg_usage->insert;
3992     $minutes -= $cdr_cust_pkg_usage->minutes;
3993   }
3994   if ( $order and $minutes > 0 and !$error ) {
3995     # then try to steal minutes from another call
3996     my %search = (
3997         'table'     => 'cdr_cust_pkg_usage',
3998         'addl_from' => ' JOIN cust_pkg_usage        USING (pkgusagenum)'.
3999                        ' JOIN part_pkg_usage        USING (pkgusagepart)'.
4000                        ' JOIN cust_pkg              USING (pkgnum)'.
4001                        ' JOIN part_pkg_usage_class  USING (pkgusagepart)'.
4002                        ' JOIN cdr                   USING (acctid)',
4003         'select'    => 'cdr_cust_pkg_usage.*',
4004         'extra_sql' => " WHERE cdr.freesidestatus = 'rated' AND ".
4005                        " ( cust_pkg.pkgnum = $pkgnum OR ".
4006                        " ( cust_pkg.custnum = $custnum AND ".
4007                        " part_pkg_usage.shared IS NOT NULL ) ) AND ".
4008                        " part_pkg_usage_class.classnum = $classnum",
4009         'order_by'  => ' ORDER BY part_pkg_usage.priority ASC',
4010     );
4011     if ( $order eq 'time' ) {
4012       # find CDRs that are using minutes, but have a later startdate
4013       # than this call
4014       my $startdate = $cdr->startdate;
4015       if ($startdate !~ /^\d+$/) {
4016         die "bad cdr startdate '$startdate'";
4017       }
4018       $search{'extra_sql'} .= " AND cdr.startdate > $startdate";
4019       # minimize needless reshuffling
4020       $search{'order_by'} .= ', cdr.startdate DESC';
4021     } else {
4022       # XXX may not work correctly with rate_time schedules.  Could 
4023       # fix this by storing ratedetailnum in cdr_cust_pkg_usage, I 
4024       # think...
4025       $search{'addl_from'} .=
4026         ' JOIN rate_detail'.
4027         ' ON (cdr.rated_ratedetailnum = rate_detail.ratedetailnum)';
4028       if ( $order eq 'rate_high' ) {
4029         $search{'extra_sql'} .= ' AND rate_detail.min_charge < '.
4030                                 $rate_detail->min_charge;
4031         $search{'order_by'} .= ', rate_detail.min_charge ASC';
4032       } elsif ( $order eq 'rate_low' ) {
4033         $search{'extra_sql'} .= ' AND rate_detail.min_charge > '.
4034                                 $rate_detail->min_charge;
4035         $search{'order_by'} .= ', rate_detail.min_charge DESC';
4036       } else {
4037         #  this should really never happen
4038         die "invalid cdr-minutes_priority value '$order'\n";
4039       }
4040     }
4041     my @cdr_usage_recs = qsearch(\%search);
4042     my %reproc_cdrs;
4043     while (!$error and @cdr_usage_recs and $minutes > 0) {
4044       my $cdr_cust_pkg_usage = shift @cdr_usage_recs;
4045       my $cust_pkg_usage = $cdr_cust_pkg_usage->cust_pkg_usage;
4046       my $old_cdr = $cdr_cust_pkg_usage->cdr;
4047       $reproc_cdrs{$old_cdr->acctid} = $old_cdr;
4048       $cdr_cust_pkg_usage->select_for_update;
4049       $old_cdr->select_for_update;
4050       $cust_pkg_usage->select_for_update;
4051       # in case someone else stole the usage from this CDR
4052       # while waiting for the lock...
4053       next if $old_cdr->acctid != $cdr_cust_pkg_usage->acctid;
4054       # steal the usage allocation and flag the old CDR for reprocessing
4055       $cdr_cust_pkg_usage->set('acctid', $cdr->acctid);
4056       # if the allocation is more minutes than we need, adjust it...
4057       my $delta = $cdr_cust_pkg_usage->minutes - $minutes;
4058       if ( $delta > 0 ) {
4059         $cdr_cust_pkg_usage->set('minutes', $minutes);
4060         $cust_pkg_usage->set('minutes', $cust_pkg_usage->minutes + $delta);
4061         $error = $cust_pkg_usage->replace;
4062       }
4063       #warn 'CDR '.$cdr->acctid . ' stealing allocation '.$cdr_cust_pkg_usage->cdrusagenum.' from CDR '.$old_cdr->acctid."\n";
4064       $error ||= $cdr_cust_pkg_usage->replace;
4065       # deduct the stolen minutes
4066       $minutes -= $cdr_cust_pkg_usage->minutes;
4067     }
4068     # after all minute-stealing is done, reset the affected CDRs
4069     foreach (values %reproc_cdrs) {
4070       $error ||= $_->set_status('');
4071       # XXX or should we just call $cdr->rate right here?
4072       # it's not like we can create a loop this way, since the min_charge
4073       # or call time has to go monotonically in one direction.
4074       # we COULD get some very deep recursions going, though...
4075     }
4076   } # if $order and $minutes
4077   if ( $error ) {
4078     $dbh->rollback;
4079     die "error applying included minutes\npkgnum ".$self->pkgnum.", class $classnum, acctid ".$cdr->acctid."\n$error\n"
4080   } else {
4081     $dbh->commit if $oldAutoCommit;
4082     return $orig_minutes - $minutes;
4083   }
4084 }
4085
4086 =item supplemental_pkgs
4087
4088 Returns a list of all packages supplemental to this one.
4089
4090 =cut
4091
4092 sub supplemental_pkgs {
4093   my $self = shift;
4094   qsearch('cust_pkg', { 'main_pkgnum' => $self->pkgnum });
4095 }
4096
4097 =item main_pkg
4098
4099 Returns the package that this one is supplemental to, if any.
4100
4101 =cut
4102
4103 sub main_pkg {
4104   my $self = shift;
4105   if ( $self->main_pkgnum ) {
4106     return FS::cust_pkg->by_key($self->main_pkgnum);
4107   }
4108   return;
4109 }
4110
4111 =back
4112
4113 =head1 CLASS METHODS
4114
4115 =over 4
4116
4117 =item recurring_sql
4118
4119 Returns an SQL expression identifying recurring packages.
4120
4121 =cut
4122
4123 sub recurring_sql { "
4124   '0' != ( select freq from part_pkg
4125              where cust_pkg.pkgpart = part_pkg.pkgpart )
4126 "; }
4127
4128 =item onetime_sql
4129
4130 Returns an SQL expression identifying one-time packages.
4131
4132 =cut
4133
4134 sub onetime_sql { "
4135   '0' = ( select freq from part_pkg
4136             where cust_pkg.pkgpart = part_pkg.pkgpart )
4137 "; }
4138
4139 =item ordered_sql
4140
4141 Returns an SQL expression identifying ordered packages (recurring packages not
4142 yet billed).
4143
4144 =cut
4145
4146 sub ordered_sql {
4147    $_[0]->recurring_sql. " AND ". $_[0]->not_yet_billed_sql;
4148 }
4149
4150 =item active_sql
4151
4152 Returns an SQL expression identifying active packages.
4153
4154 =cut
4155
4156 sub active_sql {
4157   $_[0]->recurring_sql. "
4158   AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
4159   AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4160   AND ( cust_pkg.susp   IS NULL OR cust_pkg.susp   = 0 )
4161 "; }
4162
4163 =item not_yet_billed_sql
4164
4165 Returns an SQL expression identifying packages which have not yet been billed.
4166
4167 =cut
4168
4169 sub not_yet_billed_sql { "
4170       ( cust_pkg.setup  IS NULL OR cust_pkg.setup  = 0 )
4171   AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4172   AND ( cust_pkg.susp   IS NULL OR cust_pkg.susp   = 0 )
4173 "; }
4174
4175 =item inactive_sql
4176
4177 Returns an SQL expression identifying inactive packages (one-time packages
4178 that are otherwise unsuspended/uncancelled).
4179
4180 =cut
4181
4182 sub inactive_sql { "
4183   ". $_[0]->onetime_sql(). "
4184   AND cust_pkg.setup IS NOT NULL AND cust_pkg.setup != 0
4185   AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4186   AND ( cust_pkg.susp   IS NULL OR cust_pkg.susp   = 0 )
4187 "; }
4188
4189 =item on_hold_sql
4190
4191 Returns an SQL expression identifying on-hold packages.
4192
4193 =cut
4194
4195 sub on_hold_sql {
4196   #$_[0]->recurring_sql(). ' AND '.
4197   "
4198         ( cust_pkg.cancel IS     NULL  OR cust_pkg.cancel  = 0 )
4199     AND   cust_pkg.susp   IS NOT NULL AND cust_pkg.susp   != 0
4200     AND ( cust_pkg.setup  IS     NULL  OR cust_pkg.setup   = 0 )
4201   ";
4202 }
4203
4204 =item susp_sql
4205 =item suspended_sql
4206
4207 Returns an SQL expression identifying suspended packages.
4208
4209 =cut
4210
4211 sub suspended_sql { susp_sql(@_); }
4212 sub susp_sql {
4213   #$_[0]->recurring_sql(). ' AND '.
4214   "
4215         ( cust_pkg.cancel IS     NULL  OR cust_pkg.cancel = 0 )
4216     AND   cust_pkg.susp   IS NOT NULL AND cust_pkg.susp  != 0
4217     AND   cust_pkg.setup  IS NOT NULL AND cust_pkg.setup != 0
4218   ";
4219 }
4220
4221 =item cancel_sql
4222 =item cancelled_sql
4223
4224 Returns an SQL exprression identifying cancelled packages.
4225
4226 =cut
4227
4228 sub cancelled_sql { cancel_sql(@_); }
4229 sub cancel_sql { 
4230   #$_[0]->recurring_sql(). ' AND '.
4231   "cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0";
4232 }
4233
4234 =item status_sql
4235
4236 Returns an SQL expression to give the package status as a string.
4237
4238 =cut
4239
4240 sub status_sql {
4241 "CASE
4242   WHEN cust_pkg.cancel IS NOT NULL THEN 'cancelled'
4243   WHEN ( cust_pkg.susp IS NOT NULL AND cust_pkg.setup IS NULL ) THEN 'on hold'
4244   WHEN cust_pkg.susp IS NOT NULL THEN 'suspended'
4245   WHEN cust_pkg.setup IS NULL THEN 'not yet billed'
4246   WHEN ".onetime_sql()." THEN 'one-time charge'
4247   ELSE 'active'
4248 END"
4249 }
4250
4251 =item fcc_477_count
4252
4253 Returns a list of two package counts.  The first is a count of packages
4254 based on the supplied criteria and the second is the count of residential
4255 packages with those same criteria.  Criteria are specified as in the search
4256 method.
4257
4258 =cut
4259
4260 sub fcc_477_count {
4261   my ($class, $params) = @_;
4262
4263   my $sql_query = $class->search( $params );
4264
4265   my $count_sql = delete($sql_query->{'count_query'});
4266   $count_sql =~ s/ FROM/,count(CASE WHEN cust_main.company IS NULL OR cust_main.company = '' THEN 1 END) FROM/
4267     or die "couldn't parse count_sql";
4268
4269   my $count_sth = dbh->prepare($count_sql)
4270     or die "Error preparing $count_sql: ". dbh->errstr;
4271   $count_sth->execute
4272     or die "Error executing $count_sql: ". $count_sth->errstr;
4273   my $count_arrayref = $count_sth->fetchrow_arrayref;
4274
4275   return ( @$count_arrayref );
4276
4277 }
4278
4279 =item tax_locationnum_sql
4280
4281 Returns an SQL expression for the tax location for a package, based
4282 on the settings of 'tax-pkg_address' and 'tax-ship_address'.
4283
4284 =cut
4285
4286 sub tax_locationnum_sql {
4287   my $conf = FS::Conf->new;
4288   if ( $conf->exists('tax-pkg_address') ) {
4289     'cust_pkg.locationnum';
4290   }
4291   elsif ( $conf->exists('tax-ship_address') ) {
4292     'cust_main.ship_locationnum';
4293   }
4294   else {
4295     'cust_main.bill_locationnum';
4296   }
4297 }
4298
4299 =item location_sql
4300
4301 Returns a list: the first item is an SQL fragment identifying matching 
4302 packages/customers via location (taking into account shipping and package
4303 address taxation, if enabled), and subsequent items are the parameters to
4304 substitute for the placeholders in that fragment.
4305
4306 =cut
4307
4308 sub location_sql {
4309   my($class, %opt) = @_;
4310   my $ornull = $opt{'ornull'};
4311
4312   my $conf = new FS::Conf;
4313
4314   # '?' placeholders in _location_sql_where
4315   my $x = $ornull ? 3 : 2;
4316   my @bill_param = ( 
4317     ('district')x3,
4318     ('city')x3, 
4319     ('county')x$x,
4320     ('state')x$x,
4321     'country'
4322   );
4323
4324   my $main_where;
4325   my @main_param;
4326   if ( $conf->exists('tax-ship_address') ) {
4327
4328     $main_where = "(
4329          (     ( ship_last IS NULL     OR  ship_last  = '' )
4330            AND ". _location_sql_where('cust_main', '', $ornull ). "
4331          )
4332       OR (       ship_last IS NOT NULL AND ship_last != ''
4333            AND ". _location_sql_where('cust_main', 'ship_', $ornull ). "
4334          )
4335     )";
4336     #    AND payby != 'COMP'
4337
4338     @main_param = ( @bill_param, @bill_param );
4339
4340   } else {
4341
4342     $main_where = _location_sql_where('cust_main'); # AND payby != 'COMP'
4343     @main_param = @bill_param;
4344
4345   }
4346
4347   my $where;
4348   my @param;
4349   if ( $conf->exists('tax-pkg_address') ) {
4350
4351     my $loc_where = _location_sql_where( 'cust_location', '', $ornull );
4352
4353     $where = " (
4354                     ( cust_pkg.locationnum IS     NULL AND $main_where )
4355                  OR ( cust_pkg.locationnum IS NOT NULL AND $loc_where  )
4356                )
4357              ";
4358     @param = ( @main_param, @bill_param );
4359   
4360   } else {
4361
4362     $where = $main_where;
4363     @param = @main_param;
4364
4365   }
4366
4367   ( $where, @param );
4368
4369 }
4370
4371 #subroutine, helper for location_sql
4372 sub _location_sql_where {
4373   my $table  = shift;
4374   my $prefix = @_ ? shift : '';
4375   my $ornull = @_ ? shift : '';
4376
4377 #  $ornull             = $ornull          ? " OR ( ? IS NULL AND $table.${prefix}county IS NULL ) " : '';
4378
4379   $ornull = $ornull ? ' OR ? IS NULL ' : '';
4380
4381   my $or_empty_city     = " OR ( ? = '' AND $table.${prefix}city     IS NULL )";
4382   my $or_empty_county   = " OR ( ? = '' AND $table.${prefix}county   IS NULL )";
4383   my $or_empty_state    = " OR ( ? = '' AND $table.${prefix}state    IS NULL )";
4384
4385   my $text = (driver_name =~ /^mysql/i) ? 'char' : 'text';
4386
4387 #        ( $table.${prefix}city    = ? $or_empty_city   $ornull )
4388   "
4389         ( $table.district = ? OR ? = '' OR CAST(? AS $text) IS NULL )
4390     AND ( $table.${prefix}city     = ? OR ? = '' OR CAST(? AS $text) IS NULL )
4391     AND ( $table.${prefix}county   = ? $or_empty_county $ornull )
4392     AND ( $table.${prefix}state    = ? $or_empty_state  $ornull )
4393     AND   $table.${prefix}country  = ?
4394   ";
4395 }
4396
4397 sub _X_show_zero {
4398   my( $self, $what ) = @_;
4399
4400   my $what_show_zero = $what. '_show_zero';
4401   length($self->$what_show_zero())
4402     ? ($self->$what_show_zero() eq 'Y')
4403     : $self->part_pkg->$what_show_zero();
4404 }
4405
4406 =head1 SUBROUTINES
4407
4408 =over 4
4409
4410 =item order CUSTNUM, PKGPARTS_ARYREF, [ REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF [ REFNUM ] ] ]
4411
4412 CUSTNUM is a customer (see L<FS::cust_main>)
4413
4414 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
4415 L<FS::part_pkg>) to order for this customer.  Duplicates are of course
4416 permitted.
4417
4418 REMOVE_PKGNUMS is an optional list of pkgnums specifying the billing items to
4419 remove for this customer.  The services (see L<FS::cust_svc>) are moved to the
4420 new billing items.  An error is returned if this is not possible (see
4421 L<FS::pkg_svc>).  An empty arrayref is equivalent to not specifying this
4422 parameter.
4423
4424 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
4425 newly-created cust_pkg objects.
4426
4427 REFNUM, if specified, will specify the FS::pkg_referral record to be created
4428 and inserted.  Multiple FS::pkg_referral records can be created by
4429 setting I<refnum> to an array reference of refnums or a hash reference with
4430 refnums as keys.  If no I<refnum> is defined, a default FS::pkg_referral
4431 record will be created corresponding to cust_main.refnum.
4432
4433 =cut
4434
4435 sub order {
4436   my ($custnum, $pkgparts, $remove_pkgnum, $return_cust_pkg, $refnum) = @_;
4437
4438   my $conf = new FS::Conf;
4439
4440   # Transactionize this whole mess
4441   my $oldAutoCommit = $FS::UID::AutoCommit;
4442   local $FS::UID::AutoCommit = 0;
4443   my $dbh = dbh;
4444
4445   my $error;
4446 #  my $cust_main = qsearchs('cust_main', { custnum => $custnum });
4447 #  return "Customer not found: $custnum" unless $cust_main;
4448
4449   warn "$me order: pkgnums to remove: ". join(',', @$remove_pkgnum). "\n"
4450     if $DEBUG;
4451
4452   my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
4453                          @$remove_pkgnum;
4454
4455   my $change = scalar(@old_cust_pkg) != 0;
4456
4457   my %hash = (); 
4458   if ( scalar(@old_cust_pkg) == 1 && scalar(@$pkgparts) == 1 ) {
4459
4460     warn "$me order: changing pkgnum ". $old_cust_pkg[0]->pkgnum.
4461          " to pkgpart ". $pkgparts->[0]. "\n"
4462       if $DEBUG;
4463
4464     my $err_or_cust_pkg =
4465       $old_cust_pkg[0]->change( 'pkgpart' => $pkgparts->[0],
4466                                 'refnum'  => $refnum,
4467                               );
4468
4469     unless (ref($err_or_cust_pkg)) {
4470       $dbh->rollback if $oldAutoCommit;
4471       return $err_or_cust_pkg;
4472     }
4473
4474     push @$return_cust_pkg, $err_or_cust_pkg;
4475     $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4476     return '';
4477
4478   }
4479
4480   # Create the new packages.
4481   foreach my $pkgpart (@$pkgparts) {
4482
4483     warn "$me order: inserting pkgpart $pkgpart\n" if $DEBUG;
4484
4485     my $cust_pkg = new FS::cust_pkg { custnum => $custnum,
4486                                       pkgpart => $pkgpart,
4487                                       refnum  => $refnum,
4488                                       %hash,
4489                                     };
4490     $error = $cust_pkg->insert( 'change' => $change );
4491     push @$return_cust_pkg, $cust_pkg;
4492
4493     foreach my $link ($cust_pkg->part_pkg->supp_part_pkg_link) {
4494       my $supp_pkg = FS::cust_pkg->new({
4495           custnum => $custnum,
4496           pkgpart => $link->dst_pkgpart,
4497           refnum  => $refnum,
4498           main_pkgnum => $cust_pkg->pkgnum,
4499           %hash,
4500       });
4501       $error ||= $supp_pkg->insert( 'change' => $change );
4502       push @$return_cust_pkg, $supp_pkg;
4503     }
4504
4505     if ($error) {
4506       $dbh->rollback if $oldAutoCommit;
4507       return $error;
4508     }
4509
4510   }
4511   # $return_cust_pkg now contains refs to all of the newly 
4512   # created packages.
4513
4514   # Transfer services and cancel old packages.
4515   foreach my $old_pkg (@old_cust_pkg) {
4516
4517     warn "$me order: transferring services from pkgnum ". $old_pkg->pkgnum. "\n"
4518       if $DEBUG;
4519
4520     foreach my $new_pkg (@$return_cust_pkg) {
4521       $error = $old_pkg->transfer($new_pkg);
4522       if ($error and $error == 0) {
4523         # $old_pkg->transfer failed.
4524         $dbh->rollback if $oldAutoCommit;
4525         return $error;
4526       }
4527     }
4528
4529     if ( $error > 0 && $conf->exists('cust_pkg-change_svcpart') ) {
4530       warn "trying transfer again with change_svcpart option\n" if $DEBUG;
4531       foreach my $new_pkg (@$return_cust_pkg) {
4532         $error = $old_pkg->transfer($new_pkg, 'change_svcpart'=>1 );
4533         if ($error and $error == 0) {
4534           # $old_pkg->transfer failed.
4535         $dbh->rollback if $oldAutoCommit;
4536         return $error;
4537         }
4538       }
4539     }
4540
4541     if ($error > 0) {
4542       # Transfers were successful, but we went through all of the 
4543       # new packages and still had services left on the old package.
4544       # We can't cancel the package under the circumstances, so abort.
4545       $dbh->rollback if $oldAutoCommit;
4546       return "Unable to transfer all services from package ".$old_pkg->pkgnum;
4547     }
4548     $error = $old_pkg->cancel( quiet=>1 );
4549     if ($error) {
4550       $dbh->rollback;
4551       return $error;
4552     }
4553   }
4554   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4555   '';
4556 }
4557
4558 =item bulk_change PKGPARTS_ARYREF, REMOVE_PKGNUMS_ARYREF [ RETURN_CUST_PKG_ARRAYREF ]
4559
4560 A bulk change method to change packages for multiple customers.
4561
4562 PKGPARTS is a list of pkgparts specifying the the billing item definitions (see
4563 L<FS::part_pkg>) to order for each customer.  Duplicates are of course
4564 permitted.
4565
4566 REMOVE_PKGNUMS is an list of pkgnums specifying the billing items to
4567 replace.  The services (see L<FS::cust_svc>) are moved to the
4568 new billing items.  An error is returned if this is not possible (see
4569 L<FS::pkg_svc>).
4570
4571 RETURN_CUST_PKG_ARRAYREF, if specified, will be filled in with the
4572 newly-created cust_pkg objects.
4573
4574 =cut
4575
4576 sub bulk_change {
4577   my ($pkgparts, $remove_pkgnum, $return_cust_pkg) = @_;
4578
4579   # Transactionize this whole mess
4580   my $oldAutoCommit = $FS::UID::AutoCommit;
4581   local $FS::UID::AutoCommit = 0;
4582   my $dbh = dbh;
4583
4584   my @errors;
4585   my @old_cust_pkg = map { qsearchs('cust_pkg', { pkgnum => $_ }) }
4586                          @$remove_pkgnum;
4587
4588   while(scalar(@old_cust_pkg)) {
4589     my @return = ();
4590     my $custnum = $old_cust_pkg[0]->custnum;
4591     my (@remove) = map { $_->pkgnum }
4592                    grep { $_->custnum == $custnum } @old_cust_pkg;
4593     @old_cust_pkg = grep { $_->custnum != $custnum } @old_cust_pkg;
4594
4595     my $error = order $custnum, $pkgparts, \@remove, \@return;
4596
4597     push @errors, $error
4598       if $error;
4599     push @$return_cust_pkg, @return;
4600   }
4601
4602   if (scalar(@errors)) {
4603     $dbh->rollback if $oldAutoCommit;
4604     return join(' / ', @errors);
4605   }
4606
4607   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4608   '';
4609 }
4610
4611 # Used by FS::Upgrade to migrate to a new database.
4612 sub _upgrade_data {  # class method
4613   my ($class, %opts) = @_;
4614   $class->_upgrade_otaker(%opts);
4615   my @statements = (
4616     # RT#10139, bug resulting in contract_end being set when it shouldn't
4617   'UPDATE cust_pkg SET contract_end = NULL WHERE contract_end = -1',
4618     # RT#10830, bad calculation of prorate date near end of year
4619     # the date range for bill is December 2009, and we move it forward
4620     # one year if it's before the previous bill date (which it should 
4621     # never be)
4622   'UPDATE cust_pkg SET bill = bill + (365*24*60*60) WHERE bill < last_bill
4623   AND bill > 1259654400 AND bill < 1262332800 AND (SELECT plan FROM part_pkg 
4624   WHERE part_pkg.pkgpart = cust_pkg.pkgpart) = \'prorate\'',
4625     # RT6628, add order_date to cust_pkg
4626     'update cust_pkg set order_date = (select history_date from h_cust_pkg 
4627         where h_cust_pkg.pkgnum = cust_pkg.pkgnum and 
4628         history_action = \'insert\') where order_date is null',
4629   );
4630   foreach my $sql (@statements) {
4631     my $sth = dbh->prepare($sql);
4632     $sth->execute or die $sth->errstr;
4633   }
4634 }
4635
4636 =back
4637
4638 =head1 BUGS
4639
4640 sub order is not OO.  Perhaps it should be moved to FS::cust_main and made so?
4641
4642 In sub order, the @pkgparts array (passed by reference) is clobbered.
4643
4644 Also in sub order, no money is adjusted.  Once FS::part_pkg defines a standard
4645 method to pass dates to the recur_prog expression, it should do so.
4646
4647 FS::svc_acct, FS::svc_domain, FS::svc_www, FS::svc_ip and FS::svc_forward are
4648 loaded via 'use' at compile time, rather than via 'require' in sub { setup,
4649 suspend, unsuspend, cancel } because they use %FS::UID::callback to load
4650 configuration values.  Probably need a subroutine which decides what to do
4651 based on whether or not we've fetched the user yet, rather than a hash.  See
4652 FS::UID and the TODO.
4653
4654 Now that things are transactional should the check in the insert method be
4655 moved to check ?
4656
4657 =head1 SEE ALSO
4658
4659 L<FS::Record>, L<FS::cust_main>, L<FS::part_pkg>, L<FS::cust_svc>,
4660 L<FS::pkg_svc>, schema.html from the base documentation
4661
4662 =cut
4663
4664 1;
4665