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