multiple usage classes checkpoint
[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 [ CLASS ]
805
806 Returns all associated FS::part_pkg_taxoverride objects (see
807 L<FS::part_pkg_taxoverride>).  Limits the returned set to those
808 of class CLASS if defined.  Class may be one of 'setup', 'recur',
809 the empty string (default), or a usage class number (see L<FS::usage_class>).
810 When a class is specified, the empty string class (default) is returned
811 if no more specific values exist.
812
813 =cut
814
815 sub part_pkg_taxoverride {
816   my $self = shift;
817   my $class = shift;
818
819   my $hashref = { 'pkgpart' => $self->pkgpart };
820   $hashref->{'usage_class'} = $class if defined($class);
821   my @overrides = qsearch('part_pkg_taxoverride', $hashref );
822
823   unless ( scalar(@overrides) || !defined($class) || !$class ){
824     $hashref->{'usage_class'} = '';
825     @overrides = qsearch('part_pkg_taxoverride', $hashref );
826   }
827
828   @overrides;
829 }
830
831 =item has_taxproduct
832
833 Returns true if this package has any taxproduct associated with it.  
834
835 =cut
836
837 sub has_taxproduct {
838   my $self = shift;
839
840   $self->taxproductnum ||
841   scalar(grep { $_ =~/^usage_taxproductnum_/ } keys %{ {$self->options} } )
842
843 }
844
845
846 =item taxproduct [ CLASS ]
847
848 Returns the associated tax product for this package definition (see
849 L<FS::part_pkg_taxproduct>).  CLASS may be one of 'setup', 'recur' or
850 the usage classnum (see L<FS::usage_class>).  Returns the default
851 tax product for this record if the more specific CLASS value does
852 not exist.
853
854 =cut
855
856 sub taxproduct {
857   my $self = shift;
858   my $class = shift;
859
860   my $part_pkg_taxproduct;
861
862   my $taxproductnum = $self->taxproductnum;
863   if ($class) { 
864     my $class_taxproductnum = $self->option("usage_taxproductnum_$class", 1);
865     $taxproductnum = $class_taxproductnum
866       if $class_taxproductnum
867   }
868   
869   $part_pkg_taxproduct =
870     qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
871
872   unless ($part_pkg_taxproduct || $taxproductnum eq $self->taxproductnum ) {
873     $taxproductnum = $self->taxproductnum;
874     $part_pkg_taxproduct =
875       qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
876   }
877
878   $part_pkg_taxproduct;
879 }
880
881 =item taxproduct_description [ CLASS ]
882
883 Returns the description of the associated tax product for this package
884 definition (see L<FS::part_pkg_taxproduct>).
885
886 =cut
887
888 sub taxproduct_description {
889   my $self = shift;
890   my $part_pkg_taxproduct = $self->taxproduct(@_);
891   $part_pkg_taxproduct ? $part_pkg_taxproduct->description : '';
892 }
893
894 =item part_pkg_taxrate DATA_PROVIDER, GEOCODE, [ CLASS ]
895
896 Returns the package to taxrate m2m records for this package in the location
897 specified by GEOCODE (see L<FS::part_pkg_taxrate>) and usage class CLASS.
898 CLASS may be one of 'setup', 'recur', or one of the usage classes numbers
899 (see L<FS::usage_class>).
900
901 =cut
902
903 sub _expand_cch_taxproductnum {
904   my $self = shift;
905   my $class = shift;
906   my $part_pkg_taxproduct = $self->taxproduct($class);
907
908   my ($a,$b,$c,$d) = ( $part_pkg_taxproduct
909                          ? ( split ':', $part_pkg_taxproduct->taxproduct )
910                          : ()
911                      );
912   my $extra_sql = "AND ( taxproduct = '$a:$b:$c:$d'
913                       OR taxproduct = '$a:$b:$c:'
914                       OR taxproduct = '$a:$b:".":$d'
915                       OR taxproduct = '$a:$b:".":' )";
916   map { $_->taxproductnum } qsearch( { 'table'     => 'part_pkg_taxproduct',
917                                        'hashref'   => { 'data_vendor'=>'cch' },
918                                        'extra_sql' => $extra_sql,
919                                    } );
920                                      
921 }
922
923 sub part_pkg_taxrate {
924   my $self = shift;
925   my ($data_vendor, $geocode, $class) = @_;
926
927   my $dbh = dbh;
928   my $extra_sql = 'WHERE part_pkg_taxproduct.data_vendor = '.
929                   dbh->quote($data_vendor);
930   
931   # CCH oddness in m2m
932   $extra_sql .= ' AND ('.
933     join(' OR ', map{ 'geocode = '. $dbh->quote(substr($geocode, 0, $_)) }
934                  qw(10 5 2)
935         ).
936     ')';
937   # much more CCH oddness in m2m -- this is kludgy
938   $extra_sql .= ' AND ('.
939     join(' OR ', map{ "taxproductnum = $_" }
940                  $self->_expand_cch_taxproductnum($class)
941         ).
942     ')';
943
944   my $addl_from = 'LEFT JOIN part_pkg_taxproduct USING ( taxproductnum )';
945   my $order_by = 'ORDER BY taxclassnum, length(geocode) desc, length(taxproduct) desc';
946   my $select   = 'DISTINCT ON(taxclassnum) *, taxproduct';
947
948   # should qsearch preface columns with the table to facilitate joins?
949   qsearch( { 'table'     => 'part_pkg_taxrate',
950              'select'    => $select,
951              'hashref'   => { # 'data_vendor'   => $data_vendor,
952                               # 'taxproductnum' => $self->taxproductnum,
953                             },
954              'addl_from' => $addl_from,
955              'extra_sql' => $extra_sql,
956              'order_by'  => $order_by,
957          } );
958 }
959
960 =item _rebless
961
962 Reblesses the object into the FS::part_pkg::PLAN class (if available), where
963 PLAN is the object's I<plan> field.  There should be better docs
964 on how to create new price plans, but until then, see L</NEW PLAN CLASSES>.
965
966 =cut
967
968 sub _rebless {
969   my $self = shift;
970   my $plan = $self->plan;
971   unless ( $plan ) {
972     cluck "no price plan found for pkgpart ". $self->pkgpart. "\n"
973       if $DEBUG;
974     return $self;
975   }
976   return $self if ref($self) =~ /::$plan$/; #already blessed into plan subclass
977   my $class = ref($self). "::$plan";
978   warn "reblessing $self into $class" if $DEBUG;
979   eval "use $class;";
980   die $@ if $@;
981   bless($self, $class) unless $@;
982   $self;
983 }
984
985 #fallbacks that eval the setup and recur fields, for backwards compat
986
987 sub calc_setup {
988   my $self = shift;
989   warn 'no price plan class for '. $self->plan. ", eval-ing setup\n";
990   $self->_calc_eval('setup', @_);
991 }
992
993 sub calc_recur {
994   my $self = shift;
995   warn 'no price plan class for '. $self->plan. ", eval-ing recur\n";
996   $self->_calc_eval('recur', @_);
997 }
998
999 use vars qw( $sdate @details );
1000 sub _calc_eval {
1001   #my( $self, $field, $cust_pkg ) = @_;
1002   my( $self, $field, $cust_pkg, $sdateref, $detailsref ) = @_;
1003   *sdate = $sdateref;
1004   *details = $detailsref;
1005   $self->$field() =~ /^(.*)$/
1006     or die "Illegal $field (pkgpart ". $self->pkgpart. '): '.
1007             $self->$field(). "\n";
1008   my $prog = $1;
1009   return 0 if $prog =~ /^\s*$/;
1010   my $value = eval $prog;
1011   die $@ if $@;
1012   $value;
1013 }
1014
1015 #fallback that return 0 for old legacy packages with no plan
1016
1017 sub calc_remain { 0; }
1018 sub calc_cancel { 0; }
1019 sub calc_units  { 0; }
1020
1021 =back
1022
1023 =cut
1024
1025 # _upgrade_data
1026 #
1027 # Used by FS::Upgrade to migrate to a new database.
1028
1029 sub _upgrade_data { # class method
1030   my($class, %opts) = @_;
1031
1032   warn "[FS::part_pkg] upgrading $class\n" if $DEBUG;
1033
1034   my @part_pkg = qsearch({
1035     'table'     => 'part_pkg',
1036     'extra_sql' => "WHERE ". join(' OR ',
1037                      ( map "($_ IS NOT NULL AND $_ != '' )",
1038                            qw( plandata setup recur ) ),
1039                      'plan IS NULL', "plan = '' ",
1040                    ),
1041   });
1042
1043   foreach my $part_pkg (@part_pkg) {
1044
1045     unless ( $part_pkg->plan ) {
1046
1047       $part_pkg->plan('flat');
1048
1049       if ( $part_pkg->setup =~ /^\s*([\d\.]+)\s*$/ ) {
1050
1051         my $opt = new FS::part_pkg_option {
1052           'pkgpart'     => $part_pkg->pkgpart,
1053           'optionname'  => 'setup_fee',
1054           'optionvalue' => $1,
1055         };
1056         my $error = $opt->insert;
1057         die $error if $error;
1058
1059         $part_pkg->setup('');
1060
1061       } else {
1062         die "Can't parse part_pkg.setup for fee; convert pkgnum ".
1063             $part_pkg->pkgnum. " manually: ". $part_pkg->setup. "\n";
1064       }
1065
1066       if ( $part_pkg->recur =~ /^\s*([\d\.]+)\s*$/ ) {
1067
1068         my $opt = new FS::part_pkg_option {
1069           'pkgpart'     => $part_pkg->pkgpart,
1070           'optionname'  => 'recur_fee',
1071           'optionvalue' => $1,
1072         };
1073         my $error = $opt->insert;
1074         die $error if $error;
1075
1076         $part_pkg->recur('');
1077
1078       } else {
1079         die "Can't parse part_pkg.setup for fee; convert pkgnum ".
1080             $part_pkg->pkgnum. " manually: ". $part_pkg->setup. "\n";
1081       }
1082
1083     }
1084
1085     $part_pkg->replace; #this should take care of plandata, right?
1086
1087   }
1088
1089 }
1090
1091 =head1 SUBROUTINES
1092
1093 =over 4
1094
1095 =item plan_info
1096
1097 =cut
1098
1099 #false laziness w/part_export & cdr
1100 my %info;
1101 foreach my $INC ( @INC ) {
1102   warn "globbing $INC/FS/part_pkg/*.pm\n" if $DEBUG;
1103   foreach my $file ( glob("$INC/FS/part_pkg/*.pm") ) {
1104     warn "attempting to load plan info from $file\n" if $DEBUG;
1105     $file =~ /\/(\w+)\.pm$/ or do {
1106       warn "unrecognized file in $INC/FS/part_pkg/: $file\n";
1107       next;
1108     };
1109     my $mod = $1;
1110     my $info = eval "use FS::part_pkg::$mod; ".
1111                     "\\%FS::part_pkg::$mod\::info;";
1112     if ( $@ ) {
1113       die "error using FS::part_pkg::$mod (skipping): $@\n" if $@;
1114       next;
1115     }
1116     unless ( keys %$info ) {
1117       warn "no %info hash found in FS::part_pkg::$mod, skipping\n";
1118       next;
1119     }
1120     warn "got plan info from FS::part_pkg::$mod: $info\n" if $DEBUG;
1121     if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
1122       warn "skipping disabled plan FS::part_pkg::$mod" if $DEBUG;
1123       next;
1124     }
1125     $info{$mod} = $info;
1126   }
1127 }
1128
1129 tie %plans, 'Tie::IxHash',
1130   map  { $_ => $info{$_} }
1131   sort { $info{$a}->{'weight'} <=> $info{$b}->{'weight'} }
1132   keys %info;
1133
1134 sub plan_info {
1135   \%plans;
1136 }
1137
1138 =item format OPTION DATA
1139
1140 Returns data formatted according to the function 'format' described
1141 in the plan info.  Returns DATA if no such function exists.
1142
1143 =cut
1144
1145 sub format {
1146   my ($self, $option, $data) = (shift, shift, shift);
1147   if (exists($plans{$self->plan}->{fields}->{$option}{format})) {
1148     &{$plans{$self->plan}->{fields}->{$option}{format}}($data);
1149   }else{
1150     $data;
1151   }
1152 }
1153
1154 =item parse OPTION DATA
1155
1156 Returns data parsed according to the function 'parse' described
1157 in the plan info.  Returns DATA if no such function exists.
1158
1159 =cut
1160
1161 sub parse {
1162   my ($self, $option, $data) = (shift, shift, shift);
1163   if (exists($plans{$self->plan}->{fields}->{$option}{parse})) {
1164     &{$plans{$self->plan}->{fields}->{$option}{parse}}($data);
1165   }else{
1166     $data;
1167   }
1168 }
1169
1170
1171 =back
1172
1173 =head1 NEW PLAN CLASSES
1174
1175 A module should be added in FS/FS/part_pkg/  Eventually, an example may be
1176 found in eg/plan_template.pm.  Until then, it is suggested that you use the
1177 other modules in FS/FS/part_pkg/ as a guide.
1178
1179 =head1 BUGS
1180
1181 The delete method is unimplemented.
1182
1183 setup and recur semantics are not yet defined (and are implemented in
1184 FS::cust_bill.  hmm.).  now they're deprecated and need to go.
1185
1186 plandata should go
1187
1188 part_pkg_taxrate is Pg specific
1189
1190 =head1 SEE ALSO
1191
1192 L<FS::Record>, L<FS::cust_pkg>, L<FS::type_pkgs>, L<FS::pkg_svc>, L<Safe>.
1193 schema.html from the base documentation.
1194
1195 =cut
1196
1197 1;
1198