0165455444e219110097e976e8034d1edb415826
[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     @taxclassnums = map { $_->taxclassnum }
1479                     grep { $_->taxable eq 'Y' } # why do we need this?
1480                     $part_pkg_taxproduct->part_pkg_taxrate($geocode);
1481   }
1482   return unless @taxclassnums;
1483
1484   warn "Found taxclassnum values of ". join(',', @taxclassnums) ."\n"
1485       if $DEBUG;
1486   my $extra_sql = "AND taxclassnum IN (". join(',', @taxclassnums) . ")";
1487   my @taxes = qsearch({ 'table'     => 'tax_rate',
1488                         'hashref'   => { 'geocode'     => $geocode,
1489                                          'data_vendor' => $vendor },
1490                         'extra_sql' => $extra_sql,
1491                       });
1492   warn "Found taxes ". join(',', map {$_->taxnum} @taxes) ."\n"
1493       if $DEBUG;
1494
1495   return @taxes;
1496 }
1497
1498 =item part_pkg_discount
1499
1500 Returns the package to discount m2m records (see L<FS::part_pkg_discount>)
1501 for this package.
1502
1503 =item part_pkg_usage
1504
1505 Returns the voice usage pools (see L<FS::part_pkg_usage>) defined for 
1506 this package.
1507
1508 =item _rebless
1509
1510 Reblesses the object into the FS::part_pkg::PLAN class (if available), where
1511 PLAN is the object's I<plan> field.  There should be better docs
1512 on how to create new price plans, but until then, see L</NEW PLAN CLASSES>.
1513
1514 =cut
1515
1516 sub _rebless {
1517   my $self = shift;
1518   my $plan = $self->plan;
1519   unless ( $plan ) {
1520     cluck "no price plan found for pkgpart ". $self->pkgpart. "\n"
1521       if $DEBUG;
1522     return $self;
1523   }
1524   return $self if ref($self) =~ /::$plan$/; #already blessed into plan subclass
1525   my $class = ref($self). "::$plan";
1526   warn "reblessing $self into $class" if $DEBUG > 1;
1527   eval "use $class;";
1528   die $@ if $@;
1529   bless($self, $class) unless $@;
1530   $self;
1531 }
1532
1533 #fatal fallbacks
1534 sub calc_setup { die 'no calc_setup for '. shift->plan. "\n"; }
1535 sub calc_recur { die 'no calc_recur for '. shift->plan. "\n"; }
1536
1537 #fallback that return 0 for old legacy packages with no plan
1538 sub calc_remain { 0; }
1539 sub calc_units  { 0; }
1540
1541 #fallback for everything not based on flat.pm
1542 sub recur_temporality { 'upcoming'; }
1543 sub calc_cancel { 0; }
1544
1545 #fallback for everything except bulk.pm
1546 sub hide_svc_detail { 0; }
1547
1548 #fallback for packages that can't/won't summarize usage
1549 sub sum_usage { 0; }
1550
1551 =item recur_cost_permonth CUST_PKG
1552
1553 recur_cost divided by freq (only supported for monthly and longer frequencies)
1554
1555 =cut
1556
1557 sub recur_cost_permonth {
1558   my($self, $cust_pkg) = @_;
1559   return 0 unless $self->freq =~ /^\d+$/ && $self->freq > 0;
1560   sprintf('%.2f', $self->recur_cost / $self->freq );
1561 }
1562
1563 =item cust_bill_pkg_recur CUST_PKG
1564
1565 Actual recurring charge for the specified customer package from customer's most
1566 recent invoice
1567
1568 =cut
1569
1570 sub cust_bill_pkg_recur {
1571   my($self, $cust_pkg) = @_;
1572   my $cust_bill_pkg = qsearchs({
1573     'table'     => 'cust_bill_pkg',
1574     'addl_from' => 'LEFT JOIN cust_bill USING ( invnum )',
1575     'hashref'   => { 'pkgnum' => $cust_pkg->pkgnum,
1576                      'recur'  => { op=>'>', value=>'0' },
1577                    },
1578     'order_by'  => 'ORDER BY cust_bill._date     DESC,
1579                              cust_bill_pkg.sdate DESC
1580                      LIMIT 1
1581                    ',
1582   }) or return 0; #die "use cust_bill_pkg_recur credits with once_perinv condition";
1583   $cust_bill_pkg->recur;
1584 }
1585
1586 =item unit_setup CUST_PKG
1587
1588 Returns the setup fee for one unit of the package.
1589
1590 =cut
1591
1592 sub unit_setup {
1593   my ($self, $cust_pkg) = @_;
1594   $self->option('setup_fee') || 0;
1595 }
1596
1597 =item setup_margin
1598
1599 unit_setup minus setup_cost
1600
1601 =cut
1602
1603 sub setup_margin {
1604   my $self = shift;
1605   $self->unit_setup(@_) - $self->setup_cost;
1606 }
1607
1608 =item recur_margin_permonth
1609
1610 base_recur_permonth minus recur_cost_permonth
1611
1612 =cut
1613
1614 sub recur_margin_permonth {
1615   my $self = shift;
1616   $self->base_recur_permonth(@_) - $self->recur_cost_permonth(@_);
1617 }
1618
1619 =item format OPTION DATA
1620
1621 Returns data formatted according to the function 'format' described
1622 in the plan info.  Returns DATA if no such function exists.
1623
1624 =cut
1625
1626 sub format {
1627   my ($self, $option, $data) = (shift, shift, shift);
1628   if (exists($plans{$self->plan}->{fields}->{$option}{format})) {
1629     &{$plans{$self->plan}->{fields}->{$option}{format}}($data);
1630   }else{
1631     $data;
1632   }
1633 }
1634
1635 =item parse OPTION DATA
1636
1637 Returns data parsed according to the function 'parse' described
1638 in the plan info.  Returns DATA if no such function exists.
1639
1640 =cut
1641
1642 sub parse {
1643   my ($self, $option, $data) = (shift, shift, shift);
1644   if (exists($plans{$self->plan}->{fields}->{$option}{parse})) {
1645     &{$plans{$self->plan}->{fields}->{$option}{parse}}($data);
1646   }else{
1647     $data;
1648   }
1649 }
1650
1651 =back
1652
1653 =cut
1654
1655 =head1 CLASS METHODS
1656
1657 =over 4
1658
1659 =cut
1660
1661 # _upgrade_data
1662 #
1663 # Used by FS::Upgrade to migrate to a new database.
1664
1665 sub _upgrade_data { # class method
1666   my($class, %opts) = @_;
1667
1668   warn "[FS::part_pkg] upgrading $class\n" if $DEBUG;
1669
1670   my @part_pkg = qsearch({
1671     'table'     => 'part_pkg',
1672     'extra_sql' => "WHERE ". join(' OR ',
1673                      'plan IS NULL', "plan = '' ",
1674                    ),
1675   });
1676
1677   foreach my $part_pkg (@part_pkg) {
1678
1679     unless ( $part_pkg->plan ) {
1680       $part_pkg->plan('flat');
1681     }
1682
1683     $part_pkg->replace;
1684
1685   }
1686   # the rest can be done asynchronously
1687 }
1688
1689 sub queueable_upgrade {
1690   # now upgrade to the explicit custom flag
1691
1692   my $search = FS::Cursor->new({
1693     'table'     => 'part_pkg',
1694     'hashref'   => { disabled => 'Y', custom => '' },
1695     'extra_sql' => "AND comment LIKE '(CUSTOM) %'",
1696   });
1697   my $dbh = dbh;
1698
1699   while (my $part_pkg = $search->fetch) {
1700     my $new = new FS::part_pkg { $part_pkg->hash };
1701     $new->custom('Y');
1702     my $comment = $part_pkg->comment;
1703     $comment =~ s/^\(CUSTOM\) //;
1704     $comment = '(none)' unless $comment =~ /\S/;
1705     $new->comment($comment);
1706
1707     my $pkg_svc = { map { $_->svcpart => $_->quantity } $part_pkg->pkg_svc };
1708     my $primary = $part_pkg->svcpart;
1709     my $options = { $part_pkg->options };
1710
1711     my $error = $new->replace( $part_pkg,
1712                                'pkg_svc'     => $pkg_svc,
1713                                'primary_svc' => $primary,
1714                                'options'     => $options,
1715                              );
1716     if ($error) {
1717       warn "pkgpart#".$part_pkg->pkgpart.": $error\n";
1718       $dbh->rollback;
1719     } else {
1720       $dbh->commit;
1721     }
1722   }
1723
1724   # set family_pkgpart on any packages that don't have it
1725   $search = FS::Cursor->new('part_pkg', { 'family_pkgpart' => '' });
1726   while (my $part_pkg = $search->fetch) {
1727     $part_pkg->set('family_pkgpart' => $part_pkg->pkgpart);
1728     my $error = $part_pkg->SUPER::replace;
1729     if ($error) {
1730       warn "pkgpart#".$part_pkg->pkgpart.": $error\n";
1731       $dbh->rollback;
1732     } else {
1733       $dbh->commit;
1734     }
1735   }
1736
1737   my @part_pkg_option = qsearch('part_pkg_option',
1738     { 'optionname'  => 'unused_credit',
1739       'optionvalue' => 1,
1740     });
1741   foreach my $old_opt (@part_pkg_option) {
1742     my $pkgpart = $old_opt->pkgpart;
1743     my $error = $old_opt->delete;
1744     die $error if $error;
1745
1746     foreach (qw(unused_credit_cancel unused_credit_change)) {
1747       my $new_opt = new FS::part_pkg_option {
1748         'pkgpart'     => $pkgpart,
1749         'optionname'  => $_,
1750         'optionvalue' => 1,
1751       };
1752       $error = $new_opt->insert;
1753       die $error if $error;
1754     }
1755   }
1756
1757   # migrate use_disposition_taqua and use_disposition to disposition_in
1758   @part_pkg_option = qsearch('part_pkg_option',
1759     { 'optionname'  => { op => 'LIKE',
1760                          value => 'use_disposition%',
1761                        },
1762       'optionvalue' => 1,
1763     });
1764   my %newopts = map { $_->pkgpart => $_ } 
1765     qsearch('part_pkg_option',  { 'optionname'  => 'disposition_in', } );
1766   foreach my $old_opt (@part_pkg_option) {
1767         my $pkgpart = $old_opt->pkgpart;
1768         my $newval = $old_opt->optionname eq 'use_disposition_taqua' ? '100' 
1769                                                                   : 'ANSWERED';
1770         my $error = $old_opt->delete;
1771         die $error if $error;
1772
1773         if ( exists($newopts{$pkgpart}) ) {
1774             my $opt = $newopts{$pkgpart};
1775             $opt->optionvalue($opt->optionvalue.",$newval");
1776             $error = $opt->replace;
1777             die $error if $error;
1778         } else {
1779             my $new_opt = new FS::part_pkg_option {
1780                 'pkgpart'     => $pkgpart,
1781                 'optionname'  => 'disposition_in',
1782                 'optionvalue' => $newval,
1783               };
1784               $error = $new_opt->insert;
1785               die $error if $error;
1786               $newopts{$pkgpart} = $new_opt;
1787         }
1788   }
1789
1790   # set any package with FCC voice lines to the "VoIP with broadband" category
1791   # for backward compatibility
1792   #
1793   # recover from a bad upgrade bug
1794   my $upgrade = 'part_pkg_fcc_voip_class_FIX';
1795   if (!FS::upgrade_journal->is_done($upgrade)) {
1796     my $bad_upgrade = qsearchs('upgrade_journal', 
1797       { upgrade => 'part_pkg_fcc_voip_class' }
1798     );
1799     if ( $bad_upgrade ) {
1800       my $where = 'WHERE history_date <= '.$bad_upgrade->_date.
1801                   ' AND  history_date >  '.($bad_upgrade->_date - 3600);
1802       my @h_part_pkg_option = map { FS::part_pkg_option->new($_->hashref) }
1803         qsearch({
1804           'select'    => '*',
1805           'table'     => 'h_part_pkg_option',
1806           'hashref'   => {},
1807           'extra_sql' => "$where AND history_action = 'delete'",
1808           'order_by'  => 'ORDER BY history_date ASC',
1809         });
1810       my @h_pkg_svc = map { FS::pkg_svc->new($_->hashref) }
1811         qsearch({
1812           'select'    => '*',
1813           'table'     => 'h_pkg_svc',
1814           'hashref'   => {},
1815           'extra_sql' => "$where AND history_action = 'replace_old'",
1816           'order_by'  => 'ORDER BY history_date ASC',
1817         });
1818       my %opt;
1819       foreach my $deleted (@h_part_pkg_option, @h_pkg_svc) {
1820         my $pkgpart ||= $deleted->pkgpart;
1821         $opt{$pkgpart} ||= {
1822           options => {},
1823           pkg_svc => {},
1824           primary_svc => '',
1825           hidden_svc => {},
1826         };
1827         if ( $deleted->isa('FS::part_pkg_option') ) {
1828           $opt{$pkgpart}{options}{ $deleted->optionname } = $deleted->optionvalue;
1829         } else { # pkg_svc
1830           my $svcpart = $deleted->svcpart;
1831           $opt{$pkgpart}{pkg_svc}{$svcpart} = $deleted->quantity;
1832           $opt{$pkgpart}{hidden_svc}{$svcpart} ||= $deleted->hidden;
1833           $opt{$pkgpart}{primary_svc} = $svcpart if $deleted->primary_svc;
1834         }
1835       }
1836       foreach my $pkgpart (keys %opt) {
1837         my $part_pkg = FS::part_pkg->by_key($pkgpart);
1838         my $error = $part_pkg->replace( $part_pkg->replace_old, $opt{$pkgpart} );
1839         if ( $error ) {
1840           die "error recovering damaged pkgpart $pkgpart:\n$error\n";
1841         }
1842       }
1843     } # $bad_upgrade exists
1844     else { # do the original upgrade, but correctly this time
1845       my @part_pkg = qsearch('part_pkg', {
1846           fcc_ds0s        => { op => '>', value => 0 },
1847           fcc_voip_class  => ''
1848       });
1849       foreach my $part_pkg (@part_pkg) {
1850         $part_pkg->set(fcc_voip_class => 2);
1851         my @pkg_svc = $part_pkg->pkg_svc;
1852         my %quantity = map {$_->svcpart, $_->quantity} @pkg_svc;
1853         my %hidden   = map {$_->svcpart, $_->hidden  } @pkg_svc;
1854         my $error = $part_pkg->replace(
1855           $part_pkg->replace_old,
1856           options     => { $part_pkg->options },
1857           pkg_svc     => \%quantity,
1858           hidden_svc  => \%hidden,
1859           primary_svc => ($part_pkg->svcpart || ''),
1860         );
1861         die $error if $error;
1862       }
1863     }
1864     FS::upgrade_journal->set_done($upgrade);
1865   }
1866
1867 }
1868
1869 =item curuser_pkgs_sql
1870
1871 Returns an SQL fragment for searching for packages the current user can
1872 use, either via part_pkg.agentnum directly, or via agent type (see
1873 L<FS::type_pkgs>).
1874
1875 =cut
1876
1877 sub curuser_pkgs_sql {
1878   my $class = shift;
1879
1880   $class->_pkgs_sql( $FS::CurrentUser::CurrentUser->agentnums );
1881
1882 }
1883
1884 =item agent_pkgs_sql AGENT | AGENTNUM, ...
1885
1886 Returns an SQL fragment for searching for packages the provided agent or agents
1887 can use, either via part_pkg.agentnum directly, or via agent type (see
1888 L<FS::type_pkgs>).
1889
1890 =cut
1891
1892 sub agent_pkgs_sql {
1893   my $class = shift;  #i'm a class method, not a sub (the question is... why??)
1894   my @agentnums = map { ref($_) ? $_->agentnum : $_ } @_;
1895
1896   $class->_pkgs_sql(@agentnums); #is this why
1897
1898 }
1899
1900 sub _pkgs_sql {
1901   my( $class, @agentnums ) = @_;
1902   my $agentnums = join(',', @agentnums);
1903
1904   "
1905     (
1906       ( agentnum IS NOT NULL AND agentnum IN ($agentnums) )
1907       OR ( agentnum IS NULL
1908            AND EXISTS ( SELECT 1
1909                           FROM type_pkgs
1910                             LEFT JOIN agent_type USING ( typenum )
1911                             LEFT JOIN agent AS typeagent USING ( typenum )
1912                           WHERE type_pkgs.pkgpart = part_pkg.pkgpart
1913                             AND typeagent.agentnum IN ($agentnums)
1914                       )
1915          )
1916     )
1917   ";
1918
1919 }
1920
1921 =back
1922
1923 =head1 SUBROUTINES
1924
1925 =over 4
1926
1927 =item plan_info
1928
1929 =cut
1930
1931 #false laziness w/part_export & cdr
1932 my %info;
1933 foreach my $INC ( @INC ) {
1934   warn "globbing $INC/FS/part_pkg/*.pm\n" if $DEBUG;
1935   foreach my $file ( glob("$INC/FS/part_pkg/*.pm") ) {
1936     warn "attempting to load plan info from $file\n" if $DEBUG;
1937     $file =~ /\/(\w+)\.pm$/ or do {
1938       warn "unrecognized file in $INC/FS/part_pkg/: $file\n";
1939       next;
1940     };
1941     my $mod = $1;
1942     my $info = eval "use FS::part_pkg::$mod; ".
1943                     "\\%FS::part_pkg::$mod\::info;";
1944     if ( $@ ) {
1945       die "error using FS::part_pkg::$mod (skipping): $@\n" if $@;
1946       next;
1947     }
1948     unless ( keys %$info ) {
1949       warn "no %info hash found in FS::part_pkg::$mod, skipping\n";
1950       next;
1951     }
1952     warn "got plan info from FS::part_pkg::$mod: $info\n" if $DEBUG;
1953     #if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
1954     #  warn "skipping disabled plan FS::part_pkg::$mod" if $DEBUG;
1955     #  next;
1956     #}
1957     $info{$mod} = $info;
1958     $info->{'weight'} ||= 0; # quiet warnings
1959   }
1960 }
1961
1962 # copy one level deep to allow replacement of fields and fieldorder
1963 tie %plans, 'Tie::IxHash',
1964   map  { my %infohash = %{ $info{$_} }; 
1965           $_ => \%infohash }
1966   sort { $info{$a}->{'weight'} <=> $info{$b}->{'weight'} }
1967   keys %info;
1968
1969 # inheritance of plan options
1970 foreach my $name (keys(%info)) {
1971   if (exists($info{$name}->{'disabled'}) and $info{$name}->{'disabled'}) {
1972     warn "skipping disabled plan FS::part_pkg::$name" if $DEBUG;
1973     delete $plans{$name};
1974     next;
1975   }
1976   my $parents = $info{$name}->{'inherit_fields'} || [];
1977   my (%fields, %field_exists, @fieldorder);
1978   foreach my $parent ($name, @$parents) {
1979     if ( !exists($info{$parent}) ) {
1980       warn "$name tried to inherit from nonexistent '$parent'\n";
1981       next;
1982     }
1983     %fields = ( # avoid replacing existing fields
1984       %{ $info{$parent}->{'fields'} || {} },
1985       %fields
1986     );
1987     foreach (@{ $info{$parent}->{'fieldorder'} || [] }) {
1988       # avoid duplicates
1989       next if $field_exists{$_};
1990       $field_exists{$_} = 1;
1991       # allow inheritors to remove inherited fields from the fieldorder
1992       push @fieldorder, $_ if !exists($fields{$_}) or
1993                               !exists($fields{$_}->{'disabled'});
1994     }
1995   }
1996   $plans{$name}->{'fields'} = \%fields;
1997   $plans{$name}->{'fieldorder'} = \@fieldorder;
1998 }
1999
2000 sub plan_info {
2001   \%plans;
2002 }
2003
2004
2005 =back
2006
2007 =head1 NEW PLAN CLASSES
2008
2009 A module should be added in FS/FS/part_pkg/  Eventually, an example may be
2010 found in eg/plan_template.pm.  Until then, it is suggested that you use the
2011 other modules in FS/FS/part_pkg/ as a guide.
2012
2013 =head1 BUGS
2014
2015 The delete method is unimplemented.
2016
2017 setup and recur semantics are not yet defined (and are implemented in
2018 FS::cust_bill.  hmm.).  now they're deprecated and need to go.
2019
2020 plandata should go
2021
2022 part_pkg_taxrate is Pg specific
2023
2024 replace should be smarter about managing the related tables (options, pkg_svc)
2025
2026 =head1 SEE ALSO
2027
2028 L<FS::Record>, L<FS::cust_pkg>, L<FS::type_pkgs>, L<FS::pkg_svc>, L<Safe>.
2029 schema.html from the base documentation.
2030
2031 =cut
2032
2033 1;
2034