further work on agents editing own packages: fix fallout on package customization...
[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 sub pkg_svc {
564   my $self = shift;
565
566 #  #sort { $b->primary cmp $a->primary } 
567 #    grep { $_->quantity }
568 #      qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
569
570   my $opt = ref($_[0]) ? $_[0] : { @_ };
571   my %pkg_svc = map  { $_->svcpart => $_ }
572                 grep { $_->quantity }
573                 qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
574
575   unless ( $opt->{disable_linked} ) {
576     foreach my $dst_pkg ( map $_->dst_pkg, $self->svc_part_pkg_link ) {
577       my @pkg_svc = grep { $_->quantity }
578                     qsearch( 'pkg_svc', { pkgpart=>$dst_pkg->pkgpart } );
579       foreach my $pkg_svc ( @pkg_svc ) {
580         if ( $pkg_svc{$pkg_svc->svcpart} ) {
581           my $quantity = $pkg_svc{$pkg_svc->svcpart}->quantity;
582           $pkg_svc{$pkg_svc->svcpart}->quantity($quantity + $pkg_svc->quantity);
583         } else {
584           $pkg_svc{$pkg_svc->svcpart} = $pkg_svc;
585         }
586       }
587     }
588   }
589
590   values(%pkg_svc);
591
592 }
593
594 =item svcpart [ SVCDB ]
595
596 Returns the svcpart of the primary service definition (see L<FS::part_svc>)
597 associated with this package definition (see L<FS::pkg_svc>).  Returns
598 false if there not a primary service definition or exactly one service
599 definition with quantity 1, or if SVCDB is specified and does not match the
600 svcdb of the service definition, 
601
602 =cut
603
604 sub svcpart {
605   my $self = shift;
606   my $svcdb = scalar(@_) ? shift : '';
607   my @svcdb_pkg_svc =
608     grep { ( $svcdb eq $_->part_svc->svcdb || !$svcdb ) } $self->pkg_svc;
609   my @pkg_svc = grep { $_->primary_svc =~ /^Y/i } @svcdb_pkg_svc;
610   @pkg_svc = grep {$_->quantity == 1 } @svcdb_pkg_svc
611     unless @pkg_svc;
612   return '' if scalar(@pkg_svc) != 1;
613   $pkg_svc[0]->svcpart;
614 }
615
616 =item svcpart_unique_svcdb SVCDB
617
618 Returns the svcpart of the a service definition (see L<FS::part_svc>) matching
619 SVCDB associated with this package definition (see L<FS::pkg_svc>).  Returns
620 false if there not a primary service definition for SVCDB or there are multiple
621 service definitions for SVCDB.
622
623 =cut
624
625 sub svcpart_unique_svcdb {
626   my( $self, $svcdb ) = @_;
627   my @svcdb_pkg_svc = grep { ( $svcdb eq $_->part_svc->svcdb ) } $self->pkg_svc;
628   return '' if scalar(@svcdb_pkg_svc) != 1;
629   $svcdb_pkg_svc[0]->svcpart;
630 }
631
632 =item payby
633
634 Returns a list of the acceptable payment types for this package.  Eventually
635 this should come out of a database table and be editable, but currently has the
636 following logic instead:
637
638 If the package is free, the single item B<BILL> is
639 returned, otherwise, the single item B<CARD> is returned.
640
641 (CHEK?  LEC?  Probably shouldn't accept those by default, prone to abuse)
642
643 =cut
644
645 sub payby {
646   my $self = shift;
647   if ( $self->is_free ) {
648     ( 'BILL' );
649   } else {
650     ( 'CARD' );
651   }
652 }
653
654 =item is_free
655
656 Returns true if this package is free.  
657
658 =cut
659
660 sub is_free {
661   my $self = shift;
662   unless ( $self->plan ) {
663     $self->setup =~ /^\s*0+(\.0*)?\s*$/
664       && $self->recur =~ /^\s*0+(\.0*)?\s*$/;
665   } elsif ( $self->can('is_free_options') ) {
666     not grep { $_ !~ /^\s*0*(\.0*)?\s*$/ }
667          map { $self->option($_) } 
668              $self->is_free_options;
669   } else {
670     warn "FS::part_pkg::is_free: FS::part_pkg::". $self->plan. " subclass ".
671          "provides neither is_free_options nor is_free method; returning false";
672     0;
673   }
674 }
675
676
677 sub freqs_href {
678   #method, class method or sub? #my $self = shift;
679
680   tie my %freq, 'Tie::IxHash', 
681     '0'    => '(no recurring fee)',
682     '1h'   => 'hourly',
683     '1d'   => 'daily',
684     '2d'   => 'every two days',
685     '3d'   => 'every three days',
686     '1w'   => 'weekly',
687     '2w'   => 'biweekly (every 2 weeks)',
688     '1'    => 'monthly',
689     '45d'  => 'every 45 days',
690     '2'    => 'bimonthly (every 2 months)',
691     '3'    => 'quarterly (every 3 months)',
692     '4'    => 'every 4 months',
693     '137d' => 'every 4 1/2 months (137 days)',
694     '6'    => 'semiannually (every 6 months)',
695     '12'   => 'annually',
696     '13'   => 'every 13 months (annually +1 month)',
697     '24'   => 'biannually (every 2 years)',
698     '36'   => 'triannually (every 3 years)',
699     '48'   => '(every 4 years)',
700     '60'   => '(every 5 years)',
701     '120'  => '(every 10 years)',
702   ;
703
704   \%freq;
705
706 }
707
708 =item freq_pretty
709
710 Returns an english representation of the I<freq> field, such as "monthly",
711 "weekly", "semi-annually", etc.
712
713 =cut
714
715 sub freq_pretty {
716   my $self = shift;
717   my $freq = $self->freq;
718
719   #my $freqs_href = $self->freqs_href;
720   my $freqs_href = freqs_href();
721
722   if ( exists($freqs_href->{$freq}) ) {
723     $freqs_href->{$freq};
724   } else {
725     my $interval = 'month';
726     if ( $freq =~ /^(\d+)([hdw])$/ ) {
727       my %interval = ( 'h' => 'hour', 'd'=>'day', 'w'=>'week' );
728       $interval = $interval{$2};
729     }
730     if ( $1 == 1 ) {
731       "every $interval";
732     } else {
733       "every $freq ${interval}s";
734     }
735   }
736 }
737
738 =item add_freq TIMESTAMP
739
740 Adds the frequency of this package to the provided timestamp and returns
741 the resulting timestamp, or -1 if the frequency of this package could not be
742 parsed (shouldn't happen).
743
744 =cut
745
746 sub add_freq {
747   my( $self, $date ) = @_;
748   my $freq = $self->freq;
749
750   #change this bit to use Date::Manip? CAREFUL with timezones (see
751   # mailing list archive)
752   my ($sec,$min,$hour,$mday,$mon,$year) = (localtime($date) )[0,1,2,3,4,5];
753
754   if ( $self->freq =~ /^\d+$/ ) {
755     $mon += $self->freq;
756     until ( $mon < 12 ) { $mon -= 12; $year++; }
757   } elsif ( $self->freq =~ /^(\d+)w$/ ) {
758     my $weeks = $1;
759     $mday += $weeks * 7;
760   } elsif ( $self->freq =~ /^(\d+)d$/ ) {
761     my $days = $1;
762     $mday += $days;
763   } elsif ( $self->freq =~ /^(\d+)h$/ ) {
764     my $hours = $1;
765     $hour += $hours;
766   } else {
767     return -1;
768   }
769
770   timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year);
771 }
772
773 =item plandata
774
775 For backwards compatibility, returns the plandata field as well as all options
776 from FS::part_pkg_option.
777
778 =cut
779
780 sub plandata {
781   my $self = shift;
782   carp "plandata is deprecated";
783   if ( @_ ) {
784     $self->SUPER::plandata(@_);
785   } else {
786     my $plandata = $self->get('plandata');
787     my %options = $self->options;
788     $plandata .= join('', map { "$_=$options{$_}\n" } keys %options );
789     $plandata;
790   }
791 }
792
793 =item part_pkg_option
794
795 Returns all options as FS::part_pkg_option objects (see
796 L<FS::part_pkg_option>).
797
798 =cut
799
800 sub part_pkg_option {
801   my $self = shift;
802   qsearch('part_pkg_option', { 'pkgpart' => $self->pkgpart } );
803 }
804
805 =item options 
806
807 Returns a list of option names and values suitable for assigning to a hash.
808
809 =cut
810
811 sub options {
812   my $self = shift;
813   map { $_->optionname => $_->optionvalue } $self->part_pkg_option;
814 }
815
816 =item option OPTIONNAME
817
818 Returns the option value for the given name, or the empty string.
819
820 =cut
821
822 sub option {
823   my( $self, $opt, $ornull ) = @_;
824   my $part_pkg_option =
825     qsearchs('part_pkg_option', {
826       pkgpart    => $self->pkgpart,
827       optionname => $opt,
828   } );
829   return $part_pkg_option->optionvalue if $part_pkg_option;
830   my %plandata = map { /^(\w+)=(.*)$/; ( $1 => $2 ); }
831                      split("\n", $self->get('plandata') );
832   return $plandata{$opt} if exists $plandata{$opt};
833   cluck "WARNING: (pkgpart ". $self->pkgpart. ") Package def option $opt ".
834         "not found in options or plandata!\n"
835     unless $ornull;
836   '';
837 }
838
839 =item bill_part_pkg_link
840
841 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
842
843 =cut
844
845 sub bill_part_pkg_link {
846   shift->_part_pkg_link('bill', @_);
847 }
848
849 =item svc_part_pkg_link
850
851 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
852
853 =cut
854
855 sub svc_part_pkg_link {
856   shift->_part_pkg_link('svc', @_);
857 }
858
859 sub _part_pkg_link {
860   my( $self, $type ) = @_;
861   qsearch('part_pkg_link', { 'src_pkgpart' => $self->pkgpart,
862                              'link_type'   => $type,
863                            }
864          );
865 }
866
867 sub self_and_bill_linked {
868   shift->_self_and_linked('bill', @_);
869 }
870
871 sub _self_and_linked {
872   my( $self, $type ) = @_;
873
874   ( $self,
875     map { $_->dst_pkg->_self_and_linked($type) }
876         $self->_part_pkg_link($type)
877   );
878 }
879
880 =item part_pkg_taxoverride [ CLASS ]
881
882 Returns all associated FS::part_pkg_taxoverride objects (see
883 L<FS::part_pkg_taxoverride>).  Limits the returned set to those
884 of class CLASS if defined.  Class may be one of 'setup', 'recur',
885 the empty string (default), or a usage class number (see L<FS::usage_class>).
886 When a class is specified, the empty string class (default) is returned
887 if no more specific values exist.
888
889 =cut
890
891 sub part_pkg_taxoverride {
892   my $self = shift;
893   my $class = shift;
894
895   my $hashref = { 'pkgpart' => $self->pkgpart };
896   $hashref->{'usage_class'} = $class if defined($class);
897   my @overrides = qsearch('part_pkg_taxoverride', $hashref );
898
899   unless ( scalar(@overrides) || !defined($class) || !$class ){
900     $hashref->{'usage_class'} = '';
901     @overrides = qsearch('part_pkg_taxoverride', $hashref );
902   }
903
904   @overrides;
905 }
906
907 =item has_taxproduct
908
909 Returns true if this package has any taxproduct associated with it.  
910
911 =cut
912
913 sub has_taxproduct {
914   my $self = shift;
915
916   $self->taxproductnum ||
917   scalar( grep { $_ =~/^usage_taxproductnum_/ && $self->option($_) } 
918           keys %{ {$self->options} }
919   )
920
921 }
922
923
924 =item taxproduct [ CLASS ]
925
926 Returns the associated tax product for this package definition (see
927 L<FS::part_pkg_taxproduct>).  CLASS may be one of 'setup', 'recur' or
928 the usage classnum (see L<FS::usage_class>).  Returns the default
929 tax product for this record if the more specific CLASS value does
930 not exist.
931
932 =cut
933
934 sub taxproduct {
935   my $self = shift;
936   my $class = shift;
937
938   my $part_pkg_taxproduct;
939
940   my $taxproductnum = $self->taxproductnum;
941   if ($class) { 
942     my $class_taxproductnum = $self->option("usage_taxproductnum_$class", 1);
943     $taxproductnum = $class_taxproductnum
944       if $class_taxproductnum
945   }
946   
947   $part_pkg_taxproduct =
948     qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
949
950   unless ($part_pkg_taxproduct || $taxproductnum eq $self->taxproductnum ) {
951     $taxproductnum = $self->taxproductnum;
952     $part_pkg_taxproduct =
953       qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
954   }
955
956   $part_pkg_taxproduct;
957 }
958
959 =item taxproduct_description [ CLASS ]
960
961 Returns the description of the associated tax product for this package
962 definition (see L<FS::part_pkg_taxproduct>).
963
964 =cut
965
966 sub taxproduct_description {
967   my $self = shift;
968   my $part_pkg_taxproduct = $self->taxproduct(@_);
969   $part_pkg_taxproduct ? $part_pkg_taxproduct->description : '';
970 }
971
972 =item part_pkg_taxrate DATA_PROVIDER, GEOCODE, [ CLASS ]
973
974 Returns the package to taxrate m2m records for this package in the location
975 specified by GEOCODE (see L<FS::part_pkg_taxrate>) and usage class CLASS.
976 CLASS may be one of 'setup', 'recur', or one of the usage classes numbers
977 (see L<FS::usage_class>).
978
979 =cut
980
981 sub _expand_cch_taxproductnum {
982   my $self = shift;
983   my $class = shift;
984   my $part_pkg_taxproduct = $self->taxproduct($class);
985
986   my ($a,$b,$c,$d) = ( $part_pkg_taxproduct
987                          ? ( split ':', $part_pkg_taxproduct->taxproduct )
988                          : ()
989                      );
990   $a = '' unless $a; $b = '' unless $b; $c = '' unless $c; $d = '' unless $d;
991   my $extra_sql = "AND ( taxproduct = '$a:$b:$c:$d'
992                       OR taxproduct = '$a:$b:$c:'
993                       OR taxproduct = '$a:$b:".":$d'
994                       OR taxproduct = '$a:$b:".":' )";
995   map { $_->taxproductnum } qsearch( { 'table'     => 'part_pkg_taxproduct',
996                                        'hashref'   => { 'data_vendor'=>'cch' },
997                                        'extra_sql' => $extra_sql,
998                                    } );
999                                      
1000 }
1001
1002 sub part_pkg_taxrate {
1003   my $self = shift;
1004   my ($data_vendor, $geocode, $class) = @_;
1005
1006   my $dbh = dbh;
1007   my $extra_sql = 'WHERE part_pkg_taxproduct.data_vendor = '.
1008                   dbh->quote($data_vendor);
1009   
1010   # CCH oddness in m2m
1011   $extra_sql .= ' AND ('.
1012     join(' OR ', map{ 'geocode = '. $dbh->quote(substr($geocode, 0, $_)) }
1013                  qw(10 5 2)
1014         ).
1015     ')';
1016   # much more CCH oddness in m2m -- this is kludgy
1017   my @tpnums = $self->_expand_cch_taxproductnum($class);
1018   if (scalar(@tpnums)) {
1019     $extra_sql .= ' AND ('.
1020                             join(' OR ', map{ "taxproductnum = $_" } @tpnums ).
1021                        ')';
1022   } else {
1023     $extra_sql .= ' AND ( 0 = 1 )';
1024   }
1025
1026   my $addl_from = 'LEFT JOIN part_pkg_taxproduct USING ( taxproductnum )';
1027   my $order_by = 'ORDER BY taxclassnum, length(geocode) desc, length(taxproduct) desc';
1028   my $select   = 'DISTINCT ON(taxclassnum) *, taxproduct';
1029
1030   # should qsearch preface columns with the table to facilitate joins?
1031   qsearch( { 'table'     => 'part_pkg_taxrate',
1032              'select'    => $select,
1033              'hashref'   => { # 'data_vendor'   => $data_vendor,
1034                               # 'taxproductnum' => $self->taxproductnum,
1035                             },
1036              'addl_from' => $addl_from,
1037              'extra_sql' => $extra_sql,
1038              'order_by'  => $order_by,
1039          } );
1040 }
1041
1042 =item _rebless
1043
1044 Reblesses the object into the FS::part_pkg::PLAN class (if available), where
1045 PLAN is the object's I<plan> field.  There should be better docs
1046 on how to create new price plans, but until then, see L</NEW PLAN CLASSES>.
1047
1048 =cut
1049
1050 sub _rebless {
1051   my $self = shift;
1052   my $plan = $self->plan;
1053   unless ( $plan ) {
1054     cluck "no price plan found for pkgpart ". $self->pkgpart. "\n"
1055       if $DEBUG;
1056     return $self;
1057   }
1058   return $self if ref($self) =~ /::$plan$/; #already blessed into plan subclass
1059   my $class = ref($self). "::$plan";
1060   warn "reblessing $self into $class" if $DEBUG;
1061   eval "use $class;";
1062   die $@ if $@;
1063   bless($self, $class) unless $@;
1064   $self;
1065 }
1066
1067 #fallbacks that eval the setup and recur fields, for backwards compat
1068
1069 sub calc_setup {
1070   my $self = shift;
1071   warn 'no price plan class for '. $self->plan. ", eval-ing setup\n";
1072   $self->_calc_eval('setup', @_);
1073 }
1074
1075 sub calc_recur {
1076   my $self = shift;
1077   warn 'no price plan class for '. $self->plan. ", eval-ing recur\n";
1078   $self->_calc_eval('recur', @_);
1079 }
1080
1081 use vars qw( $sdate @details );
1082 sub _calc_eval {
1083   #my( $self, $field, $cust_pkg ) = @_;
1084   my( $self, $field, $cust_pkg, $sdateref, $detailsref ) = @_;
1085   *sdate = $sdateref;
1086   *details = $detailsref;
1087   $self->$field() =~ /^(.*)$/
1088     or die "Illegal $field (pkgpart ". $self->pkgpart. '): '.
1089             $self->$field(). "\n";
1090   my $prog = $1;
1091   return 0 if $prog =~ /^\s*$/;
1092   my $value = eval $prog;
1093   die $@ if $@;
1094   $value;
1095 }
1096
1097 #fallback that return 0 for old legacy packages with no plan
1098
1099 sub calc_remain { 0; }
1100 sub calc_cancel { 0; }
1101 sub calc_units  { 0; }
1102
1103 =item format OPTION DATA
1104
1105 Returns data formatted according to the function 'format' described
1106 in the plan info.  Returns DATA if no such function exists.
1107
1108 =cut
1109
1110 sub format {
1111   my ($self, $option, $data) = (shift, shift, shift);
1112   if (exists($plans{$self->plan}->{fields}->{$option}{format})) {
1113     &{$plans{$self->plan}->{fields}->{$option}{format}}($data);
1114   }else{
1115     $data;
1116   }
1117 }
1118
1119 =item parse OPTION DATA
1120
1121 Returns data parsed according to the function 'parse' described
1122 in the plan info.  Returns DATA if no such function exists.
1123
1124 =cut
1125
1126 sub parse {
1127   my ($self, $option, $data) = (shift, shift, shift);
1128   if (exists($plans{$self->plan}->{fields}->{$option}{parse})) {
1129     &{$plans{$self->plan}->{fields}->{$option}{parse}}($data);
1130   }else{
1131     $data;
1132   }
1133 }
1134
1135 =back
1136
1137 =cut
1138
1139 =head1 CLASS METHODS
1140
1141 =over 4
1142
1143 =cut
1144
1145 # _upgrade_data
1146 #
1147 # Used by FS::Upgrade to migrate to a new database.
1148
1149 sub _upgrade_data { # class method
1150   my($class, %opts) = @_;
1151
1152   warn "[FS::part_pkg] upgrading $class\n" if $DEBUG;
1153
1154   my @part_pkg = qsearch({
1155     'table'     => 'part_pkg',
1156     'extra_sql' => "WHERE ". join(' OR ',
1157                      ( map "($_ IS NOT NULL AND $_ != '' )",
1158                            qw( plandata setup recur ) ),
1159                      'plan IS NULL', "plan = '' ",
1160                    ),
1161   });
1162
1163   foreach my $part_pkg (@part_pkg) {
1164
1165     unless ( $part_pkg->plan ) {
1166
1167       $part_pkg->plan('flat');
1168
1169       if ( $part_pkg->setup =~ /^\s*([\d\.]+)\s*$/ ) {
1170
1171         my $opt = new FS::part_pkg_option {
1172           'pkgpart'     => $part_pkg->pkgpart,
1173           'optionname'  => 'setup_fee',
1174           'optionvalue' => $1,
1175         };
1176         my $error = $opt->insert;
1177         die $error if $error;
1178
1179         $part_pkg->setup('');
1180
1181       } else {
1182         die "Can't parse part_pkg.setup for fee; convert pkgnum ".
1183             $part_pkg->pkgnum. " manually: ". $part_pkg->setup. "\n";
1184       }
1185
1186       if ( $part_pkg->recur =~ /^\s*([\d\.]+)\s*$/ ) {
1187
1188         my $opt = new FS::part_pkg_option {
1189           'pkgpart'     => $part_pkg->pkgpart,
1190           'optionname'  => 'recur_fee',
1191           'optionvalue' => $1,
1192         };
1193         my $error = $opt->insert;
1194         die $error if $error;
1195
1196         $part_pkg->recur('');
1197
1198       } else {
1199         die "Can't parse part_pkg.setup for fee; convert pkgnum ".
1200             $part_pkg->pkgnum. " manually: ". $part_pkg->setup. "\n";
1201       }
1202
1203     }
1204
1205     $part_pkg->replace; #this should take care of plandata, right?
1206
1207   }
1208
1209 }
1210
1211 =item curuser_pkgs_sql
1212
1213 Returns an SQL fragment for searching for packages the current user can
1214 use, either via part_pkg.agentnum directly, or via agent type (see
1215 L<FS::type_pkgs>).
1216
1217 =cut
1218
1219 sub curuser_pkgs_sql {
1220   #my($class) = shift;
1221
1222   my $agentnums = join(',', $FS::CurrentUser::CurrentUser->agentnums);
1223
1224   "
1225     (
1226       agentnum IS NOT NULL
1227       OR
1228       0 < ( SELECT COUNT(*)
1229               FROM type_pkgs
1230                 LEFT JOIN agent_type USING ( typenum )
1231                 LEFT JOIN agent AS typeagent USING ( typenum )
1232               WHERE type_pkgs.pkgpart = part_pkg.pkgpart
1233                 AND typeagent.agentnum IN ($agentnums)
1234           )
1235     )
1236   ";
1237
1238 }
1239
1240 =back
1241
1242 =head1 SUBROUTINES
1243
1244 =over 4
1245
1246 =item plan_info
1247
1248 =cut
1249
1250 #false laziness w/part_export & cdr
1251 my %info;
1252 foreach my $INC ( @INC ) {
1253   warn "globbing $INC/FS/part_pkg/*.pm\n" if $DEBUG;
1254   foreach my $file ( glob("$INC/FS/part_pkg/*.pm") ) {
1255     warn "attempting to load plan info from $file\n" if $DEBUG;
1256     $file =~ /\/(\w+)\.pm$/ or do {
1257       warn "unrecognized file in $INC/FS/part_pkg/: $file\n";
1258       next;
1259     };
1260     my $mod = $1;
1261     my $info = eval "use FS::part_pkg::$mod; ".
1262                     "\\%FS::part_pkg::$mod\::info;";
1263     if ( $@ ) {
1264       die "error using FS::part_pkg::$mod (skipping): $@\n" if $@;
1265       next;
1266     }
1267     unless ( keys %$info ) {
1268       warn "no %info hash found in FS::part_pkg::$mod, skipping\n";
1269       next;
1270     }
1271     warn "got plan info from FS::part_pkg::$mod: $info\n" if $DEBUG;
1272     if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
1273       warn "skipping disabled plan FS::part_pkg::$mod" if $DEBUG;
1274       next;
1275     }
1276     $info{$mod} = $info;
1277   }
1278 }
1279
1280 tie %plans, 'Tie::IxHash',
1281   map  { $_ => $info{$_} }
1282   sort { $info{$a}->{'weight'} <=> $info{$b}->{'weight'} }
1283   keys %info;
1284
1285 sub plan_info {
1286   \%plans;
1287 }
1288
1289
1290 =back
1291
1292 =head1 NEW PLAN CLASSES
1293
1294 A module should be added in FS/FS/part_pkg/  Eventually, an example may be
1295 found in eg/plan_template.pm.  Until then, it is suggested that you use the
1296 other modules in FS/FS/part_pkg/ as a guide.
1297
1298 =head1 BUGS
1299
1300 The delete method is unimplemented.
1301
1302 setup and recur semantics are not yet defined (and are implemented in
1303 FS::cust_bill.  hmm.).  now they're deprecated and need to go.
1304
1305 plandata should go
1306
1307 part_pkg_taxrate is Pg specific
1308
1309 =head1 SEE ALSO
1310
1311 L<FS::Record>, L<FS::cust_pkg>, L<FS::type_pkgs>, L<FS::pkg_svc>, L<Safe>.
1312 schema.html from the base documentation.
1313
1314 =cut
1315
1316 1;
1317