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