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