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