package categories (meta package classes) and grouping invoices by them
[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>, I<primary_svc> and I<options>
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 replaced.
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 If I<options> is set to a hashref, the appropriate FS::part_pkg_option records
266 will be replaced.
267
268 =cut
269
270 sub replace {
271   my $new = shift;
272
273   my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
274               ? shift
275               : $new->replace_old;
276
277   my $options = 
278     ( ref($_[0]) eq 'HASH' )
279       ? shift
280       : { @_ };
281
282   $options->{options} = {} unless defined($options->{options});
283
284   warn "FS::part_pkg::replace called on $new to replace $old with options".
285        join(', ', map "$_ => ". $options->{$_}, keys %$options)
286     if $DEBUG;
287
288   local $SIG{HUP} = 'IGNORE';
289   local $SIG{INT} = 'IGNORE';
290   local $SIG{QUIT} = 'IGNORE';
291   local $SIG{TERM} = 'IGNORE';
292   local $SIG{TSTP} = 'IGNORE';
293   local $SIG{PIPE} = 'IGNORE';
294
295   my $oldAutoCommit = $FS::UID::AutoCommit;
296   local $FS::UID::AutoCommit = 0;
297   my $dbh = dbh;
298
299   #plandata shit stays in replace for upgrades until after 2.0 (or edit
300   #_upgrade_data)
301   warn "  saving legacy plandata" if $DEBUG;
302   my $plandata = $new->get('plandata');
303   $new->set('plandata', '');
304
305   warn "  deleting old part_pkg_option records" if $DEBUG;
306   foreach my $part_pkg_option ( $old->part_pkg_option ) {
307     my $error = $part_pkg_option->delete;
308     if ( $error ) {
309       $dbh->rollback if $oldAutoCommit;
310       return $error;
311     }
312   }
313
314   warn "  replacing part_pkg record" if $DEBUG;
315   my $error = $new->SUPER::replace($old, $options->{options} );
316   if ( $error ) {
317     $dbh->rollback if $oldAutoCommit;
318     return $error;
319   }
320
321   warn "  inserting part_pkg_option records for plandata: $plandata|" if $DEBUG;
322   foreach my $part_pkg_option ( 
323     map { /^(\w+)=(.*)$/ or do { $dbh->rollback if $oldAutoCommit;
324                                  return "illegal plandata: $plandata";
325                                };
326           new FS::part_pkg_option {
327             'pkgpart'     => $new->pkgpart,
328             'optionname'  => $1,
329             'optionvalue' => $2,
330           };
331         }
332     split("\n", $plandata)
333   ) {
334     my $error = $part_pkg_option->insert;
335     if ( $error ) {
336       $dbh->rollback if $oldAutoCommit;
337       return $error;
338     }
339   }
340
341   warn "  replacing pkg_svc records" if $DEBUG;
342   my $pkg_svc = $options->{'pkg_svc'} || {};
343   foreach my $part_svc ( qsearch('part_svc', {} ) ) {
344     my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
345     my $primary_svc = $options->{'primary_svc'} == $part_svc->svcpart ? 'Y' : '';
346
347     my $old_pkg_svc = qsearchs('pkg_svc', {
348       'pkgpart' => $old->pkgpart,
349       'svcpart' => $part_svc->svcpart,
350     } );
351     my $old_quantity = $old_pkg_svc ? $old_pkg_svc->quantity : 0;
352     my $old_primary_svc =
353       ( $old_pkg_svc && $old_pkg_svc->dbdef_table->column('primary_svc') )
354         ? $old_pkg_svc->primary_svc
355         : '';
356     next unless $old_quantity != $quantity || $old_primary_svc ne $primary_svc;
357   
358     my $new_pkg_svc = new FS::pkg_svc( {
359       'pkgsvcnum'   => ( $old_pkg_svc ? $old_pkg_svc->pkgsvcnum : '' ),
360       'pkgpart'     => $new->pkgpart,
361       'svcpart'     => $part_svc->svcpart,
362       'quantity'    => $quantity, 
363       'primary_svc' => $primary_svc,
364     } );
365     my $error = $old_pkg_svc
366                   ? $new_pkg_svc->replace($old_pkg_svc)
367                   : $new_pkg_svc->insert;
368     if ( $error ) {
369       $dbh->rollback if $oldAutoCommit;
370       return $error;
371     }
372   }
373
374   warn "  commiting transaction" if $DEBUG;
375   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
376   '';
377 }
378
379 =item check
380
381 Checks all fields to make sure this is a valid package definition.  If
382 there is an error, returns the error, otherwise returns false.  Called by the
383 insert and replace methods.
384
385 =cut
386
387 sub check {
388   my $self = shift;
389   warn "FS::part_pkg::check called on $self" if $DEBUG;
390
391   for (qw(setup recur plandata)) {
392     #$self->set($_=>0) if $self->get($_) =~ /^\s*$/; }
393     return "Use of $_ field is deprecated; set a plan and options: ".
394            $self->get($_)
395       if length($self->get($_));
396     $self->set($_, '');
397   }
398
399   if ( $self->dbdef_table->column('freq')->type =~ /(int)/i ) {
400     my $error = $self->ut_number('freq');
401     return $error if $error;
402   } else {
403     $self->freq =~ /^(\d+[hdw]?)$/
404       or return "Illegal or empty freq: ". $self->freq;
405     $self->freq($1);
406   }
407
408   my $error = $self->ut_numbern('pkgpart')
409     || $self->ut_text('pkg')
410     || $self->ut_text('comment')
411     || $self->ut_textn('promo_code')
412     || $self->ut_alphan('plan')
413     || $self->ut_enum('setuptax', [ '', 'Y' ] )
414     || $self->ut_enum('recurtax', [ '', 'Y' ] )
415     || $self->ut_textn('taxclass')
416     || $self->ut_enum('disabled', [ '', 'Y' ] )
417     || $self->ut_floatn('pay_weight')
418     || $self->ut_floatn('credit_weight')
419     || $self->ut_numbern('taxproductnum')
420     || $self->ut_foreign_keyn('taxproductnum',
421                               'part_pkg_taxproduct',
422                               'taxproductnum'
423                              )
424     || $self->ut_agentnum_acl('agentnum', 'Edit global package definitions')
425     || $self->SUPER::check
426   ;
427   return $error if $error;
428
429   if ( $self->classnum !~ /^$/ ) {
430     my $error = $self->ut_foreign_key('classnum', 'pkg_class', 'classnum');
431     return $error if $error;
432   } else {
433     $self->classnum('');
434   }
435
436   return 'Unknown plan '. $self->plan
437     unless exists($plans{$self->plan});
438
439   my $conf = new FS::Conf;
440   return 'Taxclass is required'
441     if ! $self->taxclass && $conf->exists('require_taxclasses');
442
443   '';
444 }
445
446 =item pkg_comment
447
448 Returns an (internal) string representing this package.  Currently,
449 "pkgpart: pkg - comment", is returned.  "pkg - comment" may be returned in the
450 future, omitting pkgpart.
451
452 =cut
453
454 sub pkg_comment {
455   my $self = shift;
456
457   #$self->pkg. ' - '. $self->comment;
458   #$self->pkg. ' ('. $self->comment. ')';
459   $self->pkgpart. ': '. $self->pkg. ' - '. $self->comment;
460 }
461
462 =item pkg_class
463
464 Returns the package class, as an FS::pkg_class object, or the empty string
465 if there is no package class.
466
467 =cut
468
469 sub pkg_class {
470   my $self = shift;
471   if ( $self->classnum ) {
472     qsearchs('pkg_class', { 'classnum' => $self->classnum } );
473   } else {
474     return '';
475   }
476 }
477
478 =item categoryname 
479
480 Returns the package category name, or the empty string if there is no package
481 category.
482
483 =cut
484
485 sub categoryname {
486   my $self = shift;
487   my $pkg_class = $self->pkg_class;
488   $pkg_class
489     ? $pkg_class->categoryname
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 [ HASHREF | OPTION => VALUE ]
520
521 Returns all FS::pkg_svc objects (see L<FS::pkg_svc>) for this package
522 definition (with non-zero quantity).
523
524 One option is available, I<disable_linked>.  If set true it will return the
525 services for this package definition alone, omitting services from any add-on
526 packages.
527
528 =cut
529
530 sub pkg_svc {
531   my $self = shift;
532
533 #  #sort { $b->primary cmp $a->primary } 
534 #    grep { $_->quantity }
535 #      qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
536
537   my $opt = ref($_[0]) ? $_[0] : { @_ };
538   my %pkg_svc = map  { $_->svcpart => $_ }
539                 grep { $_->quantity }
540                 qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
541
542   unless ( $opt->{disable_linked} ) {
543     foreach my $dst_pkg ( map $_->dst_pkg, $self->svc_part_pkg_link ) {
544       my @pkg_svc = grep { $_->quantity }
545                     qsearch( 'pkg_svc', { pkgpart=>$dst_pkg->pkgpart } );
546       foreach my $pkg_svc ( @pkg_svc ) {
547         if ( $pkg_svc{$pkg_svc->svcpart} ) {
548           my $quantity = $pkg_svc{$pkg_svc->svcpart}->quantity;
549           $pkg_svc{$pkg_svc->svcpart}->quantity($quantity + $pkg_svc->quantity);
550         } else {
551           $pkg_svc{$pkg_svc->svcpart} = $pkg_svc;
552         }
553       }
554     }
555   }
556
557   values(%pkg_svc);
558
559 }
560
561 =item svcpart [ SVCDB ]
562
563 Returns the svcpart of the primary service definition (see L<FS::part_svc>)
564 associated with this package definition (see L<FS::pkg_svc>).  Returns
565 false if there not a primary service definition or exactly one service
566 definition with quantity 1, or if SVCDB is specified and does not match the
567 svcdb of the service definition, 
568
569 =cut
570
571 sub svcpart {
572   my $self = shift;
573   my $svcdb = scalar(@_) ? shift : '';
574   my @svcdb_pkg_svc =
575     grep { ( $svcdb eq $_->part_svc->svcdb || !$svcdb ) } $self->pkg_svc;
576   my @pkg_svc = ();
577   @pkg_svc = grep { $_->primary_svc =~ /^Y/i } @svcdb_pkg_svc
578     if dbdef->table('pkg_svc')->column('primary_svc');
579   @pkg_svc = grep {$_->quantity == 1 } @svcdb_pkg_svc
580     unless @pkg_svc;
581   return '' if scalar(@pkg_svc) != 1;
582   $pkg_svc[0]->svcpart;
583 }
584
585 =item payby
586
587 Returns a list of the acceptable payment types for this package.  Eventually
588 this should come out of a database table and be editable, but currently has the
589 following logic instead:
590
591 If the package is free, the single item B<BILL> is
592 returned, otherwise, the single item B<CARD> is returned.
593
594 (CHEK?  LEC?  Probably shouldn't accept those by default, prone to abuse)
595
596 =cut
597
598 sub payby {
599   my $self = shift;
600   if ( $self->is_free ) {
601     ( 'BILL' );
602   } else {
603     ( 'CARD' );
604   }
605 }
606
607 =item is_free
608
609 Returns true if this package is free.  
610
611 =cut
612
613 sub is_free {
614   my $self = shift;
615   unless ( $self->plan ) {
616     $self->setup =~ /^\s*0+(\.0*)?\s*$/
617       && $self->recur =~ /^\s*0+(\.0*)?\s*$/;
618   } elsif ( $self->can('is_free_options') ) {
619     not grep { $_ !~ /^\s*0*(\.0*)?\s*$/ }
620          map { $self->option($_) } 
621              $self->is_free_options;
622   } else {
623     warn "FS::part_pkg::is_free: FS::part_pkg::". $self->plan. " subclass ".
624          "provides neither is_free_options nor is_free method; returning false";
625     0;
626   }
627 }
628
629
630 sub freqs_href {
631   #method, class method or sub? #my $self = shift;
632
633   tie my %freq, 'Tie::IxHash', 
634     '0'    => '(no recurring fee)',
635     '1h'   => 'hourly',
636     '1d'   => 'daily',
637     '2d'   => 'every two days',
638     '3d'   => 'every three days',
639     '1w'   => 'weekly',
640     '2w'   => 'biweekly (every 2 weeks)',
641     '1'    => 'monthly',
642     '45d'  => 'every 45 days',
643     '2'    => 'bimonthly (every 2 months)',
644     '3'    => 'quarterly (every 3 months)',
645     '4'    => 'every 4 months',
646     '137d' => 'every 4 1/2 months (137 days)',
647     '6'    => 'semiannually (every 6 months)',
648     '12'   => 'annually',
649     '13'   => 'every 13 months (annually +1 month)',
650     '24'   => 'biannually (every 2 years)',
651     '36'   => 'triannually (every 3 years)',
652     '48'   => '(every 4 years)',
653     '60'   => '(every 5 years)',
654     '120'  => '(every 10 years)',
655   ;
656
657   \%freq;
658
659 }
660
661 =item freq_pretty
662
663 Returns an english representation of the I<freq> field, such as "monthly",
664 "weekly", "semi-annually", etc.
665
666 =cut
667
668 sub freq_pretty {
669   my $self = shift;
670   my $freq = $self->freq;
671
672   #my $freqs_href = $self->freqs_href;
673   my $freqs_href = freqs_href();
674
675   if ( exists($freqs_href->{$freq}) ) {
676     $freqs_href->{$freq};
677   } else {
678     my $interval = 'month';
679     if ( $freq =~ /^(\d+)([hdw])$/ ) {
680       my %interval = ( 'h' => 'hour', 'd'=>'day', 'w'=>'week' );
681       $interval = $interval{$2};
682     }
683     if ( $1 == 1 ) {
684       "every $interval";
685     } else {
686       "every $freq ${interval}s";
687     }
688   }
689 }
690
691 =item plandata
692
693 For backwards compatibility, returns the plandata field as well as all options
694 from FS::part_pkg_option.
695
696 =cut
697
698 sub plandata {
699   my $self = shift;
700   carp "plandata is deprecated";
701   if ( @_ ) {
702     $self->SUPER::plandata(@_);
703   } else {
704     my $plandata = $self->get('plandata');
705     my %options = $self->options;
706     $plandata .= join('', map { "$_=$options{$_}\n" } keys %options );
707     $plandata;
708   }
709 }
710
711 =item part_pkg_option
712
713 Returns all options as FS::part_pkg_option objects (see
714 L<FS::part_pkg_option>).
715
716 =cut
717
718 sub part_pkg_option {
719   my $self = shift;
720   qsearch('part_pkg_option', { 'pkgpart' => $self->pkgpart } );
721 }
722
723 =item options 
724
725 Returns a list of option names and values suitable for assigning to a hash.
726
727 =cut
728
729 sub options {
730   my $self = shift;
731   map { $_->optionname => $_->optionvalue } $self->part_pkg_option;
732 }
733
734 =item option OPTIONNAME
735
736 Returns the option value for the given name, or the empty string.
737
738 =cut
739
740 sub option {
741   my( $self, $opt, $ornull ) = @_;
742   my $part_pkg_option =
743     qsearchs('part_pkg_option', {
744       pkgpart    => $self->pkgpart,
745       optionname => $opt,
746   } );
747   return $part_pkg_option->optionvalue if $part_pkg_option;
748   my %plandata = map { /^(\w+)=(.*)$/; ( $1 => $2 ); }
749                      split("\n", $self->get('plandata') );
750   return $plandata{$opt} if exists $plandata{$opt};
751   cluck "WARNING: (pkgpart ". $self->pkgpart. ") Package def option $opt ".
752         "not found in options or plandata!\n"
753     unless $ornull;
754   '';
755 }
756
757 =item bill_part_pkg_link
758
759 Returns the associated part_pkg_link records (see L<FS::part_pkg_link).
760
761 =cut
762
763 sub bill_part_pkg_link {
764   shift->_part_pkg_link('bill', @_);
765 }
766
767 =item svc_part_pkg_link
768
769 =cut
770
771 sub svc_part_pkg_link {
772   shift->_part_pkg_link('svc', @_);
773 }
774
775 sub _part_pkg_link {
776   my( $self, $type ) = @_;
777   qsearch('part_pkg_link', { 'src_pkgpart' => $self->pkgpart,
778                              'link_type'   => $type,
779                            }
780          );
781 }
782
783 sub self_and_bill_linked {
784   shift->_self_and_linked('bill', @_);
785 }
786
787 sub _self_and_linked {
788   my( $self, $type ) = @_;
789
790   ( $self,
791     map { $_->dst_pkg->_self_and_linked($type) }
792         $self->_part_pkg_link($type)
793   );
794 }
795
796 =item part_pkg_taxoverride
797
798 Returns all associated FS::part_pkg_taxoverride objects (see
799 L<FS::part_pkg_taxoverride>).
800
801 =cut
802
803 sub part_pkg_taxoverride {
804   my $self = shift;
805   qsearch('part_pkg_taxoverride', { 'pkgpart' => $self->pkgpart } );
806 }
807
808 =item taxproduct_description
809
810 Returns the description of the associated tax product for this package
811 definition (see L<FS::part_pkg_taxproduct>).
812
813 =cut
814
815 sub taxproduct_description {
816   my $self = shift;
817   my $part_pkg_taxproduct =
818     qsearchs( 'part_pkg_taxproduct',
819               { 'taxproductnum' => $self->taxproductnum }
820             );
821   $part_pkg_taxproduct ? $part_pkg_taxproduct->description : '';
822 }
823
824 =item part_pkg_taxrate DATA_PROVIDER, GEOCODE
825
826 Returns the package to taxrate m2m records for this package in the location
827 specified by GEOCODE (see L<FS::part_pkg_taxrate> and ).
828
829 =cut
830
831 sub _expand_cch_taxproductnum {
832   my $self = shift;
833   my $part_pkg_taxproduct =
834     qsearchs( 'part_pkg_taxproduct',
835               { 'taxproductnum' => $self->taxproductnum }
836             );
837   my ($a,$b,$c,$d) = ( $part_pkg_taxproduct
838                          ? ( split ':', $part_pkg_taxproduct->taxproduct )
839                          : ()
840                      );
841   my $extra_sql = "AND ( taxproduct = '$a:$b:$c:$d'
842                       OR taxproduct = '$a:$b:$c:'
843                       OR taxproduct = '$a:$b:".":$d'
844                       OR taxproduct = '$a:$b:".":' )";
845   map { $_->taxproductnum } qsearch( { 'table'     => 'part_pkg_taxproduct',
846                                        'hashref'   => { 'data_vendor'=>'cch' },
847                                        'extra_sql' => $extra_sql,
848                                    } );
849                                      
850 }
851
852 sub part_pkg_taxrate {
853   my $self = shift;
854   my ($data_vendor, $geocode) = @_;
855
856   my $dbh = dbh;
857   my $extra_sql = 'WHERE part_pkg_taxproduct.data_vendor = '.
858                   dbh->quote($data_vendor);
859   
860   # CCH oddness in m2m
861   $extra_sql .= ' AND ('.
862     join(' OR ', map{ 'geocode = '. $dbh->quote(substr($geocode, 0, $_)) }
863                  qw(10 5 2)
864         ).
865     ')';
866   # much more CCH oddness in m2m -- this is kludgy
867   $extra_sql .= ' AND ('.
868     join(' OR ', map{ "taxproductnum = $_" } $self->_expand_cch_taxproductnum).
869     ')';
870
871   my $addl_from = 'LEFT JOIN part_pkg_taxproduct USING ( taxproductnum )';
872   my $order_by = 'ORDER BY taxclassnum, length(geocode) desc, length(taxproduct) desc';
873   my $select   = 'DISTINCT ON(taxclassnum) *, taxproduct';
874
875   # should qsearch preface columns with the table to facilitate joins?
876   qsearch( { 'table'     => 'part_pkg_taxrate',
877              'select'    => $select,
878              'hashref'   => { # 'data_vendor'   => $data_vendor,
879                               # 'taxproductnum' => $self->taxproductnum,
880                             },
881              'addl_from' => $addl_from,
882              'extra_sql' => $extra_sql,
883              'order_by'  => $order_by,
884          } );
885 }
886
887 =item _rebless
888
889 Reblesses the object into the FS::part_pkg::PLAN class (if available), where
890 PLAN is the object's I<plan> field.  There should be better docs
891 on how to create new price plans, but until then, see L</NEW PLAN CLASSES>.
892
893 =cut
894
895 sub _rebless {
896   my $self = shift;
897   my $plan = $self->plan;
898   unless ( $plan ) {
899     cluck "no price plan found for pkgpart ". $self->pkgpart. "\n"
900       if $DEBUG;
901     return $self;
902   }
903   return $self if ref($self) =~ /::$plan$/; #already blessed into plan subclass
904   my $class = ref($self). "::$plan";
905   warn "reblessing $self into $class" if $DEBUG;
906   eval "use $class;";
907   die $@ if $@;
908   bless($self, $class) unless $@;
909   $self;
910 }
911
912 #fallbacks that eval the setup and recur fields, for backwards compat
913
914 sub calc_setup {
915   my $self = shift;
916   warn 'no price plan class for '. $self->plan. ", eval-ing setup\n";
917   $self->_calc_eval('setup', @_);
918 }
919
920 sub calc_recur {
921   my $self = shift;
922   warn 'no price plan class for '. $self->plan. ", eval-ing recur\n";
923   $self->_calc_eval('recur', @_);
924 }
925
926 use vars qw( $sdate @details );
927 sub _calc_eval {
928   #my( $self, $field, $cust_pkg ) = @_;
929   my( $self, $field, $cust_pkg, $sdateref, $detailsref ) = @_;
930   *sdate = $sdateref;
931   *details = $detailsref;
932   $self->$field() =~ /^(.*)$/
933     or die "Illegal $field (pkgpart ". $self->pkgpart. '): '.
934             $self->$field(). "\n";
935   my $prog = $1;
936   return 0 if $prog =~ /^\s*$/;
937   my $value = eval $prog;
938   die $@ if $@;
939   $value;
940 }
941
942 #fallback that return 0 for old legacy packages with no plan
943
944 sub calc_remain { 0; }
945 sub calc_cancel { 0; }
946 sub calc_units  { 0; }
947
948 =back
949
950 =cut
951
952 # _upgrade_data
953 #
954 # Used by FS::Upgrade to migrate to a new database.
955
956 sub _upgrade_data { # class method
957   my($class, %opts) = @_;
958
959   warn "[FS::part_pkg] upgrading $class\n" if $DEBUG;
960
961   my @part_pkg = qsearch({
962     'table'     => 'part_pkg',
963     'extra_sql' => "WHERE ". join(' OR ',
964                      ( map "($_ IS NOT NULL AND $_ != '' )",
965                            qw( plandata setup recur ) ),
966                      'plan IS NULL', "plan = '' ",
967                    ),
968   });
969
970   foreach my $part_pkg (@part_pkg) {
971
972     unless ( $part_pkg->plan ) {
973
974       $part_pkg->plan('flat');
975
976       if ( $part_pkg->setup =~ /^\s*([\d\.]+)\s*$/ ) {
977
978         my $opt = new FS::part_pkg_option {
979           'pkgpart'     => $part_pkg->pkgpart,
980           'optionname'  => 'setup_fee',
981           'optionvalue' => $1,
982         };
983         my $error = $opt->insert;
984         die $error if $error;
985
986         $part_pkg->setup('');
987
988       } else {
989         die "Can't parse part_pkg.setup for fee; convert pkgnum ".
990             $part_pkg->pkgnum. " manually: ". $part_pkg->setup. "\n";
991       }
992
993       if ( $part_pkg->recur =~ /^\s*([\d\.]+)\s*$/ ) {
994
995         my $opt = new FS::part_pkg_option {
996           'pkgpart'     => $part_pkg->pkgpart,
997           'optionname'  => 'recur_fee',
998           'optionvalue' => $1,
999         };
1000         my $error = $opt->insert;
1001         die $error if $error;
1002
1003         $part_pkg->recur('');
1004
1005       } else {
1006         die "Can't parse part_pkg.setup for fee; convert pkgnum ".
1007             $part_pkg->pkgnum. " manually: ". $part_pkg->setup. "\n";
1008       }
1009
1010     }
1011
1012     $part_pkg->replace; #this should take care of plandata, right?
1013
1014   }
1015
1016 }
1017
1018 =head1 SUBROUTINES
1019
1020 =over 4
1021
1022 =item plan_info
1023
1024 =cut
1025
1026 my %info;
1027 foreach my $INC ( @INC ) {
1028   warn "globbing $INC/FS/part_pkg/*.pm\n" if $DEBUG;
1029   foreach my $file ( glob("$INC/FS/part_pkg/*.pm") ) {
1030     warn "attempting to load plan info from $file\n" if $DEBUG;
1031     $file =~ /\/(\w+)\.pm$/ or do {
1032       warn "unrecognized file in $INC/FS/part_pkg/: $file\n";
1033       next;
1034     };
1035     my $mod = $1;
1036     my $info = eval "use FS::part_pkg::$mod; ".
1037                     "\\%FS::part_pkg::$mod\::info;";
1038     if ( $@ ) {
1039       die "error using FS::part_pkg::$mod (skipping): $@\n" if $@;
1040       next;
1041     }
1042     unless ( keys %$info ) {
1043       warn "no %info hash found in FS::part_pkg::$mod, skipping\n"
1044         unless $mod =~ /^(passwdfile|null)$/; #hack but what the heck
1045       next;
1046     }
1047     warn "got plan info from FS::part_pkg::$mod: $info\n" if $DEBUG;
1048     if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
1049       warn "skipping disabled plan FS::part_pkg::$mod" if $DEBUG;
1050       next;
1051     }
1052     $info{$mod} = $info;
1053   }
1054 }
1055
1056 tie %plans, 'Tie::IxHash',
1057   map { $_ => $info{$_} }
1058   sort { $info{$a}->{'weight'} <=> $info{$b}->{'weight'} }
1059   keys %info;
1060
1061 sub plan_info {
1062   \%plans;
1063 }
1064
1065 =item format OPTION DATA
1066
1067 Returns data formatted according to the function 'format' described
1068 in the plan info.  Returns DATA if no such function exists.
1069
1070 =cut
1071
1072 sub format {
1073   my ($self, $option, $data) = (shift, shift, shift);
1074   if (exists($plans{$self->plan}->{fields}->{$option}{format})) {
1075     &{$plans{$self->plan}->{fields}->{$option}{format}}($data);
1076   }else{
1077     $data;
1078   }
1079 }
1080
1081 =item parse OPTION DATA
1082
1083 Returns data parsed according to the function 'parse' described
1084 in the plan info.  Returns DATA if no such function exists.
1085
1086 =cut
1087
1088 sub parse {
1089   my ($self, $option, $data) = (shift, shift, shift);
1090   if (exists($plans{$self->plan}->{fields}->{$option}{parse})) {
1091     &{$plans{$self->plan}->{fields}->{$option}{parse}}($data);
1092   }else{
1093     $data;
1094   }
1095 }
1096
1097
1098 =back
1099
1100 =head1 NEW PLAN CLASSES
1101
1102 A module should be added in FS/FS/part_pkg/  Eventually, an example may be
1103 found in eg/plan_template.pm.  Until then, it is suggested that you use the
1104 other modules in FS/FS/part_pkg/ as a guide.
1105
1106 =head1 BUGS
1107
1108 The delete method is unimplemented.
1109
1110 setup and recur semantics are not yet defined (and are implemented in
1111 FS::cust_bill.  hmm.).  now they're deprecated and need to go.
1112
1113 plandata should go
1114
1115 part_pkg_taxrate is Pg specific
1116
1117 =head1 SEE ALSO
1118
1119 L<FS::Record>, L<FS::cust_pkg>, L<FS::type_pkgs>, L<FS::pkg_svc>, L<Safe>.
1120 schema.html from the base documentation.
1121
1122 =cut
1123
1124 1;
1125