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