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