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