2 use base qw( FS::m2m_Common FS::o2m_Common FS::option_Common );
5 use vars qw( %plans $DEBUG $setup_hack $skip_pkg_svc_hack );
6 use Carp qw(carp cluck confess);
7 use Scalar::Util qw( blessed );
8 use Time::Local qw( timelocal timelocal_nocheck );
11 use FS::Record qw( qsearch qsearchs dbh dbdef );
17 use FS::part_pkg_option;
20 use FS::part_pkg_msgcat;
21 use FS::part_pkg_taxrate;
22 use FS::part_pkg_taxoverride;
23 use FS::part_pkg_taxproduct;
24 use FS::part_pkg_link;
25 use FS::part_pkg_discount;
26 use FS::part_pkg_usage;
27 use FS::part_pkg_vendor;
28 use FS::part_pkg_currency;
32 $skip_pkg_svc_hack = 0;
36 FS::part_pkg - Object methods for part_pkg objects
42 $record = new FS::part_pkg \%hash
43 $record = new FS::part_pkg { 'column' => 'value' };
45 $custom_record = $template_record->clone;
47 $error = $record->insert;
49 $error = $new_record->replace($old_record);
51 $error = $record->delete;
53 $error = $record->check;
55 @pkg_svc = $record->pkg_svc;
57 $svcnum = $record->svcpart;
58 $svcnum = $record->svcpart( 'svc_acct' );
62 An FS::part_pkg object represents a package definition. FS::part_pkg
63 inherits from FS::Record. The following fields are currently supported:
67 =item pkgpart - primary key (assigned automatically for new package definitions)
69 =item pkg - Text name of this package definition (customer-viewable)
71 =item comment - Text name of this package definition (non-customer-viewable)
73 =item classnum - Optional package class (see L<FS::pkg_class>)
75 =item promo_code - Promotional code
77 =item setup - Setup fee expression (deprecated)
79 =item freq - Frequency of recurring fee
81 =item recur - Recurring fee expression (deprecated)
83 =item setuptax - Setup fee tax exempt flag, empty or `Y'
85 =item recurtax - Recurring fee tax exempt flag, empty or `Y'
87 =item taxclass - Tax class
89 =item plan - Price plan
91 =item plandata - Price plan data (deprecated - see L<FS::part_pkg_option> instead)
93 =item disabled - Disabled flag, empty or `Y'
95 =item custom - Custom flag, empty or `Y'
97 =item setup_cost - for cost tracking
99 =item recur_cost - for cost tracking
101 =item pay_weight - Weight (relative to credit_weight and other package definitions) that controls payment application to specific line items.
103 =item credit_weight - Weight (relative to other package definitions) that controls credit application to specific line items.
105 =item agentnum - Optional agentnum (see L<FS::agent>)
107 =item fcc_ds0s - Optional DS0 equivalency number for FCC form 477
109 =item fcc_voip_class - Which column of FCC form 477 part II.B this package
112 =item successor - Foreign key for the part_pkg that replaced this record.
113 If this record is not obsolete, will be null.
115 =item family_pkgpart - Foreign key for the part_pkg that was the earliest
116 ancestor of this record. If this record is not a successor to another
117 part_pkg, will be equal to pkgpart.
119 =item delay_start - Number of days to delay package start, by default
129 Creates a new package definition. To add the package definition to
130 the database, see L<"insert">.
134 sub table { 'part_pkg'; }
138 An alternate constructor. Creates a new package definition by duplicating
139 an existing definition. A new pkgpart is assigned and the custom flag is
140 set to Y. To add the package definition to the database, see L<"insert">.
146 my $class = ref($self);
147 my %hash = $self->hash;
148 $hash{'pkgpart'} = '';
149 $hash{'custom'} = 'Y';
150 #new FS::part_pkg ( \%hash ); # ?
151 new $class ( \%hash ); # ?
154 =item insert [ , OPTION => VALUE ... ]
156 Adds this package definition to the database. If there is an error,
157 returns the error, otherwise returns false.
159 Currently available options are: I<pkg_svc>, I<primary_svc>, I<cust_pkg>,
160 I<custnum_ref> and I<options>.
162 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
163 values, appropriate FS::pkg_svc records will be inserted. I<hidden_svc> can
164 be set to a hashref of svcparts and flag values ('Y' or '') to set the
165 'hidden' field in these records.
167 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
168 FS::pkg_svc record will be updated.
170 If I<cust_pkg> is set to a pkgnum of a FS::cust_pkg record (or the FS::cust_pkg
171 record itself), the object will be updated to point to this package definition.
173 In conjunction with I<cust_pkg>, if I<custnum_ref> is set to a scalar reference,
174 the scalar will be updated with the custnum value from the cust_pkg record.
176 If I<tax_overrides> is set to a hashref with usage classes as keys and comma
177 separated tax class numbers as values, appropriate FS::part_pkg_taxoverride
178 records will be inserted.
180 If I<options> is set to a hashref of options, appropriate FS::part_pkg_option
181 records will be inserted.
183 If I<part_pkg_currency> is set to a hashref of options (with the keys as
184 option_CURRENCY), appropriate FS::part_pkg::currency records will be inserted.
191 warn "FS::part_pkg::insert called on $self with options ".
192 join(', ', map "$_=>$options{$_}", keys %options)
195 local $SIG{HUP} = 'IGNORE';
196 local $SIG{INT} = 'IGNORE';
197 local $SIG{QUIT} = 'IGNORE';
198 local $SIG{TERM} = 'IGNORE';
199 local $SIG{TSTP} = 'IGNORE';
200 local $SIG{PIPE} = 'IGNORE';
202 my $oldAutoCommit = $FS::UID::AutoCommit;
203 local $FS::UID::AutoCommit = 0;
206 warn " inserting part_pkg record" if $DEBUG;
207 my $error = $self->SUPER::insert( $options{options} );
209 $dbh->rollback if $oldAutoCommit;
214 if ( $self->get('family_pkgpart') eq '' ) {
215 $self->set('family_pkgpart' => $self->pkgpart);
216 $error = $self->SUPER::replace;
218 $dbh->rollback if $oldAutoCommit;
223 my $conf = new FS::Conf;
224 if ( $conf->exists('agent_defaultpkg') ) {
225 warn " agent_defaultpkg set; allowing all agents to purchase package"
227 foreach my $agent_type ( qsearch('agent_type', {} ) ) {
228 my $type_pkgs = new FS::type_pkgs({
229 'typenum' => $agent_type->typenum,
230 'pkgpart' => $self->pkgpart,
232 my $error = $type_pkgs->insert;
234 $dbh->rollback if $oldAutoCommit;
240 warn " inserting part_pkg_taxoverride records" if $DEBUG;
241 my %overrides = %{ $options{'tax_overrides'} || {} };
242 foreach my $usage_class ( keys %overrides ) {
244 ( exists($overrides{$usage_class}) && defined($overrides{$usage_class}) )
245 ? $overrides{$usage_class}
247 my @overrides = (grep "$_", split(',', $override) );
248 my $error = $self->process_m2m (
249 'link_table' => 'part_pkg_taxoverride',
250 'target_table' => 'tax_class',
251 'hashref' => { 'usage_class' => $usage_class },
252 'params' => \@overrides,
255 $dbh->rollback if $oldAutoCommit;
260 warn " inserting part_pkg_currency records" if $DEBUG;
261 my %part_pkg_currency = %{ $options{'part_pkg_currency'} || {} };
262 foreach my $key ( keys %part_pkg_currency ) {
263 $key =~ /^(.+)_([A-Z]{3})$/ or next;
264 my $part_pkg_currency = new FS::part_pkg_currency {
265 'pkgpart' => $self->pkgpart,
268 'optionvalue' => $part_pkg_currency{$key},
270 my $error = $part_pkg_currency->insert;
272 $dbh->rollback if $oldAutoCommit;
277 unless ( $skip_pkg_svc_hack ) {
279 warn " inserting pkg_svc records" if $DEBUG;
280 my $pkg_svc = $options{'pkg_svc'} || {};
281 my $hidden_svc = $options{'hidden_svc'} || {};
282 foreach my $part_svc ( qsearch('part_svc', {} ) ) {
283 my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
285 ( $options{'primary_svc'} && $options{'primary_svc'}==$part_svc->svcpart )
289 my $pkg_svc = new FS::pkg_svc( {
290 'pkgpart' => $self->pkgpart,
291 'svcpart' => $part_svc->svcpart,
292 'quantity' => $quantity,
293 'primary_svc' => $primary_svc,
294 'hidden' => $hidden_svc->{$part_svc->svcpart},
296 my $error = $pkg_svc->insert;
298 $dbh->rollback if $oldAutoCommit;
305 if ( $options{'cust_pkg'} ) {
306 warn " updating cust_pkg record " if $DEBUG;
308 ref($options{'cust_pkg'})
309 ? $options{'cust_pkg'}
310 : qsearchs('cust_pkg', { pkgnum => $options{'cust_pkg'} } );
311 ${ $options{'custnum_ref'} } = $old_cust_pkg->custnum
312 if $options{'custnum_ref'};
313 my %hash = $old_cust_pkg->hash;
314 $hash{'pkgpart'} = $self->pkgpart,
315 my $new_cust_pkg = new FS::cust_pkg \%hash;
316 local($FS::cust_pkg::disable_agentcheck) = 1;
317 my $error = $new_cust_pkg->replace($old_cust_pkg);
319 $dbh->rollback if $oldAutoCommit;
320 return "Error modifying cust_pkg record: $error";
324 if ( $options{'part_pkg_vendor'} ) {
325 while ( my ($exportnum, $vendor_pkg_id) =
326 each %{ $options{part_pkg_vendor} }
329 my $ppv = new FS::part_pkg_vendor( {
330 'pkgpart' => $self->pkgpart,
331 'exportnum' => $exportnum,
332 'vendor_pkg_id' => $vendor_pkg_id,
334 my $error = $ppv->insert;
336 $dbh->rollback if $oldAutoCommit;
337 return "Error inserting part_pkg_vendor record: $error";
342 warn " committing transaction" if $DEBUG and $oldAutoCommit;
343 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
350 Currently unimplemented.
355 return "Can't (yet?) delete package definitions.";
356 # check & make sure the pkgpart isn't in cust_pkg or type_pkgs?
359 =item replace OLD_RECORD [ , OPTION => VALUE ... ]
361 Replaces OLD_RECORD with this one in the database. If there is an error,
362 returns the error, otherwise returns false.
364 Currently available options are: I<pkg_svc>, I<hidden_svc>, I<primary_svc>
367 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
368 values, the appropriate FS::pkg_svc records will be replaced. I<hidden_svc>
369 can be set to a hashref of svcparts and flag values ('Y' or '') to set the
370 'hidden' field in these records.
372 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
373 FS::pkg_svc record will be updated.
375 If I<options> is set to a hashref, the appropriate FS::part_pkg_option records
378 If I<part_pkg_currency> is set to a hashref of options (with the keys as
379 option_CURRENCY), appropriate FS::part_pkg::currency records will be replaced.
386 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
391 ( ref($_[0]) eq 'HASH' )
395 $options->{options} = { $old->options } unless defined($options->{options});
397 warn "FS::part_pkg::replace called on $new to replace $old with options".
398 join(', ', map "$_ => ". $options->{$_}, keys %$options)
401 local $SIG{HUP} = 'IGNORE';
402 local $SIG{INT} = 'IGNORE';
403 local $SIG{QUIT} = 'IGNORE';
404 local $SIG{TERM} = 'IGNORE';
405 local $SIG{TSTP} = 'IGNORE';
406 local $SIG{PIPE} = 'IGNORE';
408 my $oldAutoCommit = $FS::UID::AutoCommit;
409 local $FS::UID::AutoCommit = 0;
412 my $conf = new FS::Conf;
413 if ( $conf->exists('part_pkg-lineage') ) {
414 if ( grep { $options->{options}->{$_} ne $old->option($_, 1) }
415 qw(setup_fee recur_fee) #others? config?
418 warn " superseding package" if $DEBUG;
420 my $error = $new->supersede($old, %$options);
422 $dbh->rollback if $oldAutoCommit;
426 warn " committing transaction" if $DEBUG and $oldAutoCommit;
427 $dbh->commit if $oldAutoCommit;
434 #plandata shit stays in replace for upgrades until after 2.0 (or edit
436 warn " saving legacy plandata" if $DEBUG;
437 my $plandata = $new->get('plandata');
438 $new->set('plandata', '');
440 warn " deleting old part_pkg_option records" if $DEBUG;
441 foreach my $part_pkg_option ( $old->part_pkg_option ) {
442 my $error = $part_pkg_option->delete;
444 $dbh->rollback if $oldAutoCommit;
449 warn " replacing part_pkg record" if $DEBUG;
450 my $error = $new->SUPER::replace($old, $options->{options} );
452 $dbh->rollback if $oldAutoCommit;
456 warn " inserting part_pkg_option records for plandata: $plandata|" if $DEBUG;
457 foreach my $part_pkg_option (
458 map { /^(\w+)=(.*)$/ or do { $dbh->rollback if $oldAutoCommit;
459 return "illegal plandata: $plandata";
461 new FS::part_pkg_option {
462 'pkgpart' => $new->pkgpart,
467 split("\n", $plandata)
469 my $error = $part_pkg_option->insert;
471 $dbh->rollback if $oldAutoCommit;
476 #trivial nit: not the most efficient to delete and reinsert
477 warn " deleting old part_pkg_currency records" if $DEBUG;
478 foreach my $part_pkg_currency ( $old->part_pkg_currency ) {
479 my $error = $part_pkg_currency->delete;
481 $dbh->rollback if $oldAutoCommit;
482 return "error deleting part_pkg_currency record: $error";
486 warn " inserting new part_pkg_currency records" if $DEBUG;
487 my %part_pkg_currency = %{ $options->{'part_pkg_currency'} || {} };
488 foreach my $key ( keys %part_pkg_currency ) {
489 $key =~ /^(.+)_([A-Z]{3})$/ or next;
490 my $part_pkg_currency = new FS::part_pkg_currency {
491 'pkgpart' => $new->pkgpart,
494 'optionvalue' => $part_pkg_currency{$key},
496 my $error = $part_pkg_currency->insert;
498 $dbh->rollback if $oldAutoCommit;
499 return "error inserting part_pkg_currency record: $error";
504 warn " replacing pkg_svc records" if $DEBUG;
505 my $pkg_svc = $options->{'pkg_svc'};
506 my $hidden_svc = $options->{'hidden_svc'} || {};
507 if ( $pkg_svc ) { # if it wasn't passed, don't change existing pkg_svcs
508 foreach my $part_svc ( qsearch('part_svc', {} ) ) {
509 my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
510 my $hidden = $hidden_svc->{$part_svc->svcpart} || '';
512 ( defined($options->{'primary_svc'}) && $options->{'primary_svc'}
513 && $options->{'primary_svc'} == $part_svc->svcpart
518 my $old_pkg_svc = qsearchs('pkg_svc', {
519 'pkgpart' => $old->pkgpart,
520 'svcpart' => $part_svc->svcpart,
523 my $old_quantity = 0;
524 my $old_primary_svc = '';
526 if ( $old_pkg_svc ) {
527 $old_quantity = $old_pkg_svc->quantity;
528 $old_primary_svc = $old_pkg_svc->primary_svc
529 if $old_pkg_svc->dbdef_table->column('primary_svc'); # is this needed?
530 $old_hidden = $old_pkg_svc->hidden;
533 next unless $old_quantity != $quantity ||
534 $old_primary_svc ne $primary_svc ||
535 $old_hidden ne $hidden;
537 my $new_pkg_svc = new FS::pkg_svc( {
538 'pkgsvcnum' => ( $old_pkg_svc ? $old_pkg_svc->pkgsvcnum : '' ),
539 'pkgpart' => $new->pkgpart,
540 'svcpart' => $part_svc->svcpart,
541 'quantity' => $quantity,
542 'primary_svc' => $primary_svc,
545 my $error = $old_pkg_svc
546 ? $new_pkg_svc->replace($old_pkg_svc)
547 : $new_pkg_svc->insert;
549 $dbh->rollback if $oldAutoCommit;
553 } #if $options->{pkg_svc}
555 my @part_pkg_vendor = $old->part_pkg_vendor;
556 my @current_exportnum = ();
557 if ( $options->{'part_pkg_vendor'} ) {
558 my($exportnum,$vendor_pkg_id);
559 while ( ($exportnum,$vendor_pkg_id)
560 = each %{$options->{'part_pkg_vendor'}} ) {
562 foreach my $part_pkg_vendor ( @part_pkg_vendor ) {
563 if($exportnum == $part_pkg_vendor->exportnum
564 && $vendor_pkg_id ne $part_pkg_vendor->vendor_pkg_id) {
565 $part_pkg_vendor->vendor_pkg_id($vendor_pkg_id);
566 my $error = $part_pkg_vendor->replace;
568 $dbh->rollback if $oldAutoCommit;
569 return "Error replacing part_pkg_vendor record: $error";
574 elsif($exportnum == $part_pkg_vendor->exportnum
575 && $vendor_pkg_id eq $part_pkg_vendor->vendor_pkg_id) {
580 unless ( $noinsert ) {
581 my $ppv = new FS::part_pkg_vendor( {
582 'pkgpart' => $new->pkgpart,
583 'exportnum' => $exportnum,
584 'vendor_pkg_id' => $vendor_pkg_id,
586 my $error = $ppv->insert;
588 $dbh->rollback if $oldAutoCommit;
589 return "Error inserting part_pkg_vendor record: $error";
592 push @current_exportnum, $exportnum;
595 foreach my $part_pkg_vendor ( @part_pkg_vendor ) {
596 unless ( grep($_ eq $part_pkg_vendor->exportnum, @current_exportnum) ) {
597 my $error = $part_pkg_vendor->delete;
599 $dbh->rollback if $oldAutoCommit;
600 return "Error deleting part_pkg_vendor record: $error";
605 # propagate changes to certain core fields
606 if ( $conf->exists('part_pkg-lineage') ) {
607 warn " propagating changes to family" if $DEBUG;
608 my $error = $new->propagate($old);
610 $dbh->rollback if $oldAutoCommit;
615 warn " committing transaction" if $DEBUG and $oldAutoCommit;
616 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
622 Checks all fields to make sure this is a valid package definition. If
623 there is an error, returns the error, otherwise returns false. Called by the
624 insert and replace methods.
630 warn "FS::part_pkg::check called on $self" if $DEBUG;
632 for (qw(setup recur plandata)) {
633 #$self->set($_=>0) if $self->get($_) =~ /^\s*$/; }
634 return "Use of $_ field is deprecated; set a plan and options: ".
636 if length($self->get($_));
640 if ( $self->dbdef_table->column('freq')->type =~ /(int)/i ) {
641 my $error = $self->ut_number('freq');
642 return $error if $error;
644 $self->freq =~ /^(\d+[hdw]?)$/
645 or return "Illegal or empty freq: ". $self->freq;
649 my @null_agentnum_right = ( 'Edit global package definitions' );
650 push @null_agentnum_right, 'One-time charge'
651 if $self->freq =~ /^0/;
652 push @null_agentnum_right, 'Customize customer package'
653 if $self->disabled eq 'Y'; #good enough
655 my $error = $self->ut_numbern('pkgpart')
656 || $self->ut_text('pkg')
657 || $self->ut_text('comment')
658 || $self->ut_textn('promo_code')
659 || $self->ut_alphan('plan')
660 || $self->ut_enum('setuptax', [ '', 'Y' ] )
661 || $self->ut_enum('recurtax', [ '', 'Y' ] )
662 || $self->ut_textn('taxclass')
663 || $self->ut_enum('disabled', [ '', 'Y' ] )
664 || $self->ut_enum('custom', [ '', 'Y' ] )
665 || $self->ut_enum('no_auto', [ '', 'Y' ])
666 || $self->ut_enum('recur_show_zero', [ '', 'Y' ])
667 || $self->ut_enum('setup_show_zero', [ '', 'Y' ])
668 #|| $self->ut_moneyn('setup_cost')
669 #|| $self->ut_moneyn('recur_cost')
670 || $self->ut_floatn('setup_cost')
671 || $self->ut_floatn('recur_cost')
672 || $self->ut_floatn('pay_weight')
673 || $self->ut_floatn('credit_weight')
674 || $self->ut_numbern('taxproductnum')
675 || $self->ut_foreign_keyn('classnum', 'pkg_class', 'classnum')
676 || $self->ut_foreign_keyn('addon_classnum', 'pkg_class', 'classnum')
677 || $self->ut_foreign_keyn('taxproductnum',
678 'part_pkg_taxproduct',
682 ? $self->ut_foreign_keyn('agentnum', 'agent', 'agentnum' )
683 : $self->ut_agentnum_acl('agentnum', \@null_agentnum_right)
685 || $self->ut_numbern('fcc_ds0s')
686 || $self->ut_numbern('fcc_voip_class')
687 || $self->ut_numbern('delay_start')
688 || $self->ut_foreign_keyn('successor', 'part_pkg', 'pkgpart')
689 || $self->ut_foreign_keyn('family_pkgpart', 'part_pkg', 'pkgpart')
690 || $self->SUPER::check
692 return $error if $error;
694 return 'Unknown plan '. $self->plan
695 unless exists($plans{$self->plan});
697 my $conf = new FS::Conf;
698 return 'Taxclass is required'
699 if ! $self->taxclass && $conf->exists('require_taxclasses');
704 =item supersede OLD [, OPTION => VALUE ... ]
706 Inserts this package as a successor to the package OLD. All options are as
707 for C<insert>. After inserting, disables OLD and sets the new package as its
713 my ($new, $old, %options) = @_;
716 $new->set('pkgpart' => '');
717 $new->set('family_pkgpart' => $old->family_pkgpart);
718 warn " inserting successor package\n" if $DEBUG;
719 $error = $new->insert(%options);
720 return $error if $error;
722 warn " disabling superseded package\n" if $DEBUG;
723 $old->set('successor' => $new->pkgpart);
724 $old->set('disabled' => 'Y');
725 $error = $old->SUPER::replace; # don't change its options/pkg_svc records
726 return $error if $error;
728 warn " propagating changes to family" if $DEBUG;
729 $new->propagate($old);
734 If any of certain fields have changed from OLD to this package, then,
735 for all packages in the same lineage as this one, sets those fields
736 to their values in this package.
740 my @propagate_fields = (
741 qw( pkg classnum setup_cost recur_cost taxclass
742 setuptax recurtax pay_weight credit_weight
750 map { $_ => $new->get($_) }
751 grep { $new->get($_) ne $old->get($_) }
755 my @part_pkg = qsearch('part_pkg', {
756 'family_pkgpart' => $new->family_pkgpart
759 foreach my $part_pkg ( @part_pkg ) {
760 my $pkgpart = $part_pkg->pkgpart;
761 next if $pkgpart == $new->pkgpart; # don't modify $new
762 warn " propagating to pkgpart $pkgpart\n" if $DEBUG;
763 foreach ( keys %fields ) {
764 $part_pkg->set($_, $fields{$_});
766 # SUPER::replace to avoid changing non-core fields
767 my $error = $part_pkg->SUPER::replace;
768 push @error, "pkgpart $pkgpart: $error"
774 =item pkg_locale LOCALE
776 Returns a customer-viewable string representing this package for the given
777 locale, from the part_pkg_msgcat table. If the given locale is empty or no
778 localized string is found, returns the base pkg field.
783 my( $self, $locale ) = @_;
784 return $self->pkg unless $locale;
785 my $part_pkg_msgcat = $self->part_pkg_msgcat($locale) or return $self->pkg;
786 $part_pkg_msgcat->pkg;
789 =item part_pkg_msgcat LOCALE
791 Like pkg_locale, but returns the FS::part_pkg_msgcat object itself.
795 sub part_pkg_msgcat {
796 my( $self, $locale ) = @_;
797 qsearchs( 'part_pkg_msgcat', {
798 pkgpart => $self->pkgpart,
803 =item pkg_comment [ OPTION => VALUE... ]
805 Returns an (internal) string representing this package. Currently,
806 "pkgpart: pkg - comment", is returned. "pkg - comment" may be returned in the
807 future, omitting pkgpart. The comment will have '(CUSTOM) ' prepended if
810 If the option nopkgpart is true then the "pkgpart: ' is omitted.
818 #$self->pkg. ' - '. $self->comment;
819 #$self->pkg. ' ('. $self->comment. ')';
820 my $pre = $opt{nopkgpart} ? '' : $self->pkgpart. ': ';
821 $pre. $self->pkg. ' - '. $self->custom_comment;
824 sub price_info { # safety, in case a part_pkg hasn't defined price_info
830 ( $self->custom ? '(CUSTOM) ' : '' ). $self->comment . ' ' . $self->price_info;
835 Returns the package class, as an FS::pkg_class object, or the empty string
836 if there is no package class.
842 if ( $self->classnum ) {
843 qsearchs('pkg_class', { 'classnum' => $self->classnum } );
849 =item addon_pkg_class
851 Returns the add-on package class, as an FS::pkg_class object, or the empty
852 string if there is no add-on package class.
856 sub addon_pkg_class {
858 if ( $self->addon_classnum ) {
859 qsearchs('pkg_class', { 'classnum' => $self->addon_classnum } );
867 Returns the package category name, or the empty string if there is no package
874 my $pkg_class = $self->pkg_class;
876 ? $pkg_class->categoryname
882 Returns the package class name, or the empty string if there is no package
889 my $pkg_class = $self->pkg_class;
891 ? $pkg_class->classname
895 =item addon_classname
897 Returns the add-on package class name, or the empty string if there is no
898 add-on package class.
902 sub addon_classname {
904 my $pkg_class = $self->addon_pkg_class;
906 ? $pkg_class->classname
912 Returns the associated agent for this event, if any, as an FS::agent object.
918 qsearchs('agent', { 'agentnum' => $self->agentnum } );
921 =item pkg_svc [ HASHREF | OPTION => VALUE ]
923 Returns all FS::pkg_svc objects (see L<FS::pkg_svc>) for this package
924 definition (with non-zero quantity).
926 One option is available, I<disable_linked>. If set true it will return the
927 services for this package definition alone, omitting services from any add-on
934 Returns all FS::type_pkgs objects (see L<FS::type_pkgs>) for this package
941 qsearch('type_pkgs', { 'pkgpart' => $self->pkgpart } );
947 # #sort { $b->primary cmp $a->primary }
948 # grep { $_->quantity }
949 # qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
951 my $opt = ref($_[0]) ? $_[0] : { @_ };
952 my %pkg_svc = map { $_->svcpart => $_ }
953 grep { $_->quantity }
954 qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
956 unless ( $opt->{disable_linked} ) {
957 foreach my $dst_pkg ( map $_->dst_pkg, $self->svc_part_pkg_link ) {
958 my @pkg_svc = grep { $_->quantity }
959 qsearch( 'pkg_svc', { pkgpart=>$dst_pkg->pkgpart } );
960 foreach my $pkg_svc ( @pkg_svc ) {
961 if ( $pkg_svc{$pkg_svc->svcpart} ) {
962 my $quantity = $pkg_svc{$pkg_svc->svcpart}->quantity;
963 $pkg_svc{$pkg_svc->svcpart}->quantity($quantity + $pkg_svc->quantity);
965 $pkg_svc{$pkg_svc->svcpart} = $pkg_svc;
975 =item svcpart [ SVCDB ]
977 Returns the svcpart of the primary service definition (see L<FS::part_svc>)
978 associated with this package definition (see L<FS::pkg_svc>). Returns
979 false if there not a primary service definition or exactly one service
980 definition with quantity 1, or if SVCDB is specified and does not match the
981 svcdb of the service definition. SVCDB can be specified as a scalar table
982 name, such as 'svc_acct', or as an arrayref of possible table names.
987 my $pkg_svc = shift->_primary_pkg_svc(@_);
988 $pkg_svc ? $pkg_svc->svcpart : '';
991 =item part_svc [ SVCDB ]
993 Like the B<svcpart> method, but returns the FS::part_svc object (see
999 my $pkg_svc = shift->_primary_pkg_svc(@_);
1000 $pkg_svc ? $pkg_svc->part_svc : '';
1003 sub _primary_pkg_svc {
1006 my $svcdb = scalar(@_) ? shift : [];
1007 $svcdb = ref($svcdb) ? $svcdb : [ $svcdb ];
1008 my %svcdb = map { $_=>1 } @$svcdb;
1011 grep { !scalar(@$svcdb) || $svcdb{ $_->part_svc->svcdb } }
1014 my @pkg_svc = grep { $_->primary_svc =~ /^Y/i } @svcdb_pkg_svc;
1015 @pkg_svc = grep {$_->quantity == 1 } @svcdb_pkg_svc
1017 return '' if scalar(@pkg_svc) != 1;
1021 =item svcpart_unique_svcdb SVCDB
1023 Returns the svcpart of a service definition (see L<FS::part_svc>) matching
1024 SVCDB associated with this package definition (see L<FS::pkg_svc>). Returns
1025 false if there not a primary service definition for SVCDB or there are multiple
1026 service definitions for SVCDB.
1030 sub svcpart_unique_svcdb {
1031 my( $self, $svcdb ) = @_;
1032 my @svcdb_pkg_svc = grep { ( $svcdb eq $_->part_svc->svcdb ) } $self->pkg_svc;
1033 return '' if scalar(@svcdb_pkg_svc) != 1;
1034 $svcdb_pkg_svc[0]->svcpart;
1039 Returns a list of the acceptable payment types for this package. Eventually
1040 this should come out of a database table and be editable, but currently has the
1041 following logic instead:
1043 If the package is free, the single item B<BILL> is
1044 returned, otherwise, the single item B<CARD> is returned.
1046 (CHEK? LEC? Probably shouldn't accept those by default, prone to abuse)
1052 if ( $self->is_free ) {
1061 Returns true if this package is free.
1067 if ( $self->can('is_free_options') ) {
1068 not grep { $_ !~ /^\s*0*(\.0*)?\s*$/ }
1069 map { $self->option($_) }
1070 $self->is_free_options;
1072 warn "FS::part_pkg::is_free: FS::part_pkg::". $self->plan. " subclass ".
1073 "provides neither is_free_options nor is_free method; returning false";
1078 # whether the plan allows discounts to be applied to this package
1079 sub can_discount { 0; }
1081 # whether the plan allows changing the start date
1082 sub can_start_date { 1; }
1084 # the default start date; takes an FS::cust_main as an argument
1085 sub default_start_date {
1087 my $cust_main = shift;
1088 my $conf = FS::Conf->new;
1090 if ( $self->delay_start ) {
1091 my $delay = $self->delay_start;
1093 my ($mday,$mon,$year) = (localtime(time))[3,4,5];
1094 my $start_date = timelocal(0,0,0,$mday,$mon,$year) + 86400 * $delay;
1097 } elsif ( $conf->exists('order_pkg-no_start_date') ) {
1101 } elsif ( $cust_main ) {
1103 return $cust_main->next_bill_date;
1112 sub can_currency_exchange { 0; }
1115 # moved to FS::Misc to make this accessible to other packages
1117 FS::Misc::pkg_freqs();
1122 Returns an english representation of the I<freq> field, such as "monthly",
1123 "weekly", "semi-annually", etc.
1129 my $freq = $self->freq;
1131 #my $freqs_href = $self->freqs_href;
1132 my $freqs_href = freqs_href();
1134 if ( exists($freqs_href->{$freq}) ) {
1135 $freqs_href->{$freq};
1137 my $interval = 'month';
1138 if ( $freq =~ /^(\d+)([hdw])$/ ) {
1139 my %interval = ( 'h' => 'hour', 'd'=>'day', 'w'=>'week' );
1140 $interval = $interval{$2};
1145 "every $freq ${interval}s";
1150 =item add_freq TIMESTAMP [ FREQ ]
1152 Adds a billing period of some frequency to the provided timestamp and
1153 returns the resulting timestamp, or -1 if the frequency could not be
1154 parsed (shouldn't happen). By default, the frequency of this package
1155 will be used; to override this, pass a different frequency as a second
1161 my( $self, $date, $freq ) = @_;
1162 $freq = $self->freq unless $freq;
1164 #change this bit to use Date::Manip? CAREFUL with timezones (see
1165 # mailing list archive)
1166 my ($sec,$min,$hour,$mday,$mon,$year) = (localtime($date) )[0,1,2,3,4,5];
1168 if ( $freq =~ /^\d+$/ ) {
1170 until ( $mon < 12 ) { $mon -= 12; $year++; }
1172 $mday = 28 if $mday > 28 && FS::Conf->new->exists('anniversary-rollback');
1174 } elsif ( $freq =~ /^(\d+)w$/ ) {
1176 $mday += $weeks * 7;
1177 } elsif ( $freq =~ /^(\d+)d$/ ) {
1180 } elsif ( $freq =~ /^(\d+)h$/ ) {
1187 timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year);
1192 For backwards compatibility, returns the plandata field as well as all options
1193 from FS::part_pkg_option.
1199 carp "plandata is deprecated";
1201 $self->SUPER::plandata(@_);
1203 my $plandata = $self->get('plandata');
1204 my %options = $self->options;
1205 $plandata .= join('', map { "$_=$options{$_}\n" } keys %options );
1210 =item part_pkg_vendor
1212 Returns all vendor/external package ids as FS::part_pkg_vendor objects (see
1213 L<FS::part_pkg_vendor>).
1217 sub part_pkg_vendor {
1219 qsearch('part_pkg_vendor', { 'pkgpart' => $self->pkgpart } );
1222 =item vendor_pkg_ids
1224 Returns a list of vendor/external package ids by exportnum
1228 sub vendor_pkg_ids {
1230 map { $_->exportnum => $_->vendor_pkg_id } $self->part_pkg_vendor;
1233 =item part_pkg_option
1235 Returns all options as FS::part_pkg_option objects (see
1236 L<FS::part_pkg_option>).
1240 sub part_pkg_option {
1242 qsearch('part_pkg_option', { 'pkgpart' => $self->pkgpart } );
1247 Returns a list of option names and values suitable for assigning to a hash.
1253 map { $_->optionname => $_->optionvalue } $self->part_pkg_option;
1256 =item option OPTIONNAME [ QUIET ]
1258 Returns the option value for the given name, or the empty string. If a true
1259 value is passed as the second argument, warnings about missing the option
1265 my( $self, $opt, $ornull ) = @_;
1266 my $part_pkg_option =
1267 qsearchs('part_pkg_option', {
1268 pkgpart => $self->pkgpart,
1271 return $part_pkg_option->optionvalue if $part_pkg_option;
1272 my %plandata = map { /^(\w+)=(.*)$/; ( $1 => $2 ); }
1273 split("\n", $self->get('plandata') );
1274 return $plandata{$opt} if exists $plandata{$opt};
1275 cluck "WARNING: (pkgpart ". $self->pkgpart. ") Package def option $opt ".
1276 "not found in options or plandata!\n"
1281 =item part_pkg_currency [ CURRENCY ]
1283 Returns all currency options as FS::part_pkg_currency objects (see
1284 L<FS::part_pkg_currency>), or, if a currency is specified, only return the
1285 objects for that currency.
1289 sub part_pkg_currency {
1291 my %hash = ( 'pkgpart' => $self->pkgpart );
1292 $hash{'currency'} = shift if @_;
1293 qsearch('part_pkg_currency', \%hash );
1296 =item part_pkg_currency_options CURRENCY
1298 Returns a list of option names and values from FS::part_pkg_currency for the
1303 sub part_pkg_currency_options {
1305 map { $_->optionname => $_->optionvalue } $self->part_pkg_currency(shift);
1308 =item part_pkg_currency_option CURRENCY OPTIONNAME
1310 Returns the option value for the given name and currency.
1314 sub part_pkg_currency_option {
1315 my( $self, $currency, $optionname ) = @_;
1316 my $part_pkg_currency =
1317 qsearchs('part_pkg_currency', { 'pkgpart' => $self->pkgpart,
1318 'currency' => $currency,
1319 'optionname' => $optionname,
1322 #fatal if not found? that works for our use cases from
1323 #part_pkg/currency_fixed, but isn't how we would typically/expect the method
1324 #to behave. have to catch it there if we change it here...
1325 or die "Unknown price for ". $self->pkg_comment. " in $currency\n";
1327 $part_pkg_currency->optionvalue;
1330 =item bill_part_pkg_link
1332 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
1336 sub bill_part_pkg_link {
1337 shift->_part_pkg_link('bill', @_);
1340 =item svc_part_pkg_link
1342 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
1346 sub svc_part_pkg_link {
1347 shift->_part_pkg_link('svc', @_);
1350 =item supp_part_pkg_link
1352 Returns the associated part_pkg_link records of type 'supp' (supplemental
1357 sub supp_part_pkg_link {
1358 shift->_part_pkg_link('supp', @_);
1361 sub _part_pkg_link {
1362 my( $self, $type ) = @_;
1363 qsearch({ table => 'part_pkg_link',
1364 hashref => { 'src_pkgpart' => $self->pkgpart,
1365 'link_type' => $type,
1366 #protection against infinite recursive links
1367 'dst_pkgpart' => { op=>'!=', value=> $self->pkgpart },
1369 order_by => "ORDER BY hidden",
1373 sub self_and_bill_linked {
1374 shift->_self_and_linked('bill', @_);
1377 sub self_and_svc_linked {
1378 shift->_self_and_linked('svc', @_);
1381 sub _self_and_linked {
1382 my( $self, $type, $hidden ) = @_;
1386 foreach ( ( $self, map { $_->dst_pkg->_self_and_linked($type, $_->hidden) }
1387 $self->_part_pkg_link($type) ) )
1389 $_->hidden($hidden) if $hidden;
1396 =item part_pkg_taxoverride [ CLASS ]
1398 Returns all associated FS::part_pkg_taxoverride objects (see
1399 L<FS::part_pkg_taxoverride>). Limits the returned set to those
1400 of class CLASS if defined. Class may be one of 'setup', 'recur',
1401 the empty string (default), or a usage class number (see L<FS::usage_class>).
1402 When a class is specified, the empty string class (default) is returned
1403 if no more specific values exist.
1407 sub part_pkg_taxoverride {
1411 my $hashref = { 'pkgpart' => $self->pkgpart };
1412 $hashref->{'usage_class'} = $class if defined($class);
1413 my @overrides = qsearch('part_pkg_taxoverride', $hashref );
1415 unless ( scalar(@overrides) || !defined($class) || !$class ){
1416 $hashref->{'usage_class'} = '';
1417 @overrides = qsearch('part_pkg_taxoverride', $hashref );
1423 =item has_taxproduct
1425 Returns true if this package has any taxproduct associated with it.
1429 sub has_taxproduct {
1432 $self->taxproductnum ||
1433 scalar( grep { $_ =~/^usage_taxproductnum_/ && $self->option($_) }
1434 keys %{ {$self->options} }
1440 =item taxproduct [ CLASS ]
1442 Returns the associated tax product for this package definition (see
1443 L<FS::part_pkg_taxproduct>). CLASS may be one of 'setup', 'recur' or
1444 the usage classnum (see L<FS::usage_class>). Returns the default
1445 tax product for this record if the more specific CLASS value does
1454 my $part_pkg_taxproduct;
1456 my $taxproductnum = $self->taxproductnum;
1458 my $class_taxproductnum = $self->option("usage_taxproductnum_$class", 1);
1459 $taxproductnum = $class_taxproductnum
1460 if $class_taxproductnum
1463 $part_pkg_taxproduct =
1464 qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
1466 unless ($part_pkg_taxproduct || $taxproductnum eq $self->taxproductnum ) {
1467 $taxproductnum = $self->taxproductnum;
1468 $part_pkg_taxproduct =
1469 qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
1472 $part_pkg_taxproduct;
1475 =item taxproduct_description [ CLASS ]
1477 Returns the description of the associated tax product for this package
1478 definition (see L<FS::part_pkg_taxproduct>).
1482 sub taxproduct_description {
1484 my $part_pkg_taxproduct = $self->taxproduct(@_);
1485 $part_pkg_taxproduct ? $part_pkg_taxproduct->description : '';
1488 =item part_pkg_taxrate DATA_PROVIDER, GEOCODE, [ CLASS ]
1490 Returns the package to taxrate m2m records for this package in the location
1491 specified by GEOCODE (see L<FS::part_pkg_taxrate>) and usage class CLASS.
1492 CLASS may be one of 'setup', 'recur', or one of the usage classes numbers
1493 (see L<FS::usage_class>).
1497 sub _expand_cch_taxproductnum {
1500 my $part_pkg_taxproduct = $self->taxproduct($class);
1502 my ($a,$b,$c,$d) = ( $part_pkg_taxproduct
1503 ? ( split ':', $part_pkg_taxproduct->taxproduct )
1506 $a = '' unless $a; $b = '' unless $b; $c = '' unless $c; $d = '' unless $d;
1507 my $extra_sql = "AND ( taxproduct = '$a:$b:$c:$d'
1508 OR taxproduct = '$a:$b:$c:'
1509 OR taxproduct = '$a:$b:".":$d'
1510 OR taxproduct = '$a:$b:".":' )";
1511 map { $_->taxproductnum } qsearch( { 'table' => 'part_pkg_taxproduct',
1512 'hashref' => { 'data_vendor'=>'cch' },
1513 'extra_sql' => $extra_sql,
1518 sub part_pkg_taxrate {
1520 my ($data_vendor, $geocode, $class) = @_;
1523 my $extra_sql = 'WHERE part_pkg_taxproduct.data_vendor = '.
1524 dbh->quote($data_vendor);
1526 # CCH oddness in m2m
1527 $extra_sql .= ' AND ('.
1528 join(' OR ', map{ 'geocode = '. $dbh->quote(substr($geocode, 0, $_)) }
1532 # much more CCH oddness in m2m -- this is kludgy
1533 my @tpnums = $self->_expand_cch_taxproductnum($class);
1534 if (scalar(@tpnums)) {
1535 $extra_sql .= ' AND ('.
1536 join(' OR ', map{ "taxproductnum = $_" } @tpnums ).
1539 $extra_sql .= ' AND ( 0 = 1 )';
1542 my $addl_from = 'LEFT JOIN part_pkg_taxproduct USING ( taxproductnum )';
1543 my $order_by = 'ORDER BY taxclassnum, length(geocode) desc, length(taxproduct) desc';
1544 my $select = 'DISTINCT ON(taxclassnum) *, taxproduct';
1546 # should qsearch preface columns with the table to facilitate joins?
1547 qsearch( { 'table' => 'part_pkg_taxrate',
1548 'select' => $select,
1549 'hashref' => { # 'data_vendor' => $data_vendor,
1550 # 'taxproductnum' => $self->taxproductnum,
1552 'addl_from' => $addl_from,
1553 'extra_sql' => $extra_sql,
1554 'order_by' => $order_by,
1558 =item part_pkg_discount
1560 Returns the package to discount m2m records (see L<FS::part_pkg_discount>)
1565 sub part_pkg_discount {
1567 qsearch('part_pkg_discount', { 'pkgpart' => $self->pkgpart });
1570 =item part_pkg_usage
1572 Returns the voice usage pools (see L<FS::part_pkg_usage>) defined for
1577 sub part_pkg_usage {
1579 qsearch('part_pkg_usage', { 'pkgpart' => $self->pkgpart });
1584 Reblesses the object into the FS::part_pkg::PLAN class (if available), where
1585 PLAN is the object's I<plan> field. There should be better docs
1586 on how to create new price plans, but until then, see L</NEW PLAN CLASSES>.
1592 my $plan = $self->plan;
1594 cluck "no price plan found for pkgpart ". $self->pkgpart. "\n"
1598 return $self if ref($self) =~ /::$plan$/; #already blessed into plan subclass
1599 my $class = ref($self). "::$plan";
1600 warn "reblessing $self into $class" if $DEBUG > 1;
1603 bless($self, $class) unless $@;
1608 sub calc_setup { die 'no calc_setup for '. shift->plan. "\n"; }
1609 sub calc_recur { die 'no calc_recur for '. shift->plan. "\n"; }
1611 #fallback that return 0 for old legacy packages with no plan
1612 sub calc_remain { 0; }
1613 sub calc_units { 0; }
1615 #fallback for everything not based on flat.pm
1616 sub recur_temporality { 'upcoming'; }
1617 sub calc_cancel { 0; }
1619 #fallback for everything except bulk.pm
1620 sub hide_svc_detail { 0; }
1622 #fallback for packages that can't/won't summarize usage
1623 sub sum_usage { 0; }
1625 =item recur_cost_permonth CUST_PKG
1627 recur_cost divided by freq (only supported for monthly and longer frequencies)
1631 sub recur_cost_permonth {
1632 my($self, $cust_pkg) = @_;
1633 return 0 unless $self->freq =~ /^\d+$/ && $self->freq > 0;
1634 sprintf('%.2f', $self->recur_cost / $self->freq );
1637 =item cust_bill_pkg_recur CUST_PKG
1639 Actual recurring charge for the specified customer package from customer's most
1644 sub cust_bill_pkg_recur {
1645 my($self, $cust_pkg) = @_;
1646 my $cust_bill_pkg = qsearchs({
1647 'table' => 'cust_bill_pkg',
1648 'addl_from' => 'LEFT JOIN cust_bill USING ( invnum )',
1649 'hashref' => { 'pkgnum' => $cust_pkg->pkgnum,
1650 'recur' => { op=>'>', value=>'0' },
1652 'order_by' => 'ORDER BY cust_bill._date DESC,
1653 cust_bill_pkg.sdate DESC
1656 }) or return 0; #die "use cust_bill_pkg_recur credits with once_perinv condition";
1657 $cust_bill_pkg->recur;
1660 =item format OPTION DATA
1662 Returns data formatted according to the function 'format' described
1663 in the plan info. Returns DATA if no such function exists.
1668 my ($self, $option, $data) = (shift, shift, shift);
1669 if (exists($plans{$self->plan}->{fields}->{$option}{format})) {
1670 &{$plans{$self->plan}->{fields}->{$option}{format}}($data);
1676 =item parse OPTION DATA
1678 Returns data parsed according to the function 'parse' described
1679 in the plan info. Returns DATA if no such function exists.
1684 my ($self, $option, $data) = (shift, shift, shift);
1685 if (exists($plans{$self->plan}->{fields}->{$option}{parse})) {
1686 &{$plans{$self->plan}->{fields}->{$option}{parse}}($data);
1696 =head1 CLASS METHODS
1704 # Used by FS::Upgrade to migrate to a new database.
1706 sub _upgrade_data { # class method
1707 my($class, %opts) = @_;
1709 warn "[FS::part_pkg] upgrading $class\n" if $DEBUG;
1711 my @part_pkg = qsearch({
1712 'table' => 'part_pkg',
1713 'extra_sql' => "WHERE ". join(' OR ',
1714 'plan IS NULL', "plan = '' ",
1718 foreach my $part_pkg (@part_pkg) {
1720 unless ( $part_pkg->plan ) {
1721 $part_pkg->plan('flat');
1728 # now upgrade to the explicit custom flag
1730 @part_pkg = qsearch({
1731 'table' => 'part_pkg',
1732 'hashref' => { disabled => 'Y', custom => '' },
1733 'extra_sql' => "AND comment LIKE '(CUSTOM) %'",
1736 foreach my $part_pkg (@part_pkg) {
1737 my $new = new FS::part_pkg { $part_pkg->hash };
1739 my $comment = $part_pkg->comment;
1740 $comment =~ s/^\(CUSTOM\) //;
1741 $comment = '(none)' unless $comment =~ /\S/;
1742 $new->comment($comment);
1744 my $pkg_svc = { map { $_->svcpart => $_->quantity } $part_pkg->pkg_svc };
1745 my $primary = $part_pkg->svcpart;
1746 my $options = { $part_pkg->options };
1748 my $error = $new->replace( $part_pkg,
1749 'pkg_svc' => $pkg_svc,
1750 'primary_svc' => $primary,
1751 'options' => $options,
1753 die $error if $error;
1756 # set family_pkgpart on any packages that don't have it
1757 @part_pkg = qsearch('part_pkg', { 'family_pkgpart' => '' });
1758 foreach my $part_pkg (@part_pkg) {
1759 $part_pkg->set('family_pkgpart' => $part_pkg->pkgpart);
1760 my $error = $part_pkg->SUPER::replace;
1761 die $error if $error;
1764 my @part_pkg_option = qsearch('part_pkg_option',
1765 { 'optionname' => 'unused_credit',
1768 foreach my $old_opt (@part_pkg_option) {
1769 my $pkgpart = $old_opt->pkgpart;
1770 my $error = $old_opt->delete;
1771 die $error if $error;
1773 foreach (qw(unused_credit_cancel unused_credit_change)) {
1774 my $new_opt = new FS::part_pkg_option {
1775 'pkgpart' => $pkgpart,
1779 $error = $new_opt->insert;
1780 die $error if $error;
1784 # migrate use_disposition_taqua and use_disposition to disposition_in
1785 @part_pkg_option = qsearch('part_pkg_option',
1786 { 'optionname' => { op => 'LIKE',
1787 value => 'use_disposition%',
1791 my %newopts = map { $_->pkgpart => $_ }
1792 qsearch('part_pkg_option', { 'optionname' => 'disposition_in', } );
1793 foreach my $old_opt (@part_pkg_option) {
1794 my $pkgpart = $old_opt->pkgpart;
1795 my $newval = $old_opt->optionname eq 'use_disposition_taqua' ? '100'
1797 my $error = $old_opt->delete;
1798 die $error if $error;
1800 if ( exists($newopts{$pkgpart}) ) {
1801 my $opt = $newopts{$pkgpart};
1802 $opt->optionvalue($opt->optionvalue.",$newval");
1803 $error = $opt->replace;
1804 die $error if $error;
1806 my $new_opt = new FS::part_pkg_option {
1807 'pkgpart' => $pkgpart,
1808 'optionname' => 'disposition_in',
1809 'optionvalue' => $newval,
1811 $error = $new_opt->insert;
1812 die $error if $error;
1813 $newopts{$pkgpart} = $new_opt;
1817 # set any package with FCC voice lines to the "VoIP with broadband" category
1818 # for backward compatibility
1820 # recover from a bad upgrade bug
1821 my $upgrade = 'part_pkg_fcc_voip_class_FIX';
1822 if (!FS::upgrade_journal->is_done($upgrade)) {
1823 my $bad_upgrade = qsearchs('upgrade_journal',
1824 { upgrade => 'part_pkg_fcc_voip_class' }
1826 if ( $bad_upgrade ) {
1827 my $where = 'WHERE history_date <= '.$bad_upgrade->_date.
1828 ' AND history_date > '.($bad_upgrade->_date - 3600);
1829 my @h_part_pkg_option = map { FS::part_pkg_option->new($_->hashref) }
1832 'table' => 'h_part_pkg_option',
1834 'extra_sql' => "$where AND history_action = 'delete'",
1835 'order_by' => 'ORDER BY history_date ASC',
1837 my @h_pkg_svc = map { FS::pkg_svc->new($_->hashref) }
1840 'table' => 'h_pkg_svc',
1842 'extra_sql' => "$where AND history_action = 'replace_old'",
1843 'order_by' => 'ORDER BY history_date ASC',
1846 foreach my $deleted (@h_part_pkg_option, @h_pkg_svc) {
1847 my $pkgpart ||= $deleted->pkgpart;
1848 $opt{$pkgpart} ||= {
1854 if ( $deleted->isa('FS::part_pkg_option') ) {
1855 $opt{$pkgpart}{options}{ $deleted->optionname } = $deleted->optionvalue;
1857 my $svcpart = $deleted->svcpart;
1858 $opt{$pkgpart}{pkg_svc}{$svcpart} = $deleted->quantity;
1859 $opt{$pkgpart}{hidden_svc}{$svcpart} ||= $deleted->hidden;
1860 $opt{$pkgpart}{primary_svc} = $svcpart if $deleted->primary_svc;
1863 foreach my $pkgpart (keys %opt) {
1864 my $part_pkg = FS::part_pkg->by_key($pkgpart);
1865 my $error = $part_pkg->replace( $part_pkg->replace_old, $opt{$pkgpart} );
1867 die "error recovering damaged pkgpart $pkgpart:\n$error\n";
1870 } # $bad_upgrade exists
1871 else { # do the original upgrade, but correctly this time
1872 @part_pkg = qsearch('part_pkg', {
1873 fcc_ds0s => { op => '>', value => 0 },
1874 fcc_voip_class => ''
1876 foreach my $part_pkg (@part_pkg) {
1877 $part_pkg->set(fcc_voip_class => 2);
1878 my @pkg_svc = $part_pkg->pkg_svc;
1879 my %quantity = map {$_->svcpart, $_->quantity} @pkg_svc;
1880 my %hidden = map {$_->svcpart, $_->hidden } @pkg_svc;
1881 my $error = $part_pkg->replace(
1882 $part_pkg->replace_old,
1883 options => { $part_pkg->options },
1884 pkg_svc => \%quantity,
1885 hidden_svc => \%hidden,
1886 primary_svc => ($part_pkg->svcpart || ''),
1888 die $error if $error;
1891 FS::upgrade_journal->set_done($upgrade);
1896 =item curuser_pkgs_sql
1898 Returns an SQL fragment for searching for packages the current user can
1899 use, either via part_pkg.agentnum directly, or via agent type (see
1904 sub curuser_pkgs_sql {
1907 $class->_pkgs_sql( $FS::CurrentUser::CurrentUser->agentnums );
1911 =item agent_pkgs_sql AGENT | AGENTNUM, ...
1913 Returns an SQL fragment for searching for packages the provided agent or agents
1914 can use, either via part_pkg.agentnum directly, or via agent type (see
1919 sub agent_pkgs_sql {
1920 my $class = shift; #i'm a class method, not a sub (the question is... why??)
1921 my @agentnums = map { ref($_) ? $_->agentnum : $_ } @_;
1923 $class->_pkgs_sql(@agentnums); #is this why
1928 my( $class, @agentnums ) = @_;
1929 my $agentnums = join(',', @agentnums);
1933 ( agentnum IS NOT NULL AND agentnum IN ($agentnums) )
1934 OR ( agentnum IS NULL
1935 AND EXISTS ( SELECT 1
1937 LEFT JOIN agent_type USING ( typenum )
1938 LEFT JOIN agent AS typeagent USING ( typenum )
1939 WHERE type_pkgs.pkgpart = part_pkg.pkgpart
1940 AND typeagent.agentnum IN ($agentnums)
1958 #false laziness w/part_export & cdr
1960 foreach my $INC ( @INC ) {
1961 warn "globbing $INC/FS/part_pkg/*.pm\n" if $DEBUG;
1962 foreach my $file ( glob("$INC/FS/part_pkg/*.pm") ) {
1963 warn "attempting to load plan info from $file\n" if $DEBUG;
1964 $file =~ /\/(\w+)\.pm$/ or do {
1965 warn "unrecognized file in $INC/FS/part_pkg/: $file\n";
1969 my $info = eval "use FS::part_pkg::$mod; ".
1970 "\\%FS::part_pkg::$mod\::info;";
1972 die "error using FS::part_pkg::$mod (skipping): $@\n" if $@;
1975 unless ( keys %$info ) {
1976 warn "no %info hash found in FS::part_pkg::$mod, skipping\n";
1979 warn "got plan info from FS::part_pkg::$mod: $info\n" if $DEBUG;
1980 #if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
1981 # warn "skipping disabled plan FS::part_pkg::$mod" if $DEBUG;
1984 $info{$mod} = $info;
1985 $info->{'weight'} ||= 0; # quiet warnings
1989 # copy one level deep to allow replacement of fields and fieldorder
1990 tie %plans, 'Tie::IxHash',
1991 map { my %infohash = %{ $info{$_} };
1993 sort { $info{$a}->{'weight'} <=> $info{$b}->{'weight'} }
1996 # inheritance of plan options
1997 foreach my $name (keys(%info)) {
1998 if (exists($info{$name}->{'disabled'}) and $info{$name}->{'disabled'}) {
1999 warn "skipping disabled plan FS::part_pkg::$name" if $DEBUG;
2000 delete $plans{$name};
2003 my $parents = $info{$name}->{'inherit_fields'} || [];
2004 my (%fields, %field_exists, @fieldorder);
2005 foreach my $parent ($name, @$parents) {
2006 if ( !exists($info{$parent}) ) {
2007 warn "$name tried to inherit from nonexistent '$parent'\n";
2010 %fields = ( # avoid replacing existing fields
2011 %{ $info{$parent}->{'fields'} || {} },
2014 foreach (@{ $info{$parent}->{'fieldorder'} || [] }) {
2016 next if $field_exists{$_};
2017 $field_exists{$_} = 1;
2018 # allow inheritors to remove inherited fields from the fieldorder
2019 push @fieldorder, $_ if !exists($fields{$_}) or
2020 !exists($fields{$_}->{'disabled'});
2023 $plans{$name}->{'fields'} = \%fields;
2024 $plans{$name}->{'fieldorder'} = \@fieldorder;
2034 =head1 NEW PLAN CLASSES
2036 A module should be added in FS/FS/part_pkg/ Eventually, an example may be
2037 found in eg/plan_template.pm. Until then, it is suggested that you use the
2038 other modules in FS/FS/part_pkg/ as a guide.
2042 The delete method is unimplemented.
2044 setup and recur semantics are not yet defined (and are implemented in
2045 FS::cust_bill. hmm.). now they're deprecated and need to go.
2049 part_pkg_taxrate is Pg specific
2051 replace should be smarter about managing the related tables (options, pkg_svc)
2055 L<FS::Record>, L<FS::cust_pkg>, L<FS::type_pkgs>, L<FS::pkg_svc>, L<Safe>.
2056 schema.html from the base documentation.