start implementing billing add-ons
[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 [ HASHREF | OPTION => VALUE ]
495
496 Returns all FS::pkg_svc objects (see L<FS::pkg_svc>) for this package
497 definition (with non-zero quantity).
498
499 One option is available, I<disable_linked>.  If set true it will return the
500 services for this package definition alone, omitting services from any add-on
501 packages.
502
503 =cut
504
505 sub pkg_svc {
506   my $self = shift;
507
508 #  #sort { $b->primary cmp $a->primary } 
509 #    grep { $_->quantity }
510 #      qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
511
512   my $opt = ref($_[0]) ? $_[0] : { @_ };
513   my %pkg_svc = map  { $_->svcpart => $_ }
514                 grep { $_->quantity }
515                 qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
516
517   unless ( $opt->{disable_linked} ) {
518     foreach my $dst_pkg ( map $_->dst_pkg, $self->svc_part_pkg_link ) {
519       my @pkg_svc = grep { $_->quantity }
520                     qsearch( 'pkg_svc', { pkgpart=>$dst_pkg->pkgpart } );
521       foreach my $pkg_svc ( @pkg_svc ) {
522         if ( $pkg_svc{$pkg_svc->svcpart} ) {
523           my $quantity = $pkg_svc{$pkg_svc->svcpart}->quantity;
524           $pkg_svc{$pkg_svc->svcpart}->quantity($quantity + $pkg_svc->quantity);
525         } else {
526           $pkg_svc{$pkg_svc->svcpart} = $pkg_svc;
527         }
528       }
529     }
530   }
531
532   values(%pkg_svc);
533
534 }
535
536 =item svcpart [ SVCDB ]
537
538 Returns the svcpart of the primary service definition (see L<FS::part_svc>)
539 associated with this package definition (see L<FS::pkg_svc>).  Returns
540 false if there not a primary service definition or exactly one service
541 definition with quantity 1, or if SVCDB is specified and does not match the
542 svcdb of the service definition, 
543
544 =cut
545
546 sub svcpart {
547   my $self = shift;
548   my $svcdb = scalar(@_) ? shift : '';
549   my @svcdb_pkg_svc =
550     grep { ( $svcdb eq $_->part_svc->svcdb || !$svcdb ) } $self->pkg_svc;
551   my @pkg_svc = ();
552   @pkg_svc = grep { $_->primary_svc =~ /^Y/i } @svcdb_pkg_svc
553     if dbdef->table('pkg_svc')->column('primary_svc');
554   @pkg_svc = grep {$_->quantity == 1 } @svcdb_pkg_svc
555     unless @pkg_svc;
556   return '' if scalar(@pkg_svc) != 1;
557   $pkg_svc[0]->svcpart;
558 }
559
560 =item payby
561
562 Returns a list of the acceptable payment types for this package.  Eventually
563 this should come out of a database table and be editable, but currently has the
564 following logic instead:
565
566 If the package is free, the single item B<BILL> is
567 returned, otherwise, the single item B<CARD> is returned.
568
569 (CHEK?  LEC?  Probably shouldn't accept those by default, prone to abuse)
570
571 =cut
572
573 sub payby {
574   my $self = shift;
575   if ( $self->is_free ) {
576     ( 'BILL' );
577   } else {
578     ( 'CARD' );
579   }
580 }
581
582 =item is_free
583
584 Returns true if this package is free.  
585
586 =cut
587
588 sub is_free {
589   my $self = shift;
590   unless ( $self->plan ) {
591     $self->setup =~ /^\s*0+(\.0*)?\s*$/
592       && $self->recur =~ /^\s*0+(\.0*)?\s*$/;
593   } elsif ( $self->can('is_free_options') ) {
594     not grep { $_ !~ /^\s*0*(\.0*)?\s*$/ }
595          map { $self->option($_) } 
596              $self->is_free_options;
597   } else {
598     warn "FS::part_pkg::is_free: FS::part_pkg::". $self->plan. " subclass ".
599          "provides neither is_free_options nor is_free method; returning false";
600     0;
601   }
602 }
603
604
605 sub freqs_href {
606   #method, class method or sub? #my $self = shift;
607
608   tie my %freq, 'Tie::IxHash', 
609     '0'    => '(no recurring fee)',
610     '1h'   => 'hourly',
611     '1d'   => 'daily',
612     '2d'   => 'every two days',
613     '3d'   => 'every three days',
614     '1w'   => 'weekly',
615     '2w'   => 'biweekly (every 2 weeks)',
616     '1'    => 'monthly',
617     '45d'  => 'every 45 days',
618     '2'    => 'bimonthly (every 2 months)',
619     '3'    => 'quarterly (every 3 months)',
620     '4'    => 'every 4 months',
621     '137d' => 'every 4 1/2 months (137 days)',
622     '6'    => 'semiannually (every 6 months)',
623     '12'   => 'annually',
624     '13'   => 'every 13 months (annually +1 month)',
625     '24'   => 'biannually (every 2 years)',
626     '36'   => 'triannually (every 3 years)',
627     '48'   => '(every 4 years)',
628     '60'   => '(every 5 years)',
629     '120'  => '(every 10 years)',
630   ;
631
632   \%freq;
633
634 }
635
636 =item freq_pretty
637
638 Returns an english representation of the I<freq> field, such as "monthly",
639 "weekly", "semi-annually", etc.
640
641 =cut
642
643 sub freq_pretty {
644   my $self = shift;
645   my $freq = $self->freq;
646
647   #my $freqs_href = $self->freqs_href;
648   my $freqs_href = freqs_href();
649
650   if ( exists($freqs_href->{$freq}) ) {
651     $freqs_href->{$freq};
652   } else {
653     my $interval = 'month';
654     if ( $freq =~ /^(\d+)([hdw])$/ ) {
655       my %interval = ( 'h' => 'hour', 'd'=>'day', 'w'=>'week' );
656       $interval = $interval{$2};
657     }
658     if ( $1 == 1 ) {
659       "every $interval";
660     } else {
661       "every $freq ${interval}s";
662     }
663   }
664 }
665
666 =item plandata
667
668 For backwards compatibility, returns the plandata field as well as all options
669 from FS::part_pkg_option.
670
671 =cut
672
673 sub plandata {
674   my $self = shift;
675   carp "plandata is deprecated";
676   if ( @_ ) {
677     $self->SUPER::plandata(@_);
678   } else {
679     my $plandata = $self->get('plandata');
680     my %options = $self->options;
681     $plandata .= join('', map { "$_=$options{$_}\n" } keys %options );
682     $plandata;
683   }
684 }
685
686 =item part_pkg_option
687
688 Returns all options as FS::part_pkg_option objects (see
689 L<FS::part_pkg_option>).
690
691 =cut
692
693 sub part_pkg_option {
694   my $self = shift;
695   qsearch('part_pkg_option', { 'pkgpart' => $self->pkgpart } );
696 }
697
698 =item options 
699
700 Returns a list of option names and values suitable for assigning to a hash.
701
702 =cut
703
704 sub options {
705   my $self = shift;
706   map { $_->optionname => $_->optionvalue } $self->part_pkg_option;
707 }
708
709 =item option OPTIONNAME
710
711 Returns the option value for the given name, or the empty string.
712
713 =cut
714
715 sub option {
716   my( $self, $opt, $ornull ) = @_;
717   my $part_pkg_option =
718     qsearchs('part_pkg_option', {
719       pkgpart    => $self->pkgpart,
720       optionname => $opt,
721   } );
722   return $part_pkg_option->optionvalue if $part_pkg_option;
723   my %plandata = map { /^(\w+)=(.*)$/; ( $1 => $2 ); }
724                      split("\n", $self->get('plandata') );
725   return $plandata{$opt} if exists $plandata{$opt};
726   cluck "WARNING: (pkgpart ". $self->pkgpart. ") Package def option $opt ".
727         "not found in options or plandata!\n"
728     unless $ornull;
729   '';
730 }
731
732 =item bill_part_pkg_link
733
734 Returns the associated part_pkg_link records (see L<FS::part_pkg_link).
735
736 =cut
737
738 sub bill_part_pkg_link {
739   shift->_part_pkg_link('bill', @_);
740 }
741
742 =item svc_part_pkg_link
743
744 =cut
745
746 sub svc_part_pkg_link {
747   shift->_part_pkg_link('svc', @_);
748 }
749
750 sub _part_pkg_link {
751   my( $self, $type ) = @_;
752   qsearch('part_pkg_link', { 'src_pkgpart' => $self->pkgpart,
753                              'link_type'   => $type,
754                            }
755          );
756 }
757
758 sub self_and_bill_linked {
759   shift->_self_and_linked('bill', @_);
760 }
761
762 sub _self_and_linked {
763   my( $self, $type ) = @_;
764
765   ( $self,
766     map { $_->dst_pkg->_self_and_linked($type) }
767         $self->_part_pkg_link($type)
768   );
769 }
770
771 =item part_pkg_taxoverride
772
773 Returns all associated FS::part_pkg_taxoverride objects (see
774 L<FS::part_pkg_taxoverride>).
775
776 =cut
777
778 sub part_pkg_taxoverride {
779   my $self = shift;
780   qsearch('part_pkg_taxoverride', { 'pkgpart' => $self->pkgpart } );
781 }
782
783 =item taxproduct_description
784
785 Returns the description of the associated tax product for this package
786 definition (see L<FS::part_pkg_taxproduct>).
787
788 =cut
789
790 sub taxproduct_description {
791   my $self = shift;
792   my $part_pkg_taxproduct =
793     qsearchs( 'part_pkg_taxproduct',
794               { 'taxproductnum' => $self->taxproductnum }
795             );
796   $part_pkg_taxproduct ? $part_pkg_taxproduct->description : '';
797 }
798
799 =item part_pkg_taxrate DATA_PROVIDER, GEOCODE
800
801 Returns the package to taxrate m2m records for this package in the location
802 specified by GEOCODE (see L<FS::part_pkg_taxrate> and ).
803
804 =cut
805
806 sub part_pkg_taxrate {
807   my $self = shift;
808   my ($data_vendor, $geocode) = @_;
809
810   my $dbh = dbh;
811   # CCH oddness in m2m
812   my $extra_sql = 'AND ('.
813     join(' OR ', map{ 'geocode = '. $dbh->quote(substr($geocode, 0, $_)) }
814                  qw(10 5 2)
815         ).
816     ')';
817   my $order_by = 'ORDER BY taxclassnum, length(geocode) desc';
818   my $select   = 'DISTINCT ON(taxclassnum) *';
819
820   qsearch( { 'table'     => 'part_pkg_taxrate',
821              'select'    => 'distinct on(taxclassnum) *',
822              'hashref'   => { 'data_vendor'   => $data_vendor,
823                               'taxproductnum' => $self->taxproductnum,
824                             },
825              'extra_sql' => $extra_sql,
826              'order_by'  => $order_by,
827          } );
828 }
829
830 =item _rebless
831
832 Reblesses the object into the FS::part_pkg::PLAN class (if available), where
833 PLAN is the object's I<plan> field.  There should be better docs
834 on how to create new price plans, but until then, see L</NEW PLAN CLASSES>.
835
836 =cut
837
838 sub _rebless {
839   my $self = shift;
840   my $plan = $self->plan;
841   unless ( $plan ) {
842     cluck "no price plan found for pkgpart ". $self->pkgpart. "\n"
843       if $DEBUG;
844     return $self;
845   }
846   return $self if ref($self) =~ /::$plan$/; #already blessed into plan subclass
847   my $class = ref($self). "::$plan";
848   warn "reblessing $self into $class" if $DEBUG;
849   eval "use $class;";
850   die $@ if $@;
851   bless($self, $class) unless $@;
852   $self;
853 }
854
855 #fallbacks that eval the setup and recur fields, for backwards compat
856
857 sub calc_setup {
858   my $self = shift;
859   warn 'no price plan class for '. $self->plan. ", eval-ing setup\n";
860   $self->_calc_eval('setup', @_);
861 }
862
863 sub calc_recur {
864   my $self = shift;
865   warn 'no price plan class for '. $self->plan. ", eval-ing recur\n";
866   $self->_calc_eval('recur', @_);
867 }
868
869 use vars qw( $sdate @details );
870 sub _calc_eval {
871   #my( $self, $field, $cust_pkg ) = @_;
872   my( $self, $field, $cust_pkg, $sdateref, $detailsref ) = @_;
873   *sdate = $sdateref;
874   *details = $detailsref;
875   $self->$field() =~ /^(.*)$/
876     or die "Illegal $field (pkgpart ". $self->pkgpart. '): '.
877             $self->$field(). "\n";
878   my $prog = $1;
879   return 0 if $prog =~ /^\s*$/;
880   my $value = eval $prog;
881   die $@ if $@;
882   $value;
883 }
884
885 #fallback that return 0 for old legacy packages with no plan
886
887 sub calc_remain { 0; }
888 sub calc_cancel { 0; }
889
890 =back
891
892 =cut
893
894 # _upgrade_data
895 #
896 # Used by FS::Upgrade to migrate to a new database.
897
898 sub _upgrade_data { # class method
899   my($class, %opts) = @_;
900
901   warn "[FS::part_pkg] upgrading $class\n" if $DEBUG;
902
903   my @part_pkg = qsearch({
904     'table'     => 'part_pkg',
905     'extra_sql' => "WHERE ". join(' OR ',
906                      ( map "($_ IS NOT NULL AND $_ != '' )",
907                            qw( plandata setup recur ) ),
908                      'plan IS NULL', "plan = '' ",
909                    ),
910   });
911
912   foreach my $part_pkg (@part_pkg) {
913
914     unless ( $part_pkg->plan ) {
915
916       $part_pkg->plan('flat');
917
918       if ( $part_pkg->setup =~ /^\s*([\d\.]+)\s*$/ ) {
919
920         my $opt = new FS::part_pkg_option {
921           'pkgpart'     => $part_pkg->pkgpart,
922           'optionname'  => 'setup_fee',
923           'optionvalue' => $1,
924         };
925         my $error = $opt->insert;
926         die $error if $error;
927
928         $part_pkg->setup('');
929
930       } else {
931         die "Can't parse part_pkg.setup for fee; convert pkgnum ".
932             $part_pkg->pkgnum. " manually: ". $part_pkg->setup. "\n";
933       }
934
935       if ( $part_pkg->recur =~ /^\s*([\d\.]+)\s*$/ ) {
936
937         my $opt = new FS::part_pkg_option {
938           'pkgpart'     => $part_pkg->pkgpart,
939           'optionname'  => 'recur_fee',
940           'optionvalue' => $1,
941         };
942         my $error = $opt->insert;
943         die $error if $error;
944
945         $part_pkg->recur('');
946
947       } else {
948         die "Can't parse part_pkg.setup for fee; convert pkgnum ".
949             $part_pkg->pkgnum. " manually: ". $part_pkg->setup. "\n";
950       }
951
952     }
953
954     $part_pkg->replace; #this should take care of plandata, right?
955
956   }
957
958 }
959
960 =head1 SUBROUTINES
961
962 =over 4
963
964 =item plan_info
965
966 =cut
967
968 my %info;
969 foreach my $INC ( @INC ) {
970   warn "globbing $INC/FS/part_pkg/*.pm\n" if $DEBUG;
971   foreach my $file ( glob("$INC/FS/part_pkg/*.pm") ) {
972     warn "attempting to load plan info from $file\n" if $DEBUG;
973     $file =~ /\/(\w+)\.pm$/ or do {
974       warn "unrecognized file in $INC/FS/part_pkg/: $file\n";
975       next;
976     };
977     my $mod = $1;
978     my $info = eval "use FS::part_pkg::$mod; ".
979                     "\\%FS::part_pkg::$mod\::info;";
980     if ( $@ ) {
981       die "error using FS::part_pkg::$mod (skipping): $@\n" if $@;
982       next;
983     }
984     unless ( keys %$info ) {
985       warn "no %info hash found in FS::part_pkg::$mod, skipping\n"
986         unless $mod =~ /^(passwdfile|null)$/; #hack but what the heck
987       next;
988     }
989     warn "got plan info from FS::part_pkg::$mod: $info\n" if $DEBUG;
990     if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
991       warn "skipping disabled plan FS::part_pkg::$mod" if $DEBUG;
992       next;
993     }
994     $info{$mod} = $info;
995   }
996 }
997
998 tie %plans, 'Tie::IxHash',
999   map { $_ => $info{$_} }
1000   sort { $info{$a}->{'weight'} <=> $info{$b}->{'weight'} }
1001   keys %info;
1002
1003 sub plan_info {
1004   \%plans;
1005 }
1006
1007 =item format OPTION DATA
1008
1009 Returns data formatted according to the function 'format' described
1010 in the plan info.  Returns DATA if no such function exists.
1011
1012 =cut
1013
1014 sub format {
1015   my ($self, $option, $data) = (shift, shift, shift);
1016   if (exists($plans{$self->plan}->{fields}->{$option}{format})) {
1017     &{$plans{$self->plan}->{fields}->{$option}{format}}($data);
1018   }else{
1019     $data;
1020   }
1021 }
1022
1023 =item parse OPTION DATA
1024
1025 Returns data parsed according to the function 'parse' described
1026 in the plan info.  Returns DATA if no such function exists.
1027
1028 =cut
1029
1030 sub parse {
1031   my ($self, $option, $data) = (shift, shift, shift);
1032   if (exists($plans{$self->plan}->{fields}->{$option}{parse})) {
1033     &{$plans{$self->plan}->{fields}->{$option}{parse}}($data);
1034   }else{
1035     $data;
1036   }
1037 }
1038
1039
1040 =back
1041
1042 =head1 NEW PLAN CLASSES
1043
1044 A module should be added in FS/FS/part_pkg/  Eventually, an example may be
1045 found in eg/plan_template.pm.  Until then, it is suggested that you use the
1046 other modules in FS/FS/part_pkg/ as a guide.
1047
1048 =head1 BUGS
1049
1050 The delete method is unimplemented.
1051
1052 setup and recur semantics are not yet defined (and are implemented in
1053 FS::cust_bill.  hmm.).  now they're deprecated and need to go.
1054
1055 plandata should go
1056
1057 =head1 SEE ALSO
1058
1059 L<FS::Record>, L<FS::cust_pkg>, L<FS::type_pkgs>, L<FS::pkg_svc>, L<Safe>.
1060 schema.html from the base documentation.
1061
1062 =cut
1063
1064 1;
1065