hidden pkg_svc flag, RT#9871
[freeside.git] / FS / FS / part_pkg.pm
1 package FS::part_pkg;
2
3 use strict;
4 use vars qw( @ISA %plans $DEBUG $setup_hack $skip_pkg_svc_hack );
5 use Carp qw(carp cluck confess);
6 use Scalar::Util qw( blessed );
7 use Time::Local qw( timelocal_nocheck );
8 use Tie::IxHash;
9 use FS::Conf;
10 use FS::Record qw( qsearch qsearchs dbh dbdef );
11 use FS::pkg_svc;
12 use FS::part_svc;
13 use FS::cust_pkg;
14 use FS::agent_type;
15 use FS::type_pkgs;
16 use FS::part_pkg_option;
17 use FS::pkg_class;
18 use FS::agent;
19 use FS::part_pkg_taxrate;
20 use FS::part_pkg_taxoverride;
21 use FS::part_pkg_taxproduct;
22 use FS::part_pkg_link;
23 use FS::part_pkg_discount;
24
25 @ISA = qw( FS::m2m_Common FS::option_Common );
26 $DEBUG = 0;
27 $setup_hack = 0;
28 $skip_pkg_svc_hack = 0;
29
30 =head1 NAME
31
32 FS::part_pkg - Object methods for part_pkg objects
33
34 =head1 SYNOPSIS
35
36   use FS::part_pkg;
37
38   $record = new FS::part_pkg \%hash
39   $record = new FS::part_pkg { 'column' => 'value' };
40
41   $custom_record = $template_record->clone;
42
43   $error = $record->insert;
44
45   $error = $new_record->replace($old_record);
46
47   $error = $record->delete;
48
49   $error = $record->check;
50
51   @pkg_svc = $record->pkg_svc;
52
53   $svcnum = $record->svcpart;
54   $svcnum = $record->svcpart( 'svc_acct' );
55
56 =head1 DESCRIPTION
57
58 An FS::part_pkg object represents a package definition.  FS::part_pkg
59 inherits from FS::Record.  The following fields are currently supported:
60
61 =over 4
62
63 =item pkgpart - primary key (assigned automatically for new package definitions)
64
65 =item pkg - Text name of this package definition (customer-viewable)
66
67 =item comment - Text name of this package definition (non-customer-viewable)
68
69 =item classnum - Optional package class (see L<FS::pkg_class>)
70
71 =item promo_code - Promotional code
72
73 =item setup - Setup fee expression (deprecated)
74
75 =item freq - Frequency of recurring fee
76
77 =item recur - Recurring fee expression (deprecated)
78
79 =item setuptax - Setup fee tax exempt flag, empty or `Y'
80
81 =item recurtax - Recurring fee tax exempt flag, empty or `Y'
82
83 =item taxclass - Tax class 
84
85 =item plan - Price plan
86
87 =item plandata - Price plan data (deprecated - see L<FS::part_pkg_option> instead)
88
89 =item disabled - Disabled flag, empty or `Y'
90
91 =item custom - Custom flag, empty or `Y'
92
93 =item setup_cost - for cost tracking
94
95 =item recur_cost - for cost tracking
96
97 =item pay_weight - Weight (relative to credit_weight and other package definitions) that controls payment application to specific line items.
98
99 =item credit_weight - Weight (relative to other package definitions) that controls credit application to specific line items.
100
101 =item agentnum - Optional agentnum (see L<FS::agent>)
102
103 =item fcc_ds0s - Optional DS0 equivalency number for FCC form 477
104
105 =back
106
107 =head1 METHODS
108
109 =over 4 
110
111 =item new HASHREF
112
113 Creates a new package definition.  To add the package definition to
114 the database, see L<"insert">.
115
116 =cut
117
118 sub table { 'part_pkg'; }
119
120 =item clone
121
122 An alternate constructor.  Creates a new package definition by duplicating
123 an existing definition.  A new pkgpart is assigned and the custom flag is
124 set to Y.  To add the package definition to the database, see L<"insert">.
125
126 =cut
127
128 sub clone {
129   my $self = shift;
130   my $class = ref($self);
131   my %hash = $self->hash;
132   $hash{'pkgpart'} = '';
133   $hash{'custom'} = 'Y';
134   #new FS::part_pkg ( \%hash ); # ?
135   new $class ( \%hash ); # ?
136 }
137
138 =item insert [ , OPTION => VALUE ... ]
139
140 Adds this package definition to the database.  If there is an error,
141 returns the error, otherwise returns false.
142
143 Currently available options are: I<pkg_svc>, I<primary_svc>, I<cust_pkg>, 
144 I<custnum_ref> and I<options>.
145
146 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
147 values, appropriate FS::pkg_svc records will be inserted.  I<hidden_svc> can 
148 be set to a hashref of svcparts and flag values ('Y' or '') to set the 
149 'hidden' field in these records.
150
151 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
152 FS::pkg_svc record will be updated.
153
154 If I<cust_pkg> is set to a pkgnum of a FS::cust_pkg record (or the FS::cust_pkg
155 record itself), the object will be updated to point to this package definition.
156
157 In conjunction with I<cust_pkg>, if I<custnum_ref> is set to a scalar reference,
158 the scalar will be updated with the custnum value from the cust_pkg record.
159
160 If I<tax_overrides> is set to a hashref with usage classes as keys and comma
161 separated tax class numbers as values, appropriate FS::part_pkg_taxoverride
162 records will be inserted.
163
164 If I<options> is set to a hashref of options, appropriate FS::part_pkg_option
165 records will be inserted.
166
167 =cut
168
169 sub insert {
170   my $self = shift;
171   my %options = @_;
172   warn "FS::part_pkg::insert called on $self with options ".
173        join(', ', map "$_=>$options{$_}", keys %options)
174     if $DEBUG;
175
176   local $SIG{HUP} = 'IGNORE';
177   local $SIG{INT} = 'IGNORE';
178   local $SIG{QUIT} = 'IGNORE';
179   local $SIG{TERM} = 'IGNORE';
180   local $SIG{TSTP} = 'IGNORE';
181   local $SIG{PIPE} = 'IGNORE';
182
183   my $oldAutoCommit = $FS::UID::AutoCommit;
184   local $FS::UID::AutoCommit = 0;
185   my $dbh = dbh;
186
187   warn "  inserting part_pkg record" if $DEBUG;
188   my $error = $self->SUPER::insert( $options{options} );
189   if ( $error ) {
190     $dbh->rollback if $oldAutoCommit;
191     return $error;
192   }
193
194   my $conf = new FS::Conf;
195   if ( $conf->exists('agent_defaultpkg') ) {
196     warn "  agent_defaultpkg set; allowing all agents to purchase package"
197       if $DEBUG;
198     foreach my $agent_type ( qsearch('agent_type', {} ) ) {
199       my $type_pkgs = new FS::type_pkgs({
200         'typenum' => $agent_type->typenum,
201         'pkgpart' => $self->pkgpart,
202       });
203       my $error = $type_pkgs->insert;
204       if ( $error ) {
205         $dbh->rollback if $oldAutoCommit;
206         return $error;
207       }
208     }
209   }
210
211   warn "  inserting part_pkg_taxoverride records" if $DEBUG;
212   my %overrides = %{ $options{'tax_overrides'} || {} };
213   foreach my $usage_class ( keys %overrides ) {
214     my $override =
215       ( exists($overrides{$usage_class}) && defined($overrides{$usage_class}) )
216         ? $overrides{$usage_class}
217         : '';
218     my @overrides = (grep "$_", split(',', $override) );
219     my $error = $self->process_m2m (
220                   'link_table'   => 'part_pkg_taxoverride',
221                   'target_table' => 'tax_class',
222                   'hashref'      => { 'usage_class' => $usage_class },
223                   'params'       => \@overrides,
224                 );
225     if ( $error ) {
226       $dbh->rollback if $oldAutoCommit;
227       return $error;
228     }
229   }
230
231   unless ( $skip_pkg_svc_hack ) {
232
233     warn "  inserting pkg_svc records" if $DEBUG;
234     my $pkg_svc = $options{'pkg_svc'} || {};
235     my $hidden_svc = $options{'hidden_svc'} || {};
236     foreach my $part_svc ( qsearch('part_svc', {} ) ) {
237       my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
238       my $primary_svc =
239         ( $options{'primary_svc'} && $options{'primary_svc'}==$part_svc->svcpart )
240           ? 'Y'
241           : '';
242
243       my $pkg_svc = new FS::pkg_svc( {
244         'pkgpart'     => $self->pkgpart,
245         'svcpart'     => $part_svc->svcpart,
246         'quantity'    => $quantity, 
247         'primary_svc' => $primary_svc,
248         'hidden'      => $hidden_svc->{$part_svc->svcpart},
249       } );
250       my $error = $pkg_svc->insert;
251       if ( $error ) {
252         $dbh->rollback if $oldAutoCommit;
253         return $error;
254       }
255     }
256
257   }
258
259   if ( $options{'cust_pkg'} ) {
260     warn "  updating cust_pkg record " if $DEBUG;
261     my $old_cust_pkg =
262       ref($options{'cust_pkg'})
263         ? $options{'cust_pkg'}
264         : qsearchs('cust_pkg', { pkgnum => $options{'cust_pkg'} } );
265     ${ $options{'custnum_ref'} } = $old_cust_pkg->custnum
266       if $options{'custnum_ref'};
267     my %hash = $old_cust_pkg->hash;
268     $hash{'pkgpart'} = $self->pkgpart,
269     my $new_cust_pkg = new FS::cust_pkg \%hash;
270     local($FS::cust_pkg::disable_agentcheck) = 1;
271     my $error = $new_cust_pkg->replace($old_cust_pkg);
272     if ( $error ) {
273       $dbh->rollback if $oldAutoCommit;
274       return "Error modifying cust_pkg record: $error";
275     }
276   }
277
278   warn "  commiting transaction" if $DEBUG;
279   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
280
281   '';
282 }
283
284 =item delete
285
286 Currently unimplemented.
287
288 =cut
289
290 sub delete {
291   return "Can't (yet?) delete package definitions.";
292 # check & make sure the pkgpart isn't in cust_pkg or type_pkgs?
293 }
294
295 =item replace OLD_RECORD [ , OPTION => VALUE ... ]
296
297 Replaces OLD_RECORD with this one in the database.  If there is an error,
298 returns the error, otherwise returns false.
299
300 Currently available options are: I<pkg_svc>, I<hidden_svc>, I<primary_svc> 
301 and I<options>
302
303 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
304 values, the appropriate FS::pkg_svc records will be replaced.  I<hidden_svc>
305 can be set to a hashref of svcparts and flag values ('Y' or '') to set the 
306 'hidden' field in these records.
307
308 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
309 FS::pkg_svc record will be updated.
310
311 If I<options> is set to a hashref, the appropriate FS::part_pkg_option records
312 will be replaced.
313
314 =cut
315
316 sub replace {
317   my $new = shift;
318
319   my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
320               ? shift
321               : $new->replace_old;
322
323   my $options = 
324     ( ref($_[0]) eq 'HASH' )
325       ? shift
326       : { @_ };
327
328   $options->{options} = {} unless defined($options->{options});
329
330   warn "FS::part_pkg::replace called on $new to replace $old with options".
331        join(', ', map "$_ => ". $options->{$_}, keys %$options)
332     if $DEBUG;
333
334   local $SIG{HUP} = 'IGNORE';
335   local $SIG{INT} = 'IGNORE';
336   local $SIG{QUIT} = 'IGNORE';
337   local $SIG{TERM} = 'IGNORE';
338   local $SIG{TSTP} = 'IGNORE';
339   local $SIG{PIPE} = 'IGNORE';
340
341   my $oldAutoCommit = $FS::UID::AutoCommit;
342   local $FS::UID::AutoCommit = 0;
343   my $dbh = dbh;
344
345   #plandata shit stays in replace for upgrades until after 2.0 (or edit
346   #_upgrade_data)
347   warn "  saving legacy plandata" if $DEBUG;
348   my $plandata = $new->get('plandata');
349   $new->set('plandata', '');
350
351   warn "  deleting old part_pkg_option records" if $DEBUG;
352   foreach my $part_pkg_option ( $old->part_pkg_option ) {
353     my $error = $part_pkg_option->delete;
354     if ( $error ) {
355       $dbh->rollback if $oldAutoCommit;
356       return $error;
357     }
358   }
359
360   warn "  replacing part_pkg record" if $DEBUG;
361   my $error = $new->SUPER::replace($old, $options->{options} );
362   if ( $error ) {
363     $dbh->rollback if $oldAutoCommit;
364     return $error;
365   }
366
367   warn "  inserting part_pkg_option records for plandata: $plandata|" if $DEBUG;
368   foreach my $part_pkg_option ( 
369     map { /^(\w+)=(.*)$/ or do { $dbh->rollback if $oldAutoCommit;
370                                  return "illegal plandata: $plandata";
371                                };
372           new FS::part_pkg_option {
373             'pkgpart'     => $new->pkgpart,
374             'optionname'  => $1,
375             'optionvalue' => $2,
376           };
377         }
378     split("\n", $plandata)
379   ) {
380     my $error = $part_pkg_option->insert;
381     if ( $error ) {
382       $dbh->rollback if $oldAutoCommit;
383       return $error;
384     }
385   }
386
387   warn "  replacing pkg_svc records" if $DEBUG;
388   my $pkg_svc = $options->{'pkg_svc'} || {};
389   my $hidden_svc = $options->{'hidden_svc'} || {};
390   foreach my $part_svc ( qsearch('part_svc', {} ) ) {
391     my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
392     my $hidden = $hidden_svc->{$part_svc->svcpart} || '';
393     my $primary_svc =
394       ( defined($options->{'primary_svc'}) && $options->{'primary_svc'}
395         && $options->{'primary_svc'} == $part_svc->svcpart
396       )
397         ? 'Y'
398         : '';
399
400     my $old_pkg_svc = qsearchs('pkg_svc', {
401         'pkgpart' => $old->pkgpart,
402         'svcpart' => $part_svc->svcpart,
403       }
404     );
405     my $old_quantity = 0;
406     my $old_primary_svc = '';
407     my $old_hidden = '';
408     if ( $old_pkg_svc ) {
409       $old_quantity = $old_pkg_svc->quantity;
410       $old_primary_svc = $old_pkg_svc->primary_svc 
411         if $old_pkg_svc->dbdef_table->column('primary_svc'); # is this needed?
412       $old_hidden = $old_pkg_svc->hidden;
413     }
414  
415     next unless $old_quantity != $quantity || 
416                 $old_primary_svc ne $primary_svc ||
417                 $old_hidden ne $hidden;
418   
419     my $new_pkg_svc = new FS::pkg_svc( {
420       'pkgsvcnum'   => ( $old_pkg_svc ? $old_pkg_svc->pkgsvcnum : '' ),
421       'pkgpart'     => $new->pkgpart,
422       'svcpart'     => $part_svc->svcpart,
423       'quantity'    => $quantity, 
424       'primary_svc' => $primary_svc,
425       'hidden'      => $hidden,
426     } );
427     my $error = $old_pkg_svc
428                   ? $new_pkg_svc->replace($old_pkg_svc)
429                   : $new_pkg_svc->insert;
430     if ( $error ) {
431       $dbh->rollback if $oldAutoCommit;
432       return $error;
433     }
434   }
435
436   warn "  commiting transaction" if $DEBUG;
437   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
438   '';
439 }
440
441 =item check
442
443 Checks all fields to make sure this is a valid package definition.  If
444 there is an error, returns the error, otherwise returns false.  Called by the
445 insert and replace methods.
446
447 =cut
448
449 sub check {
450   my $self = shift;
451   warn "FS::part_pkg::check called on $self" if $DEBUG;
452
453   for (qw(setup recur plandata)) {
454     #$self->set($_=>0) if $self->get($_) =~ /^\s*$/; }
455     return "Use of $_ field is deprecated; set a plan and options: ".
456            $self->get($_)
457       if length($self->get($_));
458     $self->set($_, '');
459   }
460
461   if ( $self->dbdef_table->column('freq')->type =~ /(int)/i ) {
462     my $error = $self->ut_number('freq');
463     return $error if $error;
464   } else {
465     $self->freq =~ /^(\d+[hdw]?)$/
466       or return "Illegal or empty freq: ". $self->freq;
467     $self->freq($1);
468   }
469
470   my @null_agentnum_right = ( 'Edit global package definitions' );
471   push @null_agentnum_right, 'One-time charge'
472     if $self->freq =~ /^0/;
473   push @null_agentnum_right, 'Customize customer package'
474     if $self->disabled eq 'Y'; #good enough
475
476   my $error = $self->ut_numbern('pkgpart')
477     || $self->ut_text('pkg')
478     || $self->ut_text('comment')
479     || $self->ut_textn('promo_code')
480     || $self->ut_alphan('plan')
481     || $self->ut_enum('setuptax', [ '', 'Y' ] )
482     || $self->ut_enum('recurtax', [ '', 'Y' ] )
483     || $self->ut_textn('taxclass')
484     || $self->ut_enum('disabled', [ '', 'Y' ] )
485     || $self->ut_enum('custom', [ '', 'Y' ] )
486     || $self->ut_enum('no_auto', [ '', 'Y' ])
487     #|| $self->ut_moneyn('setup_cost')
488     #|| $self->ut_moneyn('recur_cost')
489     || $self->ut_floatn('setup_cost')
490     || $self->ut_floatn('recur_cost')
491     || $self->ut_floatn('pay_weight')
492     || $self->ut_floatn('credit_weight')
493     || $self->ut_numbern('taxproductnum')
494     || $self->ut_foreign_keyn('classnum',       'pkg_class', 'classnum')
495     || $self->ut_foreign_keyn('addon_classnum', 'pkg_class', 'classnum')
496     || $self->ut_foreign_keyn('taxproductnum',
497                               'part_pkg_taxproduct',
498                               'taxproductnum'
499                              )
500     || ( $setup_hack
501            ? $self->ut_foreign_keyn('agentnum', 'agent', 'agentnum' )
502            : $self->ut_agentnum_acl('agentnum', \@null_agentnum_right)
503        )
504     || $self->ut_numbern('fcc_ds0s')
505     || $self->SUPER::check
506   ;
507   return $error if $error;
508
509   return 'Unknown plan '. $self->plan
510     unless exists($plans{$self->plan});
511
512   my $conf = new FS::Conf;
513   return 'Taxclass is required'
514     if ! $self->taxclass && $conf->exists('require_taxclasses');
515
516   '';
517 }
518
519 =item pkg_comment [ OPTION => VALUE... ]
520
521 Returns an (internal) string representing this package.  Currently,
522 "pkgpart: pkg - comment", is returned.  "pkg - comment" may be returned in the
523 future, omitting pkgpart.  The comment will have '(CUSTOM) ' prepended if
524 custom is Y.
525
526 If the option nopkgpart is true then the "pkgpart: ' is omitted.
527
528 =cut
529
530 sub pkg_comment {
531   my $self = shift;
532   my %opt = @_;
533
534   #$self->pkg. ' - '. $self->comment;
535   #$self->pkg. ' ('. $self->comment. ')';
536   my $pre = $opt{nopkgpart} ? '' : $self->pkgpart. ': ';
537   $pre. $self->pkg. ' - '. $self->custom_comment;
538 }
539
540 sub custom_comment {
541   my $self = shift;
542   ( $self->custom ? '(CUSTOM) ' : '' ). $self->comment;
543 }
544
545 =item pkg_class
546
547 Returns the package class, as an FS::pkg_class object, or the empty string
548 if there is no package class.
549
550 =cut
551
552 sub pkg_class {
553   my $self = shift;
554   if ( $self->classnum ) {
555     qsearchs('pkg_class', { 'classnum' => $self->classnum } );
556   } else {
557     return '';
558   }
559 }
560
561 =item addon_pkg_class
562
563 Returns the add-on package class, as an FS::pkg_class object, or the empty
564 string if there is no add-on package class.
565
566 =cut
567
568 sub addon_pkg_class {
569   my $self = shift;
570   if ( $self->addon_classnum ) {
571     qsearchs('pkg_class', { 'classnum' => $self->addon_classnum } );
572   } else {
573     return '';
574   }
575 }
576
577 =item categoryname 
578
579 Returns the package category name, or the empty string if there is no package
580 category.
581
582 =cut
583
584 sub categoryname {
585   my $self = shift;
586   my $pkg_class = $self->pkg_class;
587   $pkg_class
588     ? $pkg_class->categoryname
589     : '';
590 }
591
592 =item classname 
593
594 Returns the package class name, or the empty string if there is no package
595 class.
596
597 =cut
598
599 sub classname {
600   my $self = shift;
601   my $pkg_class = $self->pkg_class;
602   $pkg_class
603     ? $pkg_class->classname
604     : '';
605 }
606
607 =item addon_classname 
608
609 Returns the add-on package class name, or the empty string if there is no
610 add-on package class.
611
612 =cut
613
614 sub addon_classname {
615   my $self = shift;
616   my $pkg_class = $self->addon_pkg_class;
617   $pkg_class
618     ? $pkg_class->classname
619     : '';
620 }
621
622 =item agent 
623
624 Returns the associated agent for this event, if any, as an FS::agent object.
625
626 =cut
627
628 sub agent {
629   my $self = shift;
630   qsearchs('agent', { 'agentnum' => $self->agentnum } );
631 }
632
633 =item pkg_svc [ HASHREF | OPTION => VALUE ]
634
635 Returns all FS::pkg_svc objects (see L<FS::pkg_svc>) for this package
636 definition (with non-zero quantity).
637
638 One option is available, I<disable_linked>.  If set true it will return the
639 services for this package definition alone, omitting services from any add-on
640 packages.
641
642 =cut
643
644 =item type_pkgs
645
646 Returns all FS::type_pkgs objects (see L<FS::type_pkgs>) for this package
647 definition.
648
649 =cut
650
651 sub type_pkgs {
652   my $self = shift;
653   qsearch('type_pkgs', { 'pkgpart' => $self->pkgpart } );
654 }
655
656 sub pkg_svc {
657   my $self = shift;
658
659 #  #sort { $b->primary cmp $a->primary } 
660 #    grep { $_->quantity }
661 #      qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
662
663   my $opt = ref($_[0]) ? $_[0] : { @_ };
664   my %pkg_svc = map  { $_->svcpart => $_ }
665                 grep { $_->quantity }
666                 qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
667
668   unless ( $opt->{disable_linked} ) {
669     foreach my $dst_pkg ( map $_->dst_pkg, $self->svc_part_pkg_link ) {
670       my @pkg_svc = grep { $_->quantity }
671                     qsearch( 'pkg_svc', { pkgpart=>$dst_pkg->pkgpart } );
672       foreach my $pkg_svc ( @pkg_svc ) {
673         if ( $pkg_svc{$pkg_svc->svcpart} ) {
674           my $quantity = $pkg_svc{$pkg_svc->svcpart}->quantity;
675           $pkg_svc{$pkg_svc->svcpart}->quantity($quantity + $pkg_svc->quantity);
676         } else {
677           $pkg_svc{$pkg_svc->svcpart} = $pkg_svc;
678         }
679       }
680     }
681   }
682
683   values(%pkg_svc);
684
685 }
686
687 =item svcpart [ SVCDB ]
688
689 Returns the svcpart of the primary service definition (see L<FS::part_svc>)
690 associated with this package definition (see L<FS::pkg_svc>).  Returns
691 false if there not a primary service definition or exactly one service
692 definition with quantity 1, or if SVCDB is specified and does not match the
693 svcdb of the service definition.  SVCDB can be specified as a scalar table
694 name, such as 'svc_acct', or as an arrayref of possible table names.
695
696 =cut
697
698 sub svcpart {
699   my $pkg_svc = shift->_primary_pkg_svc(@_);
700   $pkg_svc ? $pkg_svc->svcpart : '';
701 }
702
703 =item part_svc [ SVCDB ]
704
705 Like the B<svcpart> method, but returns the FS::part_svc object (see
706 L<FS::part_svc>).
707
708 =cut
709
710 sub part_svc {
711   my $pkg_svc = shift->_primary_pkg_svc(@_);
712   $pkg_svc ? $pkg_svc->part_svc : '';
713 }
714
715 sub _primary_pkg_svc {
716   my $self = shift;
717
718   my $svcdb = scalar(@_) ? shift : [];
719   $svcdb = ref($svcdb) ? $svcdb : [ $svcdb ];
720   my %svcdb = map { $_=>1 } @$svcdb;
721
722   my @svcdb_pkg_svc =
723     grep { !scalar(@$svcdb) || $svcdb{ $_->part_svc->svcdb } }
724          $self->pkg_svc;
725
726   my @pkg_svc = grep { $_->primary_svc =~ /^Y/i } @svcdb_pkg_svc;
727   @pkg_svc = grep {$_->quantity == 1 } @svcdb_pkg_svc
728     unless @pkg_svc;
729   return '' if scalar(@pkg_svc) != 1;
730   $pkg_svc[0];
731 }
732
733 =item svcpart_unique_svcdb SVCDB
734
735 Returns the svcpart of a service definition (see L<FS::part_svc>) matching
736 SVCDB associated with this package definition (see L<FS::pkg_svc>).  Returns
737 false if there not a primary service definition for SVCDB or there are multiple
738 service definitions for SVCDB.
739
740 =cut
741
742 sub svcpart_unique_svcdb {
743   my( $self, $svcdb ) = @_;
744   my @svcdb_pkg_svc = grep { ( $svcdb eq $_->part_svc->svcdb ) } $self->pkg_svc;
745   return '' if scalar(@svcdb_pkg_svc) != 1;
746   $svcdb_pkg_svc[0]->svcpart;
747 }
748
749 =item payby
750
751 Returns a list of the acceptable payment types for this package.  Eventually
752 this should come out of a database table and be editable, but currently has the
753 following logic instead:
754
755 If the package is free, the single item B<BILL> is
756 returned, otherwise, the single item B<CARD> is returned.
757
758 (CHEK?  LEC?  Probably shouldn't accept those by default, prone to abuse)
759
760 =cut
761
762 sub payby {
763   my $self = shift;
764   if ( $self->is_free ) {
765     ( 'BILL' );
766   } else {
767     ( 'CARD' );
768   }
769 }
770
771 =item is_free
772
773 Returns true if this package is free.  
774
775 =cut
776
777 sub is_free {
778   my $self = shift;
779   unless ( $self->plan ) {
780     $self->setup =~ /^\s*0+(\.0*)?\s*$/
781       && $self->recur =~ /^\s*0+(\.0*)?\s*$/;
782   } elsif ( $self->can('is_free_options') ) {
783     not grep { $_ !~ /^\s*0*(\.0*)?\s*$/ }
784          map { $self->option($_) } 
785              $self->is_free_options;
786   } else {
787     warn "FS::part_pkg::is_free: FS::part_pkg::". $self->plan. " subclass ".
788          "provides neither is_free_options nor is_free method; returning false";
789     0;
790   }
791 }
792
793 sub can_discount { 0; }
794
795 sub freqs_href {
796   # moved to FS::Misc to make this accessible to other packages
797   # at initialization
798   FS::Misc::pkg_freqs();
799 }
800
801 =item freq_pretty
802
803 Returns an english representation of the I<freq> field, such as "monthly",
804 "weekly", "semi-annually", etc.
805
806 =cut
807
808 sub freq_pretty {
809   my $self = shift;
810   my $freq = $self->freq;
811
812   #my $freqs_href = $self->freqs_href;
813   my $freqs_href = freqs_href();
814
815   if ( exists($freqs_href->{$freq}) ) {
816     $freqs_href->{$freq};
817   } else {
818     my $interval = 'month';
819     if ( $freq =~ /^(\d+)([hdw])$/ ) {
820       my %interval = ( 'h' => 'hour', 'd'=>'day', 'w'=>'week' );
821       $interval = $interval{$2};
822     }
823     if ( $1 == 1 ) {
824       "every $interval";
825     } else {
826       "every $freq ${interval}s";
827     }
828   }
829 }
830
831 =item add_freq TIMESTAMP [ FREQ ]
832
833 Adds a billing period of some frequency to the provided timestamp and 
834 returns the resulting timestamp, or -1 if the frequency could not be 
835 parsed (shouldn't happen).  By default, the frequency of this package 
836 will be used; to override this, pass a different frequency as a second 
837 argument.
838
839 =cut
840
841 sub add_freq {
842   my( $self, $date, $freq ) = @_;
843   $freq = $self->freq unless $freq;
844
845   #change this bit to use Date::Manip? CAREFUL with timezones (see
846   # mailing list archive)
847   my ($sec,$min,$hour,$mday,$mon,$year) = (localtime($date) )[0,1,2,3,4,5];
848
849   if ( $freq =~ /^\d+$/ ) {
850     $mon += $freq;
851     until ( $mon < 12 ) { $mon -= 12; $year++; }
852   } elsif ( $freq =~ /^(\d+)w$/ ) {
853     my $weeks = $1;
854     $mday += $weeks * 7;
855   } elsif ( $freq =~ /^(\d+)d$/ ) {
856     my $days = $1;
857     $mday += $days;
858   } elsif ( $freq =~ /^(\d+)h$/ ) {
859     my $hours = $1;
860     $hour += $hours;
861   } else {
862     return -1;
863   }
864
865   timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year);
866 }
867
868 =item plandata
869
870 For backwards compatibility, returns the plandata field as well as all options
871 from FS::part_pkg_option.
872
873 =cut
874
875 sub plandata {
876   my $self = shift;
877   carp "plandata is deprecated";
878   if ( @_ ) {
879     $self->SUPER::plandata(@_);
880   } else {
881     my $plandata = $self->get('plandata');
882     my %options = $self->options;
883     $plandata .= join('', map { "$_=$options{$_}\n" } keys %options );
884     $plandata;
885   }
886 }
887
888 =item part_pkg_option
889
890 Returns all options as FS::part_pkg_option objects (see
891 L<FS::part_pkg_option>).
892
893 =cut
894
895 sub part_pkg_option {
896   my $self = shift;
897   qsearch('part_pkg_option', { 'pkgpart' => $self->pkgpart } );
898 }
899
900 =item options 
901
902 Returns a list of option names and values suitable for assigning to a hash.
903
904 =cut
905
906 sub options {
907   my $self = shift;
908   map { $_->optionname => $_->optionvalue } $self->part_pkg_option;
909 }
910
911 =item option OPTIONNAME [ QUIET ]
912
913 Returns the option value for the given name, or the empty string.  If a true
914 value is passed as the second argument, warnings about missing the option
915 will be suppressed.
916
917 =cut
918
919 sub option {
920   my( $self, $opt, $ornull ) = @_;
921   my $part_pkg_option =
922     qsearchs('part_pkg_option', {
923       pkgpart    => $self->pkgpart,
924       optionname => $opt,
925   } );
926   return $part_pkg_option->optionvalue if $part_pkg_option;
927   my %plandata = map { /^(\w+)=(.*)$/; ( $1 => $2 ); }
928                      split("\n", $self->get('plandata') );
929   return $plandata{$opt} if exists $plandata{$opt};
930   cluck "WARNING: (pkgpart ". $self->pkgpart. ") Package def option $opt ".
931         "not found in options or plandata!\n"
932     unless $ornull;
933   '';
934 }
935
936 =item bill_part_pkg_link
937
938 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
939
940 =cut
941
942 sub bill_part_pkg_link {
943   shift->_part_pkg_link('bill', @_);
944 }
945
946 =item svc_part_pkg_link
947
948 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
949
950 =cut
951
952 sub svc_part_pkg_link {
953   shift->_part_pkg_link('svc', @_);
954 }
955
956 sub _part_pkg_link {
957   my( $self, $type ) = @_;
958   qsearch({ table    => 'part_pkg_link',
959             hashref  => { 'src_pkgpart' => $self->pkgpart,
960                           'link_type'   => $type,
961                           #protection against infinite recursive links
962                           'dst_pkgpart' => { op=>'!=', value=> $self->pkgpart },
963                         },
964             order_by => "ORDER BY hidden",
965          });
966 }
967
968 sub self_and_bill_linked {
969   shift->_self_and_linked('bill', @_);
970 }
971
972 sub _self_and_linked {
973   my( $self, $type, $hidden ) = @_;
974   $hidden ||= '';
975
976   my @result = ();
977   foreach ( ( $self, map { $_->dst_pkg->_self_and_linked($type, $_->hidden) }
978                      $self->_part_pkg_link($type) ) )
979   {
980     $_->hidden($hidden) if $hidden;
981     push @result, $_;
982   }
983
984   (@result);
985 }
986
987 =item part_pkg_taxoverride [ CLASS ]
988
989 Returns all associated FS::part_pkg_taxoverride objects (see
990 L<FS::part_pkg_taxoverride>).  Limits the returned set to those
991 of class CLASS if defined.  Class may be one of 'setup', 'recur',
992 the empty string (default), or a usage class number (see L<FS::usage_class>).
993 When a class is specified, the empty string class (default) is returned
994 if no more specific values exist.
995
996 =cut
997
998 sub part_pkg_taxoverride {
999   my $self = shift;
1000   my $class = shift;
1001
1002   my $hashref = { 'pkgpart' => $self->pkgpart };
1003   $hashref->{'usage_class'} = $class if defined($class);
1004   my @overrides = qsearch('part_pkg_taxoverride', $hashref );
1005
1006   unless ( scalar(@overrides) || !defined($class) || !$class ){
1007     $hashref->{'usage_class'} = '';
1008     @overrides = qsearch('part_pkg_taxoverride', $hashref );
1009   }
1010
1011   @overrides;
1012 }
1013
1014 =item has_taxproduct
1015
1016 Returns true if this package has any taxproduct associated with it.  
1017
1018 =cut
1019
1020 sub has_taxproduct {
1021   my $self = shift;
1022
1023   $self->taxproductnum ||
1024   scalar( grep { $_ =~/^usage_taxproductnum_/ && $self->option($_) } 
1025           keys %{ {$self->options} }
1026   )
1027
1028 }
1029
1030
1031 =item taxproduct [ CLASS ]
1032
1033 Returns the associated tax product for this package definition (see
1034 L<FS::part_pkg_taxproduct>).  CLASS may be one of 'setup', 'recur' or
1035 the usage classnum (see L<FS::usage_class>).  Returns the default
1036 tax product for this record if the more specific CLASS value does
1037 not exist.
1038
1039 =cut
1040
1041 sub taxproduct {
1042   my $self = shift;
1043   my $class = shift;
1044
1045   my $part_pkg_taxproduct;
1046
1047   my $taxproductnum = $self->taxproductnum;
1048   if ($class) { 
1049     my $class_taxproductnum = $self->option("usage_taxproductnum_$class", 1);
1050     $taxproductnum = $class_taxproductnum
1051       if $class_taxproductnum
1052   }
1053   
1054   $part_pkg_taxproduct =
1055     qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
1056
1057   unless ($part_pkg_taxproduct || $taxproductnum eq $self->taxproductnum ) {
1058     $taxproductnum = $self->taxproductnum;
1059     $part_pkg_taxproduct =
1060       qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
1061   }
1062
1063   $part_pkg_taxproduct;
1064 }
1065
1066 =item taxproduct_description [ CLASS ]
1067
1068 Returns the description of the associated tax product for this package
1069 definition (see L<FS::part_pkg_taxproduct>).
1070
1071 =cut
1072
1073 sub taxproduct_description {
1074   my $self = shift;
1075   my $part_pkg_taxproduct = $self->taxproduct(@_);
1076   $part_pkg_taxproduct ? $part_pkg_taxproduct->description : '';
1077 }
1078
1079 =item part_pkg_taxrate DATA_PROVIDER, GEOCODE, [ CLASS ]
1080
1081 Returns the package to taxrate m2m records for this package in the location
1082 specified by GEOCODE (see L<FS::part_pkg_taxrate>) and usage class CLASS.
1083 CLASS may be one of 'setup', 'recur', or one of the usage classes numbers
1084 (see L<FS::usage_class>).
1085
1086 =cut
1087
1088 sub _expand_cch_taxproductnum {
1089   my $self = shift;
1090   my $class = shift;
1091   my $part_pkg_taxproduct = $self->taxproduct($class);
1092
1093   my ($a,$b,$c,$d) = ( $part_pkg_taxproduct
1094                          ? ( split ':', $part_pkg_taxproduct->taxproduct )
1095                          : ()
1096                      );
1097   $a = '' unless $a; $b = '' unless $b; $c = '' unless $c; $d = '' unless $d;
1098   my $extra_sql = "AND ( taxproduct = '$a:$b:$c:$d'
1099                       OR taxproduct = '$a:$b:$c:'
1100                       OR taxproduct = '$a:$b:".":$d'
1101                       OR taxproduct = '$a:$b:".":' )";
1102   map { $_->taxproductnum } qsearch( { 'table'     => 'part_pkg_taxproduct',
1103                                        'hashref'   => { 'data_vendor'=>'cch' },
1104                                        'extra_sql' => $extra_sql,
1105                                    } );
1106                                      
1107 }
1108
1109 sub part_pkg_taxrate {
1110   my $self = shift;
1111   my ($data_vendor, $geocode, $class) = @_;
1112
1113   my $dbh = dbh;
1114   my $extra_sql = 'WHERE part_pkg_taxproduct.data_vendor = '.
1115                   dbh->quote($data_vendor);
1116   
1117   # CCH oddness in m2m
1118   $extra_sql .= ' AND ('.
1119     join(' OR ', map{ 'geocode = '. $dbh->quote(substr($geocode, 0, $_)) }
1120                  qw(10 5 2)
1121         ).
1122     ')';
1123   # much more CCH oddness in m2m -- this is kludgy
1124   my @tpnums = $self->_expand_cch_taxproductnum($class);
1125   if (scalar(@tpnums)) {
1126     $extra_sql .= ' AND ('.
1127                             join(' OR ', map{ "taxproductnum = $_" } @tpnums ).
1128                        ')';
1129   } else {
1130     $extra_sql .= ' AND ( 0 = 1 )';
1131   }
1132
1133   my $addl_from = 'LEFT JOIN part_pkg_taxproduct USING ( taxproductnum )';
1134   my $order_by = 'ORDER BY taxclassnum, length(geocode) desc, length(taxproduct) desc';
1135   my $select   = 'DISTINCT ON(taxclassnum) *, taxproduct';
1136
1137   # should qsearch preface columns with the table to facilitate joins?
1138   qsearch( { 'table'     => 'part_pkg_taxrate',
1139              'select'    => $select,
1140              'hashref'   => { # 'data_vendor'   => $data_vendor,
1141                               # 'taxproductnum' => $self->taxproductnum,
1142                             },
1143              'addl_from' => $addl_from,
1144              'extra_sql' => $extra_sql,
1145              'order_by'  => $order_by,
1146          } );
1147 }
1148
1149 =item part_pkg_discount
1150
1151 Returns the package to discount m2m records (see L<FS::part_pkg_discount>)
1152 for this package.
1153
1154 =cut
1155
1156 sub part_pkg_discount {
1157   my $self = shift;
1158   qsearch('part_pkg_discount', { 'pkgpart' => $self->pkgpart });
1159 }
1160
1161 =item _rebless
1162
1163 Reblesses the object into the FS::part_pkg::PLAN class (if available), where
1164 PLAN is the object's I<plan> field.  There should be better docs
1165 on how to create new price plans, but until then, see L</NEW PLAN CLASSES>.
1166
1167 =cut
1168
1169 sub _rebless {
1170   my $self = shift;
1171   my $plan = $self->plan;
1172   unless ( $plan ) {
1173     cluck "no price plan found for pkgpart ". $self->pkgpart. "\n"
1174       if $DEBUG;
1175     return $self;
1176   }
1177   return $self if ref($self) =~ /::$plan$/; #already blessed into plan subclass
1178   my $class = ref($self). "::$plan";
1179   warn "reblessing $self into $class" if $DEBUG;
1180   eval "use $class;";
1181   die $@ if $@;
1182   bless($self, $class) unless $@;
1183   $self;
1184 }
1185
1186 #fallbacks that eval the setup and recur fields, for backwards compat
1187
1188 sub calc_setup {
1189   my $self = shift;
1190   warn 'no price plan class for '. $self->plan. ", eval-ing setup\n";
1191   $self->_calc_eval('setup', @_);
1192 }
1193
1194 sub calc_recur {
1195   my $self = shift;
1196   warn 'no price plan class for '. $self->plan. ", eval-ing recur\n";
1197   $self->_calc_eval('recur', @_);
1198 }
1199
1200 use vars qw( $sdate @details );
1201 sub _calc_eval {
1202   #my( $self, $field, $cust_pkg ) = @_;
1203   my( $self, $field, $cust_pkg, $sdateref, $detailsref ) = @_;
1204   *sdate = $sdateref;
1205   *details = $detailsref;
1206   $self->$field() =~ /^(.*)$/
1207     or die "Illegal $field (pkgpart ". $self->pkgpart. '): '.
1208             $self->$field(). "\n";
1209   my $prog = $1;
1210   return 0 if $prog =~ /^\s*$/;
1211   my $value = eval $prog;
1212   die $@ if $@;
1213   $value;
1214 }
1215
1216 #fallback that return 0 for old legacy packages with no plan
1217
1218 sub calc_remain { 0; }
1219 sub calc_cancel { 0; }
1220 sub calc_units  { 0; }
1221
1222 #fallback for everything except bulk.pm
1223 sub hide_svc_detail { 0; }
1224
1225 =item recur_cost_permonth CUST_PKG
1226
1227 recur_cost divided by freq (only supported for monthly and longer frequencies)
1228
1229 =cut
1230
1231 sub recur_cost_permonth {
1232   my($self, $cust_pkg) = @_;
1233   return 0 unless $self->freq =~ /^\d+$/ && $self->freq > 0;
1234   sprintf('%.2f', $self->recur_cost / $self->freq );
1235 }
1236
1237 =item format OPTION DATA
1238
1239 Returns data formatted according to the function 'format' described
1240 in the plan info.  Returns DATA if no such function exists.
1241
1242 =cut
1243
1244 sub format {
1245   my ($self, $option, $data) = (shift, shift, shift);
1246   if (exists($plans{$self->plan}->{fields}->{$option}{format})) {
1247     &{$plans{$self->plan}->{fields}->{$option}{format}}($data);
1248   }else{
1249     $data;
1250   }
1251 }
1252
1253 =item parse OPTION DATA
1254
1255 Returns data parsed according to the function 'parse' described
1256 in the plan info.  Returns DATA if no such function exists.
1257
1258 =cut
1259
1260 sub parse {
1261   my ($self, $option, $data) = (shift, shift, shift);
1262   if (exists($plans{$self->plan}->{fields}->{$option}{parse})) {
1263     &{$plans{$self->plan}->{fields}->{$option}{parse}}($data);
1264   }else{
1265     $data;
1266   }
1267 }
1268
1269 =back
1270
1271 =cut
1272
1273 =head1 CLASS METHODS
1274
1275 =over 4
1276
1277 =cut
1278
1279 # _upgrade_data
1280 #
1281 # Used by FS::Upgrade to migrate to a new database.
1282
1283 sub _upgrade_data { # class method
1284   my($class, %opts) = @_;
1285
1286   warn "[FS::part_pkg] upgrading $class\n" if $DEBUG;
1287
1288   my @part_pkg = qsearch({
1289     'table'     => 'part_pkg',
1290     'extra_sql' => "WHERE ". join(' OR ',
1291                      ( map "($_ IS NOT NULL AND $_ != '' )",
1292                            qw( plandata setup recur ) ),
1293                      'plan IS NULL', "plan = '' ",
1294                    ),
1295   });
1296
1297   foreach my $part_pkg (@part_pkg) {
1298
1299     unless ( $part_pkg->plan ) {
1300       $part_pkg->plan('flat');
1301     }
1302
1303     if ( length($part_pkg->option('setup_fee')) == 0 
1304          && $part_pkg->setup =~ /^\s*([\d\.]+)\s*$/ ) {
1305
1306       my $opt = new FS::part_pkg_option {
1307         'pkgpart'     => $part_pkg->pkgpart,
1308         'optionname'  => 'setup_fee',
1309         'optionvalue' => $1,
1310       };
1311       my $error = $opt->insert;
1312       die $error if $error;
1313
1314
1315       #} else {
1316       #  die "Can't parse part_pkg.setup for fee; convert pkgnum ".
1317       #      $part_pkg->pkgnum. " manually: ". $part_pkg->setup. "\n";
1318     }
1319     $part_pkg->setup('');
1320
1321     if ( length($part_pkg->option('recur_fee')) == 0
1322          && $part_pkg->recur =~ /^\s*([\d\.]+)\s*$/ ) {
1323
1324         my $opt = new FS::part_pkg_option {
1325           'pkgpart'     => $part_pkg->pkgpart,
1326           'optionname'  => 'recur_fee',
1327           'optionvalue' => $1,
1328         };
1329         my $error = $opt->insert;
1330         die $error if $error;
1331
1332
1333       #} else {
1334       #  die "Can't parse part_pkg.setup for fee; convert pkgnum ".
1335       #      $part_pkg->pkgnum. " manually: ". $part_pkg->setup. "\n";
1336     }
1337     $part_pkg->recur('');
1338
1339     $part_pkg->replace; #this should take care of plandata, right?
1340
1341   }
1342
1343   # now upgrade to the explicit custom flag
1344
1345   @part_pkg = qsearch({
1346     'table'     => 'part_pkg',
1347     'hashref'   => { disabled => 'Y', custom => '' },
1348     'extra_sql' => "AND comment LIKE '(CUSTOM) %'",
1349   });
1350
1351   foreach my $part_pkg (@part_pkg) {
1352     my $new = new FS::part_pkg { $part_pkg->hash };
1353     $new->custom('Y');
1354     my $comment = $part_pkg->comment;
1355     $comment =~ s/^\(CUSTOM\) //;
1356     $comment = '(none)' unless $comment =~ /\S/;
1357     $new->comment($comment);
1358
1359     my $pkg_svc = { map { $_->svcpart => $_->quantity } $part_pkg->pkg_svc };
1360     my $primary = $part_pkg->svcpart;
1361     my $options = { $part_pkg->options };
1362
1363     my $error = $new->replace( $part_pkg,
1364                                'pkg_svc'     => $pkg_svc,
1365                                'primary_svc' => $primary,
1366                                'options'     => $options,
1367                              );
1368     die $error if $error;
1369   }
1370
1371 }
1372
1373 =item curuser_pkgs_sql
1374
1375 Returns an SQL fragment for searching for packages the current user can
1376 use, either via part_pkg.agentnum directly, or via agent type (see
1377 L<FS::type_pkgs>).
1378
1379 =cut
1380
1381 sub curuser_pkgs_sql {
1382   my $class = shift;
1383
1384   $class->_pkgs_sql( $FS::CurrentUser::CurrentUser->agentnums );
1385
1386 }
1387
1388 =item agent_pkgs_sql AGENT | AGENTNUM, ...
1389
1390 Returns an SQL fragment for searching for packages the provided agent or agents
1391 can use, either via part_pkg.agentnum directly, or via agent type (see
1392 L<FS::type_pkgs>).
1393
1394 =cut
1395
1396 sub agent_pkgs_sql {
1397   my $class = shift;  #i'm a class method, not a sub (the question is... why??)
1398   my @agentnums = map { ref($_) ? $_->agentnum : $_ } @_;
1399
1400   $class->_pkgs_sql(@agentnums); #is this why
1401
1402 }
1403
1404 sub _pkgs_sql {
1405   my( $class, @agentnums ) = @_;
1406   my $agentnums = join(',', @agentnums);
1407
1408   "
1409     (
1410       ( agentnum IS NOT NULL AND agentnum IN ($agentnums) )
1411       OR ( agentnum IS NULL
1412            AND EXISTS ( SELECT 1
1413                           FROM type_pkgs
1414                             LEFT JOIN agent_type USING ( typenum )
1415                             LEFT JOIN agent AS typeagent USING ( typenum )
1416                           WHERE type_pkgs.pkgpart = part_pkg.pkgpart
1417                             AND typeagent.agentnum IN ($agentnums)
1418                       )
1419          )
1420     )
1421   ";
1422
1423 }
1424
1425 =back
1426
1427 =head1 SUBROUTINES
1428
1429 =over 4
1430
1431 =item plan_info
1432
1433 =cut
1434
1435 #false laziness w/part_export & cdr
1436 my %info;
1437 foreach my $INC ( @INC ) {
1438   warn "globbing $INC/FS/part_pkg/*.pm\n" if $DEBUG;
1439   foreach my $file ( glob("$INC/FS/part_pkg/*.pm") ) {
1440     warn "attempting to load plan info from $file\n" if $DEBUG;
1441     $file =~ /\/(\w+)\.pm$/ or do {
1442       warn "unrecognized file in $INC/FS/part_pkg/: $file\n";
1443       next;
1444     };
1445     my $mod = $1;
1446     my $info = eval "use FS::part_pkg::$mod; ".
1447                     "\\%FS::part_pkg::$mod\::info;";
1448     if ( $@ ) {
1449       die "error using FS::part_pkg::$mod (skipping): $@\n" if $@;
1450       next;
1451     }
1452     unless ( keys %$info ) {
1453       warn "no %info hash found in FS::part_pkg::$mod, skipping\n";
1454       next;
1455     }
1456     warn "got plan info from FS::part_pkg::$mod: $info\n" if $DEBUG;
1457     if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
1458       warn "skipping disabled plan FS::part_pkg::$mod" if $DEBUG;
1459       next;
1460     }
1461     $info{$mod} = $info;
1462   }
1463 }
1464
1465 tie %plans, 'Tie::IxHash',
1466   map  { $_ => $info{$_} }
1467   sort { $info{$a}->{'weight'} <=> $info{$b}->{'weight'} }
1468   keys %info;
1469
1470 sub plan_info {
1471   \%plans;
1472 }
1473
1474
1475 =back
1476
1477 =head1 NEW PLAN CLASSES
1478
1479 A module should be added in FS/FS/part_pkg/  Eventually, an example may be
1480 found in eg/plan_template.pm.  Until then, it is suggested that you use the
1481 other modules in FS/FS/part_pkg/ as a guide.
1482
1483 =head1 BUGS
1484
1485 The delete method is unimplemented.
1486
1487 setup and recur semantics are not yet defined (and are implemented in
1488 FS::cust_bill.  hmm.).  now they're deprecated and need to go.
1489
1490 plandata should go
1491
1492 part_pkg_taxrate is Pg specific
1493
1494 replace should be smarter about managing the related tables (options, pkg_svc)
1495
1496 =head1 SEE ALSO
1497
1498 L<FS::Record>, L<FS::cust_pkg>, L<FS::type_pkgs>, L<FS::pkg_svc>, L<Safe>.
1499 schema.html from the base documentation.
1500
1501 =cut
1502
1503 1;
1504