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