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