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