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