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