autoload methods returning foreign records, RT#13971
[freeside.git] / FS / FS / part_pkg.pm
1 package FS::part_pkg;
2 use base qw( FS::m2m_Common FS::o2m_Common FS::option_Common );
3
4 use strict;
5 use vars qw( %plans $DEBUG $setup_hack $skip_pkg_svc_hack );
6 use Carp qw(carp cluck confess);
7 use Scalar::Util qw( blessed );
8 use DateTime;
9 use Time::Local qw( timelocal timelocal_nocheck ); # eventually replace with DateTime
10 use Tie::IxHash;
11 use FS::Conf;
12 use FS::Record qw( qsearch qsearchs dbh dbdef );
13 use FS::pkg_svc;
14 use FS::part_svc;
15 use FS::cust_pkg;
16 use FS::agent_type;
17 use FS::type_pkgs;
18 use FS::part_pkg_option;
19 use FS::part_pkg_msgcat;
20 use FS::part_pkg_taxrate;
21 use FS::part_pkg_taxoverride;
22 use FS::part_pkg_taxproduct;
23 use FS::part_pkg_link;
24 use FS::part_pkg_discount;
25 use FS::part_pkg_vendor;
26 use FS::part_pkg_currency;
27
28 $DEBUG = 0;
29 $setup_hack = 0;
30 $skip_pkg_svc_hack = 0;
31
32 =head1 NAME
33
34 FS::part_pkg - Object methods for part_pkg objects
35
36 =head1 SYNOPSIS
37
38   use FS::part_pkg;
39
40   $record = new FS::part_pkg \%hash
41   $record = new FS::part_pkg { 'column' => 'value' };
42
43   $custom_record = $template_record->clone;
44
45   $error = $record->insert;
46
47   $error = $new_record->replace($old_record);
48
49   $error = $record->delete;
50
51   $error = $record->check;
52
53   @pkg_svc = $record->pkg_svc;
54
55   $svcnum = $record->svcpart;
56   $svcnum = $record->svcpart( 'svc_acct' );
57
58 =head1 DESCRIPTION
59
60 An FS::part_pkg object represents a package definition.  FS::part_pkg
61 inherits from FS::Record.  The following fields are currently supported:
62
63 =over 4
64
65 =item pkgpart - primary key (assigned automatically for new package definitions)
66
67 =item pkg - Text name of this package definition (customer-viewable)
68
69 =item comment - Text name of this package definition (non-customer-viewable)
70
71 =item classnum - Optional package class (see L<FS::pkg_class>)
72
73 =item promo_code - Promotional code
74
75 =item setup - Setup fee expression (deprecated)
76
77 =item freq - Frequency of recurring fee
78
79 =item recur - Recurring fee expression (deprecated)
80
81 =item setuptax - Setup fee tax exempt flag, empty or `Y'
82
83 =item recurtax - Recurring fee tax exempt flag, empty or `Y'
84
85 =item taxclass - Tax class 
86
87 =item plan - Price plan
88
89 =item plandata - Price plan data (deprecated - see L<FS::part_pkg_option> instead)
90
91 =item disabled - Disabled flag, empty or `Y'
92
93 =item custom - Custom flag, empty or `Y'
94
95 =item setup_cost - for cost tracking
96
97 =item recur_cost - for cost tracking
98
99 =item pay_weight - Weight (relative to credit_weight and other package definitions) that controls payment application to specific line items.
100
101 =item credit_weight - Weight (relative to other package definitions) that controls credit application to specific line items.
102
103 =item agentnum - Optional agentnum (see L<FS::agent>)
104
105 =item fcc_ds0s - Optional DS0 equivalency number for FCC form 477
106
107 =item fcc_voip_class - Which column of FCC form 477 part II.B this package 
108 belongs in.
109
110 =item successor - Foreign key for the part_pkg that replaced this record.
111 If this record is not obsolete, will be null.
112
113 =item family_pkgpart - Foreign key for the part_pkg that was the earliest
114 ancestor of this record.  If this record is not a successor to another 
115 part_pkg, will be equal to pkgpart.
116
117 =item delay_start - Number of days to delay package start, by default
118
119 =back
120
121 =head1 METHODS
122
123 =over 4 
124
125 =item new HASHREF
126
127 Creates a new package definition.  To add the package definition to
128 the database, see L<"insert">.
129
130 =cut
131
132 sub table { 'part_pkg'; }
133
134 =item clone
135
136 An alternate constructor.  Creates a new package definition by duplicating
137 an existing definition.  A new pkgpart is assigned and the custom flag is
138 set to Y.  To add the package definition to the database, see L<"insert">.
139
140 =cut
141
142 sub clone {
143   my $self = shift;
144   my $class = ref($self);
145   my %hash = $self->hash;
146   $hash{'pkgpart'} = '';
147   $hash{'custom'} = 'Y';
148   #new FS::part_pkg ( \%hash ); # ?
149   new $class ( \%hash ); # ?
150 }
151
152 =item insert [ , OPTION => VALUE ... ]
153
154 Adds this package definition to the database.  If there is an error,
155 returns the error, otherwise returns false.
156
157 Currently available options are: I<pkg_svc>, I<primary_svc>, I<cust_pkg>, 
158 I<custnum_ref> and I<options>.
159
160 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
161 values, appropriate FS::pkg_svc records will be inserted.  I<hidden_svc> can 
162 be set to a hashref of svcparts and flag values ('Y' or '') to set the 
163 'hidden' field in these records.
164
165 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
166 FS::pkg_svc record will be updated.
167
168 If I<cust_pkg> is set to a pkgnum of a FS::cust_pkg record (or the FS::cust_pkg
169 record itself), the object will be updated to point to this package definition.
170
171 In conjunction with I<cust_pkg>, if I<custnum_ref> is set to a scalar reference,
172 the scalar will be updated with the custnum value from the cust_pkg record.
173
174 If I<tax_overrides> is set to a hashref with usage classes as keys and comma
175 separated tax class numbers as values, appropriate FS::part_pkg_taxoverride
176 records will be inserted.
177
178 If I<options> is set to a hashref of options, appropriate FS::part_pkg_option
179 records will be inserted.
180
181 If I<part_pkg_currency> is set to a hashref of options (with the keys as
182 option_CURRENCY), appropriate FS::part_pkg::currency records will be inserted.
183
184 =cut
185
186 sub insert {
187   my $self = shift;
188   my %options = @_;
189   warn "FS::part_pkg::insert called on $self with options ".
190        join(', ', map "$_=>$options{$_}", keys %options)
191     if $DEBUG;
192
193   local $SIG{HUP} = 'IGNORE';
194   local $SIG{INT} = 'IGNORE';
195   local $SIG{QUIT} = 'IGNORE';
196   local $SIG{TERM} = 'IGNORE';
197   local $SIG{TSTP} = 'IGNORE';
198   local $SIG{PIPE} = 'IGNORE';
199
200   my $oldAutoCommit = $FS::UID::AutoCommit;
201   local $FS::UID::AutoCommit = 0;
202   my $dbh = dbh;
203
204   warn "  inserting part_pkg record" if $DEBUG;
205   my $error = $self->SUPER::insert( $options{options} );
206   if ( $error ) {
207     $dbh->rollback if $oldAutoCommit;
208     return $error;
209   }
210
211   # set family_pkgpart
212   if ( $self->get('family_pkgpart') eq '' ) {
213     $self->set('family_pkgpart' => $self->pkgpart);
214     $error = $self->SUPER::replace;
215     if ( $error ) {
216       $dbh->rollback if $oldAutoCommit;
217       return $error;
218     }
219   }
220
221   my $conf = new FS::Conf;
222   if ( $conf->exists('agent_defaultpkg') ) {
223     warn "  agent_defaultpkg set; allowing all agents to purchase package"
224       if $DEBUG;
225     foreach my $agent_type ( qsearch('agent_type', {} ) ) {
226       my $type_pkgs = new FS::type_pkgs({
227         'typenum' => $agent_type->typenum,
228         'pkgpart' => $self->pkgpart,
229       });
230       my $error = $type_pkgs->insert;
231       if ( $error ) {
232         $dbh->rollback if $oldAutoCommit;
233         return $error;
234       }
235     }
236   }
237
238   warn "  inserting part_pkg_taxoverride records" if $DEBUG;
239   my %overrides = %{ $options{'tax_overrides'} || {} };
240   foreach my $usage_class ( keys %overrides ) {
241     my $override =
242       ( exists($overrides{$usage_class}) && defined($overrides{$usage_class}) )
243         ? $overrides{$usage_class}
244         : '';
245     my @overrides = (grep "$_", split(',', $override) );
246     my $error = $self->process_m2m (
247                   'link_table'   => 'part_pkg_taxoverride',
248                   'target_table' => 'tax_class',
249                   'hashref'      => { 'usage_class' => $usage_class },
250                   'params'       => \@overrides,
251                 );
252     if ( $error ) {
253       $dbh->rollback if $oldAutoCommit;
254       return $error;
255     }
256   }
257
258   warn "  inserting part_pkg_currency records" if $DEBUG;
259   my %part_pkg_currency = %{ $options{'part_pkg_currency'} || {} };
260   foreach my $key ( keys %part_pkg_currency ) {
261     $key =~ /^(.+)_([A-Z]{3})$/ or next;
262     my $part_pkg_currency = new FS::part_pkg_currency {
263       'pkgpart'     => $self->pkgpart,
264       'optionname'  => $1,
265       'currency'    => $2,
266       'optionvalue' => $part_pkg_currency{$key},
267     };
268     my $error = $part_pkg_currency->insert;
269     if ( $error ) {
270       $dbh->rollback if $oldAutoCommit;
271       return $error;
272     }
273   }
274
275   unless ( $skip_pkg_svc_hack ) {
276
277     warn "  inserting pkg_svc records" if $DEBUG;
278     my $pkg_svc = $options{'pkg_svc'} || {};
279     my $hidden_svc = $options{'hidden_svc'} || {};
280     foreach my $part_svc ( qsearch('part_svc', {} ) ) {
281       my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
282       my $primary_svc =
283         ( $options{'primary_svc'} && $options{'primary_svc'}==$part_svc->svcpart )
284           ? 'Y'
285           : '';
286
287       my $pkg_svc = new FS::pkg_svc( {
288         'pkgpart'     => $self->pkgpart,
289         'svcpart'     => $part_svc->svcpart,
290         'quantity'    => $quantity, 
291         'primary_svc' => $primary_svc,
292         'hidden'      => $hidden_svc->{$part_svc->svcpart},
293       } );
294       my $error = $pkg_svc->insert;
295       if ( $error ) {
296         $dbh->rollback if $oldAutoCommit;
297         return $error;
298       }
299     }
300
301   }
302
303   if ( $options{'cust_pkg'} ) {
304     warn "  updating cust_pkg record " if $DEBUG;
305     my $old_cust_pkg =
306       ref($options{'cust_pkg'})
307         ? $options{'cust_pkg'}
308         : qsearchs('cust_pkg', { pkgnum => $options{'cust_pkg'} } );
309     ${ $options{'custnum_ref'} } = $old_cust_pkg->custnum
310       if $options{'custnum_ref'};
311     my %hash = $old_cust_pkg->hash;
312     $hash{'pkgpart'} = $self->pkgpart,
313     my $new_cust_pkg = new FS::cust_pkg \%hash;
314     local($FS::cust_pkg::disable_agentcheck) = 1;
315     my $error = $new_cust_pkg->replace($old_cust_pkg);
316     if ( $error ) {
317       $dbh->rollback if $oldAutoCommit;
318       return "Error modifying cust_pkg record: $error";
319     }
320   }
321
322   if ( $options{'part_pkg_vendor'} ) {
323       while ( my ($exportnum, $vendor_pkg_id) =
324                 each %{ $options{part_pkg_vendor} }
325             )
326       {
327             my $ppv = new FS::part_pkg_vendor( {
328                     'pkgpart' => $self->pkgpart,
329                     'exportnum' => $exportnum,
330                     'vendor_pkg_id' => $vendor_pkg_id, 
331                 } );
332             my $error = $ppv->insert;
333             if ( $error ) {
334               $dbh->rollback if $oldAutoCommit;
335               return "Error inserting part_pkg_vendor record: $error";
336             }
337       }
338   }
339
340   warn "  committing transaction" if $DEBUG and $oldAutoCommit;
341   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
342
343   '';
344 }
345
346 =item delete
347
348 Currently unimplemented.
349
350 =cut
351
352 sub delete {
353   return "Can't (yet?) delete package definitions.";
354 # check & make sure the pkgpart isn't in cust_pkg or type_pkgs?
355 }
356
357 =item replace OLD_RECORD [ , OPTION => VALUE ... ]
358
359 Replaces OLD_RECORD with this one in the database.  If there is an error,
360 returns the error, otherwise returns false.
361
362 Currently available options are: I<pkg_svc>, I<hidden_svc>, I<primary_svc> 
363 and I<options>
364
365 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
366 values, the appropriate FS::pkg_svc records will be replaced.  I<hidden_svc>
367 can be set to a hashref of svcparts and flag values ('Y' or '') to set the 
368 'hidden' field in these records.  I<bulk_skip> can be set to a hashref of
369 svcparts and flag values ('Y' or '') to set the 'bulk_skip' field in those
370 records.
371
372 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
373 FS::pkg_svc record will be updated.
374
375 If I<options> is set to a hashref, the appropriate FS::part_pkg_option records
376 will be replaced.
377
378 If I<part_pkg_currency> is set to a hashref of options (with the keys as
379 option_CURRENCY), appropriate FS::part_pkg::currency records will be replaced.
380
381 =cut
382
383 sub replace {
384   my $new = shift;
385
386   my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
387               ? shift
388               : $new->replace_old;
389
390   my $options = 
391     ( ref($_[0]) eq 'HASH' )
392       ? shift
393       : { @_ };
394
395   $options->{options} = { $old->options } unless defined($options->{options});
396
397   warn "FS::part_pkg::replace called on $new to replace $old with options".
398        join(', ', map "$_ => ". $options->{$_}, keys %$options)
399     if $DEBUG;
400
401   local $SIG{HUP} = 'IGNORE';
402   local $SIG{INT} = 'IGNORE';
403   local $SIG{QUIT} = 'IGNORE';
404   local $SIG{TERM} = 'IGNORE';
405   local $SIG{TSTP} = 'IGNORE';
406   local $SIG{PIPE} = 'IGNORE';
407
408   my $oldAutoCommit = $FS::UID::AutoCommit;
409   local $FS::UID::AutoCommit = 0;
410   my $dbh = dbh;
411   
412   my $conf = new FS::Conf;
413   if ( $conf->exists('part_pkg-lineage') ) {
414     if ( grep { $options->{options}->{$_} ne $old->option($_, 1) }
415           qw(setup_fee recur_fee) #others? config?
416         ) { 
417     
418       warn "  superseding package" if $DEBUG;
419
420       my $error = $new->supersede($old, %$options);
421       if ( $error ) {
422         $dbh->rollback if $oldAutoCommit;
423         return $error;
424       }
425       else {
426         warn "  committing transaction" if $DEBUG and $oldAutoCommit;
427         $dbh->commit if $oldAutoCommit;
428         return $error;
429       }
430     }
431     #else nothing
432   }
433
434   #plandata shit stays in replace for upgrades until after 2.0 (or edit
435   #_upgrade_data)
436   warn "  saving legacy plandata" if $DEBUG;
437   my $plandata = $new->get('plandata');
438   $new->set('plandata', '');
439
440   warn "  deleting old part_pkg_option records" if $DEBUG;
441   foreach my $part_pkg_option ( $old->part_pkg_option ) {
442     my $error = $part_pkg_option->delete;
443     if ( $error ) {
444       $dbh->rollback if $oldAutoCommit;
445       return $error;
446     }
447   }
448
449   warn "  replacing part_pkg record" if $DEBUG;
450   my $error = $new->SUPER::replace($old, $options->{options} );
451   if ( $error ) {
452     $dbh->rollback if $oldAutoCommit;
453     return $error;
454   }
455
456   warn "  inserting part_pkg_option records for plandata: $plandata|" if $DEBUG;
457   foreach my $part_pkg_option ( 
458     map { /^(\w+)=(.*)$/ or do { $dbh->rollback if $oldAutoCommit;
459                                  return "illegal plandata: $plandata";
460                                };
461           new FS::part_pkg_option {
462             'pkgpart'     => $new->pkgpart,
463             'optionname'  => $1,
464             'optionvalue' => $2,
465           };
466         }
467     split("\n", $plandata)
468   ) {
469     my $error = $part_pkg_option->insert;
470     if ( $error ) {
471       $dbh->rollback if $oldAutoCommit;
472       return $error;
473     }
474   }
475
476   #trivial nit: not the most efficient to delete and reinsert
477   warn "  deleting old part_pkg_currency records" if $DEBUG;
478   foreach my $part_pkg_currency ( $old->part_pkg_currency ) {
479     my $error = $part_pkg_currency->delete;
480     if ( $error ) {
481       $dbh->rollback if $oldAutoCommit;
482       return "error deleting part_pkg_currency record: $error";
483     }
484   }
485
486   warn "  inserting new part_pkg_currency records" if $DEBUG;
487   my %part_pkg_currency = %{ $options->{'part_pkg_currency'} || {} };
488   foreach my $key ( keys %part_pkg_currency ) {
489     $key =~ /^(.+)_([A-Z]{3})$/ or next;
490     my $part_pkg_currency = new FS::part_pkg_currency {
491       'pkgpart'     => $new->pkgpart,
492       'optionname'  => $1,
493       'currency'    => $2,
494       'optionvalue' => $part_pkg_currency{$key},
495     };
496     my $error = $part_pkg_currency->insert;
497     if ( $error ) {
498       $dbh->rollback if $oldAutoCommit;
499       return "error inserting part_pkg_currency record: $error";
500     }
501   }
502
503
504   warn "  replacing pkg_svc records" if $DEBUG;
505   my $pkg_svc = $options->{'pkg_svc'};
506   my $hidden_svc = $options->{'hidden_svc'} || {};
507   my $bulk_skip  = $options->{'bulk_skip'} || {};
508   if ( $pkg_svc ) { # if it wasn't passed, don't change existing pkg_svcs
509     foreach my $part_svc ( qsearch('part_svc', {} ) ) {
510       my $quantity  = $pkg_svc->{$part_svc->svcpart} || 0;
511       my $hidden    = $hidden_svc->{$part_svc->svcpart} || '';
512       my $bulk_skip = $bulk_skip->{$part_svc->svcpart} || '';
513       my $primary_svc =
514         ( defined($options->{'primary_svc'}) && $options->{'primary_svc'}
515           && $options->{'primary_svc'} == $part_svc->svcpart
516         )
517           ? 'Y'
518           : '';
519
520       my $old_pkg_svc = qsearchs('pkg_svc', {
521           'pkgpart' => $old->pkgpart,
522           'svcpart' => $part_svc->svcpart,
523         }
524       );
525       my $old_quantity = 0;
526       my $old_primary_svc = '';
527       my $old_hidden = '';
528       my $old_bulk_skip = '';
529       if ( $old_pkg_svc ) {
530         $old_quantity = $old_pkg_svc->quantity;
531         $old_primary_svc = $old_pkg_svc->primary_svc 
532           if $old_pkg_svc->dbdef_table->column('primary_svc'); # is this needed?
533         $old_hidden = $old_pkg_svc->hidden;
534         $old_bulk_skip = $old_pkg_svc->old_bulk_skip;
535       }
536    
537       next unless $old_quantity    != $quantity
538                || $old_primary_svc ne $primary_svc
539                || $old_hidden      ne $hidden
540                || $old_bulk_skip   ne $bulk_skip;
541     
542       my $new_pkg_svc = new FS::pkg_svc( {
543         'pkgsvcnum'   => ( $old_pkg_svc ? $old_pkg_svc->pkgsvcnum : '' ),
544         'pkgpart'     => $new->pkgpart,
545         'svcpart'     => $part_svc->svcpart,
546         'quantity'    => $quantity, 
547         'primary_svc' => $primary_svc,
548         'hidden'      => $hidden,
549         'bulk_skip'   => $bulk_skip,
550       } );
551       my $error = $old_pkg_svc
552                     ? $new_pkg_svc->replace($old_pkg_svc)
553                     : $new_pkg_svc->insert;
554       if ( $error ) {
555         $dbh->rollback if $oldAutoCommit;
556         return $error;
557       }
558     } #foreach $part_svc
559   } #if $options->{pkg_svc}
560   
561   my @part_pkg_vendor = $old->part_pkg_vendor;
562   my @current_exportnum = ();
563   if ( $options->{'part_pkg_vendor'} ) {
564       my($exportnum,$vendor_pkg_id);
565       while ( ($exportnum,$vendor_pkg_id) 
566                                 = each %{$options->{'part_pkg_vendor'}} ) {
567           my $noinsert = 0;
568           foreach my $part_pkg_vendor ( @part_pkg_vendor ) {
569             if($exportnum == $part_pkg_vendor->exportnum
570                 && $vendor_pkg_id ne $part_pkg_vendor->vendor_pkg_id) {
571                 $part_pkg_vendor->vendor_pkg_id($vendor_pkg_id);
572                 my $error = $part_pkg_vendor->replace;
573                 if ( $error ) {
574                   $dbh->rollback if $oldAutoCommit;
575                   return "Error replacing part_pkg_vendor record: $error";
576                 }
577                 $noinsert = 1;
578                 last;
579             }
580             elsif($exportnum == $part_pkg_vendor->exportnum
581                 && $vendor_pkg_id eq $part_pkg_vendor->vendor_pkg_id) {
582                 $noinsert = 1;
583                 last;
584             }
585           }
586           unless ( $noinsert ) {
587             my $ppv = new FS::part_pkg_vendor( {
588                     'pkgpart' => $new->pkgpart,
589                     'exportnum' => $exportnum,
590                     'vendor_pkg_id' => $vendor_pkg_id, 
591                 } );
592             my $error = $ppv->insert;
593             if ( $error ) {
594               $dbh->rollback if $oldAutoCommit;
595               return "Error inserting part_pkg_vendor record: $error";
596             }
597           }
598           push @current_exportnum, $exportnum;
599       }
600   }
601   foreach my $part_pkg_vendor ( @part_pkg_vendor ) {
602       unless ( grep($_ eq $part_pkg_vendor->exportnum, @current_exportnum) ) {
603         my $error = $part_pkg_vendor->delete;
604         if ( $error ) {
605           $dbh->rollback if $oldAutoCommit;
606           return "Error deleting part_pkg_vendor record: $error";
607         }
608       }
609   }
610   
611   # propagate changes to certain core fields
612   if ( $conf->exists('part_pkg-lineage') ) {
613     warn "  propagating changes to family" if $DEBUG;
614     my $error = $new->propagate($old);
615     if ( $error ) {
616       $dbh->rollback if $oldAutoCommit;
617       return $error;
618     }
619   }
620
621   warn "  committing transaction" if $DEBUG and $oldAutoCommit;
622   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
623   '';
624 }
625
626 =item check
627
628 Checks all fields to make sure this is a valid package definition.  If
629 there is an error, returns the error, otherwise returns false.  Called by the
630 insert and replace methods.
631
632 =cut
633
634 sub check {
635   my $self = shift;
636   warn "FS::part_pkg::check called on $self" if $DEBUG;
637
638   for (qw(setup recur plandata)) {
639     #$self->set($_=>0) if $self->get($_) =~ /^\s*$/; }
640     return "Use of $_ field is deprecated; set a plan and options: ".
641            $self->get($_)
642       if length($self->get($_));
643     $self->set($_, '');
644   }
645
646   if ( $self->dbdef_table->column('freq')->type =~ /(int)/i ) {
647     my $error = $self->ut_number('freq');
648     return $error if $error;
649   } else {
650     $self->freq =~ /^(\d+[hdw]?)$/
651       or return "Illegal or empty freq: ". $self->freq;
652     $self->freq($1);
653   }
654
655   my @null_agentnum_right = ( 'Edit global package definitions' );
656   push @null_agentnum_right, 'One-time charge'
657     if $self->freq =~ /^0/;
658   push @null_agentnum_right, 'Customize customer package'
659     if $self->disabled eq 'Y'; #good enough
660
661   my $error = $self->ut_numbern('pkgpart')
662     || $self->ut_text('pkg')
663     || $self->ut_text('comment')
664     || $self->ut_textn('promo_code')
665     || $self->ut_alphan('plan')
666     || $self->ut_enum('setuptax', [ '', 'Y' ] )
667     || $self->ut_enum('recurtax', [ '', 'Y' ] )
668     || $self->ut_textn('taxclass')
669     || $self->ut_enum('disabled', [ '', 'Y' ] )
670     || $self->ut_enum('custom', [ '', 'Y' ] )
671     || $self->ut_enum('no_auto', [ '', 'Y' ])
672     || $self->ut_enum('recur_show_zero', [ '', 'Y' ])
673     || $self->ut_enum('setup_show_zero', [ '', 'Y' ])
674     #|| $self->ut_moneyn('setup_cost')
675     #|| $self->ut_moneyn('recur_cost')
676     || $self->ut_floatn('setup_cost')
677     || $self->ut_floatn('recur_cost')
678     || $self->ut_floatn('pay_weight')
679     || $self->ut_floatn('credit_weight')
680     || $self->ut_numbern('taxproductnum')
681     || $self->ut_foreign_keyn('classnum',       'pkg_class', 'classnum')
682     || $self->ut_foreign_keyn('addon_classnum', 'pkg_class', 'classnum')
683     || $self->ut_foreign_keyn('taxproductnum',
684                               'part_pkg_taxproduct',
685                               'taxproductnum'
686                              )
687     || ( $setup_hack
688            ? $self->ut_foreign_keyn('agentnum', 'agent', 'agentnum' )
689            : $self->ut_agentnum_acl('agentnum', \@null_agentnum_right)
690        )
691     || $self->ut_numbern('fcc_ds0s')
692     || $self->ut_numbern('fcc_voip_class')
693     || $self->ut_numbern('delay_start')
694     || $self->ut_foreign_keyn('successor', 'part_pkg', 'pkgpart')
695     || $self->ut_foreign_keyn('family_pkgpart', 'part_pkg', 'pkgpart')
696     || $self->SUPER::check
697   ;
698   return $error if $error;
699
700   return 'Unknown plan '. $self->plan
701     unless exists($plans{$self->plan});
702
703   my $conf = new FS::Conf;
704   return 'Taxclass is required'
705     if ! $self->taxclass && $conf->exists('require_taxclasses');
706
707   '';
708 }
709
710 =item supersede OLD [, OPTION => VALUE ... ]
711
712 Inserts this package as a successor to the package OLD.  All options are as
713 for C<insert>.  After inserting, disables OLD and sets the new package as its
714 successor.
715
716 =cut
717
718 sub supersede {
719   my ($new, $old, %options) = @_;
720   my $error;
721
722   $new->set('pkgpart' => '');
723   $new->set('family_pkgpart' => $old->family_pkgpart);
724   warn "    inserting successor package\n" if $DEBUG;
725   $error = $new->insert(%options);
726   return $error if $error;
727  
728   warn "    disabling superseded package\n" if $DEBUG; 
729   $old->set('successor' => $new->pkgpart);
730   $old->set('disabled' => 'Y');
731   $error = $old->SUPER::replace; # don't change its options/pkg_svc records
732   return $error if $error;
733
734   warn "  propagating changes to family" if $DEBUG;
735   $new->propagate($old);
736 }
737
738 =item propagate OLD
739
740 If any of certain fields have changed from OLD to this package, then,
741 for all packages in the same lineage as this one, sets those fields 
742 to their values in this package.
743
744 =cut
745
746 my @propagate_fields = (
747   qw( pkg classnum setup_cost recur_cost taxclass
748   setuptax recurtax pay_weight credit_weight
749   )
750 );
751
752 sub propagate {
753   my $new = shift;
754   my $old = shift;
755   my %fields = (
756     map { $_ => $new->get($_) }
757     grep { $new->get($_) ne $old->get($_) }
758     @propagate_fields
759   );
760
761   my @part_pkg = qsearch('part_pkg', { 
762       'family_pkgpart' => $new->family_pkgpart 
763   });
764   my @error;
765   foreach my $part_pkg ( @part_pkg ) {
766     my $pkgpart = $part_pkg->pkgpart;
767     next if $pkgpart == $new->pkgpart; # don't modify $new
768     warn "    propagating to pkgpart $pkgpart\n" if $DEBUG;
769     foreach ( keys %fields ) {
770       $part_pkg->set($_, $fields{$_});
771     }
772     # SUPER::replace to avoid changing non-core fields
773     my $error = $part_pkg->SUPER::replace;
774     push @error, "pkgpart $pkgpart: $error"
775       if $error;
776   }
777   join("\n", @error);
778 }
779
780 =item pkg_locale LOCALE
781
782 Returns a customer-viewable string representing this package for the given
783 locale, from the part_pkg_msgcat table.  If the given locale is empty or no
784 localized string is found, returns the base pkg field.
785
786 =cut
787
788 sub pkg_locale {
789   my( $self, $locale ) = @_;
790   return $self->pkg unless $locale;
791   my $part_pkg_msgcat = $self->part_pkg_msgcat($locale) or return $self->pkg;
792   $part_pkg_msgcat->pkg;
793 }
794
795 =item part_pkg_msgcat LOCALE
796
797 Like pkg_locale, but returns the FS::part_pkg_msgcat object itself.
798
799 =cut
800
801 sub part_pkg_msgcat {
802   my( $self, $locale ) = @_;
803   qsearchs( 'part_pkg_msgcat', {
804     pkgpart => $self->pkgpart,
805     locale  => $locale,
806   });
807 }
808
809 =item pkg_comment [ OPTION => VALUE... ]
810
811 Returns an (internal) string representing this package.  Currently,
812 "pkgpart: pkg - comment", is returned.  "pkg - comment" may be returned in the
813 future, omitting pkgpart.  The comment will have '(CUSTOM) ' prepended if
814 custom is Y.
815
816 If the option nopkgpart is true then the "pkgpart: ' is omitted.
817
818 =cut
819
820 sub pkg_comment {
821   my $self = shift;
822   my %opt = @_;
823
824   #$self->pkg. ' - '. $self->comment;
825   #$self->pkg. ' ('. $self->comment. ')';
826   my $pre = $opt{nopkgpart} ? '' : $self->pkgpart. ': ';
827   $pre. $self->pkg. ' - '. $self->custom_comment;
828 }
829
830 sub price_info { # safety, in case a part_pkg hasn't defined price_info
831     '';
832 }
833
834 sub custom_comment {
835   my $self = shift;
836   ( $self->custom ? '(CUSTOM) ' : '' ). $self->comment . ' ' . $self->price_info;
837 }
838
839 =item pkg_class
840
841 Returns the package class, as an FS::pkg_class object, or the empty string
842 if there is no package class.
843
844 =item addon_pkg_class
845
846 Returns the add-on package class, as an FS::pkg_class object, or the empty
847 string if there is no add-on package class.
848
849 =cut
850
851 sub addon_pkg_class {
852   my $self = shift;
853   if ( $self->addon_classnum ) {
854     qsearchs('pkg_class', { 'classnum' => $self->addon_classnum } );
855   } else {
856     return '';
857   }
858 }
859
860 =item categoryname 
861
862 Returns the package category name, or the empty string if there is no package
863 category.
864
865 =cut
866
867 sub categoryname {
868   my $self = shift;
869   my $pkg_class = $self->pkg_class;
870   $pkg_class
871     ? $pkg_class->categoryname
872     : '';
873 }
874
875 =item classname 
876
877 Returns the package class name, or the empty string if there is no package
878 class.
879
880 =cut
881
882 sub classname {
883   my $self = shift;
884   my $pkg_class = $self->pkg_class;
885   $pkg_class
886     ? $pkg_class->classname
887     : '';
888 }
889
890 =item addon_classname 
891
892 Returns the add-on package class name, or the empty string if there is no
893 add-on package class.
894
895 =cut
896
897 sub addon_classname {
898   my $self = shift;
899   my $pkg_class = $self->addon_pkg_class;
900   $pkg_class
901     ? $pkg_class->classname
902     : '';
903 }
904
905 =item agent 
906
907 Returns the associated agent for this event, if any, as an FS::agent object.
908
909 =item pkg_svc [ HASHREF | OPTION => VALUE ]
910
911 Returns all FS::pkg_svc objects (see L<FS::pkg_svc>) for this package
912 definition (with non-zero quantity).
913
914 One option is available, I<disable_linked>.  If set true it will return the
915 services for this package definition alone, omitting services from any add-on
916 packages.
917
918 =cut
919
920 =item type_pkgs
921
922 Returns all FS::type_pkgs objects (see L<FS::type_pkgs>) for this package
923 definition.
924
925 =cut
926
927 sub pkg_svc {
928   my $self = shift;
929
930 #  #sort { $b->primary cmp $a->primary } 
931 #    grep { $_->quantity }
932 #      qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
933
934   my $opt = ref($_[0]) ? $_[0] : { @_ };
935   my %pkg_svc = map  { $_->svcpart => $_ }
936                 grep { $_->quantity }
937                 qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
938
939   unless ( $opt->{disable_linked} ) {
940     foreach my $dst_pkg ( map $_->dst_pkg, $self->svc_part_pkg_link ) {
941       my @pkg_svc = grep { $_->quantity }
942                     qsearch( 'pkg_svc', { pkgpart=>$dst_pkg->pkgpart } );
943       foreach my $pkg_svc ( @pkg_svc ) {
944         if ( $pkg_svc{$pkg_svc->svcpart} ) {
945           my $quantity = $pkg_svc{$pkg_svc->svcpart}->quantity;
946           $pkg_svc{$pkg_svc->svcpart}->quantity($quantity + $pkg_svc->quantity);
947         } else {
948           $pkg_svc{$pkg_svc->svcpart} = $pkg_svc;
949         }
950       }
951     }
952   }
953
954   values(%pkg_svc);
955
956 }
957
958 =item svcpart [ SVCDB ]
959
960 Returns the svcpart of the primary service definition (see L<FS::part_svc>)
961 associated with this package definition (see L<FS::pkg_svc>).  Returns
962 false if there not a primary service definition or exactly one service
963 definition with quantity 1, or if SVCDB is specified and does not match the
964 svcdb of the service definition.  SVCDB can be specified as a scalar table
965 name, such as 'svc_acct', or as an arrayref of possible table names.
966
967 =cut
968
969 sub svcpart {
970   my $pkg_svc = shift->_primary_pkg_svc(@_);
971   $pkg_svc ? $pkg_svc->svcpart : '';
972 }
973
974 =item part_svc [ SVCDB ]
975
976 Like the B<svcpart> method, but returns the FS::part_svc object (see
977 L<FS::part_svc>).
978
979 =cut
980
981 sub part_svc {
982   my $pkg_svc = shift->_primary_pkg_svc(@_);
983   $pkg_svc ? $pkg_svc->part_svc : '';
984 }
985
986 sub _primary_pkg_svc {
987   my $self = shift;
988
989   my $svcdb = scalar(@_) ? shift : [];
990   $svcdb = ref($svcdb) ? $svcdb : [ $svcdb ];
991   my %svcdb = map { $_=>1 } @$svcdb;
992
993   my @svcdb_pkg_svc =
994     grep { !scalar(@$svcdb) || $svcdb{ $_->part_svc->svcdb } }
995          $self->pkg_svc;
996
997   my @pkg_svc = grep { $_->primary_svc =~ /^Y/i } @svcdb_pkg_svc;
998   @pkg_svc = grep {$_->quantity == 1 } @svcdb_pkg_svc
999     unless @pkg_svc;
1000   return '' if scalar(@pkg_svc) != 1;
1001   $pkg_svc[0];
1002 }
1003
1004 =item svcpart_unique_svcdb SVCDB
1005
1006 Returns the svcpart of a service definition (see L<FS::part_svc>) matching
1007 SVCDB associated with this package definition (see L<FS::pkg_svc>).  Returns
1008 false if there not a primary service definition for SVCDB or there are multiple
1009 service definitions for SVCDB.
1010
1011 =cut
1012
1013 sub svcpart_unique_svcdb {
1014   my( $self, $svcdb ) = @_;
1015   my @svcdb_pkg_svc = grep { ( $svcdb eq $_->part_svc->svcdb ) } $self->pkg_svc;
1016   return '' if scalar(@svcdb_pkg_svc) != 1;
1017   $svcdb_pkg_svc[0]->svcpart;
1018 }
1019
1020 =item payby
1021
1022 Returns a list of the acceptable payment types for this package.  Eventually
1023 this should come out of a database table and be editable, but currently has the
1024 following logic instead:
1025
1026 If the package is free, the single item B<BILL> is
1027 returned, otherwise, the single item B<CARD> is returned.
1028
1029 (CHEK?  LEC?  Probably shouldn't accept those by default, prone to abuse)
1030
1031 =cut
1032
1033 sub payby {
1034   my $self = shift;
1035   if ( $self->is_free ) {
1036     ( 'BILL' );
1037   } else {
1038     ( 'CARD' );
1039   }
1040 }
1041
1042 =item is_free
1043
1044 Returns true if this package is free.  
1045
1046 =cut
1047
1048 sub is_free {
1049   my $self = shift;
1050   if ( $self->can('is_free_options') ) {
1051     not grep { $_ !~ /^\s*0*(\.0*)?\s*$/ }
1052          map { $self->option($_) } 
1053              $self->is_free_options;
1054   } else {
1055     warn "FS::part_pkg::is_free: FS::part_pkg::". $self->plan. " subclass ".
1056          "provides neither is_free_options nor is_free method; returning false";
1057     0;
1058   }
1059 }
1060
1061 # whether the plan allows discounts to be applied to this package
1062 sub can_discount { 0; }
1063  
1064 # whether the plan allows changing the start date
1065 sub can_start_date { 1; }
1066   
1067 # the delay start date if present
1068 sub delay_start_date {
1069   my $self = shift;
1070
1071   my $delay = $self->delay_start or return '';
1072
1073   # avoid timelocal silliness  
1074   my $dt = DateTime->today(time_zone => 'local');
1075   $dt->add(days => $delay);
1076   $dt->epoch;
1077 }
1078
1079 sub can_currency_exchange { 0; }
1080
1081 sub freqs_href {
1082   # moved to FS::Misc to make this accessible to other packages
1083   # at initialization
1084   FS::Misc::pkg_freqs();
1085 }
1086
1087 =item freq_pretty
1088
1089 Returns an english representation of the I<freq> field, such as "monthly",
1090 "weekly", "semi-annually", etc.
1091
1092 =cut
1093
1094 sub freq_pretty {
1095   my $self = shift;
1096   my $freq = $self->freq;
1097
1098   #my $freqs_href = $self->freqs_href;
1099   my $freqs_href = freqs_href();
1100
1101   if ( exists($freqs_href->{$freq}) ) {
1102     $freqs_href->{$freq};
1103   } else {
1104     my $interval = 'month';
1105     if ( $freq =~ /^(\d+)([hdw])$/ ) {
1106       my %interval = ( 'h' => 'hour', 'd'=>'day', 'w'=>'week' );
1107       $interval = $interval{$2};
1108     }
1109     if ( $1 == 1 ) {
1110       "every $interval";
1111     } else {
1112       "every $freq ${interval}s";
1113     }
1114   }
1115 }
1116
1117 =item add_freq TIMESTAMP [ FREQ ]
1118
1119 Adds a billing period of some frequency to the provided timestamp and 
1120 returns the resulting timestamp, or -1 if the frequency could not be 
1121 parsed (shouldn't happen).  By default, the frequency of this package 
1122 will be used; to override this, pass a different frequency as a second 
1123 argument.
1124
1125 =cut
1126
1127 sub add_freq {
1128   my( $self, $date, $freq ) = @_;
1129   $freq = $self->freq unless $freq;
1130
1131   #change this bit to use Date::Manip? CAREFUL with timezones (see
1132   # mailing list archive)
1133   my ($sec,$min,$hour,$mday,$mon,$year) = (localtime($date) )[0,1,2,3,4,5];
1134
1135   if ( $freq =~ /^\d+$/ ) {
1136     $mon += $freq;
1137     until ( $mon < 12 ) { $mon -= 12; $year++; }
1138
1139     $mday = 28 if $mday > 28 && FS::Conf->new->exists('anniversary-rollback');
1140
1141   } elsif ( $freq =~ /^(\d+)w$/ ) {
1142     my $weeks = $1;
1143     $mday += $weeks * 7;
1144   } elsif ( $freq =~ /^(\d+)d$/ ) {
1145     my $days = $1;
1146     $mday += $days;
1147   } elsif ( $freq =~ /^(\d+)h$/ ) {
1148     my $hours = $1;
1149     $hour += $hours;
1150   } else {
1151     return -1;
1152   }
1153
1154   timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year);
1155 }
1156
1157 =item plandata
1158
1159 For backwards compatibility, returns the plandata field as well as all options
1160 from FS::part_pkg_option.
1161
1162 =cut
1163
1164 sub plandata {
1165   my $self = shift;
1166   carp "plandata is deprecated";
1167   if ( @_ ) {
1168     $self->SUPER::plandata(@_);
1169   } else {
1170     my $plandata = $self->get('plandata');
1171     my %options = $self->options;
1172     $plandata .= join('', map { "$_=$options{$_}\n" } keys %options );
1173     $plandata;
1174   }
1175 }
1176
1177 =item part_pkg_vendor
1178
1179 Returns all vendor/external package ids as FS::part_pkg_vendor objects (see
1180 L<FS::part_pkg_vendor>).
1181
1182 =item vendor_pkg_ids
1183
1184 Returns a list of vendor/external package ids by exportnum
1185
1186 =cut
1187
1188 sub vendor_pkg_ids {
1189   my $self = shift;
1190   map { $_->exportnum => $_->vendor_pkg_id } $self->part_pkg_vendor;
1191 }
1192
1193 =item part_pkg_option
1194
1195 Returns all options as FS::part_pkg_option objects (see
1196 L<FS::part_pkg_option>).
1197
1198 =item options 
1199
1200 Returns a list of option names and values suitable for assigning to a hash.
1201
1202 =cut
1203
1204 sub options {
1205   my $self = shift;
1206   map { $_->optionname => $_->optionvalue } $self->part_pkg_option;
1207 }
1208
1209 =item option OPTIONNAME [ QUIET ]
1210
1211 Returns the option value for the given name, or the empty string.  If a true
1212 value is passed as the second argument, warnings about missing the option
1213 will be suppressed.
1214
1215 =cut
1216
1217 sub option {
1218   my( $self, $opt, $ornull ) = @_;
1219   my $part_pkg_option =
1220     qsearchs('part_pkg_option', {
1221       pkgpart    => $self->pkgpart,
1222       optionname => $opt,
1223   } );
1224   return $part_pkg_option->optionvalue if $part_pkg_option;
1225   my %plandata = map { /^(\w+)=(.*)$/; ( $1 => $2 ); }
1226                      split("\n", $self->get('plandata') );
1227   return $plandata{$opt} if exists $plandata{$opt};
1228   cluck "WARNING: (pkgpart ". $self->pkgpart. ") Package def option $opt ".
1229         "not found in options or plandata!\n"
1230     unless $ornull;
1231   '';
1232 }
1233
1234 =item part_pkg_currency [ CURRENCY ]
1235
1236 Returns all currency options as FS::part_pkg_currency objects (see
1237 L<FS::part_pkg_currency>), or, if a currency is specified, only return the
1238 objects for that currency.
1239
1240 =cut
1241
1242 sub part_pkg_currency {
1243   my $self = shift;
1244   my %hash = ( 'pkgpart' => $self->pkgpart );
1245   $hash{'currency'} = shift if @_;
1246   qsearch('part_pkg_currency', \%hash );
1247 }
1248
1249 =item part_pkg_currency_options CURRENCY
1250
1251 Returns a list of option names and values from FS::part_pkg_currency for the
1252 specified currency.
1253
1254 =cut
1255
1256 sub part_pkg_currency_options {
1257   my $self = shift;
1258   map { $_->optionname => $_->optionvalue } $self->part_pkg_currency(shift);
1259 }
1260
1261 =item part_pkg_currency_option CURRENCY OPTIONNAME
1262
1263 Returns the option value for the given name and currency.
1264
1265 =cut
1266
1267 sub part_pkg_currency_option {
1268   my( $self, $currency, $optionname ) = @_; 
1269   my $part_pkg_currency =
1270     qsearchs('part_pkg_currency', { 'pkgpart'    => $self->pkgpart,
1271                                     'currency'   => $currency,
1272                                     'optionname' => $optionname,
1273                                   }
1274             )#;
1275   #fatal if not found?  that works for our use cases from
1276   #part_pkg/currency_fixed, but isn't how we would typically/expect the method
1277   #to behave.  have to catch it there if we change it here...
1278     or die "Unknown price for ". $self->pkg_comment. " in $currency\n";
1279
1280   $part_pkg_currency->optionvalue;
1281 }
1282
1283 =item bill_part_pkg_link
1284
1285 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
1286
1287 =cut
1288
1289 sub bill_part_pkg_link {
1290   shift->_part_pkg_link('bill', @_);
1291 }
1292
1293 =item svc_part_pkg_link
1294
1295 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
1296
1297 =cut
1298
1299 sub svc_part_pkg_link {
1300   shift->_part_pkg_link('svc', @_);
1301 }
1302
1303 =item supp_part_pkg_link
1304
1305 Returns the associated part_pkg_link records of type 'supp' (supplemental
1306 packages).
1307
1308 =cut
1309
1310 sub supp_part_pkg_link {
1311   shift->_part_pkg_link('supp', @_);
1312 }
1313
1314 sub _part_pkg_link {
1315   my( $self, $type ) = @_;
1316   qsearch({ table    => 'part_pkg_link',
1317             hashref  => { 'src_pkgpart' => $self->pkgpart,
1318                           'link_type'   => $type,
1319                           #protection against infinite recursive links
1320                           'dst_pkgpart' => { op=>'!=', value=> $self->pkgpart },
1321                         },
1322             order_by => "ORDER BY hidden",
1323          });
1324 }
1325
1326 sub self_and_bill_linked {
1327   shift->_self_and_linked('bill', @_);
1328 }
1329
1330 sub self_and_svc_linked {
1331   shift->_self_and_linked('svc', @_);
1332 }
1333
1334 sub _self_and_linked {
1335   my( $self, $type, $hidden ) = @_;
1336   $hidden ||= '';
1337
1338   my @result = ();
1339   foreach ( ( $self, map { $_->dst_pkg->_self_and_linked($type, $_->hidden) }
1340                      $self->_part_pkg_link($type) ) )
1341   {
1342     $_->hidden($hidden) if $hidden;
1343     push @result, $_;
1344   }
1345
1346   (@result);
1347 }
1348
1349 =item part_pkg_taxoverride [ CLASS ]
1350
1351 Returns all associated FS::part_pkg_taxoverride objects (see
1352 L<FS::part_pkg_taxoverride>).  Limits the returned set to those
1353 of class CLASS if defined.  Class may be one of 'setup', 'recur',
1354 the empty string (default), or a usage class number (see L<FS::usage_class>).
1355 When a class is specified, the empty string class (default) is returned
1356 if no more specific values exist.
1357
1358 =cut
1359
1360 sub part_pkg_taxoverride {
1361   my $self = shift;
1362   my $class = shift;
1363
1364   my $hashref = { 'pkgpart' => $self->pkgpart };
1365   $hashref->{'usage_class'} = $class if defined($class);
1366   my @overrides = qsearch('part_pkg_taxoverride', $hashref );
1367
1368   unless ( scalar(@overrides) || !defined($class) || !$class ){
1369     $hashref->{'usage_class'} = '';
1370     @overrides = qsearch('part_pkg_taxoverride', $hashref );
1371   }
1372
1373   @overrides;
1374 }
1375
1376 =item has_taxproduct
1377
1378 Returns true if this package has any taxproduct associated with it.  
1379
1380 =cut
1381
1382 sub has_taxproduct {
1383   my $self = shift;
1384
1385   $self->taxproductnum ||
1386   scalar( grep { $_ =~/^usage_taxproductnum_/ && $self->option($_) } 
1387           keys %{ {$self->options} }
1388   )
1389
1390 }
1391
1392
1393 =item taxproduct [ CLASS ]
1394
1395 Returns the associated tax product for this package definition (see
1396 L<FS::part_pkg_taxproduct>).  CLASS may be one of 'setup', 'recur' or
1397 the usage classnum (see L<FS::usage_class>).  Returns the default
1398 tax product for this record if the more specific CLASS value does
1399 not exist.
1400
1401 =cut
1402
1403 sub taxproduct {
1404   my $self = shift;
1405   my $class = shift;
1406
1407   my $part_pkg_taxproduct;
1408
1409   my $taxproductnum = $self->taxproductnum;
1410   if ($class) { 
1411     my $class_taxproductnum = $self->option("usage_taxproductnum_$class", 1);
1412     $taxproductnum = $class_taxproductnum
1413       if $class_taxproductnum
1414   }
1415   
1416   $part_pkg_taxproduct =
1417     qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
1418
1419   unless ($part_pkg_taxproduct || $taxproductnum eq $self->taxproductnum ) {
1420     $taxproductnum = $self->taxproductnum;
1421     $part_pkg_taxproduct =
1422       qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
1423   }
1424
1425   $part_pkg_taxproduct;
1426 }
1427
1428 =item taxproduct_description [ CLASS ]
1429
1430 Returns the description of the associated tax product for this package
1431 definition (see L<FS::part_pkg_taxproduct>).
1432
1433 =cut
1434
1435 sub taxproduct_description {
1436   my $self = shift;
1437   my $part_pkg_taxproduct = $self->taxproduct(@_);
1438   $part_pkg_taxproduct ? $part_pkg_taxproduct->description : '';
1439 }
1440
1441 =item part_pkg_taxrate DATA_PROVIDER, GEOCODE, [ CLASS ]
1442
1443 Returns the package to taxrate m2m records for this package in the location
1444 specified by GEOCODE (see L<FS::part_pkg_taxrate>) and usage class CLASS.
1445 CLASS may be one of 'setup', 'recur', or one of the usage classes numbers
1446 (see L<FS::usage_class>).
1447
1448 =cut
1449
1450 sub _expand_cch_taxproductnum {
1451   my $self = shift;
1452   my $class = shift;
1453   my $part_pkg_taxproduct = $self->taxproduct($class);
1454
1455   my ($a,$b,$c,$d) = ( $part_pkg_taxproduct
1456                          ? ( split ':', $part_pkg_taxproduct->taxproduct )
1457                          : ()
1458                      );
1459   $a = '' unless $a; $b = '' unless $b; $c = '' unless $c; $d = '' unless $d;
1460   my $extra_sql = "AND ( taxproduct = '$a:$b:$c:$d'
1461                       OR taxproduct = '$a:$b:$c:'
1462                       OR taxproduct = '$a:$b:".":$d'
1463                       OR taxproduct = '$a:$b:".":' )";
1464   map { $_->taxproductnum } qsearch( { 'table'     => 'part_pkg_taxproduct',
1465                                        'hashref'   => { 'data_vendor'=>'cch' },
1466                                        'extra_sql' => $extra_sql,
1467                                    } );
1468                                      
1469 }
1470
1471 sub part_pkg_taxrate {
1472   my $self = shift;
1473   my ($data_vendor, $geocode, $class) = @_;
1474
1475   my $dbh = dbh;
1476   my $extra_sql = 'WHERE part_pkg_taxproduct.data_vendor = '.
1477                   dbh->quote($data_vendor);
1478   
1479   # CCH oddness in m2m
1480   $extra_sql .= ' AND ('.
1481     join(' OR ', map{ 'geocode = '. $dbh->quote(substr($geocode, 0, $_)) }
1482                  qw(10 5 2)
1483         ).
1484     ')';
1485   # much more CCH oddness in m2m -- this is kludgy
1486   my @tpnums = $self->_expand_cch_taxproductnum($class);
1487   if (scalar(@tpnums)) {
1488     $extra_sql .= ' AND ('.
1489                             join(' OR ', map{ "taxproductnum = $_" } @tpnums ).
1490                        ')';
1491   } else {
1492     $extra_sql .= ' AND ( 0 = 1 )';
1493   }
1494
1495   my $addl_from = 'LEFT JOIN part_pkg_taxproduct USING ( taxproductnum )';
1496   my $order_by = 'ORDER BY taxclassnum, length(geocode) desc, length(taxproduct) desc';
1497   my $select   = 'DISTINCT ON(taxclassnum) *, taxproduct';
1498
1499   # should qsearch preface columns with the table to facilitate joins?
1500   qsearch( { 'table'     => 'part_pkg_taxrate',
1501              'select'    => $select,
1502              'hashref'   => { # 'data_vendor'   => $data_vendor,
1503                               # 'taxproductnum' => $self->taxproductnum,
1504                             },
1505              'addl_from' => $addl_from,
1506              'extra_sql' => $extra_sql,
1507              'order_by'  => $order_by,
1508          } );
1509 }
1510
1511 =item part_pkg_discount
1512
1513 Returns the package to discount m2m records (see L<FS::part_pkg_discount>)
1514 for this package.
1515
1516 =item part_pkg_usage
1517
1518 Returns the voice usage pools (see L<FS::part_pkg_usage>) defined for 
1519 this package.
1520
1521 =item _rebless
1522
1523 Reblesses the object into the FS::part_pkg::PLAN class (if available), where
1524 PLAN is the object's I<plan> field.  There should be better docs
1525 on how to create new price plans, but until then, see L</NEW PLAN CLASSES>.
1526
1527 =cut
1528
1529 sub _rebless {
1530   my $self = shift;
1531   my $plan = $self->plan;
1532   unless ( $plan ) {
1533     cluck "no price plan found for pkgpart ". $self->pkgpart. "\n"
1534       if $DEBUG;
1535     return $self;
1536   }
1537   return $self if ref($self) =~ /::$plan$/; #already blessed into plan subclass
1538   my $class = ref($self). "::$plan";
1539   warn "reblessing $self into $class" if $DEBUG > 1;
1540   eval "use $class;";
1541   die $@ if $@;
1542   bless($self, $class) unless $@;
1543   $self;
1544 }
1545
1546 #fatal fallbacks
1547 sub calc_setup { die 'no calc_setup for '. shift->plan. "\n"; }
1548 sub calc_recur { die 'no calc_recur for '. shift->plan. "\n"; }
1549
1550 #fallback that return 0 for old legacy packages with no plan
1551 sub calc_remain { 0; }
1552 sub calc_units  { 0; }
1553
1554 #fallback for everything not based on flat.pm
1555 sub recur_temporality { 'upcoming'; }
1556 sub calc_cancel { 0; }
1557
1558 #fallback for everything except bulk.pm
1559 sub hide_svc_detail { 0; }
1560
1561 #fallback for packages that can't/won't summarize usage
1562 sub sum_usage { 0; }
1563
1564 =item recur_cost_permonth CUST_PKG
1565
1566 recur_cost divided by freq (only supported for monthly and longer frequencies)
1567
1568 =cut
1569
1570 sub recur_cost_permonth {
1571   my($self, $cust_pkg) = @_;
1572   return 0 unless $self->freq =~ /^\d+$/ && $self->freq > 0;
1573   sprintf('%.2f', $self->recur_cost / $self->freq );
1574 }
1575
1576 =item cust_bill_pkg_recur CUST_PKG
1577
1578 Actual recurring charge for the specified customer package from customer's most
1579 recent invoice
1580
1581 =cut
1582
1583 sub cust_bill_pkg_recur {
1584   my($self, $cust_pkg) = @_;
1585   my $cust_bill_pkg = qsearchs({
1586     'table'     => 'cust_bill_pkg',
1587     'addl_from' => 'LEFT JOIN cust_bill USING ( invnum )',
1588     'hashref'   => { 'pkgnum' => $cust_pkg->pkgnum,
1589                      'recur'  => { op=>'>', value=>'0' },
1590                    },
1591     'order_by'  => 'ORDER BY cust_bill._date     DESC,
1592                              cust_bill_pkg.sdate DESC
1593                      LIMIT 1
1594                    ',
1595   }) or return 0; #die "use cust_bill_pkg_recur credits with once_perinv condition";
1596   $cust_bill_pkg->recur;
1597 }
1598
1599 =item unit_setup CUST_PKG
1600
1601 Returns the setup fee for one unit of the package.
1602
1603 =cut
1604
1605 sub unit_setup {
1606   my ($self, $cust_pkg) = @_;
1607   $self->option('setup_fee') || 0;
1608 }
1609
1610 =item format OPTION DATA
1611
1612 Returns data formatted according to the function 'format' described
1613 in the plan info.  Returns DATA if no such function exists.
1614
1615 =cut
1616
1617 sub format {
1618   my ($self, $option, $data) = (shift, shift, shift);
1619   if (exists($plans{$self->plan}->{fields}->{$option}{format})) {
1620     &{$plans{$self->plan}->{fields}->{$option}{format}}($data);
1621   }else{
1622     $data;
1623   }
1624 }
1625
1626 =item parse OPTION DATA
1627
1628 Returns data parsed according to the function 'parse' described
1629 in the plan info.  Returns DATA if no such function exists.
1630
1631 =cut
1632
1633 sub parse {
1634   my ($self, $option, $data) = (shift, shift, shift);
1635   if (exists($plans{$self->plan}->{fields}->{$option}{parse})) {
1636     &{$plans{$self->plan}->{fields}->{$option}{parse}}($data);
1637   }else{
1638     $data;
1639   }
1640 }
1641
1642 =back
1643
1644 =cut
1645
1646 =head1 CLASS METHODS
1647
1648 =over 4
1649
1650 =cut
1651
1652 # _upgrade_data
1653 #
1654 # Used by FS::Upgrade to migrate to a new database.
1655
1656 sub _upgrade_data { # class method
1657   my($class, %opts) = @_;
1658
1659   warn "[FS::part_pkg] upgrading $class\n" if $DEBUG;
1660
1661   my @part_pkg = qsearch({
1662     'table'     => 'part_pkg',
1663     'extra_sql' => "WHERE ". join(' OR ',
1664                      'plan IS NULL', "plan = '' ",
1665                    ),
1666   });
1667
1668   foreach my $part_pkg (@part_pkg) {
1669
1670     unless ( $part_pkg->plan ) {
1671       $part_pkg->plan('flat');
1672     }
1673
1674     $part_pkg->replace;
1675
1676   }
1677
1678   # now upgrade to the explicit custom flag
1679
1680   @part_pkg = qsearch({
1681     'table'     => 'part_pkg',
1682     'hashref'   => { disabled => 'Y', custom => '' },
1683     'extra_sql' => "AND comment LIKE '(CUSTOM) %'",
1684   });
1685
1686   foreach my $part_pkg (@part_pkg) {
1687     my $new = new FS::part_pkg { $part_pkg->hash };
1688     $new->custom('Y');
1689     my $comment = $part_pkg->comment;
1690     $comment =~ s/^\(CUSTOM\) //;
1691     $comment = '(none)' unless $comment =~ /\S/;
1692     $new->comment($comment);
1693
1694     my $pkg_svc = { map { $_->svcpart => $_->quantity } $part_pkg->pkg_svc };
1695     my $primary = $part_pkg->svcpart;
1696     my $options = { $part_pkg->options };
1697
1698     my $error = $new->replace( $part_pkg,
1699                                'pkg_svc'     => $pkg_svc,
1700                                'primary_svc' => $primary,
1701                                'options'     => $options,
1702                              );
1703     die $error if $error;
1704   }
1705
1706   # set family_pkgpart on any packages that don't have it
1707   @part_pkg = qsearch('part_pkg', { 'family_pkgpart' => '' });
1708   foreach my $part_pkg (@part_pkg) {
1709     $part_pkg->set('family_pkgpart' => $part_pkg->pkgpart);
1710     my $error = $part_pkg->SUPER::replace;
1711     die $error if $error;
1712   }
1713
1714   my @part_pkg_option = qsearch('part_pkg_option',
1715     { 'optionname'  => 'unused_credit',
1716       'optionvalue' => 1,
1717     });
1718   foreach my $old_opt (@part_pkg_option) {
1719     my $pkgpart = $old_opt->pkgpart;
1720     my $error = $old_opt->delete;
1721     die $error if $error;
1722
1723     foreach (qw(unused_credit_cancel unused_credit_change)) {
1724       my $new_opt = new FS::part_pkg_option {
1725         'pkgpart'     => $pkgpart,
1726         'optionname'  => $_,
1727         'optionvalue' => 1,
1728       };
1729       $error = $new_opt->insert;
1730       die $error if $error;
1731     }
1732   }
1733
1734   # migrate use_disposition_taqua and use_disposition to disposition_in
1735   @part_pkg_option = qsearch('part_pkg_option',
1736     { 'optionname'  => { op => 'LIKE',
1737                          value => 'use_disposition%',
1738                        },
1739       'optionvalue' => 1,
1740     });
1741   my %newopts = map { $_->pkgpart => $_ } 
1742     qsearch('part_pkg_option',  { 'optionname'  => 'disposition_in', } );
1743   foreach my $old_opt (@part_pkg_option) {
1744         my $pkgpart = $old_opt->pkgpart;
1745         my $newval = $old_opt->optionname eq 'use_disposition_taqua' ? '100' 
1746                                                                   : 'ANSWERED';
1747         my $error = $old_opt->delete;
1748         die $error if $error;
1749
1750         if ( exists($newopts{$pkgpart}) ) {
1751             my $opt = $newopts{$pkgpart};
1752             $opt->optionvalue($opt->optionvalue.",$newval");
1753             $error = $opt->replace;
1754             die $error if $error;
1755         } else {
1756             my $new_opt = new FS::part_pkg_option {
1757                 'pkgpart'     => $pkgpart,
1758                 'optionname'  => 'disposition_in',
1759                 'optionvalue' => $newval,
1760               };
1761               $error = $new_opt->insert;
1762               die $error if $error;
1763               $newopts{$pkgpart} = $new_opt;
1764         }
1765   }
1766
1767   # set any package with FCC voice lines to the "VoIP with broadband" category
1768   # for backward compatibility
1769   #
1770   # recover from a bad upgrade bug
1771   my $upgrade = 'part_pkg_fcc_voip_class_FIX';
1772   if (!FS::upgrade_journal->is_done($upgrade)) {
1773     my $bad_upgrade = qsearchs('upgrade_journal', 
1774       { upgrade => 'part_pkg_fcc_voip_class' }
1775     );
1776     if ( $bad_upgrade ) {
1777       my $where = 'WHERE history_date <= '.$bad_upgrade->_date.
1778                   ' AND  history_date >  '.($bad_upgrade->_date - 3600);
1779       my @h_part_pkg_option = map { FS::part_pkg_option->new($_->hashref) }
1780         qsearch({
1781           'select'    => '*',
1782           'table'     => 'h_part_pkg_option',
1783           'hashref'   => {},
1784           'extra_sql' => "$where AND history_action = 'delete'",
1785           'order_by'  => 'ORDER BY history_date ASC',
1786         });
1787       my @h_pkg_svc = map { FS::pkg_svc->new($_->hashref) }
1788         qsearch({
1789           'select'    => '*',
1790           'table'     => 'h_pkg_svc',
1791           'hashref'   => {},
1792           'extra_sql' => "$where AND history_action = 'replace_old'",
1793           'order_by'  => 'ORDER BY history_date ASC',
1794         });
1795       my %opt;
1796       foreach my $deleted (@h_part_pkg_option, @h_pkg_svc) {
1797         my $pkgpart ||= $deleted->pkgpart;
1798         $opt{$pkgpart} ||= {
1799           options => {},
1800           pkg_svc => {},
1801           primary_svc => '',
1802           hidden_svc => {},
1803         };
1804         if ( $deleted->isa('FS::part_pkg_option') ) {
1805           $opt{$pkgpart}{options}{ $deleted->optionname } = $deleted->optionvalue;
1806         } else { # pkg_svc
1807           my $svcpart = $deleted->svcpart;
1808           $opt{$pkgpart}{pkg_svc}{$svcpart} = $deleted->quantity;
1809           $opt{$pkgpart}{hidden_svc}{$svcpart} ||= $deleted->hidden;
1810           $opt{$pkgpart}{primary_svc} = $svcpart if $deleted->primary_svc;
1811         }
1812       }
1813       foreach my $pkgpart (keys %opt) {
1814         my $part_pkg = FS::part_pkg->by_key($pkgpart);
1815         my $error = $part_pkg->replace( $part_pkg->replace_old, $opt{$pkgpart} );
1816         if ( $error ) {
1817           die "error recovering damaged pkgpart $pkgpart:\n$error\n";
1818         }
1819       }
1820     } # $bad_upgrade exists
1821     else { # do the original upgrade, but correctly this time
1822       @part_pkg = qsearch('part_pkg', {
1823           fcc_ds0s        => { op => '>', value => 0 },
1824           fcc_voip_class  => ''
1825       });
1826       foreach my $part_pkg (@part_pkg) {
1827         $part_pkg->set(fcc_voip_class => 2);
1828         my @pkg_svc = $part_pkg->pkg_svc;
1829         my %quantity = map {$_->svcpart, $_->quantity} @pkg_svc;
1830         my %hidden   = map {$_->svcpart, $_->hidden  } @pkg_svc;
1831         my $error = $part_pkg->replace(
1832           $part_pkg->replace_old,
1833           options     => { $part_pkg->options },
1834           pkg_svc     => \%quantity,
1835           hidden_svc  => \%hidden,
1836           primary_svc => ($part_pkg->svcpart || ''),
1837         );
1838         die $error if $error;
1839       }
1840     }
1841     FS::upgrade_journal->set_done($upgrade);
1842   }
1843
1844 }
1845
1846 =item curuser_pkgs_sql
1847
1848 Returns an SQL fragment for searching for packages the current user can
1849 use, either via part_pkg.agentnum directly, or via agent type (see
1850 L<FS::type_pkgs>).
1851
1852 =cut
1853
1854 sub curuser_pkgs_sql {
1855   my $class = shift;
1856
1857   $class->_pkgs_sql( $FS::CurrentUser::CurrentUser->agentnums );
1858
1859 }
1860
1861 =item agent_pkgs_sql AGENT | AGENTNUM, ...
1862
1863 Returns an SQL fragment for searching for packages the provided agent or agents
1864 can use, either via part_pkg.agentnum directly, or via agent type (see
1865 L<FS::type_pkgs>).
1866
1867 =cut
1868
1869 sub agent_pkgs_sql {
1870   my $class = shift;  #i'm a class method, not a sub (the question is... why??)
1871   my @agentnums = map { ref($_) ? $_->agentnum : $_ } @_;
1872
1873   $class->_pkgs_sql(@agentnums); #is this why
1874
1875 }
1876
1877 sub _pkgs_sql {
1878   my( $class, @agentnums ) = @_;
1879   my $agentnums = join(',', @agentnums);
1880
1881   "
1882     (
1883       ( agentnum IS NOT NULL AND agentnum IN ($agentnums) )
1884       OR ( agentnum IS NULL
1885            AND EXISTS ( SELECT 1
1886                           FROM type_pkgs
1887                             LEFT JOIN agent_type USING ( typenum )
1888                             LEFT JOIN agent AS typeagent USING ( typenum )
1889                           WHERE type_pkgs.pkgpart = part_pkg.pkgpart
1890                             AND typeagent.agentnum IN ($agentnums)
1891                       )
1892          )
1893     )
1894   ";
1895
1896 }
1897
1898 =back
1899
1900 =head1 SUBROUTINES
1901
1902 =over 4
1903
1904 =item plan_info
1905
1906 =cut
1907
1908 #false laziness w/part_export & cdr
1909 my %info;
1910 foreach my $INC ( @INC ) {
1911   warn "globbing $INC/FS/part_pkg/*.pm\n" if $DEBUG;
1912   foreach my $file ( glob("$INC/FS/part_pkg/*.pm") ) {
1913     warn "attempting to load plan info from $file\n" if $DEBUG;
1914     $file =~ /\/(\w+)\.pm$/ or do {
1915       warn "unrecognized file in $INC/FS/part_pkg/: $file\n";
1916       next;
1917     };
1918     my $mod = $1;
1919     my $info = eval "use FS::part_pkg::$mod; ".
1920                     "\\%FS::part_pkg::$mod\::info;";
1921     if ( $@ ) {
1922       die "error using FS::part_pkg::$mod (skipping): $@\n" if $@;
1923       next;
1924     }
1925     unless ( keys %$info ) {
1926       warn "no %info hash found in FS::part_pkg::$mod, skipping\n";
1927       next;
1928     }
1929     warn "got plan info from FS::part_pkg::$mod: $info\n" if $DEBUG;
1930     #if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
1931     #  warn "skipping disabled plan FS::part_pkg::$mod" if $DEBUG;
1932     #  next;
1933     #}
1934     $info{$mod} = $info;
1935     $info->{'weight'} ||= 0; # quiet warnings
1936   }
1937 }
1938
1939 # copy one level deep to allow replacement of fields and fieldorder
1940 tie %plans, 'Tie::IxHash',
1941   map  { my %infohash = %{ $info{$_} }; 
1942           $_ => \%infohash }
1943   sort { $info{$a}->{'weight'} <=> $info{$b}->{'weight'} }
1944   keys %info;
1945
1946 # inheritance of plan options
1947 foreach my $name (keys(%info)) {
1948   if (exists($info{$name}->{'disabled'}) and $info{$name}->{'disabled'}) {
1949     warn "skipping disabled plan FS::part_pkg::$name" if $DEBUG;
1950     delete $plans{$name};
1951     next;
1952   }
1953   my $parents = $info{$name}->{'inherit_fields'} || [];
1954   my (%fields, %field_exists, @fieldorder);
1955   foreach my $parent ($name, @$parents) {
1956     if ( !exists($info{$parent}) ) {
1957       warn "$name tried to inherit from nonexistent '$parent'\n";
1958       next;
1959     }
1960     %fields = ( # avoid replacing existing fields
1961       %{ $info{$parent}->{'fields'} || {} },
1962       %fields
1963     );
1964     foreach (@{ $info{$parent}->{'fieldorder'} || [] }) {
1965       # avoid duplicates
1966       next if $field_exists{$_};
1967       $field_exists{$_} = 1;
1968       # allow inheritors to remove inherited fields from the fieldorder
1969       push @fieldorder, $_ if !exists($fields{$_}) or
1970                               !exists($fields{$_}->{'disabled'});
1971     }
1972   }
1973   $plans{$name}->{'fields'} = \%fields;
1974   $plans{$name}->{'fieldorder'} = \@fieldorder;
1975 }
1976
1977 sub plan_info {
1978   \%plans;
1979 }
1980
1981
1982 =back
1983
1984 =head1 NEW PLAN CLASSES
1985
1986 A module should be added in FS/FS/part_pkg/  Eventually, an example may be
1987 found in eg/plan_template.pm.  Until then, it is suggested that you use the
1988 other modules in FS/FS/part_pkg/ as a guide.
1989
1990 =head1 BUGS
1991
1992 The delete method is unimplemented.
1993
1994 setup and recur semantics are not yet defined (and are implemented in
1995 FS::cust_bill.  hmm.).  now they're deprecated and need to go.
1996
1997 plandata should go
1998
1999 part_pkg_taxrate is Pg specific
2000
2001 replace should be smarter about managing the related tables (options, pkg_svc)
2002
2003 =head1 SEE ALSO
2004
2005 L<FS::Record>, L<FS::cust_pkg>, L<FS::type_pkgs>, L<FS::pkg_svc>, L<Safe>.
2006 schema.html from the base documentation.
2007
2008 =cut
2009
2010 1;
2011