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