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