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