improve performance of package ordering, RT#24955, fallout from future start dates...
[freeside.git] / FS / FS / part_pkg.pm
1 package FS::part_pkg;
2 use base qw( FS::m2m_Common FS::o2m_Common FS::option_Common );
3
4 use strict;
5 use vars qw( %plans $DEBUG $setup_hack $skip_pkg_svc_hack );
6 use Carp qw(carp cluck confess);
7 use Scalar::Util qw( blessed );
8 use Time::Local qw( timelocal timelocal_nocheck );
9 use Tie::IxHash;
10 use FS::Conf;
11 use FS::Record qw( qsearch qsearchs dbh dbdef );
12 use FS::pkg_svc;
13 use FS::part_svc;
14 use FS::cust_pkg;
15 use FS::agent_type;
16 use FS::type_pkgs;
17 use FS::part_pkg_option;
18 use FS::pkg_class;
19 use FS::agent;
20 use FS::part_pkg_msgcat;
21 use FS::part_pkg_taxrate;
22 use FS::part_pkg_taxoverride;
23 use FS::part_pkg_taxproduct;
24 use FS::part_pkg_link;
25 use FS::part_pkg_discount;
26 use FS::part_pkg_usage;
27 use FS::part_pkg_vendor;
28 use FS::part_pkg_currency;
29
30 $DEBUG = 0;
31 $setup_hack = 0;
32 $skip_pkg_svc_hack = 0;
33
34 =head1 NAME
35
36 FS::part_pkg - Object methods for part_pkg objects
37
38 =head1 SYNOPSIS
39
40   use FS::part_pkg;
41
42   $record = new FS::part_pkg \%hash
43   $record = new FS::part_pkg { 'column' => 'value' };
44
45   $custom_record = $template_record->clone;
46
47   $error = $record->insert;
48
49   $error = $new_record->replace($old_record);
50
51   $error = $record->delete;
52
53   $error = $record->check;
54
55   @pkg_svc = $record->pkg_svc;
56
57   $svcnum = $record->svcpart;
58   $svcnum = $record->svcpart( 'svc_acct' );
59
60 =head1 DESCRIPTION
61
62 An FS::part_pkg object represents a package definition.  FS::part_pkg
63 inherits from FS::Record.  The following fields are currently supported:
64
65 =over 4
66
67 =item pkgpart - primary key (assigned automatically for new package definitions)
68
69 =item pkg - Text name of this package definition (customer-viewable)
70
71 =item comment - Text name of this package definition (non-customer-viewable)
72
73 =item classnum - Optional package class (see L<FS::pkg_class>)
74
75 =item promo_code - Promotional code
76
77 =item setup - Setup fee expression (deprecated)
78
79 =item freq - Frequency of recurring fee
80
81 =item recur - Recurring fee expression (deprecated)
82
83 =item setuptax - Setup fee tax exempt flag, empty or `Y'
84
85 =item recurtax - Recurring fee tax exempt flag, empty or `Y'
86
87 =item taxclass - Tax class 
88
89 =item plan - Price plan
90
91 =item plandata - Price plan data (deprecated - see L<FS::part_pkg_option> instead)
92
93 =item disabled - Disabled flag, empty or `Y'
94
95 =item custom - Custom flag, empty or `Y'
96
97 =item setup_cost - for cost tracking
98
99 =item recur_cost - for cost tracking
100
101 =item pay_weight - Weight (relative to credit_weight and other package definitions) that controls payment application to specific line items.
102
103 =item credit_weight - Weight (relative to other package definitions) that controls credit application to specific line items.
104
105 =item agentnum - Optional agentnum (see L<FS::agent>)
106
107 =item fcc_ds0s - Optional DS0 equivalency number for FCC form 477
108
109 =item fcc_voip_class - Which column of FCC form 477 part II.B this package 
110 belongs in.
111
112 =item successor - Foreign key for the part_pkg that replaced this record.
113 If this record is not obsolete, will be null.
114
115 =item family_pkgpart - Foreign key for the part_pkg that was the earliest
116 ancestor of this record.  If this record is not a successor to another 
117 part_pkg, will be equal to pkgpart.
118
119 =item delay_start - Number of days to delay package start, by default
120
121 =back
122
123 =head1 METHODS
124
125 =over 4 
126
127 =item new HASHREF
128
129 Creates a new package definition.  To add the package definition to
130 the database, see L<"insert">.
131
132 =cut
133
134 sub table { 'part_pkg'; }
135
136 =item clone
137
138 An alternate constructor.  Creates a new package definition by duplicating
139 an existing definition.  A new pkgpart is assigned and the custom flag is
140 set to Y.  To add the package definition to the database, see L<"insert">.
141
142 =cut
143
144 sub clone {
145   my $self = shift;
146   my $class = ref($self);
147   my %hash = $self->hash;
148   $hash{'pkgpart'} = '';
149   $hash{'custom'} = 'Y';
150   #new FS::part_pkg ( \%hash ); # ?
151   new $class ( \%hash ); # ?
152 }
153
154 =item insert [ , OPTION => VALUE ... ]
155
156 Adds this package definition to the database.  If there is an error,
157 returns the error, otherwise returns false.
158
159 Currently available options are: I<pkg_svc>, I<primary_svc>, I<cust_pkg>, 
160 I<custnum_ref> and I<options>.
161
162 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
163 values, appropriate FS::pkg_svc records will be inserted.  I<hidden_svc> can 
164 be set to a hashref of svcparts and flag values ('Y' or '') to set the 
165 'hidden' field in these records.
166
167 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
168 FS::pkg_svc record will be updated.
169
170 If I<cust_pkg> is set to a pkgnum of a FS::cust_pkg record (or the FS::cust_pkg
171 record itself), the object will be updated to point to this package definition.
172
173 In conjunction with I<cust_pkg>, if I<custnum_ref> is set to a scalar reference,
174 the scalar will be updated with the custnum value from the cust_pkg record.
175
176 If I<tax_overrides> is set to a hashref with usage classes as keys and comma
177 separated tax class numbers as values, appropriate FS::part_pkg_taxoverride
178 records will be inserted.
179
180 If I<options> is set to a hashref of options, appropriate FS::part_pkg_option
181 records will be inserted.
182
183 If I<part_pkg_currency> is set to a hashref of options (with the keys as
184 option_CURRENCY), appropriate FS::part_pkg::currency records will be inserted.
185
186 =cut
187
188 sub insert {
189   my $self = shift;
190   my %options = @_;
191   warn "FS::part_pkg::insert called on $self with options ".
192        join(', ', map "$_=>$options{$_}", keys %options)
193     if $DEBUG;
194
195   local $SIG{HUP} = 'IGNORE';
196   local $SIG{INT} = 'IGNORE';
197   local $SIG{QUIT} = 'IGNORE';
198   local $SIG{TERM} = 'IGNORE';
199   local $SIG{TSTP} = 'IGNORE';
200   local $SIG{PIPE} = 'IGNORE';
201
202   my $oldAutoCommit = $FS::UID::AutoCommit;
203   local $FS::UID::AutoCommit = 0;
204   my $dbh = dbh;
205
206   warn "  inserting part_pkg record" if $DEBUG;
207   my $error = $self->SUPER::insert( $options{options} );
208   if ( $error ) {
209     $dbh->rollback if $oldAutoCommit;
210     return $error;
211   }
212
213   # set family_pkgpart
214   if ( $self->get('family_pkgpart') eq '' ) {
215     $self->set('family_pkgpart' => $self->pkgpart);
216     $error = $self->SUPER::replace;
217     if ( $error ) {
218       $dbh->rollback if $oldAutoCommit;
219       return $error;
220     }
221   }
222
223   my $conf = new FS::Conf;
224   if ( $conf->exists('agent_defaultpkg') ) {
225     warn "  agent_defaultpkg set; allowing all agents to purchase package"
226       if $DEBUG;
227     foreach my $agent_type ( qsearch('agent_type', {} ) ) {
228       my $type_pkgs = new FS::type_pkgs({
229         'typenum' => $agent_type->typenum,
230         'pkgpart' => $self->pkgpart,
231       });
232       my $error = $type_pkgs->insert;
233       if ( $error ) {
234         $dbh->rollback if $oldAutoCommit;
235         return $error;
236       }
237     }
238   }
239
240   warn "  inserting part_pkg_taxoverride records" if $DEBUG;
241   my %overrides = %{ $options{'tax_overrides'} || {} };
242   foreach my $usage_class ( keys %overrides ) {
243     my $override =
244       ( exists($overrides{$usage_class}) && defined($overrides{$usage_class}) )
245         ? $overrides{$usage_class}
246         : '';
247     my @overrides = (grep "$_", split(',', $override) );
248     my $error = $self->process_m2m (
249                   'link_table'   => 'part_pkg_taxoverride',
250                   'target_table' => 'tax_class',
251                   'hashref'      => { 'usage_class' => $usage_class },
252                   'params'       => \@overrides,
253                 );
254     if ( $error ) {
255       $dbh->rollback if $oldAutoCommit;
256       return $error;
257     }
258   }
259
260   warn "  inserting part_pkg_currency records" if $DEBUG;
261   my %part_pkg_currency = %{ $options{'part_pkg_currency'} || {} };
262   foreach my $key ( keys %part_pkg_currency ) {
263     $key =~ /^(.+)_([A-Z]{3})$/ or next;
264     my $part_pkg_currency = new FS::part_pkg_currency {
265       'pkgpart'     => $self->pkgpart,
266       'optionname'  => $1,
267       'currency'    => $2,
268       'optionvalue' => $part_pkg_currency{$key},
269     };
270     my $error = $part_pkg_currency->insert;
271     if ( $error ) {
272       $dbh->rollback if $oldAutoCommit;
273       return $error;
274     }
275   }
276
277   unless ( $skip_pkg_svc_hack ) {
278
279     warn "  inserting pkg_svc records" if $DEBUG;
280     my $pkg_svc = $options{'pkg_svc'} || {};
281     my $hidden_svc = $options{'hidden_svc'} || {};
282     foreach my $part_svc ( qsearch('part_svc', {} ) ) {
283       my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
284       my $primary_svc =
285         ( $options{'primary_svc'} && $options{'primary_svc'}==$part_svc->svcpart )
286           ? 'Y'
287           : '';
288
289       my $pkg_svc = new FS::pkg_svc( {
290         'pkgpart'     => $self->pkgpart,
291         'svcpart'     => $part_svc->svcpart,
292         'quantity'    => $quantity, 
293         'primary_svc' => $primary_svc,
294         'hidden'      => $hidden_svc->{$part_svc->svcpart},
295       } );
296       my $error = $pkg_svc->insert;
297       if ( $error ) {
298         $dbh->rollback if $oldAutoCommit;
299         return $error;
300       }
301     }
302
303   }
304
305   if ( $options{'cust_pkg'} ) {
306     warn "  updating cust_pkg record " if $DEBUG;
307     my $old_cust_pkg =
308       ref($options{'cust_pkg'})
309         ? $options{'cust_pkg'}
310         : qsearchs('cust_pkg', { pkgnum => $options{'cust_pkg'} } );
311     ${ $options{'custnum_ref'} } = $old_cust_pkg->custnum
312       if $options{'custnum_ref'};
313     my %hash = $old_cust_pkg->hash;
314     $hash{'pkgpart'} = $self->pkgpart,
315     my $new_cust_pkg = new FS::cust_pkg \%hash;
316     local($FS::cust_pkg::disable_agentcheck) = 1;
317     my $error = $new_cust_pkg->replace($old_cust_pkg);
318     if ( $error ) {
319       $dbh->rollback if $oldAutoCommit;
320       return "Error modifying cust_pkg record: $error";
321     }
322   }
323
324   if ( $options{'part_pkg_vendor'} ) {
325       while ( my ($exportnum, $vendor_pkg_id) =
326                 each %{ $options{part_pkg_vendor} }
327             )
328       {
329             my $ppv = new FS::part_pkg_vendor( {
330                     'pkgpart' => $self->pkgpart,
331                     'exportnum' => $exportnum,
332                     'vendor_pkg_id' => $vendor_pkg_id, 
333                 } );
334             my $error = $ppv->insert;
335             if ( $error ) {
336               $dbh->rollback if $oldAutoCommit;
337               return "Error inserting part_pkg_vendor record: $error";
338             }
339       }
340   }
341
342   warn "  committing transaction" if $DEBUG and $oldAutoCommit;
343   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
344
345   '';
346 }
347
348 =item delete
349
350 Currently unimplemented.
351
352 =cut
353
354 sub delete {
355   return "Can't (yet?) delete package definitions.";
356 # check & make sure the pkgpart isn't in cust_pkg or type_pkgs?
357 }
358
359 =item replace OLD_RECORD [ , OPTION => VALUE ... ]
360
361 Replaces OLD_RECORD with this one in the database.  If there is an error,
362 returns the error, otherwise returns false.
363
364 Currently available options are: I<pkg_svc>, I<hidden_svc>, I<primary_svc> 
365 and I<options>
366
367 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
368 values, the appropriate FS::pkg_svc records will be replaced.  I<hidden_svc>
369 can be set to a hashref of svcparts and flag values ('Y' or '') to set the 
370 'hidden' field in these records.  I<bulk_skip> can be set to a hashref of
371 svcparts and flag values ('Y' or '') to set the 'bulk_skip' field in those
372 records.
373
374 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
375 FS::pkg_svc record will be updated.
376
377 If I<options> is set to a hashref, the appropriate FS::part_pkg_option records
378 will be replaced.
379
380 If I<part_pkg_currency> is set to a hashref of options (with the keys as
381 option_CURRENCY), appropriate FS::part_pkg::currency records will be replaced.
382
383 =cut
384
385 sub replace {
386   my $new = shift;
387
388   my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
389               ? shift
390               : $new->replace_old;
391
392   my $options = 
393     ( ref($_[0]) eq 'HASH' )
394       ? shift
395       : { @_ };
396
397   $options->{options} = { $old->options } unless defined($options->{options});
398
399   warn "FS::part_pkg::replace called on $new to replace $old with options".
400        join(', ', map "$_ => ". $options->{$_}, keys %$options)
401     if $DEBUG;
402
403   local $SIG{HUP} = 'IGNORE';
404   local $SIG{INT} = 'IGNORE';
405   local $SIG{QUIT} = 'IGNORE';
406   local $SIG{TERM} = 'IGNORE';
407   local $SIG{TSTP} = 'IGNORE';
408   local $SIG{PIPE} = 'IGNORE';
409
410   my $oldAutoCommit = $FS::UID::AutoCommit;
411   local $FS::UID::AutoCommit = 0;
412   my $dbh = dbh;
413   
414   my $conf = new FS::Conf;
415   if ( $conf->exists('part_pkg-lineage') ) {
416     if ( grep { $options->{options}->{$_} ne $old->option($_, 1) }
417           qw(setup_fee recur_fee) #others? config?
418         ) { 
419     
420       warn "  superseding package" if $DEBUG;
421
422       my $error = $new->supersede($old, %$options);
423       if ( $error ) {
424         $dbh->rollback if $oldAutoCommit;
425         return $error;
426       }
427       else {
428         warn "  committing transaction" if $DEBUG and $oldAutoCommit;
429         $dbh->commit if $oldAutoCommit;
430         return $error;
431       }
432     }
433     #else nothing
434   }
435
436   #plandata shit stays in replace for upgrades until after 2.0 (or edit
437   #_upgrade_data)
438   warn "  saving legacy plandata" if $DEBUG;
439   my $plandata = $new->get('plandata');
440   $new->set('plandata', '');
441
442   warn "  deleting old part_pkg_option records" if $DEBUG;
443   foreach my $part_pkg_option ( $old->part_pkg_option ) {
444     my $error = $part_pkg_option->delete;
445     if ( $error ) {
446       $dbh->rollback if $oldAutoCommit;
447       return $error;
448     }
449   }
450
451   warn "  replacing part_pkg record" if $DEBUG;
452   my $error = $new->SUPER::replace($old, $options->{options} );
453   if ( $error ) {
454     $dbh->rollback if $oldAutoCommit;
455     return $error;
456   }
457
458   warn "  inserting part_pkg_option records for plandata: $plandata|" if $DEBUG;
459   foreach my $part_pkg_option ( 
460     map { /^(\w+)=(.*)$/ or do { $dbh->rollback if $oldAutoCommit;
461                                  return "illegal plandata: $plandata";
462                                };
463           new FS::part_pkg_option {
464             'pkgpart'     => $new->pkgpart,
465             'optionname'  => $1,
466             'optionvalue' => $2,
467           };
468         }
469     split("\n", $plandata)
470   ) {
471     my $error = $part_pkg_option->insert;
472     if ( $error ) {
473       $dbh->rollback if $oldAutoCommit;
474       return $error;
475     }
476   }
477
478   #trivial nit: not the most efficient to delete and reinsert
479   warn "  deleting old part_pkg_currency records" if $DEBUG;
480   foreach my $part_pkg_currency ( $old->part_pkg_currency ) {
481     my $error = $part_pkg_currency->delete;
482     if ( $error ) {
483       $dbh->rollback if $oldAutoCommit;
484       return "error deleting part_pkg_currency record: $error";
485     }
486   }
487
488   warn "  inserting new part_pkg_currency records" if $DEBUG;
489   my %part_pkg_currency = %{ $options->{'part_pkg_currency'} || {} };
490   foreach my $key ( keys %part_pkg_currency ) {
491     $key =~ /^(.+)_([A-Z]{3})$/ or next;
492     my $part_pkg_currency = new FS::part_pkg_currency {
493       'pkgpart'     => $new->pkgpart,
494       'optionname'  => $1,
495       'currency'    => $2,
496       'optionvalue' => $part_pkg_currency{$key},
497     };
498     my $error = $part_pkg_currency->insert;
499     if ( $error ) {
500       $dbh->rollback if $oldAutoCommit;
501       return "error inserting part_pkg_currency record: $error";
502     }
503   }
504
505
506   warn "  replacing pkg_svc records" if $DEBUG;
507   my $pkg_svc = $options->{'pkg_svc'};
508   my $hidden_svc = $options->{'hidden_svc'} || {};
509   my $bulk_skip  = $options->{'bulk_skip'} || {};
510   if ( $pkg_svc ) { # if it wasn't passed, don't change existing pkg_svcs
511     foreach my $part_svc ( qsearch('part_svc', {} ) ) {
512       my $quantity  = $pkg_svc->{$part_svc->svcpart} || 0;
513       my $hidden    = $hidden_svc->{$part_svc->svcpart} || '';
514       my $bulk_skip = $bulk_skip->{$part_svc->svcpart} || '';
515       my $primary_svc =
516         ( defined($options->{'primary_svc'}) && $options->{'primary_svc'}
517           && $options->{'primary_svc'} == $part_svc->svcpart
518         )
519           ? 'Y'
520           : '';
521
522       my $old_pkg_svc = qsearchs('pkg_svc', {
523           'pkgpart' => $old->pkgpart,
524           'svcpart' => $part_svc->svcpart,
525         }
526       );
527       my $old_quantity = 0;
528       my $old_primary_svc = '';
529       my $old_hidden = '';
530       my $old_bulk_skip = '';
531       if ( $old_pkg_svc ) {
532         $old_quantity = $old_pkg_svc->quantity;
533         $old_primary_svc = $old_pkg_svc->primary_svc 
534           if $old_pkg_svc->dbdef_table->column('primary_svc'); # is this needed?
535         $old_hidden = $old_pkg_svc->hidden;
536         $old_bulk_skip = $old_pkg_svc->old_bulk_skip;
537       }
538    
539       next unless $old_quantity    != $quantity
540                || $old_primary_svc ne $primary_svc
541                || $old_hidden      ne $hidden
542                || $old_bulk_skip   ne $bulk_skip;
543     
544       my $new_pkg_svc = new FS::pkg_svc( {
545         'pkgsvcnum'   => ( $old_pkg_svc ? $old_pkg_svc->pkgsvcnum : '' ),
546         'pkgpart'     => $new->pkgpart,
547         'svcpart'     => $part_svc->svcpart,
548         'quantity'    => $quantity, 
549         'primary_svc' => $primary_svc,
550         'hidden'      => $hidden,
551         'bulk_skip'   => $bulk_skip,
552       } );
553       my $error = $old_pkg_svc
554                     ? $new_pkg_svc->replace($old_pkg_svc)
555                     : $new_pkg_svc->insert;
556       if ( $error ) {
557         $dbh->rollback if $oldAutoCommit;
558         return $error;
559       }
560     } #foreach $part_svc
561   } #if $options->{pkg_svc}
562   
563   my @part_pkg_vendor = $old->part_pkg_vendor;
564   my @current_exportnum = ();
565   if ( $options->{'part_pkg_vendor'} ) {
566       my($exportnum,$vendor_pkg_id);
567       while ( ($exportnum,$vendor_pkg_id) 
568                                 = each %{$options->{'part_pkg_vendor'}} ) {
569           my $noinsert = 0;
570           foreach my $part_pkg_vendor ( @part_pkg_vendor ) {
571             if($exportnum == $part_pkg_vendor->exportnum
572                 && $vendor_pkg_id ne $part_pkg_vendor->vendor_pkg_id) {
573                 $part_pkg_vendor->vendor_pkg_id($vendor_pkg_id);
574                 my $error = $part_pkg_vendor->replace;
575                 if ( $error ) {
576                   $dbh->rollback if $oldAutoCommit;
577                   return "Error replacing part_pkg_vendor record: $error";
578                 }
579                 $noinsert = 1;
580                 last;
581             }
582             elsif($exportnum == $part_pkg_vendor->exportnum
583                 && $vendor_pkg_id eq $part_pkg_vendor->vendor_pkg_id) {
584                 $noinsert = 1;
585                 last;
586             }
587           }
588           unless ( $noinsert ) {
589             my $ppv = new FS::part_pkg_vendor( {
590                     'pkgpart' => $new->pkgpart,
591                     'exportnum' => $exportnum,
592                     'vendor_pkg_id' => $vendor_pkg_id, 
593                 } );
594             my $error = $ppv->insert;
595             if ( $error ) {
596               $dbh->rollback if $oldAutoCommit;
597               return "Error inserting part_pkg_vendor record: $error";
598             }
599           }
600           push @current_exportnum, $exportnum;
601       }
602   }
603   foreach my $part_pkg_vendor ( @part_pkg_vendor ) {
604       unless ( grep($_ eq $part_pkg_vendor->exportnum, @current_exportnum) ) {
605         my $error = $part_pkg_vendor->delete;
606         if ( $error ) {
607           $dbh->rollback if $oldAutoCommit;
608           return "Error deleting part_pkg_vendor record: $error";
609         }
610       }
611   }
612   
613   # propagate changes to certain core fields
614   if ( $conf->exists('part_pkg-lineage') ) {
615     warn "  propagating changes to family" if $DEBUG;
616     my $error = $new->propagate($old);
617     if ( $error ) {
618       $dbh->rollback if $oldAutoCommit;
619       return $error;
620     }
621   }
622
623   warn "  committing transaction" if $DEBUG and $oldAutoCommit;
624   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
625   '';
626 }
627
628 =item check
629
630 Checks all fields to make sure this is a valid package definition.  If
631 there is an error, returns the error, otherwise returns false.  Called by the
632 insert and replace methods.
633
634 =cut
635
636 sub check {
637   my $self = shift;
638   warn "FS::part_pkg::check called on $self" if $DEBUG;
639
640   for (qw(setup recur plandata)) {
641     #$self->set($_=>0) if $self->get($_) =~ /^\s*$/; }
642     return "Use of $_ field is deprecated; set a plan and options: ".
643            $self->get($_)
644       if length($self->get($_));
645     $self->set($_, '');
646   }
647
648   if ( $self->dbdef_table->column('freq')->type =~ /(int)/i ) {
649     my $error = $self->ut_number('freq');
650     return $error if $error;
651   } else {
652     $self->freq =~ /^(\d+[hdw]?)$/
653       or return "Illegal or empty freq: ". $self->freq;
654     $self->freq($1);
655   }
656
657   my @null_agentnum_right = ( 'Edit global package definitions' );
658   push @null_agentnum_right, 'One-time charge'
659     if $self->freq =~ /^0/;
660   push @null_agentnum_right, 'Customize customer package'
661     if $self->disabled eq 'Y'; #good enough
662
663   my $error = $self->ut_numbern('pkgpart')
664     || $self->ut_text('pkg')
665     || $self->ut_text('comment')
666     || $self->ut_textn('promo_code')
667     || $self->ut_alphan('plan')
668     || $self->ut_enum('setuptax', [ '', 'Y' ] )
669     || $self->ut_enum('recurtax', [ '', 'Y' ] )
670     || $self->ut_textn('taxclass')
671     || $self->ut_enum('disabled', [ '', 'Y' ] )
672     || $self->ut_enum('custom', [ '', 'Y' ] )
673     || $self->ut_enum('no_auto', [ '', 'Y' ])
674     || $self->ut_enum('recur_show_zero', [ '', 'Y' ])
675     || $self->ut_enum('setup_show_zero', [ '', 'Y' ])
676     #|| $self->ut_moneyn('setup_cost')
677     #|| $self->ut_moneyn('recur_cost')
678     || $self->ut_floatn('setup_cost')
679     || $self->ut_floatn('recur_cost')
680     || $self->ut_floatn('pay_weight')
681     || $self->ut_floatn('credit_weight')
682     || $self->ut_numbern('taxproductnum')
683     || $self->ut_foreign_keyn('classnum',       'pkg_class', 'classnum')
684     || $self->ut_foreign_keyn('addon_classnum', 'pkg_class', 'classnum')
685     || $self->ut_foreign_keyn('taxproductnum',
686                               'part_pkg_taxproduct',
687                               'taxproductnum'
688                              )
689     || ( $setup_hack
690            ? $self->ut_foreign_keyn('agentnum', 'agent', 'agentnum' )
691            : $self->ut_agentnum_acl('agentnum', \@null_agentnum_right)
692        )
693     || $self->ut_numbern('fcc_ds0s')
694     || $self->ut_numbern('fcc_voip_class')
695     || $self->ut_numbern('delay_start')
696     || $self->ut_foreign_keyn('successor', 'part_pkg', 'pkgpart')
697     || $self->ut_foreign_keyn('family_pkgpart', 'part_pkg', 'pkgpart')
698     || $self->SUPER::check
699   ;
700   return $error if $error;
701
702   return 'Unknown plan '. $self->plan
703     unless exists($plans{$self->plan});
704
705   my $conf = new FS::Conf;
706   return 'Taxclass is required'
707     if ! $self->taxclass && $conf->exists('require_taxclasses');
708
709   '';
710 }
711
712 =item supersede OLD [, OPTION => VALUE ... ]
713
714 Inserts this package as a successor to the package OLD.  All options are as
715 for C<insert>.  After inserting, disables OLD and sets the new package as its
716 successor.
717
718 =cut
719
720 sub supersede {
721   my ($new, $old, %options) = @_;
722   my $error;
723
724   $new->set('pkgpart' => '');
725   $new->set('family_pkgpart' => $old->family_pkgpart);
726   warn "    inserting successor package\n" if $DEBUG;
727   $error = $new->insert(%options);
728   return $error if $error;
729  
730   warn "    disabling superseded package\n" if $DEBUG; 
731   $old->set('successor' => $new->pkgpart);
732   $old->set('disabled' => 'Y');
733   $error = $old->SUPER::replace; # don't change its options/pkg_svc records
734   return $error if $error;
735
736   warn "  propagating changes to family" if $DEBUG;
737   $new->propagate($old);
738 }
739
740 =item propagate OLD
741
742 If any of certain fields have changed from OLD to this package, then,
743 for all packages in the same lineage as this one, sets those fields 
744 to their values in this package.
745
746 =cut
747
748 my @propagate_fields = (
749   qw( pkg classnum setup_cost recur_cost taxclass
750   setuptax recurtax pay_weight credit_weight
751   )
752 );
753
754 sub propagate {
755   my $new = shift;
756   my $old = shift;
757   my %fields = (
758     map { $_ => $new->get($_) }
759     grep { $new->get($_) ne $old->get($_) }
760     @propagate_fields
761   );
762
763   my @part_pkg = qsearch('part_pkg', { 
764       'family_pkgpart' => $new->family_pkgpart 
765   });
766   my @error;
767   foreach my $part_pkg ( @part_pkg ) {
768     my $pkgpart = $part_pkg->pkgpart;
769     next if $pkgpart == $new->pkgpart; # don't modify $new
770     warn "    propagating to pkgpart $pkgpart\n" if $DEBUG;
771     foreach ( keys %fields ) {
772       $part_pkg->set($_, $fields{$_});
773     }
774     # SUPER::replace to avoid changing non-core fields
775     my $error = $part_pkg->SUPER::replace;
776     push @error, "pkgpart $pkgpart: $error"
777       if $error;
778   }
779   join("\n", @error);
780 }
781
782 =item pkg_locale LOCALE
783
784 Returns a customer-viewable string representing this package for the given
785 locale, from the part_pkg_msgcat table.  If the given locale is empty or no
786 localized string is found, returns the base pkg field.
787
788 =cut
789
790 sub pkg_locale {
791   my( $self, $locale ) = @_;
792   return $self->pkg unless $locale;
793   my $part_pkg_msgcat = $self->part_pkg_msgcat($locale) or return $self->pkg;
794   $part_pkg_msgcat->pkg;
795 }
796
797 =item part_pkg_msgcat LOCALE
798
799 Like pkg_locale, but returns the FS::part_pkg_msgcat object itself.
800
801 =cut
802
803 sub part_pkg_msgcat {
804   my( $self, $locale ) = @_;
805   qsearchs( 'part_pkg_msgcat', {
806     pkgpart => $self->pkgpart,
807     locale  => $locale,
808   });
809 }
810
811 =item pkg_comment [ OPTION => VALUE... ]
812
813 Returns an (internal) string representing this package.  Currently,
814 "pkgpart: pkg - comment", is returned.  "pkg - comment" may be returned in the
815 future, omitting pkgpart.  The comment will have '(CUSTOM) ' prepended if
816 custom is Y.
817
818 If the option nopkgpart is true then the "pkgpart: ' is omitted.
819
820 =cut
821
822 sub pkg_comment {
823   my $self = shift;
824   my %opt = @_;
825
826   #$self->pkg. ' - '. $self->comment;
827   #$self->pkg. ' ('. $self->comment. ')';
828   my $pre = $opt{nopkgpart} ? '' : $self->pkgpart. ': ';
829   $pre. $self->pkg. ' - '. $self->custom_comment;
830 }
831
832 sub price_info { # safety, in case a part_pkg hasn't defined price_info
833     '';
834 }
835
836 sub custom_comment {
837   my $self = shift;
838   ( $self->custom ? '(CUSTOM) ' : '' ). $self->comment . ' ' . $self->price_info;
839 }
840
841 =item pkg_class
842
843 Returns the package class, as an FS::pkg_class object, or the empty string
844 if there is no package class.
845
846 =cut
847
848 sub pkg_class {
849   my $self = shift;
850   if ( $self->classnum ) {
851     qsearchs('pkg_class', { 'classnum' => $self->classnum } );
852   } else {
853     return '';
854   }
855 }
856
857 =item addon_pkg_class
858
859 Returns the add-on package class, as an FS::pkg_class object, or the empty
860 string if there is no add-on package class.
861
862 =cut
863
864 sub addon_pkg_class {
865   my $self = shift;
866   if ( $self->addon_classnum ) {
867     qsearchs('pkg_class', { 'classnum' => $self->addon_classnum } );
868   } else {
869     return '';
870   }
871 }
872
873 =item categoryname 
874
875 Returns the package category name, or the empty string if there is no package
876 category.
877
878 =cut
879
880 sub categoryname {
881   my $self = shift;
882   my $pkg_class = $self->pkg_class;
883   $pkg_class
884     ? $pkg_class->categoryname
885     : '';
886 }
887
888 =item classname 
889
890 Returns the package class name, or the empty string if there is no package
891 class.
892
893 =cut
894
895 sub classname {
896   my $self = shift;
897   my $pkg_class = $self->pkg_class;
898   $pkg_class
899     ? $pkg_class->classname
900     : '';
901 }
902
903 =item addon_classname 
904
905 Returns the add-on package class name, or the empty string if there is no
906 add-on package class.
907
908 =cut
909
910 sub addon_classname {
911   my $self = shift;
912   my $pkg_class = $self->addon_pkg_class;
913   $pkg_class
914     ? $pkg_class->classname
915     : '';
916 }
917
918 =item agent 
919
920 Returns the associated agent for this event, if any, as an FS::agent object.
921
922 =cut
923
924 sub agent {
925   my $self = shift;
926   qsearchs('agent', { 'agentnum' => $self->agentnum } );
927 }
928
929 =item pkg_svc [ HASHREF | OPTION => VALUE ]
930
931 Returns all FS::pkg_svc objects (see L<FS::pkg_svc>) for this package
932 definition (with non-zero quantity).
933
934 One option is available, I<disable_linked>.  If set true it will return the
935 services for this package definition alone, omitting services from any add-on
936 packages.
937
938 =cut
939
940 =item type_pkgs
941
942 Returns all FS::type_pkgs objects (see L<FS::type_pkgs>) for this package
943 definition.
944
945 =cut
946
947 sub type_pkgs {
948   my $self = shift;
949   qsearch('type_pkgs', { 'pkgpart' => $self->pkgpart } );
950 }
951
952 sub pkg_svc {
953   my $self = shift;
954
955 #  #sort { $b->primary cmp $a->primary } 
956 #    grep { $_->quantity }
957 #      qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
958
959   my $opt = ref($_[0]) ? $_[0] : { @_ };
960   my %pkg_svc = map  { $_->svcpart => $_ }
961                 grep { $_->quantity }
962                 qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
963
964   unless ( $opt->{disable_linked} ) {
965     foreach my $dst_pkg ( map $_->dst_pkg, $self->svc_part_pkg_link ) {
966       my @pkg_svc = grep { $_->quantity }
967                     qsearch( 'pkg_svc', { pkgpart=>$dst_pkg->pkgpart } );
968       foreach my $pkg_svc ( @pkg_svc ) {
969         if ( $pkg_svc{$pkg_svc->svcpart} ) {
970           my $quantity = $pkg_svc{$pkg_svc->svcpart}->quantity;
971           $pkg_svc{$pkg_svc->svcpart}->quantity($quantity + $pkg_svc->quantity);
972         } else {
973           $pkg_svc{$pkg_svc->svcpart} = $pkg_svc;
974         }
975       }
976     }
977   }
978
979   values(%pkg_svc);
980
981 }
982
983 =item svcpart [ SVCDB ]
984
985 Returns the svcpart of the primary service definition (see L<FS::part_svc>)
986 associated with this package definition (see L<FS::pkg_svc>).  Returns
987 false if there not a primary service definition or exactly one service
988 definition with quantity 1, or if SVCDB is specified and does not match the
989 svcdb of the service definition.  SVCDB can be specified as a scalar table
990 name, such as 'svc_acct', or as an arrayref of possible table names.
991
992 =cut
993
994 sub svcpart {
995   my $pkg_svc = shift->_primary_pkg_svc(@_);
996   $pkg_svc ? $pkg_svc->svcpart : '';
997 }
998
999 =item part_svc [ SVCDB ]
1000
1001 Like the B<svcpart> method, but returns the FS::part_svc object (see
1002 L<FS::part_svc>).
1003
1004 =cut
1005
1006 sub part_svc {
1007   my $pkg_svc = shift->_primary_pkg_svc(@_);
1008   $pkg_svc ? $pkg_svc->part_svc : '';
1009 }
1010
1011 sub _primary_pkg_svc {
1012   my $self = shift;
1013
1014   my $svcdb = scalar(@_) ? shift : [];
1015   $svcdb = ref($svcdb) ? $svcdb : [ $svcdb ];
1016   my %svcdb = map { $_=>1 } @$svcdb;
1017
1018   my @svcdb_pkg_svc =
1019     grep { !scalar(@$svcdb) || $svcdb{ $_->part_svc->svcdb } }
1020          $self->pkg_svc;
1021
1022   my @pkg_svc = grep { $_->primary_svc =~ /^Y/i } @svcdb_pkg_svc;
1023   @pkg_svc = grep {$_->quantity == 1 } @svcdb_pkg_svc
1024     unless @pkg_svc;
1025   return '' if scalar(@pkg_svc) != 1;
1026   $pkg_svc[0];
1027 }
1028
1029 =item svcpart_unique_svcdb SVCDB
1030
1031 Returns the svcpart of a service definition (see L<FS::part_svc>) matching
1032 SVCDB associated with this package definition (see L<FS::pkg_svc>).  Returns
1033 false if there not a primary service definition for SVCDB or there are multiple
1034 service definitions for SVCDB.
1035
1036 =cut
1037
1038 sub svcpart_unique_svcdb {
1039   my( $self, $svcdb ) = @_;
1040   my @svcdb_pkg_svc = grep { ( $svcdb eq $_->part_svc->svcdb ) } $self->pkg_svc;
1041   return '' if scalar(@svcdb_pkg_svc) != 1;
1042   $svcdb_pkg_svc[0]->svcpart;
1043 }
1044
1045 =item payby
1046
1047 Returns a list of the acceptable payment types for this package.  Eventually
1048 this should come out of a database table and be editable, but currently has the
1049 following logic instead:
1050
1051 If the package is free, the single item B<BILL> is
1052 returned, otherwise, the single item B<CARD> is returned.
1053
1054 (CHEK?  LEC?  Probably shouldn't accept those by default, prone to abuse)
1055
1056 =cut
1057
1058 sub payby {
1059   my $self = shift;
1060   if ( $self->is_free ) {
1061     ( 'BILL' );
1062   } else {
1063     ( 'CARD' );
1064   }
1065 }
1066
1067 =item is_free
1068
1069 Returns true if this package is free.  
1070
1071 =cut
1072
1073 sub is_free {
1074   my $self = shift;
1075   if ( $self->can('is_free_options') ) {
1076     not grep { $_ !~ /^\s*0*(\.0*)?\s*$/ }
1077          map { $self->option($_) } 
1078              $self->is_free_options;
1079   } else {
1080     warn "FS::part_pkg::is_free: FS::part_pkg::". $self->plan. " subclass ".
1081          "provides neither is_free_options nor is_free method; returning false";
1082     0;
1083   }
1084 }
1085
1086 # whether the plan allows discounts to be applied to this package
1087 sub can_discount { 0; }
1088  
1089 # whether the plan allows changing the start date
1090 sub can_start_date { 1; }
1091   
1092 # the delay start date if present
1093 sub delay_start_date {
1094   my $self = shift;
1095
1096   my $delay = $self->delay_start or return '';
1097     
1098   my ($mday,$mon,$year) = (localtime(time))[3,4,5];
1099   timelocal(0,0,0,$mday,$mon,$year) + 86400 * $delay;
1100
1101 }
1102
1103 sub can_currency_exchange { 0; }
1104
1105 sub freqs_href {
1106   # moved to FS::Misc to make this accessible to other packages
1107   # at initialization
1108   FS::Misc::pkg_freqs();
1109 }
1110
1111 =item freq_pretty
1112
1113 Returns an english representation of the I<freq> field, such as "monthly",
1114 "weekly", "semi-annually", etc.
1115
1116 =cut
1117
1118 sub freq_pretty {
1119   my $self = shift;
1120   my $freq = $self->freq;
1121
1122   #my $freqs_href = $self->freqs_href;
1123   my $freqs_href = freqs_href();
1124
1125   if ( exists($freqs_href->{$freq}) ) {
1126     $freqs_href->{$freq};
1127   } else {
1128     my $interval = 'month';
1129     if ( $freq =~ /^(\d+)([hdw])$/ ) {
1130       my %interval = ( 'h' => 'hour', 'd'=>'day', 'w'=>'week' );
1131       $interval = $interval{$2};
1132     }
1133     if ( $1 == 1 ) {
1134       "every $interval";
1135     } else {
1136       "every $freq ${interval}s";
1137     }
1138   }
1139 }
1140
1141 =item add_freq TIMESTAMP [ FREQ ]
1142
1143 Adds a billing period of some frequency to the provided timestamp and 
1144 returns the resulting timestamp, or -1 if the frequency could not be 
1145 parsed (shouldn't happen).  By default, the frequency of this package 
1146 will be used; to override this, pass a different frequency as a second 
1147 argument.
1148
1149 =cut
1150
1151 sub add_freq {
1152   my( $self, $date, $freq ) = @_;
1153   $freq = $self->freq unless $freq;
1154
1155   #change this bit to use Date::Manip? CAREFUL with timezones (see
1156   # mailing list archive)
1157   my ($sec,$min,$hour,$mday,$mon,$year) = (localtime($date) )[0,1,2,3,4,5];
1158
1159   if ( $freq =~ /^\d+$/ ) {
1160     $mon += $freq;
1161     until ( $mon < 12 ) { $mon -= 12; $year++; }
1162
1163     $mday = 28 if $mday > 28 && FS::Conf->new->exists('anniversary-rollback');
1164
1165   } elsif ( $freq =~ /^(\d+)w$/ ) {
1166     my $weeks = $1;
1167     $mday += $weeks * 7;
1168   } elsif ( $freq =~ /^(\d+)d$/ ) {
1169     my $days = $1;
1170     $mday += $days;
1171   } elsif ( $freq =~ /^(\d+)h$/ ) {
1172     my $hours = $1;
1173     $hour += $hours;
1174   } else {
1175     return -1;
1176   }
1177
1178   timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year);
1179 }
1180
1181 =item plandata
1182
1183 For backwards compatibility, returns the plandata field as well as all options
1184 from FS::part_pkg_option.
1185
1186 =cut
1187
1188 sub plandata {
1189   my $self = shift;
1190   carp "plandata is deprecated";
1191   if ( @_ ) {
1192     $self->SUPER::plandata(@_);
1193   } else {
1194     my $plandata = $self->get('plandata');
1195     my %options = $self->options;
1196     $plandata .= join('', map { "$_=$options{$_}\n" } keys %options );
1197     $plandata;
1198   }
1199 }
1200
1201 =item part_pkg_vendor
1202
1203 Returns all vendor/external package ids as FS::part_pkg_vendor objects (see
1204 L<FS::part_pkg_vendor>).
1205
1206 =cut
1207
1208 sub part_pkg_vendor {
1209   my $self = shift;
1210   qsearch('part_pkg_vendor', { 'pkgpart' => $self->pkgpart } );
1211 }
1212
1213 =item vendor_pkg_ids
1214
1215 Returns a list of vendor/external package ids by exportnum
1216
1217 =cut
1218
1219 sub vendor_pkg_ids {
1220   my $self = shift;
1221   map { $_->exportnum => $_->vendor_pkg_id } $self->part_pkg_vendor;
1222 }
1223
1224 =item part_pkg_option
1225
1226 Returns all options as FS::part_pkg_option objects (see
1227 L<FS::part_pkg_option>).
1228
1229 =cut
1230
1231 sub part_pkg_option {
1232   my $self = shift;
1233   qsearch('part_pkg_option', { 'pkgpart' => $self->pkgpart } );
1234 }
1235
1236 =item options 
1237
1238 Returns a list of option names and values suitable for assigning to a hash.
1239
1240 =cut
1241
1242 sub options {
1243   my $self = shift;
1244   map { $_->optionname => $_->optionvalue } $self->part_pkg_option;
1245 }
1246
1247 =item option OPTIONNAME [ QUIET ]
1248
1249 Returns the option value for the given name, or the empty string.  If a true
1250 value is passed as the second argument, warnings about missing the option
1251 will be suppressed.
1252
1253 =cut
1254
1255 sub option {
1256   my( $self, $opt, $ornull ) = @_;
1257   my $part_pkg_option =
1258     qsearchs('part_pkg_option', {
1259       pkgpart    => $self->pkgpart,
1260       optionname => $opt,
1261   } );
1262   return $part_pkg_option->optionvalue if $part_pkg_option;
1263   my %plandata = map { /^(\w+)=(.*)$/; ( $1 => $2 ); }
1264                      split("\n", $self->get('plandata') );
1265   return $plandata{$opt} if exists $plandata{$opt};
1266   cluck "WARNING: (pkgpart ". $self->pkgpart. ") Package def option $opt ".
1267         "not found in options or plandata!\n"
1268     unless $ornull;
1269   '';
1270 }
1271
1272 =item part_pkg_currency [ CURRENCY ]
1273
1274 Returns all currency options as FS::part_pkg_currency objects (see
1275 L<FS::part_pkg_currency>), or, if a currency is specified, only return the
1276 objects for that currency.
1277
1278 =cut
1279
1280 sub part_pkg_currency {
1281   my $self = shift;
1282   my %hash = ( 'pkgpart' => $self->pkgpart );
1283   $hash{'currency'} = shift if @_;
1284   qsearch('part_pkg_currency', \%hash );
1285 }
1286
1287 =item part_pkg_currency_options CURRENCY
1288
1289 Returns a list of option names and values from FS::part_pkg_currency for the
1290 specified currency.
1291
1292 =cut
1293
1294 sub part_pkg_currency_options {
1295   my $self = shift;
1296   map { $_->optionname => $_->optionvalue } $self->part_pkg_currency(shift);
1297 }
1298
1299 =item part_pkg_currency_option CURRENCY OPTIONNAME
1300
1301 Returns the option value for the given name and currency.
1302
1303 =cut
1304
1305 sub part_pkg_currency_option {
1306   my( $self, $currency, $optionname ) = @_; 
1307   my $part_pkg_currency =
1308     qsearchs('part_pkg_currency', { 'pkgpart'    => $self->pkgpart,
1309                                     'currency'   => $currency,
1310                                     'optionname' => $optionname,
1311                                   }
1312             )#;
1313   #fatal if not found?  that works for our use cases from
1314   #part_pkg/currency_fixed, but isn't how we would typically/expect the method
1315   #to behave.  have to catch it there if we change it here...
1316     or die "Unknown price for ". $self->pkg_comment. " in $currency\n";
1317
1318   $part_pkg_currency->optionvalue;
1319 }
1320
1321 =item bill_part_pkg_link
1322
1323 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
1324
1325 =cut
1326
1327 sub bill_part_pkg_link {
1328   shift->_part_pkg_link('bill', @_);
1329 }
1330
1331 =item svc_part_pkg_link
1332
1333 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
1334
1335 =cut
1336
1337 sub svc_part_pkg_link {
1338   shift->_part_pkg_link('svc', @_);
1339 }
1340
1341 =item supp_part_pkg_link
1342
1343 Returns the associated part_pkg_link records of type 'supp' (supplemental
1344 packages).
1345
1346 =cut
1347
1348 sub supp_part_pkg_link {
1349   shift->_part_pkg_link('supp', @_);
1350 }
1351
1352 sub _part_pkg_link {
1353   my( $self, $type ) = @_;
1354   qsearch({ table    => 'part_pkg_link',
1355             hashref  => { 'src_pkgpart' => $self->pkgpart,
1356                           'link_type'   => $type,
1357                           #protection against infinite recursive links
1358                           'dst_pkgpart' => { op=>'!=', value=> $self->pkgpart },
1359                         },
1360             order_by => "ORDER BY hidden",
1361          });
1362 }
1363
1364 sub self_and_bill_linked {
1365   shift->_self_and_linked('bill', @_);
1366 }
1367
1368 sub self_and_svc_linked {
1369   shift->_self_and_linked('svc', @_);
1370 }
1371
1372 sub _self_and_linked {
1373   my( $self, $type, $hidden ) = @_;
1374   $hidden ||= '';
1375
1376   my @result = ();
1377   foreach ( ( $self, map { $_->dst_pkg->_self_and_linked($type, $_->hidden) }
1378                      $self->_part_pkg_link($type) ) )
1379   {
1380     $_->hidden($hidden) if $hidden;
1381     push @result, $_;
1382   }
1383
1384   (@result);
1385 }
1386
1387 =item part_pkg_taxoverride [ CLASS ]
1388
1389 Returns all associated FS::part_pkg_taxoverride objects (see
1390 L<FS::part_pkg_taxoverride>).  Limits the returned set to those
1391 of class CLASS if defined.  Class may be one of 'setup', 'recur',
1392 the empty string (default), or a usage class number (see L<FS::usage_class>).
1393 When a class is specified, the empty string class (default) is returned
1394 if no more specific values exist.
1395
1396 =cut
1397
1398 sub part_pkg_taxoverride {
1399   my $self = shift;
1400   my $class = shift;
1401
1402   my $hashref = { 'pkgpart' => $self->pkgpart };
1403   $hashref->{'usage_class'} = $class if defined($class);
1404   my @overrides = qsearch('part_pkg_taxoverride', $hashref );
1405
1406   unless ( scalar(@overrides) || !defined($class) || !$class ){
1407     $hashref->{'usage_class'} = '';
1408     @overrides = qsearch('part_pkg_taxoverride', $hashref );
1409   }
1410
1411   @overrides;
1412 }
1413
1414 =item has_taxproduct
1415
1416 Returns true if this package has any taxproduct associated with it.  
1417
1418 =cut
1419
1420 sub has_taxproduct {
1421   my $self = shift;
1422
1423   $self->taxproductnum ||
1424   scalar( grep { $_ =~/^usage_taxproductnum_/ && $self->option($_) } 
1425           keys %{ {$self->options} }
1426   )
1427
1428 }
1429
1430
1431 =item taxproduct [ CLASS ]
1432
1433 Returns the associated tax product for this package definition (see
1434 L<FS::part_pkg_taxproduct>).  CLASS may be one of 'setup', 'recur' or
1435 the usage classnum (see L<FS::usage_class>).  Returns the default
1436 tax product for this record if the more specific CLASS value does
1437 not exist.
1438
1439 =cut
1440
1441 sub taxproduct {
1442   my $self = shift;
1443   my $class = shift;
1444
1445   my $part_pkg_taxproduct;
1446
1447   my $taxproductnum = $self->taxproductnum;
1448   if ($class) { 
1449     my $class_taxproductnum = $self->option("usage_taxproductnum_$class", 1);
1450     $taxproductnum = $class_taxproductnum
1451       if $class_taxproductnum
1452   }
1453   
1454   $part_pkg_taxproduct =
1455     qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
1456
1457   unless ($part_pkg_taxproduct || $taxproductnum eq $self->taxproductnum ) {
1458     $taxproductnum = $self->taxproductnum;
1459     $part_pkg_taxproduct =
1460       qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
1461   }
1462
1463   $part_pkg_taxproduct;
1464 }
1465
1466 =item taxproduct_description [ CLASS ]
1467
1468 Returns the description of the associated tax product for this package
1469 definition (see L<FS::part_pkg_taxproduct>).
1470
1471 =cut
1472
1473 sub taxproduct_description {
1474   my $self = shift;
1475   my $part_pkg_taxproduct = $self->taxproduct(@_);
1476   $part_pkg_taxproduct ? $part_pkg_taxproduct->description : '';
1477 }
1478
1479 =item part_pkg_taxrate DATA_PROVIDER, GEOCODE, [ CLASS ]
1480
1481 Returns the package to taxrate m2m records for this package in the location
1482 specified by GEOCODE (see L<FS::part_pkg_taxrate>) and usage class CLASS.
1483 CLASS may be one of 'setup', 'recur', or one of the usage classes numbers
1484 (see L<FS::usage_class>).
1485
1486 =cut
1487
1488 sub _expand_cch_taxproductnum {
1489   my $self = shift;
1490   my $class = shift;
1491   my $part_pkg_taxproduct = $self->taxproduct($class);
1492
1493   my ($a,$b,$c,$d) = ( $part_pkg_taxproduct
1494                          ? ( split ':', $part_pkg_taxproduct->taxproduct )
1495                          : ()
1496                      );
1497   $a = '' unless $a; $b = '' unless $b; $c = '' unless $c; $d = '' unless $d;
1498   my $extra_sql = "AND ( taxproduct = '$a:$b:$c:$d'
1499                       OR taxproduct = '$a:$b:$c:'
1500                       OR taxproduct = '$a:$b:".":$d'
1501                       OR taxproduct = '$a:$b:".":' )";
1502   map { $_->taxproductnum } qsearch( { 'table'     => 'part_pkg_taxproduct',
1503                                        'hashref'   => { 'data_vendor'=>'cch' },
1504                                        'extra_sql' => $extra_sql,
1505                                    } );
1506                                      
1507 }
1508
1509 sub part_pkg_taxrate {
1510   my $self = shift;
1511   my ($data_vendor, $geocode, $class) = @_;
1512
1513   my $dbh = dbh;
1514   my $extra_sql = 'WHERE part_pkg_taxproduct.data_vendor = '.
1515                   dbh->quote($data_vendor);
1516   
1517   # CCH oddness in m2m
1518   $extra_sql .= ' AND ('.
1519     join(' OR ', map{ 'geocode = '. $dbh->quote(substr($geocode, 0, $_)) }
1520                  qw(10 5 2)
1521         ).
1522     ')';
1523   # much more CCH oddness in m2m -- this is kludgy
1524   my @tpnums = $self->_expand_cch_taxproductnum($class);
1525   if (scalar(@tpnums)) {
1526     $extra_sql .= ' AND ('.
1527                             join(' OR ', map{ "taxproductnum = $_" } @tpnums ).
1528                        ')';
1529   } else {
1530     $extra_sql .= ' AND ( 0 = 1 )';
1531   }
1532
1533   my $addl_from = 'LEFT JOIN part_pkg_taxproduct USING ( taxproductnum )';
1534   my $order_by = 'ORDER BY taxclassnum, length(geocode) desc, length(taxproduct) desc';
1535   my $select   = 'DISTINCT ON(taxclassnum) *, taxproduct';
1536
1537   # should qsearch preface columns with the table to facilitate joins?
1538   qsearch( { 'table'     => 'part_pkg_taxrate',
1539              'select'    => $select,
1540              'hashref'   => { # 'data_vendor'   => $data_vendor,
1541                               # 'taxproductnum' => $self->taxproductnum,
1542                             },
1543              'addl_from' => $addl_from,
1544              'extra_sql' => $extra_sql,
1545              'order_by'  => $order_by,
1546          } );
1547 }
1548
1549 =item part_pkg_discount
1550
1551 Returns the package to discount m2m records (see L<FS::part_pkg_discount>)
1552 for this package.
1553
1554 =cut
1555
1556 sub part_pkg_discount {
1557   my $self = shift;
1558   qsearch('part_pkg_discount', { 'pkgpart' => $self->pkgpart });
1559 }
1560
1561 =item part_pkg_usage
1562
1563 Returns the voice usage pools (see L<FS::part_pkg_usage>) defined for 
1564 this package.
1565
1566 =cut
1567
1568 sub part_pkg_usage {
1569   my $self = shift;
1570   qsearch('part_pkg_usage', { 'pkgpart' => $self->pkgpart });
1571 }
1572
1573 =item _rebless
1574
1575 Reblesses the object into the FS::part_pkg::PLAN class (if available), where
1576 PLAN is the object's I<plan> field.  There should be better docs
1577 on how to create new price plans, but until then, see L</NEW PLAN CLASSES>.
1578
1579 =cut
1580
1581 sub _rebless {
1582   my $self = shift;
1583   my $plan = $self->plan;
1584   unless ( $plan ) {
1585     cluck "no price plan found for pkgpart ". $self->pkgpart. "\n"
1586       if $DEBUG;
1587     return $self;
1588   }
1589   return $self if ref($self) =~ /::$plan$/; #already blessed into plan subclass
1590   my $class = ref($self). "::$plan";
1591   warn "reblessing $self into $class" if $DEBUG > 1;
1592   eval "use $class;";
1593   die $@ if $@;
1594   bless($self, $class) unless $@;
1595   $self;
1596 }
1597
1598 #fatal fallbacks
1599 sub calc_setup { die 'no calc_setup for '. shift->plan. "\n"; }
1600 sub calc_recur { die 'no calc_recur for '. shift->plan. "\n"; }
1601
1602 #fallback that return 0 for old legacy packages with no plan
1603 sub calc_remain { 0; }
1604 sub calc_units  { 0; }
1605
1606 #fallback for everything not based on flat.pm
1607 sub recur_temporality { 'upcoming'; }
1608 sub calc_cancel { 0; }
1609
1610 #fallback for everything except bulk.pm
1611 sub hide_svc_detail { 0; }
1612
1613 #fallback for packages that can't/won't summarize usage
1614 sub sum_usage { 0; }
1615
1616 =item recur_cost_permonth CUST_PKG
1617
1618 recur_cost divided by freq (only supported for monthly and longer frequencies)
1619
1620 =cut
1621
1622 sub recur_cost_permonth {
1623   my($self, $cust_pkg) = @_;
1624   return 0 unless $self->freq =~ /^\d+$/ && $self->freq > 0;
1625   sprintf('%.2f', $self->recur_cost / $self->freq );
1626 }
1627
1628 =item cust_bill_pkg_recur CUST_PKG
1629
1630 Actual recurring charge for the specified customer package from customer's most
1631 recent invoice
1632
1633 =cut
1634
1635 sub cust_bill_pkg_recur {
1636   my($self, $cust_pkg) = @_;
1637   my $cust_bill_pkg = qsearchs({
1638     'table'     => 'cust_bill_pkg',
1639     'addl_from' => 'LEFT JOIN cust_bill USING ( invnum )',
1640     'hashref'   => { 'pkgnum' => $cust_pkg->pkgnum,
1641                      'recur'  => { op=>'>', value=>'0' },
1642                    },
1643     'order_by'  => 'ORDER BY cust_bill._date     DESC,
1644                              cust_bill_pkg.sdate DESC
1645                      LIMIT 1
1646                    ',
1647   }) or return 0; #die "use cust_bill_pkg_recur credits with once_perinv condition";
1648   $cust_bill_pkg->recur;
1649 }
1650
1651 =item format OPTION DATA
1652
1653 Returns data formatted according to the function 'format' described
1654 in the plan info.  Returns DATA if no such function exists.
1655
1656 =cut
1657
1658 sub format {
1659   my ($self, $option, $data) = (shift, shift, shift);
1660   if (exists($plans{$self->plan}->{fields}->{$option}{format})) {
1661     &{$plans{$self->plan}->{fields}->{$option}{format}}($data);
1662   }else{
1663     $data;
1664   }
1665 }
1666
1667 =item parse OPTION DATA
1668
1669 Returns data parsed according to the function 'parse' described
1670 in the plan info.  Returns DATA if no such function exists.
1671
1672 =cut
1673
1674 sub parse {
1675   my ($self, $option, $data) = (shift, shift, shift);
1676   if (exists($plans{$self->plan}->{fields}->{$option}{parse})) {
1677     &{$plans{$self->plan}->{fields}->{$option}{parse}}($data);
1678   }else{
1679     $data;
1680   }
1681 }
1682
1683 =back
1684
1685 =cut
1686
1687 =head1 CLASS METHODS
1688
1689 =over 4
1690
1691 =cut
1692
1693 # _upgrade_data
1694 #
1695 # Used by FS::Upgrade to migrate to a new database.
1696
1697 sub _upgrade_data { # class method
1698   my($class, %opts) = @_;
1699
1700   warn "[FS::part_pkg] upgrading $class\n" if $DEBUG;
1701
1702   my @part_pkg = qsearch({
1703     'table'     => 'part_pkg',
1704     'extra_sql' => "WHERE ". join(' OR ',
1705                      'plan IS NULL', "plan = '' ",
1706                    ),
1707   });
1708
1709   foreach my $part_pkg (@part_pkg) {
1710
1711     unless ( $part_pkg->plan ) {
1712       $part_pkg->plan('flat');
1713     }
1714
1715     $part_pkg->replace;
1716
1717   }
1718
1719   # now upgrade to the explicit custom flag
1720
1721   @part_pkg = qsearch({
1722     'table'     => 'part_pkg',
1723     'hashref'   => { disabled => 'Y', custom => '' },
1724     'extra_sql' => "AND comment LIKE '(CUSTOM) %'",
1725   });
1726
1727   foreach my $part_pkg (@part_pkg) {
1728     my $new = new FS::part_pkg { $part_pkg->hash };
1729     $new->custom('Y');
1730     my $comment = $part_pkg->comment;
1731     $comment =~ s/^\(CUSTOM\) //;
1732     $comment = '(none)' unless $comment =~ /\S/;
1733     $new->comment($comment);
1734
1735     my $pkg_svc = { map { $_->svcpart => $_->quantity } $part_pkg->pkg_svc };
1736     my $primary = $part_pkg->svcpart;
1737     my $options = { $part_pkg->options };
1738
1739     my $error = $new->replace( $part_pkg,
1740                                'pkg_svc'     => $pkg_svc,
1741                                'primary_svc' => $primary,
1742                                'options'     => $options,
1743                              );
1744     die $error if $error;
1745   }
1746
1747   # set family_pkgpart on any packages that don't have it
1748   @part_pkg = qsearch('part_pkg', { 'family_pkgpart' => '' });
1749   foreach my $part_pkg (@part_pkg) {
1750     $part_pkg->set('family_pkgpart' => $part_pkg->pkgpart);
1751     my $error = $part_pkg->SUPER::replace;
1752     die $error if $error;
1753   }
1754
1755   my @part_pkg_option = qsearch('part_pkg_option',
1756     { 'optionname'  => 'unused_credit',
1757       'optionvalue' => 1,
1758     });
1759   foreach my $old_opt (@part_pkg_option) {
1760     my $pkgpart = $old_opt->pkgpart;
1761     my $error = $old_opt->delete;
1762     die $error if $error;
1763
1764     foreach (qw(unused_credit_cancel unused_credit_change)) {
1765       my $new_opt = new FS::part_pkg_option {
1766         'pkgpart'     => $pkgpart,
1767         'optionname'  => $_,
1768         'optionvalue' => 1,
1769       };
1770       $error = $new_opt->insert;
1771       die $error if $error;
1772     }
1773   }
1774
1775   # migrate use_disposition_taqua and use_disposition to disposition_in
1776   @part_pkg_option = qsearch('part_pkg_option',
1777     { 'optionname'  => { op => 'LIKE',
1778                          value => 'use_disposition%',
1779                        },
1780       'optionvalue' => 1,
1781     });
1782   my %newopts = map { $_->pkgpart => $_ } 
1783     qsearch('part_pkg_option',  { 'optionname'  => 'disposition_in', } );
1784   foreach my $old_opt (@part_pkg_option) {
1785         my $pkgpart = $old_opt->pkgpart;
1786         my $newval = $old_opt->optionname eq 'use_disposition_taqua' ? '100' 
1787                                                                   : 'ANSWERED';
1788         my $error = $old_opt->delete;
1789         die $error if $error;
1790
1791         if ( exists($newopts{$pkgpart}) ) {
1792             my $opt = $newopts{$pkgpart};
1793             $opt->optionvalue($opt->optionvalue.",$newval");
1794             $error = $opt->replace;
1795             die $error if $error;
1796         } else {
1797             my $new_opt = new FS::part_pkg_option {
1798                 'pkgpart'     => $pkgpart,
1799                 'optionname'  => 'disposition_in',
1800                 'optionvalue' => $newval,
1801               };
1802               $error = $new_opt->insert;
1803               die $error if $error;
1804               $newopts{$pkgpart} = $new_opt;
1805         }
1806   }
1807
1808   # set any package with FCC voice lines to the "VoIP with broadband" category
1809   # for backward compatibility
1810   #
1811   # recover from a bad upgrade bug
1812   my $upgrade = 'part_pkg_fcc_voip_class_FIX';
1813   if (!FS::upgrade_journal->is_done($upgrade)) {
1814     my $bad_upgrade = qsearchs('upgrade_journal', 
1815       { upgrade => 'part_pkg_fcc_voip_class' }
1816     );
1817     if ( $bad_upgrade ) {
1818       my $where = 'WHERE history_date <= '.$bad_upgrade->_date.
1819                   ' AND  history_date >  '.($bad_upgrade->_date - 3600);
1820       my @h_part_pkg_option = map { FS::part_pkg_option->new($_->hashref) }
1821         qsearch({
1822           'select'    => '*',
1823           'table'     => 'h_part_pkg_option',
1824           'hashref'   => {},
1825           'extra_sql' => "$where AND history_action = 'delete'",
1826           'order_by'  => 'ORDER BY history_date ASC',
1827         });
1828       my @h_pkg_svc = map { FS::pkg_svc->new($_->hashref) }
1829         qsearch({
1830           'select'    => '*',
1831           'table'     => 'h_pkg_svc',
1832           'hashref'   => {},
1833           'extra_sql' => "$where AND history_action = 'replace_old'",
1834           'order_by'  => 'ORDER BY history_date ASC',
1835         });
1836       my %opt;
1837       foreach my $deleted (@h_part_pkg_option, @h_pkg_svc) {
1838         my $pkgpart ||= $deleted->pkgpart;
1839         $opt{$pkgpart} ||= {
1840           options => {},
1841           pkg_svc => {},
1842           primary_svc => '',
1843           hidden_svc => {},
1844         };
1845         if ( $deleted->isa('FS::part_pkg_option') ) {
1846           $opt{$pkgpart}{options}{ $deleted->optionname } = $deleted->optionvalue;
1847         } else { # pkg_svc
1848           my $svcpart = $deleted->svcpart;
1849           $opt{$pkgpart}{pkg_svc}{$svcpart} = $deleted->quantity;
1850           $opt{$pkgpart}{hidden_svc}{$svcpart} ||= $deleted->hidden;
1851           $opt{$pkgpart}{primary_svc} = $svcpart if $deleted->primary_svc;
1852         }
1853       }
1854       foreach my $pkgpart (keys %opt) {
1855         my $part_pkg = FS::part_pkg->by_key($pkgpart);
1856         my $error = $part_pkg->replace( $part_pkg->replace_old, $opt{$pkgpart} );
1857         if ( $error ) {
1858           die "error recovering damaged pkgpart $pkgpart:\n$error\n";
1859         }
1860       }
1861     } # $bad_upgrade exists
1862     else { # do the original upgrade, but correctly this time
1863       @part_pkg = qsearch('part_pkg', {
1864           fcc_ds0s        => { op => '>', value => 0 },
1865           fcc_voip_class  => ''
1866       });
1867       foreach my $part_pkg (@part_pkg) {
1868         $part_pkg->set(fcc_voip_class => 2);
1869         my @pkg_svc = $part_pkg->pkg_svc;
1870         my %quantity = map {$_->svcpart, $_->quantity} @pkg_svc;
1871         my %hidden   = map {$_->svcpart, $_->hidden  } @pkg_svc;
1872         my $error = $part_pkg->replace(
1873           $part_pkg->replace_old,
1874           options     => { $part_pkg->options },
1875           pkg_svc     => \%quantity,
1876           hidden_svc  => \%hidden,
1877           primary_svc => ($part_pkg->svcpart || ''),
1878         );
1879         die $error if $error;
1880       }
1881     }
1882     FS::upgrade_journal->set_done($upgrade);
1883   }
1884
1885 }
1886
1887 =item curuser_pkgs_sql
1888
1889 Returns an SQL fragment for searching for packages the current user can
1890 use, either via part_pkg.agentnum directly, or via agent type (see
1891 L<FS::type_pkgs>).
1892
1893 =cut
1894
1895 sub curuser_pkgs_sql {
1896   my $class = shift;
1897
1898   $class->_pkgs_sql( $FS::CurrentUser::CurrentUser->agentnums );
1899
1900 }
1901
1902 =item agent_pkgs_sql AGENT | AGENTNUM, ...
1903
1904 Returns an SQL fragment for searching for packages the provided agent or agents
1905 can use, either via part_pkg.agentnum directly, or via agent type (see
1906 L<FS::type_pkgs>).
1907
1908 =cut
1909
1910 sub agent_pkgs_sql {
1911   my $class = shift;  #i'm a class method, not a sub (the question is... why??)
1912   my @agentnums = map { ref($_) ? $_->agentnum : $_ } @_;
1913
1914   $class->_pkgs_sql(@agentnums); #is this why
1915
1916 }
1917
1918 sub _pkgs_sql {
1919   my( $class, @agentnums ) = @_;
1920   my $agentnums = join(',', @agentnums);
1921
1922   "
1923     (
1924       ( agentnum IS NOT NULL AND agentnum IN ($agentnums) )
1925       OR ( agentnum IS NULL
1926            AND EXISTS ( SELECT 1
1927                           FROM type_pkgs
1928                             LEFT JOIN agent_type USING ( typenum )
1929                             LEFT JOIN agent AS typeagent USING ( typenum )
1930                           WHERE type_pkgs.pkgpart = part_pkg.pkgpart
1931                             AND typeagent.agentnum IN ($agentnums)
1932                       )
1933          )
1934     )
1935   ";
1936
1937 }
1938
1939 =back
1940
1941 =head1 SUBROUTINES
1942
1943 =over 4
1944
1945 =item plan_info
1946
1947 =cut
1948
1949 #false laziness w/part_export & cdr
1950 my %info;
1951 foreach my $INC ( @INC ) {
1952   warn "globbing $INC/FS/part_pkg/*.pm\n" if $DEBUG;
1953   foreach my $file ( glob("$INC/FS/part_pkg/*.pm") ) {
1954     warn "attempting to load plan info from $file\n" if $DEBUG;
1955     $file =~ /\/(\w+)\.pm$/ or do {
1956       warn "unrecognized file in $INC/FS/part_pkg/: $file\n";
1957       next;
1958     };
1959     my $mod = $1;
1960     my $info = eval "use FS::part_pkg::$mod; ".
1961                     "\\%FS::part_pkg::$mod\::info;";
1962     if ( $@ ) {
1963       die "error using FS::part_pkg::$mod (skipping): $@\n" if $@;
1964       next;
1965     }
1966     unless ( keys %$info ) {
1967       warn "no %info hash found in FS::part_pkg::$mod, skipping\n";
1968       next;
1969     }
1970     warn "got plan info from FS::part_pkg::$mod: $info\n" if $DEBUG;
1971     #if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
1972     #  warn "skipping disabled plan FS::part_pkg::$mod" if $DEBUG;
1973     #  next;
1974     #}
1975     $info{$mod} = $info;
1976     $info->{'weight'} ||= 0; # quiet warnings
1977   }
1978 }
1979
1980 # copy one level deep to allow replacement of fields and fieldorder
1981 tie %plans, 'Tie::IxHash',
1982   map  { my %infohash = %{ $info{$_} }; 
1983           $_ => \%infohash }
1984   sort { $info{$a}->{'weight'} <=> $info{$b}->{'weight'} }
1985   keys %info;
1986
1987 # inheritance of plan options
1988 foreach my $name (keys(%info)) {
1989   if (exists($info{$name}->{'disabled'}) and $info{$name}->{'disabled'}) {
1990     warn "skipping disabled plan FS::part_pkg::$name" if $DEBUG;
1991     delete $plans{$name};
1992     next;
1993   }
1994   my $parents = $info{$name}->{'inherit_fields'} || [];
1995   my (%fields, %field_exists, @fieldorder);
1996   foreach my $parent ($name, @$parents) {
1997     if ( !exists($info{$parent}) ) {
1998       warn "$name tried to inherit from nonexistent '$parent'\n";
1999       next;
2000     }
2001     %fields = ( # avoid replacing existing fields
2002       %{ $info{$parent}->{'fields'} || {} },
2003       %fields
2004     );
2005     foreach (@{ $info{$parent}->{'fieldorder'} || [] }) {
2006       # avoid duplicates
2007       next if $field_exists{$_};
2008       $field_exists{$_} = 1;
2009       # allow inheritors to remove inherited fields from the fieldorder
2010       push @fieldorder, $_ if !exists($fields{$_}) or
2011                               !exists($fields{$_}->{'disabled'});
2012     }
2013   }
2014   $plans{$name}->{'fields'} = \%fields;
2015   $plans{$name}->{'fieldorder'} = \@fieldorder;
2016 }
2017
2018 sub plan_info {
2019   \%plans;
2020 }
2021
2022
2023 =back
2024
2025 =head1 NEW PLAN CLASSES
2026
2027 A module should be added in FS/FS/part_pkg/  Eventually, an example may be
2028 found in eg/plan_template.pm.  Until then, it is suggested that you use the
2029 other modules in FS/FS/part_pkg/ as a guide.
2030
2031 =head1 BUGS
2032
2033 The delete method is unimplemented.
2034
2035 setup and recur semantics are not yet defined (and are implemented in
2036 FS::cust_bill.  hmm.).  now they're deprecated and need to go.
2037
2038 plandata should go
2039
2040 part_pkg_taxrate is Pg specific
2041
2042 replace should be smarter about managing the related tables (options, pkg_svc)
2043
2044 =head1 SEE ALSO
2045
2046 L<FS::Record>, L<FS::cust_pkg>, L<FS::type_pkgs>, L<FS::pkg_svc>, L<Safe>.
2047 schema.html from the base documentation.
2048
2049 =cut
2050
2051 1;
2052