add agent type list to package def browse, RT#4880
[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 Time::Local qw( timelocal_nocheck );
8 use Tie::IxHash;
9 use FS::Conf;
10 use FS::Record qw( qsearch qsearchs dbh dbdef );
11 use FS::pkg_svc;
12 use FS::part_svc;
13 use FS::cust_pkg;
14 use FS::agent_type;
15 use FS::type_pkgs;
16 use FS::part_pkg_option;
17 use FS::pkg_class;
18 use FS::agent;
19 use FS::part_pkg_taxoverride;
20 use FS::part_pkg_taxproduct;
21 use FS::part_pkg_link;
22
23 @ISA = qw( FS::m2m_Common FS::option_Common );
24 $DEBUG = 0;
25
26 =head1 NAME
27
28 FS::part_pkg - Object methods for part_pkg objects
29
30 =head1 SYNOPSIS
31
32   use FS::part_pkg;
33
34   $record = new FS::part_pkg \%hash
35   $record = new FS::part_pkg { 'column' => 'value' };
36
37   $custom_record = $template_record->clone;
38
39   $error = $record->insert;
40
41   $error = $new_record->replace($old_record);
42
43   $error = $record->delete;
44
45   $error = $record->check;
46
47   @pkg_svc = $record->pkg_svc;
48
49   $svcnum = $record->svcpart;
50   $svcnum = $record->svcpart( 'svc_acct' );
51
52 =head1 DESCRIPTION
53
54 An FS::part_pkg object represents a package definition.  FS::part_pkg
55 inherits from FS::Record.  The following fields are currently supported:
56
57 =over 4
58
59 =item pkgpart - primary key (assigned automatically for new package definitions)
60
61 =item pkg - Text name of this package definition (customer-viewable)
62
63 =item comment - Text name of this package definition (non-customer-viewable)
64
65 =item classnum - Optional package class (see L<FS::pkg_class>)
66
67 =item promo_code - Promotional code
68
69 =item setup - Setup fee expression (deprecated)
70
71 =item freq - Frequency of recurring fee
72
73 =item recur - Recurring fee expression (deprecated)
74
75 =item setuptax - Setup fee tax exempt flag, empty or `Y'
76
77 =item recurtax - Recurring fee tax exempt flag, empty or `Y'
78
79 =item taxclass - Tax class 
80
81 =item plan - Price plan
82
83 =item plandata - Price plan data (deprecated - see L<FS::part_pkg_option> instead)
84
85 =item disabled - Disabled flag, empty or `Y'
86
87 =item pay_weight - Weight (relative to credit_weight and other package definitions) that controls payment application to specific line items.
88
89 =item credit_weight - Weight (relative to other package definitions) that controls credit application to specific line items.
90
91 =item agentnum - Optional agentnum (see L<FS::agent>)
92
93 =back
94
95 =head1 METHODS
96
97 =over 4 
98
99 =item new HASHREF
100
101 Creates a new package definition.  To add the package definition to
102 the database, see L<"insert">.
103
104 =cut
105
106 sub table { 'part_pkg'; }
107
108 =item clone
109
110 An alternate constructor.  Creates a new package definition by duplicating
111 an existing definition.  A new pkgpart is assigned and `(CUSTOM) ' is prepended
112 to the comment field.  To add the package definition to the database, see
113 L<"insert">.
114
115 =cut
116
117 sub clone {
118   my $self = shift;
119   my $class = ref($self);
120   my %hash = $self->hash;
121   $hash{'pkgpart'} = '';
122   $hash{'comment'} = "(CUSTOM) ". $hash{'comment'}
123     unless $hash{'comment'} =~ /^\(CUSTOM\) /;
124   #new FS::part_pkg ( \%hash ); # ?
125   new $class ( \%hash ); # ?
126 }
127
128 =item insert [ , OPTION => VALUE ... ]
129
130 Adds this package definition to the database.  If there is an error,
131 returns the error, otherwise returns false.
132
133 Currently available options are: I<pkg_svc>, I<primary_svc>, I<cust_pkg>, 
134 I<custnum_ref> and I<options>.
135
136 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
137 values, appropriate FS::pkg_svc records will be inserted.
138
139 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
140 FS::pkg_svc record will be updated.
141
142 If I<cust_pkg> is set to a pkgnum of a FS::cust_pkg record (or the FS::cust_pkg
143 record itself), the object will be updated to point to this package definition.
144
145 In conjunction with I<cust_pkg>, if I<custnum_ref> is set to a scalar reference,
146 the scalar will be updated with the custnum value from the cust_pkg record.
147
148 If I<tax_overrides> is set to a hashref with usage classes as keys and comma
149 separated tax class numbers as values, appropriate FS::part_pkg_taxoverride
150 records will be inserted.
151
152 If I<options> is set to a hashref of options, appropriate FS::part_pkg_option
153 records will be inserted.
154
155 =cut
156
157 sub insert {
158   my $self = shift;
159   my %options = @_;
160   warn "FS::part_pkg::insert called on $self with options ".
161        join(', ', map "$_=>$options{$_}", keys %options)
162     if $DEBUG;
163
164   local $SIG{HUP} = 'IGNORE';
165   local $SIG{INT} = 'IGNORE';
166   local $SIG{QUIT} = 'IGNORE';
167   local $SIG{TERM} = 'IGNORE';
168   local $SIG{TSTP} = 'IGNORE';
169   local $SIG{PIPE} = 'IGNORE';
170
171   my $oldAutoCommit = $FS::UID::AutoCommit;
172   local $FS::UID::AutoCommit = 0;
173   my $dbh = dbh;
174
175   warn "  inserting part_pkg record" if $DEBUG;
176   my $error = $self->SUPER::insert( $options{options} );
177   if ( $error ) {
178     $dbh->rollback if $oldAutoCommit;
179     return $error;
180   }
181
182   my $conf = new FS::Conf;
183   if ( $conf->exists('agent_defaultpkg') ) {
184     warn "  agent_defaultpkg set; allowing all agents to purchase package"
185       if $DEBUG;
186     foreach my $agent_type ( qsearch('agent_type', {} ) ) {
187       my $type_pkgs = new FS::type_pkgs({
188         'typenum' => $agent_type->typenum,
189         'pkgpart' => $self->pkgpart,
190       });
191       my $error = $type_pkgs->insert;
192       if ( $error ) {
193         $dbh->rollback if $oldAutoCommit;
194         return $error;
195       }
196     }
197   }
198
199   warn "  inserting part_pkg_taxoverride records" if $DEBUG;
200   my %overrides = %{ $options{'tax_overrides'} || {} };
201   foreach my $usage_class ( keys %overrides ) {
202     my @overrides = (grep "$_", split (',', $overrides{$usage_class}) );
203     my $error = $self->process_m2m (
204                   'link_table'   => 'part_pkg_taxoverride',
205                   'target_table' => 'tax_class',
206                   'hashref'      => { 'usage_class' => $usage_class },
207                   'params'       => \@overrides,
208                 );
209     if ( $error ) {
210       $dbh->rollback if $oldAutoCommit;
211       return $error;
212     }
213   }
214
215   warn "  inserting pkg_svc records" if $DEBUG;
216   my $pkg_svc = $options{'pkg_svc'} || {};
217   foreach my $part_svc ( qsearch('part_svc', {} ) ) {
218     my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
219     my $primary_svc =
220       ( $options{'primary_svc'} && $options{'primary_svc'}==$part_svc->svcpart )
221         ? 'Y'
222         : '';
223
224     my $pkg_svc = new FS::pkg_svc( {
225       'pkgpart'     => $self->pkgpart,
226       'svcpart'     => $part_svc->svcpart,
227       'quantity'    => $quantity, 
228       'primary_svc' => $primary_svc,
229     } );
230     my $error = $pkg_svc->insert;
231     if ( $error ) {
232       $dbh->rollback if $oldAutoCommit;
233       return $error;
234     }
235   }
236
237   if ( $options{'cust_pkg'} ) {
238     warn "  updating cust_pkg record " if $DEBUG;
239     my $old_cust_pkg =
240       ref($options{'cust_pkg'})
241         ? $options{'cust_pkg'}
242         : qsearchs('cust_pkg', { pkgnum => $options{'cust_pkg'} } );
243     ${ $options{'custnum_ref'} } = $old_cust_pkg->custnum
244       if $options{'custnum_ref'};
245     my %hash = $old_cust_pkg->hash;
246     $hash{'pkgpart'} = $self->pkgpart,
247     my $new_cust_pkg = new FS::cust_pkg \%hash;
248     local($FS::cust_pkg::disable_agentcheck) = 1;
249     my $error = $new_cust_pkg->replace($old_cust_pkg);
250     if ( $error ) {
251       $dbh->rollback if $oldAutoCommit;
252       return "Error modifying cust_pkg record: $error";
253     }
254   }
255
256   warn "  commiting transaction" if $DEBUG;
257   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
258
259   '';
260 }
261
262 =item delete
263
264 Currently unimplemented.
265
266 =cut
267
268 sub delete {
269   return "Can't (yet?) delete package definitions.";
270 # check & make sure the pkgpart isn't in cust_pkg or type_pkgs?
271 }
272
273 =item replace OLD_RECORD [ , OPTION => VALUE ... ]
274
275 Replaces OLD_RECORD with this one in the database.  If there is an error,
276 returns the error, otherwise returns false.
277
278 Currently available options are: I<pkg_svc>, I<primary_svc> and I<options>
279
280 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
281 values, the appropriate FS::pkg_svc records will be replaced.
282
283 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
284 FS::pkg_svc record will be updated.
285
286 If I<options> is set to a hashref, the appropriate FS::part_pkg_option records
287 will be replaced.
288
289 =cut
290
291 sub replace {
292   my $new = shift;
293
294   my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
295               ? shift
296               : $new->replace_old;
297
298   my $options = 
299     ( ref($_[0]) eq 'HASH' )
300       ? shift
301       : { @_ };
302
303   $options->{options} = {} unless defined($options->{options});
304
305   warn "FS::part_pkg::replace called on $new to replace $old with options".
306        join(', ', map "$_ => ". $options->{$_}, keys %$options)
307     if $DEBUG;
308
309   local $SIG{HUP} = 'IGNORE';
310   local $SIG{INT} = 'IGNORE';
311   local $SIG{QUIT} = 'IGNORE';
312   local $SIG{TERM} = 'IGNORE';
313   local $SIG{TSTP} = 'IGNORE';
314   local $SIG{PIPE} = 'IGNORE';
315
316   my $oldAutoCommit = $FS::UID::AutoCommit;
317   local $FS::UID::AutoCommit = 0;
318   my $dbh = dbh;
319
320   #plandata shit stays in replace for upgrades until after 2.0 (or edit
321   #_upgrade_data)
322   warn "  saving legacy plandata" if $DEBUG;
323   my $plandata = $new->get('plandata');
324   $new->set('plandata', '');
325
326   warn "  deleting old part_pkg_option records" if $DEBUG;
327   foreach my $part_pkg_option ( $old->part_pkg_option ) {
328     my $error = $part_pkg_option->delete;
329     if ( $error ) {
330       $dbh->rollback if $oldAutoCommit;
331       return $error;
332     }
333   }
334
335   warn "  replacing part_pkg record" if $DEBUG;
336   my $error = $new->SUPER::replace($old, $options->{options} );
337   if ( $error ) {
338     $dbh->rollback if $oldAutoCommit;
339     return $error;
340   }
341
342   warn "  inserting part_pkg_option records for plandata: $plandata|" if $DEBUG;
343   foreach my $part_pkg_option ( 
344     map { /^(\w+)=(.*)$/ or do { $dbh->rollback if $oldAutoCommit;
345                                  return "illegal plandata: $plandata";
346                                };
347           new FS::part_pkg_option {
348             'pkgpart'     => $new->pkgpart,
349             'optionname'  => $1,
350             'optionvalue' => $2,
351           };
352         }
353     split("\n", $plandata)
354   ) {
355     my $error = $part_pkg_option->insert;
356     if ( $error ) {
357       $dbh->rollback if $oldAutoCommit;
358       return $error;
359     }
360   }
361
362   warn "  replacing pkg_svc records" if $DEBUG;
363   my $pkg_svc = $options->{'pkg_svc'} || {};
364   foreach my $part_svc ( qsearch('part_svc', {} ) ) {
365     my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
366     my $primary_svc =
367       ( defined($options->{'primary_svc'})
368         && $options->{'primary_svc'} == $part_svc->svcpart
369       )
370         ? 'Y'
371         : '';
372
373
374     my $old_pkg_svc = qsearchs('pkg_svc', {
375       'pkgpart' => $old->pkgpart,
376       'svcpart' => $part_svc->svcpart,
377     } );
378     my $old_quantity = $old_pkg_svc ? $old_pkg_svc->quantity : 0;
379     my $old_primary_svc =
380       ( $old_pkg_svc && $old_pkg_svc->dbdef_table->column('primary_svc') )
381         ? $old_pkg_svc->primary_svc
382         : '';
383     next unless $old_quantity != $quantity || $old_primary_svc ne $primary_svc;
384   
385     my $new_pkg_svc = new FS::pkg_svc( {
386       'pkgsvcnum'   => ( $old_pkg_svc ? $old_pkg_svc->pkgsvcnum : '' ),
387       'pkgpart'     => $new->pkgpart,
388       'svcpart'     => $part_svc->svcpart,
389       'quantity'    => $quantity, 
390       'primary_svc' => $primary_svc,
391     } );
392     my $error = $old_pkg_svc
393                   ? $new_pkg_svc->replace($old_pkg_svc)
394                   : $new_pkg_svc->insert;
395     if ( $error ) {
396       $dbh->rollback if $oldAutoCommit;
397       return $error;
398     }
399   }
400
401   warn "  commiting transaction" if $DEBUG;
402   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
403   '';
404 }
405
406 =item check
407
408 Checks all fields to make sure this is a valid package definition.  If
409 there is an error, returns the error, otherwise returns false.  Called by the
410 insert and replace methods.
411
412 =cut
413
414 sub check {
415   my $self = shift;
416   warn "FS::part_pkg::check called on $self" if $DEBUG;
417
418   for (qw(setup recur plandata)) {
419     #$self->set($_=>0) if $self->get($_) =~ /^\s*$/; }
420     return "Use of $_ field is deprecated; set a plan and options: ".
421            $self->get($_)
422       if length($self->get($_));
423     $self->set($_, '');
424   }
425
426   if ( $self->dbdef_table->column('freq')->type =~ /(int)/i ) {
427     my $error = $self->ut_number('freq');
428     return $error if $error;
429   } else {
430     $self->freq =~ /^(\d+[hdw]?)$/
431       or return "Illegal or empty freq: ". $self->freq;
432     $self->freq($1);
433   }
434
435   my @null_agentnum_right = ( 'Edit global package definitions' );
436   push @null_agentnum_right, 'One-time charge'
437     if $self->freq =~ /^0/;
438   push @null_agentnum_right, 'Customize customer package'
439     if $self->disabled eq 'Y'; #good enough
440
441   my $error = $self->ut_numbern('pkgpart')
442     || $self->ut_text('pkg')
443     || $self->ut_text('comment')
444     || $self->ut_textn('promo_code')
445     || $self->ut_alphan('plan')
446     || $self->ut_enum('setuptax', [ '', 'Y' ] )
447     || $self->ut_enum('recurtax', [ '', 'Y' ] )
448     || $self->ut_textn('taxclass')
449     || $self->ut_enum('disabled', [ '', 'Y' ] )
450     || $self->ut_floatn('pay_weight')
451     || $self->ut_floatn('credit_weight')
452     || $self->ut_numbern('taxproductnum')
453     || $self->ut_foreign_keyn('taxproductnum',
454                               'part_pkg_taxproduct',
455                               'taxproductnum'
456                              )
457     || $self->ut_agentnum_acl('agentnum', \@null_agentnum_right)
458     || $self->SUPER::check
459   ;
460   return $error if $error;
461
462   if ( $self->classnum !~ /^$/ ) {
463     my $error = $self->ut_foreign_key('classnum', 'pkg_class', 'classnum');
464     return $error if $error;
465   } else {
466     $self->classnum('');
467   }
468
469   return 'Unknown plan '. $self->plan
470     unless exists($plans{$self->plan});
471
472   my $conf = new FS::Conf;
473   return 'Taxclass is required'
474     if ! $self->taxclass && $conf->exists('require_taxclasses');
475
476   '';
477 }
478
479 =item pkg_comment
480
481 Returns an (internal) string representing this package.  Currently,
482 "pkgpart: pkg - comment", is returned.  "pkg - comment" may be returned in the
483 future, omitting pkgpart.
484
485 =cut
486
487 sub pkg_comment {
488   my $self = shift;
489
490   #$self->pkg. ' - '. $self->comment;
491   #$self->pkg. ' ('. $self->comment. ')';
492   $self->pkgpart. ': '. $self->pkg. ' - '. $self->comment;
493 }
494
495 =item pkg_class
496
497 Returns the package class, as an FS::pkg_class object, or the empty string
498 if there is no package class.
499
500 =cut
501
502 sub pkg_class {
503   my $self = shift;
504   if ( $self->classnum ) {
505     qsearchs('pkg_class', { 'classnum' => $self->classnum } );
506   } else {
507     return '';
508   }
509 }
510
511 =item categoryname 
512
513 Returns the package category name, or the empty string if there is no package
514 category.
515
516 =cut
517
518 sub categoryname {
519   my $self = shift;
520   my $pkg_class = $self->pkg_class;
521   $pkg_class
522     ? $pkg_class->categoryname
523     : '';
524 }
525
526 =item classname 
527
528 Returns the package class name, or the empty string if there is no package
529 class.
530
531 =cut
532
533 sub classname {
534   my $self = shift;
535   my $pkg_class = $self->pkg_class;
536   $pkg_class
537     ? $pkg_class->classname
538     : '';
539 }
540
541 =item agent 
542
543 Returns the associated agent for this event, if any, as an FS::agent object.
544
545 =cut
546
547 sub agent {
548   my $self = shift;
549   qsearchs('agent', { 'agentnum' => $self->agentnum } );
550 }
551
552 =item pkg_svc [ HASHREF | OPTION => VALUE ]
553
554 Returns all FS::pkg_svc objects (see L<FS::pkg_svc>) for this package
555 definition (with non-zero quantity).
556
557 One option is available, I<disable_linked>.  If set true it will return the
558 services for this package definition alone, omitting services from any add-on
559 packages.
560
561 =cut
562
563 =item type_pkgs
564
565 Returns all FS::type_pkgs objects (see L<FS::type_pkgs>) for this package
566 definition.
567
568 =cut
569
570 sub type_pkgs {
571   my $self = shift;
572   qsearch('type_pkgs', { 'pkgpart' => $self->pkgpart } );
573 }
574
575 sub pkg_svc {
576   my $self = shift;
577
578 #  #sort { $b->primary cmp $a->primary } 
579 #    grep { $_->quantity }
580 #      qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
581
582   my $opt = ref($_[0]) ? $_[0] : { @_ };
583   my %pkg_svc = map  { $_->svcpart => $_ }
584                 grep { $_->quantity }
585                 qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
586
587   unless ( $opt->{disable_linked} ) {
588     foreach my $dst_pkg ( map $_->dst_pkg, $self->svc_part_pkg_link ) {
589       my @pkg_svc = grep { $_->quantity }
590                     qsearch( 'pkg_svc', { pkgpart=>$dst_pkg->pkgpart } );
591       foreach my $pkg_svc ( @pkg_svc ) {
592         if ( $pkg_svc{$pkg_svc->svcpart} ) {
593           my $quantity = $pkg_svc{$pkg_svc->svcpart}->quantity;
594           $pkg_svc{$pkg_svc->svcpart}->quantity($quantity + $pkg_svc->quantity);
595         } else {
596           $pkg_svc{$pkg_svc->svcpart} = $pkg_svc;
597         }
598       }
599     }
600   }
601
602   values(%pkg_svc);
603
604 }
605
606 =item svcpart [ SVCDB ]
607
608 Returns the svcpart of the primary service definition (see L<FS::part_svc>)
609 associated with this package definition (see L<FS::pkg_svc>).  Returns
610 false if there not a primary service definition or exactly one service
611 definition with quantity 1, or if SVCDB is specified and does not match the
612 svcdb of the service definition, 
613
614 =cut
615
616 sub svcpart {
617   my $self = shift;
618   my $svcdb = scalar(@_) ? shift : '';
619   my @svcdb_pkg_svc =
620     grep { ( $svcdb eq $_->part_svc->svcdb || !$svcdb ) } $self->pkg_svc;
621   my @pkg_svc = grep { $_->primary_svc =~ /^Y/i } @svcdb_pkg_svc;
622   @pkg_svc = grep {$_->quantity == 1 } @svcdb_pkg_svc
623     unless @pkg_svc;
624   return '' if scalar(@pkg_svc) != 1;
625   $pkg_svc[0]->svcpart;
626 }
627
628 =item svcpart_unique_svcdb SVCDB
629
630 Returns the svcpart of the a service definition (see L<FS::part_svc>) matching
631 SVCDB associated with this package definition (see L<FS::pkg_svc>).  Returns
632 false if there not a primary service definition for SVCDB or there are multiple
633 service definitions for SVCDB.
634
635 =cut
636
637 sub svcpart_unique_svcdb {
638   my( $self, $svcdb ) = @_;
639   my @svcdb_pkg_svc = grep { ( $svcdb eq $_->part_svc->svcdb ) } $self->pkg_svc;
640   return '' if scalar(@svcdb_pkg_svc) != 1;
641   $svcdb_pkg_svc[0]->svcpart;
642 }
643
644 =item payby
645
646 Returns a list of the acceptable payment types for this package.  Eventually
647 this should come out of a database table and be editable, but currently has the
648 following logic instead:
649
650 If the package is free, the single item B<BILL> is
651 returned, otherwise, the single item B<CARD> is returned.
652
653 (CHEK?  LEC?  Probably shouldn't accept those by default, prone to abuse)
654
655 =cut
656
657 sub payby {
658   my $self = shift;
659   if ( $self->is_free ) {
660     ( 'BILL' );
661   } else {
662     ( 'CARD' );
663   }
664 }
665
666 =item is_free
667
668 Returns true if this package is free.  
669
670 =cut
671
672 sub is_free {
673   my $self = shift;
674   unless ( $self->plan ) {
675     $self->setup =~ /^\s*0+(\.0*)?\s*$/
676       && $self->recur =~ /^\s*0+(\.0*)?\s*$/;
677   } elsif ( $self->can('is_free_options') ) {
678     not grep { $_ !~ /^\s*0*(\.0*)?\s*$/ }
679          map { $self->option($_) } 
680              $self->is_free_options;
681   } else {
682     warn "FS::part_pkg::is_free: FS::part_pkg::". $self->plan. " subclass ".
683          "provides neither is_free_options nor is_free method; returning false";
684     0;
685   }
686 }
687
688
689 sub freqs_href {
690   #method, class method or sub? #my $self = shift;
691
692   tie my %freq, 'Tie::IxHash', 
693     '0'    => '(no recurring fee)',
694     '1h'   => 'hourly',
695     '1d'   => 'daily',
696     '2d'   => 'every two days',
697     '3d'   => 'every three days',
698     '1w'   => 'weekly',
699     '2w'   => 'biweekly (every 2 weeks)',
700     '1'    => 'monthly',
701     '45d'  => 'every 45 days',
702     '2'    => 'bimonthly (every 2 months)',
703     '3'    => 'quarterly (every 3 months)',
704     '4'    => 'every 4 months',
705     '137d' => 'every 4 1/2 months (137 days)',
706     '6'    => 'semiannually (every 6 months)',
707     '12'   => 'annually',
708     '13'   => 'every 13 months (annually +1 month)',
709     '24'   => 'biannually (every 2 years)',
710     '36'   => 'triannually (every 3 years)',
711     '48'   => '(every 4 years)',
712     '60'   => '(every 5 years)',
713     '120'  => '(every 10 years)',
714   ;
715
716   \%freq;
717
718 }
719
720 =item freq_pretty
721
722 Returns an english representation of the I<freq> field, such as "monthly",
723 "weekly", "semi-annually", etc.
724
725 =cut
726
727 sub freq_pretty {
728   my $self = shift;
729   my $freq = $self->freq;
730
731   #my $freqs_href = $self->freqs_href;
732   my $freqs_href = freqs_href();
733
734   if ( exists($freqs_href->{$freq}) ) {
735     $freqs_href->{$freq};
736   } else {
737     my $interval = 'month';
738     if ( $freq =~ /^(\d+)([hdw])$/ ) {
739       my %interval = ( 'h' => 'hour', 'd'=>'day', 'w'=>'week' );
740       $interval = $interval{$2};
741     }
742     if ( $1 == 1 ) {
743       "every $interval";
744     } else {
745       "every $freq ${interval}s";
746     }
747   }
748 }
749
750 =item add_freq TIMESTAMP
751
752 Adds the frequency of this package to the provided timestamp and returns
753 the resulting timestamp, or -1 if the frequency of this package could not be
754 parsed (shouldn't happen).
755
756 =cut
757
758 sub add_freq {
759   my( $self, $date ) = @_;
760   my $freq = $self->freq;
761
762   #change this bit to use Date::Manip? CAREFUL with timezones (see
763   # mailing list archive)
764   my ($sec,$min,$hour,$mday,$mon,$year) = (localtime($date) )[0,1,2,3,4,5];
765
766   if ( $self->freq =~ /^\d+$/ ) {
767     $mon += $self->freq;
768     until ( $mon < 12 ) { $mon -= 12; $year++; }
769   } elsif ( $self->freq =~ /^(\d+)w$/ ) {
770     my $weeks = $1;
771     $mday += $weeks * 7;
772   } elsif ( $self->freq =~ /^(\d+)d$/ ) {
773     my $days = $1;
774     $mday += $days;
775   } elsif ( $self->freq =~ /^(\d+)h$/ ) {
776     my $hours = $1;
777     $hour += $hours;
778   } else {
779     return -1;
780   }
781
782   timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year);
783 }
784
785 =item plandata
786
787 For backwards compatibility, returns the plandata field as well as all options
788 from FS::part_pkg_option.
789
790 =cut
791
792 sub plandata {
793   my $self = shift;
794   carp "plandata is deprecated";
795   if ( @_ ) {
796     $self->SUPER::plandata(@_);
797   } else {
798     my $plandata = $self->get('plandata');
799     my %options = $self->options;
800     $plandata .= join('', map { "$_=$options{$_}\n" } keys %options );
801     $plandata;
802   }
803 }
804
805 =item part_pkg_option
806
807 Returns all options as FS::part_pkg_option objects (see
808 L<FS::part_pkg_option>).
809
810 =cut
811
812 sub part_pkg_option {
813   my $self = shift;
814   qsearch('part_pkg_option', { 'pkgpart' => $self->pkgpart } );
815 }
816
817 =item options 
818
819 Returns a list of option names and values suitable for assigning to a hash.
820
821 =cut
822
823 sub options {
824   my $self = shift;
825   map { $_->optionname => $_->optionvalue } $self->part_pkg_option;
826 }
827
828 =item option OPTIONNAME
829
830 Returns the option value for the given name, or the empty string.
831
832 =cut
833
834 sub option {
835   my( $self, $opt, $ornull ) = @_;
836   my $part_pkg_option =
837     qsearchs('part_pkg_option', {
838       pkgpart    => $self->pkgpart,
839       optionname => $opt,
840   } );
841   return $part_pkg_option->optionvalue if $part_pkg_option;
842   my %plandata = map { /^(\w+)=(.*)$/; ( $1 => $2 ); }
843                      split("\n", $self->get('plandata') );
844   return $plandata{$opt} if exists $plandata{$opt};
845   cluck "WARNING: (pkgpart ". $self->pkgpart. ") Package def option $opt ".
846         "not found in options or plandata!\n"
847     unless $ornull;
848   '';
849 }
850
851 =item bill_part_pkg_link
852
853 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
854
855 =cut
856
857 sub bill_part_pkg_link {
858   shift->_part_pkg_link('bill', @_);
859 }
860
861 =item svc_part_pkg_link
862
863 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
864
865 =cut
866
867 sub svc_part_pkg_link {
868   shift->_part_pkg_link('svc', @_);
869 }
870
871 sub _part_pkg_link {
872   my( $self, $type ) = @_;
873   qsearch('part_pkg_link', { 'src_pkgpart' => $self->pkgpart,
874                              'link_type'   => $type,
875                            }
876          );
877 }
878
879 sub self_and_bill_linked {
880   shift->_self_and_linked('bill', @_);
881 }
882
883 sub _self_and_linked {
884   my( $self, $type ) = @_;
885
886   ( $self,
887     map { $_->dst_pkg->_self_and_linked($type) }
888         $self->_part_pkg_link($type)
889   );
890 }
891
892 =item part_pkg_taxoverride [ CLASS ]
893
894 Returns all associated FS::part_pkg_taxoverride objects (see
895 L<FS::part_pkg_taxoverride>).  Limits the returned set to those
896 of class CLASS if defined.  Class may be one of 'setup', 'recur',
897 the empty string (default), or a usage class number (see L<FS::usage_class>).
898 When a class is specified, the empty string class (default) is returned
899 if no more specific values exist.
900
901 =cut
902
903 sub part_pkg_taxoverride {
904   my $self = shift;
905   my $class = shift;
906
907   my $hashref = { 'pkgpart' => $self->pkgpart };
908   $hashref->{'usage_class'} = $class if defined($class);
909   my @overrides = qsearch('part_pkg_taxoverride', $hashref );
910
911   unless ( scalar(@overrides) || !defined($class) || !$class ){
912     $hashref->{'usage_class'} = '';
913     @overrides = qsearch('part_pkg_taxoverride', $hashref );
914   }
915
916   @overrides;
917 }
918
919 =item has_taxproduct
920
921 Returns true if this package has any taxproduct associated with it.  
922
923 =cut
924
925 sub has_taxproduct {
926   my $self = shift;
927
928   $self->taxproductnum ||
929   scalar( grep { $_ =~/^usage_taxproductnum_/ && $self->option($_) } 
930           keys %{ {$self->options} }
931   )
932
933 }
934
935
936 =item taxproduct [ CLASS ]
937
938 Returns the associated tax product for this package definition (see
939 L<FS::part_pkg_taxproduct>).  CLASS may be one of 'setup', 'recur' or
940 the usage classnum (see L<FS::usage_class>).  Returns the default
941 tax product for this record if the more specific CLASS value does
942 not exist.
943
944 =cut
945
946 sub taxproduct {
947   my $self = shift;
948   my $class = shift;
949
950   my $part_pkg_taxproduct;
951
952   my $taxproductnum = $self->taxproductnum;
953   if ($class) { 
954     my $class_taxproductnum = $self->option("usage_taxproductnum_$class", 1);
955     $taxproductnum = $class_taxproductnum
956       if $class_taxproductnum
957   }
958   
959   $part_pkg_taxproduct =
960     qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
961
962   unless ($part_pkg_taxproduct || $taxproductnum eq $self->taxproductnum ) {
963     $taxproductnum = $self->taxproductnum;
964     $part_pkg_taxproduct =
965       qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
966   }
967
968   $part_pkg_taxproduct;
969 }
970
971 =item taxproduct_description [ CLASS ]
972
973 Returns the description of the associated tax product for this package
974 definition (see L<FS::part_pkg_taxproduct>).
975
976 =cut
977
978 sub taxproduct_description {
979   my $self = shift;
980   my $part_pkg_taxproduct = $self->taxproduct(@_);
981   $part_pkg_taxproduct ? $part_pkg_taxproduct->description : '';
982 }
983
984 =item part_pkg_taxrate DATA_PROVIDER, GEOCODE, [ CLASS ]
985
986 Returns the package to taxrate m2m records for this package in the location
987 specified by GEOCODE (see L<FS::part_pkg_taxrate>) and usage class CLASS.
988 CLASS may be one of 'setup', 'recur', or one of the usage classes numbers
989 (see L<FS::usage_class>).
990
991 =cut
992
993 sub _expand_cch_taxproductnum {
994   my $self = shift;
995   my $class = shift;
996   my $part_pkg_taxproduct = $self->taxproduct($class);
997
998   my ($a,$b,$c,$d) = ( $part_pkg_taxproduct
999                          ? ( split ':', $part_pkg_taxproduct->taxproduct )
1000                          : ()
1001                      );
1002   $a = '' unless $a; $b = '' unless $b; $c = '' unless $c; $d = '' unless $d;
1003   my $extra_sql = "AND ( taxproduct = '$a:$b:$c:$d'
1004                       OR taxproduct = '$a:$b:$c:'
1005                       OR taxproduct = '$a:$b:".":$d'
1006                       OR taxproduct = '$a:$b:".":' )";
1007   map { $_->taxproductnum } qsearch( { 'table'     => 'part_pkg_taxproduct',
1008                                        'hashref'   => { 'data_vendor'=>'cch' },
1009                                        'extra_sql' => $extra_sql,
1010                                    } );
1011                                      
1012 }
1013
1014 sub part_pkg_taxrate {
1015   my $self = shift;
1016   my ($data_vendor, $geocode, $class) = @_;
1017
1018   my $dbh = dbh;
1019   my $extra_sql = 'WHERE part_pkg_taxproduct.data_vendor = '.
1020                   dbh->quote($data_vendor);
1021   
1022   # CCH oddness in m2m
1023   $extra_sql .= ' AND ('.
1024     join(' OR ', map{ 'geocode = '. $dbh->quote(substr($geocode, 0, $_)) }
1025                  qw(10 5 2)
1026         ).
1027     ')';
1028   # much more CCH oddness in m2m -- this is kludgy
1029   my @tpnums = $self->_expand_cch_taxproductnum($class);
1030   if (scalar(@tpnums)) {
1031     $extra_sql .= ' AND ('.
1032                             join(' OR ', map{ "taxproductnum = $_" } @tpnums ).
1033                        ')';
1034   } else {
1035     $extra_sql .= ' AND ( 0 = 1 )';
1036   }
1037
1038   my $addl_from = 'LEFT JOIN part_pkg_taxproduct USING ( taxproductnum )';
1039   my $order_by = 'ORDER BY taxclassnum, length(geocode) desc, length(taxproduct) desc';
1040   my $select   = 'DISTINCT ON(taxclassnum) *, taxproduct';
1041
1042   # should qsearch preface columns with the table to facilitate joins?
1043   qsearch( { 'table'     => 'part_pkg_taxrate',
1044              'select'    => $select,
1045              'hashref'   => { # 'data_vendor'   => $data_vendor,
1046                               # 'taxproductnum' => $self->taxproductnum,
1047                             },
1048              'addl_from' => $addl_from,
1049              'extra_sql' => $extra_sql,
1050              'order_by'  => $order_by,
1051          } );
1052 }
1053
1054 =item _rebless
1055
1056 Reblesses the object into the FS::part_pkg::PLAN class (if available), where
1057 PLAN is the object's I<plan> field.  There should be better docs
1058 on how to create new price plans, but until then, see L</NEW PLAN CLASSES>.
1059
1060 =cut
1061
1062 sub _rebless {
1063   my $self = shift;
1064   my $plan = $self->plan;
1065   unless ( $plan ) {
1066     cluck "no price plan found for pkgpart ". $self->pkgpart. "\n"
1067       if $DEBUG;
1068     return $self;
1069   }
1070   return $self if ref($self) =~ /::$plan$/; #already blessed into plan subclass
1071   my $class = ref($self). "::$plan";
1072   warn "reblessing $self into $class" if $DEBUG;
1073   eval "use $class;";
1074   die $@ if $@;
1075   bless($self, $class) unless $@;
1076   $self;
1077 }
1078
1079 #fallbacks that eval the setup and recur fields, for backwards compat
1080
1081 sub calc_setup {
1082   my $self = shift;
1083   warn 'no price plan class for '. $self->plan. ", eval-ing setup\n";
1084   $self->_calc_eval('setup', @_);
1085 }
1086
1087 sub calc_recur {
1088   my $self = shift;
1089   warn 'no price plan class for '. $self->plan. ", eval-ing recur\n";
1090   $self->_calc_eval('recur', @_);
1091 }
1092
1093 use vars qw( $sdate @details );
1094 sub _calc_eval {
1095   #my( $self, $field, $cust_pkg ) = @_;
1096   my( $self, $field, $cust_pkg, $sdateref, $detailsref ) = @_;
1097   *sdate = $sdateref;
1098   *details = $detailsref;
1099   $self->$field() =~ /^(.*)$/
1100     or die "Illegal $field (pkgpart ". $self->pkgpart. '): '.
1101             $self->$field(). "\n";
1102   my $prog = $1;
1103   return 0 if $prog =~ /^\s*$/;
1104   my $value = eval $prog;
1105   die $@ if $@;
1106   $value;
1107 }
1108
1109 #fallback that return 0 for old legacy packages with no plan
1110
1111 sub calc_remain { 0; }
1112 sub calc_cancel { 0; }
1113 sub calc_units  { 0; }
1114
1115 =item format OPTION DATA
1116
1117 Returns data formatted according to the function 'format' described
1118 in the plan info.  Returns DATA if no such function exists.
1119
1120 =cut
1121
1122 sub format {
1123   my ($self, $option, $data) = (shift, shift, shift);
1124   if (exists($plans{$self->plan}->{fields}->{$option}{format})) {
1125     &{$plans{$self->plan}->{fields}->{$option}{format}}($data);
1126   }else{
1127     $data;
1128   }
1129 }
1130
1131 =item parse OPTION DATA
1132
1133 Returns data parsed according to the function 'parse' described
1134 in the plan info.  Returns DATA if no such function exists.
1135
1136 =cut
1137
1138 sub parse {
1139   my ($self, $option, $data) = (shift, shift, shift);
1140   if (exists($plans{$self->plan}->{fields}->{$option}{parse})) {
1141     &{$plans{$self->plan}->{fields}->{$option}{parse}}($data);
1142   }else{
1143     $data;
1144   }
1145 }
1146
1147 =back
1148
1149 =cut
1150
1151 =head1 CLASS METHODS
1152
1153 =over 4
1154
1155 =cut
1156
1157 # _upgrade_data
1158 #
1159 # Used by FS::Upgrade to migrate to a new database.
1160
1161 sub _upgrade_data { # class method
1162   my($class, %opts) = @_;
1163
1164   warn "[FS::part_pkg] upgrading $class\n" if $DEBUG;
1165
1166   my @part_pkg = qsearch({
1167     'table'     => 'part_pkg',
1168     'extra_sql' => "WHERE ". join(' OR ',
1169                      ( map "($_ IS NOT NULL AND $_ != '' )",
1170                            qw( plandata setup recur ) ),
1171                      'plan IS NULL', "plan = '' ",
1172                    ),
1173   });
1174
1175   foreach my $part_pkg (@part_pkg) {
1176
1177     unless ( $part_pkg->plan ) {
1178
1179       $part_pkg->plan('flat');
1180
1181       if ( $part_pkg->setup =~ /^\s*([\d\.]+)\s*$/ ) {
1182
1183         my $opt = new FS::part_pkg_option {
1184           'pkgpart'     => $part_pkg->pkgpart,
1185           'optionname'  => 'setup_fee',
1186           'optionvalue' => $1,
1187         };
1188         my $error = $opt->insert;
1189         die $error if $error;
1190
1191         $part_pkg->setup('');
1192
1193       } else {
1194         die "Can't parse part_pkg.setup for fee; convert pkgnum ".
1195             $part_pkg->pkgnum. " manually: ". $part_pkg->setup. "\n";
1196       }
1197
1198       if ( $part_pkg->recur =~ /^\s*([\d\.]+)\s*$/ ) {
1199
1200         my $opt = new FS::part_pkg_option {
1201           'pkgpart'     => $part_pkg->pkgpart,
1202           'optionname'  => 'recur_fee',
1203           'optionvalue' => $1,
1204         };
1205         my $error = $opt->insert;
1206         die $error if $error;
1207
1208         $part_pkg->recur('');
1209
1210       } else {
1211         die "Can't parse part_pkg.setup for fee; convert pkgnum ".
1212             $part_pkg->pkgnum. " manually: ". $part_pkg->setup. "\n";
1213       }
1214
1215     }
1216
1217     $part_pkg->replace; #this should take care of plandata, right?
1218
1219   }
1220
1221 }
1222
1223 =item curuser_pkgs_sql
1224
1225 Returns an SQL fragment for searching for packages the current user can
1226 use, either via part_pkg.agentnum directly, or via agent type (see
1227 L<FS::type_pkgs>).
1228
1229 =cut
1230
1231 sub curuser_pkgs_sql {
1232   #my($class) = shift;
1233
1234   my $agentnums = join(',', $FS::CurrentUser::CurrentUser->agentnums);
1235
1236   "
1237     (
1238       agentnum IS NOT NULL
1239       OR
1240       0 < ( SELECT COUNT(*)
1241               FROM type_pkgs
1242                 LEFT JOIN agent_type USING ( typenum )
1243                 LEFT JOIN agent AS typeagent USING ( typenum )
1244               WHERE type_pkgs.pkgpart = part_pkg.pkgpart
1245                 AND typeagent.agentnum IN ($agentnums)
1246           )
1247     )
1248   ";
1249
1250 }
1251
1252 =back
1253
1254 =head1 SUBROUTINES
1255
1256 =over 4
1257
1258 =item plan_info
1259
1260 =cut
1261
1262 #false laziness w/part_export & cdr
1263 my %info;
1264 foreach my $INC ( @INC ) {
1265   warn "globbing $INC/FS/part_pkg/*.pm\n" if $DEBUG;
1266   foreach my $file ( glob("$INC/FS/part_pkg/*.pm") ) {
1267     warn "attempting to load plan info from $file\n" if $DEBUG;
1268     $file =~ /\/(\w+)\.pm$/ or do {
1269       warn "unrecognized file in $INC/FS/part_pkg/: $file\n";
1270       next;
1271     };
1272     my $mod = $1;
1273     my $info = eval "use FS::part_pkg::$mod; ".
1274                     "\\%FS::part_pkg::$mod\::info;";
1275     if ( $@ ) {
1276       die "error using FS::part_pkg::$mod (skipping): $@\n" if $@;
1277       next;
1278     }
1279     unless ( keys %$info ) {
1280       warn "no %info hash found in FS::part_pkg::$mod, skipping\n";
1281       next;
1282     }
1283     warn "got plan info from FS::part_pkg::$mod: $info\n" if $DEBUG;
1284     if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
1285       warn "skipping disabled plan FS::part_pkg::$mod" if $DEBUG;
1286       next;
1287     }
1288     $info{$mod} = $info;
1289   }
1290 }
1291
1292 tie %plans, 'Tie::IxHash',
1293   map  { $_ => $info{$_} }
1294   sort { $info{$a}->{'weight'} <=> $info{$b}->{'weight'} }
1295   keys %info;
1296
1297 sub plan_info {
1298   \%plans;
1299 }
1300
1301
1302 =back
1303
1304 =head1 NEW PLAN CLASSES
1305
1306 A module should be added in FS/FS/part_pkg/  Eventually, an example may be
1307 found in eg/plan_template.pm.  Until then, it is suggested that you use the
1308 other modules in FS/FS/part_pkg/ as a guide.
1309
1310 =head1 BUGS
1311
1312 The delete method is unimplemented.
1313
1314 setup and recur semantics are not yet defined (and are implemented in
1315 FS::cust_bill.  hmm.).  now they're deprecated and need to go.
1316
1317 plandata should go
1318
1319 part_pkg_taxrate is Pg specific
1320
1321 =head1 SEE ALSO
1322
1323 L<FS::Record>, L<FS::cust_pkg>, L<FS::type_pkgs>, L<FS::pkg_svc>, L<Safe>.
1324 schema.html from the base documentation.
1325
1326 =cut
1327
1328 1;
1329