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