dc0a4d58aad57ba8f1a0f981c2ab6f8d7fffbe47
[freeside.git] / FS / FS / part_pkg.pm
1 package FS::part_pkg;
2
3 use strict;
4 use vars qw( @ISA %plans $DEBUG );
5 use Carp qw(carp cluck confess);
6 use Tie::IxHash;
7 use FS::Conf;
8 use FS::Record qw( qsearch qsearchs dbh dbdef );
9 use FS::pkg_svc;
10 use FS::part_svc;
11 use FS::cust_pkg;
12 use FS::agent_type;
13 use FS::type_pkgs;
14 use FS::part_pkg_option;
15 use FS::pkg_class;
16 use FS::agent;
17 use FS::part_pkg_taxoverride;
18 use FS::part_pkg_taxproduct;
19
20 @ISA = qw( FS::m2m_Common FS::Record ); # FS::option_Common ); # this can use option_Common
21                                                 # when all the plandata bs is
22                                                 # gone
23
24 $DEBUG = 0;
25
26 =head1 NAME
27
28 FS::part_pkg - Object methods for part_pkg objects
29
30 =head1 SYNOPSIS
31
32   use FS::part_pkg;
33
34   $record = new FS::part_pkg \%hash
35   $record = new FS::part_pkg { 'column' => 'value' };
36
37   $custom_record = $template_record->clone;
38
39   $error = $record->insert;
40
41   $error = $new_record->replace($old_record);
42
43   $error = $record->delete;
44
45   $error = $record->check;
46
47   @pkg_svc = $record->pkg_svc;
48
49   $svcnum = $record->svcpart;
50   $svcnum = $record->svcpart( 'svc_acct' );
51
52 =head1 DESCRIPTION
53
54 An FS::part_pkg object represents a package definition.  FS::part_pkg
55 inherits from FS::Record.  The following fields are currently supported:
56
57 =over 4
58
59 =item pkgpart - primary key (assigned automatically for new package definitions)
60
61 =item pkg - Text name of this package definition (customer-viewable)
62
63 =item comment - Text name of this package definition (non-customer-viewable)
64
65 =item classnum - Optional package class (see L<FS::pkg_class>)
66
67 =item promo_code - Promotional code
68
69 =item setup - Setup fee expression (deprecated)
70
71 =item freq - Frequency of recurring fee
72
73 =item recur - Recurring fee expression (deprecated)
74
75 =item setuptax - Setup fee tax exempt flag, empty or `Y'
76
77 =item recurtax - Recurring fee tax exempt flag, empty or `Y'
78
79 =item taxclass - Tax class 
80
81 =item plan - Price plan
82
83 =item plandata - Price plan data (deprecated - see L<FS::part_pkg_option> instead)
84
85 =item disabled - Disabled flag, empty or `Y'
86
87 =item pay_weight - Weight (relative to credit_weight and other package definitions) that controls payment application to specific line items.
88
89 =item credit_weight - Weight (relative to other package definitions) that controls credit application to specific line items.
90
91 =item agentnum - Optional agentnum (see L<FS::agent>)
92
93 =back
94
95 =head1 METHODS
96
97 =over 4 
98
99 =item new HASHREF
100
101 Creates a new package definition.  To add the package definition to
102 the database, see L<"insert">.
103
104 =cut
105
106 sub table { 'part_pkg'; }
107
108 =item clone
109
110 An alternate constructor.  Creates a new package definition by duplicating
111 an existing definition.  A new pkgpart is assigned and `(CUSTOM) ' is prepended
112 to the comment field.  To add the package definition to the database, see
113 L<"insert">.
114
115 =cut
116
117 sub clone {
118   my $self = shift;
119   my $class = ref($self);
120   my %hash = $self->hash;
121   $hash{'pkgpart'} = '';
122   $hash{'comment'} = "(CUSTOM) ". $hash{'comment'}
123     unless $hash{'comment'} =~ /^\(CUSTOM\) /;
124   #new FS::part_pkg ( \%hash ); # ?
125   new $class ( \%hash ); # ?
126 }
127
128 =item insert [ , OPTION => VALUE ... ]
129
130 Adds this package definition to the database.  If there is an error,
131 returns the error, otherwise returns false.
132
133 Currently available options are: I<pkg_svc>, I<primary_svc>, I<cust_pkg>, 
134 I<custnum_ref> and I<options>.
135
136 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
137 values, appropriate FS::pkg_svc records will be inserted.
138
139 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
140 FS::pkg_svc record will be updated.
141
142 If I<cust_pkg> is set to a pkgnum of a FS::cust_pkg record (or the FS::cust_pkg
143 record itself), the object will be updated to point to this package definition.
144
145 In conjunction with I<cust_pkg>, if I<custnum_ref> is set to a scalar reference,
146 the scalar will be updated with the custnum value from the cust_pkg record.
147
148 If I<options> is set to a hashref of options, appropriate FS::part_pkg_option
149 records will be inserted.
150
151 =cut
152
153 sub insert {
154   my $self = shift;
155   my %options = @_;
156   warn "FS::part_pkg::insert called on $self with options ".
157        join(', ', map "$_=>$options{$_}", keys %options)
158     if $DEBUG;
159
160   local $SIG{HUP} = 'IGNORE';
161   local $SIG{INT} = 'IGNORE';
162   local $SIG{QUIT} = 'IGNORE';
163   local $SIG{TERM} = 'IGNORE';
164   local $SIG{TSTP} = 'IGNORE';
165   local $SIG{PIPE} = 'IGNORE';
166
167   my $oldAutoCommit = $FS::UID::AutoCommit;
168   local $FS::UID::AutoCommit = 0;
169   my $dbh = dbh;
170
171   warn "  saving legacy plandata" if $DEBUG;
172   my $plandata = $self->get('plandata');
173   $self->set('plandata', '');
174
175   warn "  inserting part_pkg record" if $DEBUG;
176   my $error = $self->SUPER::insert;
177   if ( $error ) {
178     $dbh->rollback if $oldAutoCommit;
179     return $error;
180   }
181
182   if ( $plandata ) {
183
184     warn "  inserting part_pkg_option records for plandata" if $DEBUG;
185     foreach my $part_pkg_option ( 
186       map { /^(\w+)=(.*)$/ or do { $dbh->rollback if $oldAutoCommit;
187                                    return "illegal plandata: $plandata";
188                                  };
189             new FS::part_pkg_option {
190               'pkgpart'     => $self->pkgpart,
191               'optionname'  => $1,
192               'optionvalue' => $2,
193             };
194           }
195       split("\n", $plandata)
196     ) {
197       my $error = $part_pkg_option->insert;
198       if ( $error ) {
199         $dbh->rollback if $oldAutoCommit;
200         return $error;
201       }
202     }
203
204   } elsif ( $options{'options'} ) {
205
206     warn "  inserting part_pkg_option records for options hashref" if $DEBUG;
207     foreach my $optionname ( keys %{$options{'options'}} ) {
208
209       my $part_pkg_option =
210         new FS::part_pkg_option {
211           'pkgpart'     => $self->pkgpart,
212           'optionname'  => $optionname,
213           'optionvalue' => $options{'options'}->{$optionname},
214         };
215
216       my $error = $part_pkg_option->insert;
217       if ( $error ) {
218         $dbh->rollback if $oldAutoCommit;
219         return $error;
220       }
221
222     }
223
224   }
225
226   my $conf = new FS::Conf;
227   if ( $conf->exists('agent_defaultpkg') ) {
228     warn "  agent_defaultpkg set; allowing all agents to purchase package"
229       if $DEBUG;
230     foreach my $agent_type ( qsearch('agent_type', {} ) ) {
231       my $type_pkgs = new FS::type_pkgs({
232         'typenum' => $agent_type->typenum,
233         'pkgpart' => $self->pkgpart,
234       });
235       my $error = $type_pkgs->insert;
236       if ( $error ) {
237         $dbh->rollback if $oldAutoCommit;
238         return $error;
239       }
240     }
241   }
242
243   warn "  inserting pkg_svc records" if $DEBUG;
244   my $pkg_svc = $options{'pkg_svc'} || {};
245   foreach my $part_svc ( qsearch('part_svc', {} ) ) {
246     my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
247     my $primary_svc =
248       ( $options{'primary_svc'} && $options{'primary_svc'}==$part_svc->svcpart )
249         ? 'Y'
250         : '';
251
252     my $pkg_svc = new FS::pkg_svc( {
253       'pkgpart'     => $self->pkgpart,
254       'svcpart'     => $part_svc->svcpart,
255       'quantity'    => $quantity, 
256       'primary_svc' => $primary_svc,
257     } );
258     my $error = $pkg_svc->insert;
259     if ( $error ) {
260       $dbh->rollback if $oldAutoCommit;
261       return $error;
262     }
263   }
264
265   if ( $options{'cust_pkg'} ) {
266     warn "  updating cust_pkg record " if $DEBUG;
267     my $old_cust_pkg =
268       ref($options{'cust_pkg'})
269         ? $options{'cust_pkg'}
270         : qsearchs('cust_pkg', { pkgnum => $options{'cust_pkg'} } );
271     ${ $options{'custnum_ref'} } = $old_cust_pkg->custnum
272       if $options{'custnum_ref'};
273     my %hash = $old_cust_pkg->hash;
274     $hash{'pkgpart'} = $self->pkgpart,
275     my $new_cust_pkg = new FS::cust_pkg \%hash;
276     local($FS::cust_pkg::disable_agentcheck) = 1;
277     my $error = $new_cust_pkg->replace($old_cust_pkg);
278     if ( $error ) {
279       $dbh->rollback if $oldAutoCommit;
280       return "Error modifying cust_pkg record: $error";
281     }
282   }
283
284   warn "  commiting transaction" if $DEBUG;
285   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
286
287   '';
288 }
289
290 =item delete
291
292 Currently unimplemented.
293
294 =cut
295
296 sub delete {
297   return "Can't (yet?) delete package definitions.";
298 # check & make sure the pkgpart isn't in cust_pkg or type_pkgs?
299 }
300
301 =item replace OLD_RECORD [ , OPTION => VALUE ... ]
302
303 Replaces OLD_RECORD with this one in the database.  If there is an error,
304 returns the error, otherwise returns false.
305
306 Currently available options are: I<pkg_svc> and I<primary_svc>
307
308 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
309 values, the appropriate FS::pkg_svc records will be replace.
310
311 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
312 FS::pkg_svc record will be updated.
313
314 =cut
315
316 sub replace {
317   my( $new, $old ) = ( shift, shift );
318   my %options = @_;
319
320   # We absolutely have to have an old vs. new record to make this work.
321   if (!defined($old)) {
322     $old = qsearchs( 'part_pkg', { 'pkgpart' => $new->pkgpart } );
323   }
324
325   warn "FS::part_pkg::replace called on $new to replace $old ".
326        "with options %options"
327     if $DEBUG;
328
329   local $SIG{HUP} = 'IGNORE';
330   local $SIG{INT} = 'IGNORE';
331   local $SIG{QUIT} = 'IGNORE';
332   local $SIG{TERM} = 'IGNORE';
333   local $SIG{TSTP} = 'IGNORE';
334   local $SIG{PIPE} = 'IGNORE';
335
336   my $oldAutoCommit = $FS::UID::AutoCommit;
337   local $FS::UID::AutoCommit = 0;
338   my $dbh = dbh;
339
340   warn "  saving legacy plandata" if $DEBUG;
341   my $plandata = $new->get('plandata');
342   $new->set('plandata', '');
343
344   warn "  deleting old part_pkg_option records" if $DEBUG;
345   foreach my $part_pkg_option ( $old->part_pkg_option ) {
346     my $error = $part_pkg_option->delete;
347     if ( $error ) {
348       $dbh->rollback if $oldAutoCommit;
349       return $error;
350     }
351   }
352
353   warn "  replacing part_pkg record" if $DEBUG;
354   my $error = $new->SUPER::replace($old);
355   if ( $error ) {
356     $dbh->rollback if $oldAutoCommit;
357     return $error;
358   }
359
360   warn "  inserting part_pkg_option records for plandata" if $DEBUG;
361   foreach my $part_pkg_option ( 
362     map { /^(\w+)=(.*)$/ or do { $dbh->rollback if $oldAutoCommit;
363                                  return "illegal plandata: $plandata";
364                                };
365           new FS::part_pkg_option {
366             'pkgpart'     => $new->pkgpart,
367             'optionname'  => $1,
368             'optionvalue' => $2,
369           };
370         }
371     split("\n", $plandata)
372   ) {
373     my $error = $part_pkg_option->insert;
374     if ( $error ) {
375       $dbh->rollback if $oldAutoCommit;
376       return $error;
377     }
378   }
379
380   warn "  replacing pkg_svc records" if $DEBUG;
381   my $pkg_svc = $options{'pkg_svc'} || {};
382   foreach my $part_svc ( qsearch('part_svc', {} ) ) {
383     my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
384     my $primary_svc = $options{'primary_svc'} == $part_svc->svcpart ? 'Y' : '';
385
386     my $old_pkg_svc = qsearchs('pkg_svc', {
387       'pkgpart' => $old->pkgpart,
388       'svcpart' => $part_svc->svcpart,
389     } );
390     my $old_quantity = $old_pkg_svc ? $old_pkg_svc->quantity : 0;
391     my $old_primary_svc =
392       ( $old_pkg_svc && $old_pkg_svc->dbdef_table->column('primary_svc') )
393         ? $old_pkg_svc->primary_svc
394         : '';
395     next unless $old_quantity != $quantity || $old_primary_svc ne $primary_svc;
396   
397     my $new_pkg_svc = new FS::pkg_svc( {
398       'pkgsvcnum'   => ( $old_pkg_svc ? $old_pkg_svc->pkgsvcnum : '' ),
399       'pkgpart'     => $new->pkgpart,
400       'svcpart'     => $part_svc->svcpart,
401       'quantity'    => $quantity, 
402       'primary_svc' => $primary_svc,
403     } );
404     my $error = $old_pkg_svc
405                   ? $new_pkg_svc->replace($old_pkg_svc)
406                   : $new_pkg_svc->insert;
407     if ( $error ) {
408       $dbh->rollback if $oldAutoCommit;
409       return $error;
410     }
411   }
412
413   warn "  commiting transaction" if $DEBUG;
414   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
415   '';
416 }
417
418 =item check
419
420 Checks all fields to make sure this is a valid package definition.  If
421 there is an error, returns the error, otherwise returns false.  Called by the
422 insert and replace methods.
423
424 =cut
425
426 sub check {
427   my $self = shift;
428   warn "FS::part_pkg::check called on $self" if $DEBUG;
429
430   for (qw(setup recur plandata)) {
431     #$self->set($_=>0) if $self->get($_) =~ /^\s*$/; }
432     return "Use of $_ field is deprecated; set a plan and options"
433       if length($self->get($_));
434     $self->set($_, '');
435   }
436
437   if ( $self->dbdef_table->column('freq')->type =~ /(int)/i ) {
438     my $error = $self->ut_number('freq');
439     return $error if $error;
440   } else {
441     $self->freq =~ /^(\d+[hdw]?)$/
442       or return "Illegal or empty freq: ". $self->freq;
443     $self->freq($1);
444   }
445
446   my $error = $self->ut_numbern('pkgpart')
447     || $self->ut_text('pkg')
448     || $self->ut_text('comment')
449     || $self->ut_textn('promo_code')
450     || $self->ut_alphan('plan')
451     || $self->ut_enum('setuptax', [ '', 'Y' ] )
452     || $self->ut_enum('recurtax', [ '', 'Y' ] )
453     || $self->ut_textn('taxclass')
454     || $self->ut_enum('disabled', [ '', 'Y' ] )
455     || $self->ut_floatn('pay_weight')
456     || $self->ut_floatn('credit_weight')
457     || $self->ut_agentnum_acl('agentnum', 'Edit global package definitions')
458     || $self->SUPER::check
459   ;
460   return $error if $error;
461
462   if ( $self->classnum !~ /^$/ ) {
463     my $error = $self->ut_foreign_key('classnum', 'pkg_class', 'classnum');
464     return $error if $error;
465   } else {
466     $self->classnum('');
467   }
468
469   return 'Unknown plan '. $self->plan
470     unless exists($plans{$self->plan});
471
472   my $conf = new FS::Conf;
473   return 'Taxclass is required'
474     if ! $self->taxclass && $conf->exists('require_taxclasses');
475
476   '';
477 }
478
479 =item pkg_class
480
481 Returns the package class, as an FS::pkg_class object, or the empty string
482 if there is no package class.
483
484 =cut
485
486 sub pkg_class {
487   my $self = shift;
488   if ( $self->classnum ) {
489     qsearchs('pkg_class', { 'classnum' => $self->classnum } );
490   } else {
491     return '';
492   }
493 }
494
495 =item classname 
496
497 Returns the package class name, or the empty string if there is no package
498 class.
499
500 =cut
501
502 sub classname {
503   my $self = shift;
504   my $pkg_class = $self->pkg_class;
505   $pkg_class
506     ? $pkg_class->classname
507     : '';
508 }
509
510 =item agent 
511
512 Returns the associated agent for this event, if any, as an FS::agent object.
513
514 =cut
515
516 sub agent {
517   my $self = shift;
518   qsearchs('agent', { 'agentnum' => $self->agentnum } );
519 }
520
521 =item pkg_svc
522
523 Returns all FS::pkg_svc objects (see L<FS::pkg_svc>) for this package
524 definition (with non-zero quantity).
525
526 =cut
527
528 sub pkg_svc {
529   my $self = shift;
530   #sort { $b->primary cmp $a->primary } 
531     grep { $_->quantity }
532       qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
533 }
534
535 =item svcpart [ SVCDB ]
536
537 Returns the svcpart of the primary service definition (see L<FS::part_svc>)
538 associated with this package definition (see L<FS::pkg_svc>).  Returns
539 false if there not a primary service definition or exactly one service
540 definition with quantity 1, or if SVCDB is specified and does not match the
541 svcdb of the service definition, 
542
543 =cut
544
545 sub svcpart {
546   my $self = shift;
547   my $svcdb = scalar(@_) ? shift : '';
548   my @svcdb_pkg_svc =
549     grep { ( $svcdb eq $_->part_svc->svcdb || !$svcdb ) } $self->pkg_svc;
550   my @pkg_svc = ();
551   @pkg_svc = grep { $_->primary_svc =~ /^Y/i } @svcdb_pkg_svc
552     if dbdef->table('pkg_svc')->column('primary_svc');
553   @pkg_svc = grep {$_->quantity == 1 } @svcdb_pkg_svc
554     unless @pkg_svc;
555   return '' if scalar(@pkg_svc) != 1;
556   $pkg_svc[0]->svcpart;
557 }
558
559 =item payby
560
561 Returns a list of the acceptable payment types for this package.  Eventually
562 this should come out of a database table and be editable, but currently has the
563 following logic instead:
564
565 If the package is free, the single item B<BILL> is
566 returned, otherwise, the single item B<CARD> is returned.
567
568 (CHEK?  LEC?  Probably shouldn't accept those by default, prone to abuse)
569
570 =cut
571
572 sub payby {
573   my $self = shift;
574   if ( $self->is_free ) {
575     ( 'BILL' );
576   } else {
577     ( 'CARD' );
578   }
579 }
580
581 =item is_free
582
583 Returns true if this package is free.  
584
585 =cut
586
587 sub is_free {
588   my $self = shift;
589   unless ( $self->plan ) {
590     $self->setup =~ /^\s*0+(\.0*)?\s*$/
591       && $self->recur =~ /^\s*0+(\.0*)?\s*$/;
592   } elsif ( $self->can('is_free_options') ) {
593     not grep { $_ !~ /^\s*0*(\.0*)?\s*$/ }
594          map { $self->option($_) } 
595              $self->is_free_options;
596   } else {
597     warn "FS::part_pkg::is_free: FS::part_pkg::". $self->plan. " subclass ".
598          "provides neither is_free_options nor is_free method; returning false";
599     0;
600   }
601 }
602
603
604 sub freqs_href {
605   #method, class method or sub? #my $self = shift;
606
607   tie my %freq, 'Tie::IxHash', 
608     '0'    => '(no recurring fee)',
609     '1h'   => 'hourly',
610     '1d'   => 'daily',
611     '2d'   => 'every two days',
612     '3d'   => 'every three days',
613     '1w'   => 'weekly',
614     '2w'   => 'biweekly (every 2 weeks)',
615     '1'    => 'monthly',
616     '45d'  => 'every 45 days',
617     '2'    => 'bimonthly (every 2 months)',
618     '3'    => 'quarterly (every 3 months)',
619     '4'    => 'every 4 months',
620     '137d' => 'every 4 1/2 months (137 days)',
621     '6'    => 'semiannually (every 6 months)',
622     '12'   => 'annually',
623     '13'   => 'every 13 months (annually +1 month)',
624     '24'   => 'biannually (every 2 years)',
625     '36'   => 'triannually (every 3 years)',
626     '48'   => '(every 4 years)',
627     '60'   => '(every 5 years)',
628     '120'  => '(every 10 years)',
629   ;
630
631   \%freq;
632
633 }
634
635 =item freq_pretty
636
637 Returns an english representation of the I<freq> field, such as "monthly",
638 "weekly", "semi-annually", etc.
639
640 =cut
641
642 sub freq_pretty {
643   my $self = shift;
644   my $freq = $self->freq;
645
646   #my $freqs_href = $self->freqs_href;
647   my $freqs_href = freqs_href();
648
649   if ( exists($freqs_href->{$freq}) ) {
650     $freqs_href->{$freq};
651   } else {
652     my $interval = 'month';
653     if ( $freq =~ /^(\d+)([hdw])$/ ) {
654       my %interval = ( 'h' => 'hour', 'd'=>'day', 'w'=>'week' );
655       $interval = $interval{$2};
656     }
657     if ( $1 == 1 ) {
658       "every $interval";
659     } else {
660       "every $freq ${interval}s";
661     }
662   }
663 }
664
665 =item plandata
666
667 For backwards compatibility, returns the plandata field as well as all options
668 from FS::part_pkg_option.
669
670 =cut
671
672 sub plandata {
673   my $self = shift;
674   carp "plandata is deprecated";
675   if ( @_ ) {
676     $self->SUPER::plandata(@_);
677   } else {
678     my $plandata = $self->get('plandata');
679     my %options = $self->options;
680     $plandata .= join('', map { "$_=$options{$_}\n" } keys %options );
681     $plandata;
682   }
683 }
684
685 =item part_pkg_option
686
687 Returns all options as FS::part_pkg_option objects (see
688 L<FS::part_pkg_option>).
689
690 =cut
691
692 sub part_pkg_option {
693   my $self = shift;
694   qsearch('part_pkg_option', { 'pkgpart' => $self->pkgpart } );
695 }
696
697 =item options 
698
699 Returns a list of option names and values suitable for assigning to a hash.
700
701 =cut
702
703 sub options {
704   my $self = shift;
705   map { $_->optionname => $_->optionvalue } $self->part_pkg_option;
706 }
707
708 =item option OPTIONNAME
709
710 Returns the option value for the given name, or the empty string.
711
712 =cut
713
714 sub option {
715   my( $self, $opt, $ornull ) = @_;
716   my $part_pkg_option =
717     qsearchs('part_pkg_option', {
718       pkgpart    => $self->pkgpart,
719       optionname => $opt,
720   } );
721   return $part_pkg_option->optionvalue if $part_pkg_option;
722   my %plandata = map { /^(\w+)=(.*)$/; ( $1 => $2 ); }
723                      split("\n", $self->get('plandata') );
724   return $plandata{$opt} if exists $plandata{$opt};
725   cluck "WARNING: (pkgpart ". $self->pkgpart. ") Package def option $opt ".
726         "not found in options or plandata!\n"
727     unless $ornull;
728   '';
729 }
730
731 =item part_pkg_taxoverride
732
733 Returns all options as FS::part_pkg_taxoverride objects (see
734 L<FS::part_pkg_taxoverride>).
735
736 =cut
737
738 sub part_pkg_taxoverride {
739   my $self = shift;
740   qsearch('part_pkg_taxoverride', { 'pkgpart' => $self->pkgpart } );
741 }
742
743 =item taxproduct_description
744
745 Returns the description of the associated tax product for this package
746 definition (see L<FS::part_pkg_taxproduct>).
747
748 =cut
749
750 sub taxproduct_description {
751   my $self = shift;
752   my $part_pkg_taxproduct =
753     qsearchs( 'part_pkg_taxproduct',
754               { 'taxproductnum' => $self->taxproductnum }
755             );
756   $part_pkg_taxproduct ? $part_pkg_taxproduct->description : '';
757 }
758
759 =item _rebless
760
761 Reblesses the object into the FS::part_pkg::PLAN class (if available), where
762 PLAN is the object's I<plan> field.  There should be better docs
763 on how to create new price plans, but until then, see L</NEW PLAN CLASSES>.
764
765 =cut
766
767 sub _rebless {
768   my $self = shift;
769   my $plan = $self->plan;
770   unless ( $plan ) {
771     confess "no price plan found for pkgpart ". $self->pkgpart. "\n"
772       if $DEBUG;
773     return $self;
774   }
775   return $self if ref($self) =~ /::$plan$/; #already blessed into plan subclass
776   my $class = ref($self). "::$plan";
777   warn "reblessing $self into $class" if $DEBUG;
778   eval "use $class;";
779   die $@ if $@;
780   bless($self, $class) unless $@;
781   $self;
782 }
783
784 #fallbacks that eval the setup and recur fields, for backwards compat
785
786 sub calc_setup {
787   my $self = shift;
788   warn 'no price plan class for '. $self->plan. ", eval-ing setup\n";
789   $self->_calc_eval('setup', @_);
790 }
791
792 sub calc_recur {
793   my $self = shift;
794   warn 'no price plan class for '. $self->plan. ", eval-ing recur\n";
795   $self->_calc_eval('recur', @_);
796 }
797
798 use vars qw( $sdate @details );
799 sub _calc_eval {
800   #my( $self, $field, $cust_pkg ) = @_;
801   my( $self, $field, $cust_pkg, $sdateref, $detailsref ) = @_;
802   *sdate = $sdateref;
803   *details = $detailsref;
804   $self->$field() =~ /^(.*)$/
805     or die "Illegal $field (pkgpart ". $self->pkgpart. '): '.
806             $self->$field(). "\n";
807   my $prog = $1;
808   return 0 if $prog =~ /^\s*$/;
809   my $value = eval $prog;
810   die $@ if $@;
811   $value;
812 }
813
814 #fallback that return 0 for old legacy packages with no plan
815
816 sub calc_remain { 0; }
817 sub calc_cancel { 0; }
818
819 =back
820
821 =head1 SUBROUTINES
822
823 =over 4
824
825 =item plan_info
826
827 =cut
828
829 my %info;
830 foreach my $INC ( @INC ) {
831   warn "globbing $INC/FS/part_pkg/*.pm\n" if $DEBUG;
832   foreach my $file ( glob("$INC/FS/part_pkg/*.pm") ) {
833     warn "attempting to load plan info from $file\n" if $DEBUG;
834     $file =~ /\/(\w+)\.pm$/ or do {
835       warn "unrecognized file in $INC/FS/part_pkg/: $file\n";
836       next;
837     };
838     my $mod = $1;
839     my $info = eval "use FS::part_pkg::$mod; ".
840                     "\\%FS::part_pkg::$mod\::info;";
841     if ( $@ ) {
842       die "error using FS::part_pkg::$mod (skipping): $@\n" if $@;
843       next;
844     }
845     unless ( keys %$info ) {
846       warn "no %info hash found in FS::part_pkg::$mod, skipping\n"
847         unless $mod =~ /^(passwdfile|null)$/; #hack but what the heck
848       next;
849     }
850     warn "got plan info from FS::part_pkg::$mod: $info\n" if $DEBUG;
851     if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
852       warn "skipping disabled plan FS::part_pkg::$mod" if $DEBUG;
853       next;
854     }
855     $info{$mod} = $info;
856   }
857 }
858
859 tie %plans, 'Tie::IxHash',
860   map { $_ => $info{$_} }
861   sort { $info{$a}->{'weight'} <=> $info{$b}->{'weight'} }
862   keys %info;
863
864 sub plan_info {
865   \%plans;
866 }
867
868 =item format OPTION DATA
869
870 Returns data formatted according to the function 'format' described
871 in the plan info.  Returns DATA if no such function exists.
872
873 =cut
874
875 sub format {
876   my ($self, $option, $data) = (shift, shift, shift);
877   if (exists($plans{$self->plan}->{fields}->{$option}{format})) {
878     &{$plans{$self->plan}->{fields}->{$option}{format}}($data);
879   }else{
880     $data;
881   }
882 }
883
884 =item parse OPTION DATA
885
886 Returns data parsed according to the function 'parse' described
887 in the plan info.  Returns DATA if no such function exists.
888
889 =cut
890
891 sub parse {
892   my ($self, $option, $data) = (shift, shift, shift);
893   if (exists($plans{$self->plan}->{fields}->{$option}{parse})) {
894     &{$plans{$self->plan}->{fields}->{$option}{parse}}($data);
895   }else{
896     $data;
897   }
898 }
899
900
901 =back
902
903 =head1 NEW PLAN CLASSES
904
905 A module should be added in FS/FS/part_pkg/  Eventually, an example may be
906 found in eg/plan_template.pm.  Until then, it is suggested that you use the
907 other modules in FS/FS/part_pkg/ as a guide.
908
909 =head1 BUGS
910
911 The delete method is unimplemented.
912
913 setup and recur semantics are not yet defined (and are implemented in
914 FS::cust_bill.  hmm.).  now they're deprecated and need to go.
915
916 plandata should go
917
918 =head1 SEE ALSO
919
920 L<FS::Record>, L<FS::cust_pkg>, L<FS::type_pkgs>, L<FS::pkg_svc>, L<Safe>.
921 schema.html from the base documentation.
922
923 =cut
924
925 1;
926