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 );
9 use Time::Local qw( timelocal timelocal_nocheck ); # eventually replace with DateTime
12 use FS::Record qw( qsearch qsearchs dbh dbdef );
13 use FS::Cursor; # for upgrade
19 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_vendor;
27 use FS::part_pkg_currency;
31 $skip_pkg_svc_hack = 0;
35 FS::part_pkg - Object methods for part_pkg objects
41 $record = new FS::part_pkg \%hash
42 $record = new FS::part_pkg { 'column' => 'value' };
44 $custom_record = $template_record->clone;
46 $error = $record->insert;
48 $error = $new_record->replace($old_record);
50 $error = $record->delete;
52 $error = $record->check;
54 @pkg_svc = $record->pkg_svc;
56 $svcnum = $record->svcpart;
57 $svcnum = $record->svcpart( 'svc_acct' );
61 An FS::part_pkg object represents a package definition. FS::part_pkg
62 inherits from FS::Record. The following fields are currently supported:
66 =item pkgpart - primary key (assigned automatically for new package definitions)
68 =item pkg - Text name of this package definition (customer-viewable)
70 =item comment - Text name of this package definition (non-customer-viewable)
72 =item classnum - Optional package class (see L<FS::pkg_class>)
74 =item promo_code - Promotional code
76 =item setup - Setup fee expression (deprecated)
78 =item freq - Frequency of recurring fee
80 =item recur - Recurring fee expression (deprecated)
82 =item setuptax - Setup fee tax exempt flag, empty or `Y'
84 =item recurtax - Recurring fee tax exempt flag, empty or `Y'
86 =item taxclass - Tax class
88 =item plan - Price plan
90 =item plandata - Price plan data (deprecated - see L<FS::part_pkg_option> instead)
92 =item disabled - Disabled flag, empty or `Y'
94 =item custom - Custom flag, empty or `Y'
96 =item setup_cost - for cost tracking
98 =item recur_cost - for cost tracking
100 =item pay_weight - Weight (relative to credit_weight and other package definitions) that controls payment application to specific line items.
102 =item credit_weight - Weight (relative to other package definitions) that controls credit application to specific line items.
104 =item agentnum - Optional agentnum (see L<FS::agent>)
106 =item fcc_ds0s - Optional DS0 equivalency number for FCC form 477
108 =item fcc_voip_class - Which column of FCC form 477 part II.B this package
111 =item successor - Foreign key for the part_pkg that replaced this record.
112 If this record is not obsolete, will be null.
114 =item family_pkgpart - Foreign key for the part_pkg that was the earliest
115 ancestor of this record. If this record is not a successor to another
116 part_pkg, will be equal to pkgpart.
118 =item delay_start - Number of days to delay package start, by default
128 Creates a new package definition. To add the package definition to
129 the database, see L<"insert">.
133 sub table { 'part_pkg'; }
137 An alternate constructor. Creates a new package definition by duplicating
138 an existing definition. A new pkgpart is assigned and the custom flag is
139 set to Y. To add the package definition to the database, see L<"insert">.
145 my $class = ref($self);
146 my %hash = $self->hash;
147 $hash{'pkgpart'} = '';
148 $hash{'custom'} = 'Y';
149 #new FS::part_pkg ( \%hash ); # ?
150 new $class ( \%hash ); # ?
153 =item insert [ , OPTION => VALUE ... ]
155 Adds this package definition to the database. If there is an error,
156 returns the error, otherwise returns false.
158 Currently available options are: I<pkg_svc>, I<primary_svc>, I<cust_pkg>,
159 I<custnum_ref> and I<options>.
161 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
162 values, appropriate FS::pkg_svc records will be inserted. I<hidden_svc> can
163 be set to a hashref of svcparts and flag values ('Y' or '') to set the
164 'hidden' field in these records.
166 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
167 FS::pkg_svc record will be updated.
169 If I<cust_pkg> is set to a pkgnum of a FS::cust_pkg record (or the FS::cust_pkg
170 record itself), the object will be updated to point to this package definition.
172 In conjunction with I<cust_pkg>, if I<custnum_ref> is set to a scalar reference,
173 the scalar will be updated with the custnum value from the cust_pkg record.
175 If I<tax_overrides> is set to a hashref with usage classes as keys and comma
176 separated tax class numbers as values, appropriate FS::part_pkg_taxoverride
177 records will be inserted.
179 If I<options> is set to a hashref of options, appropriate FS::part_pkg_option
180 records will be inserted.
182 If I<part_pkg_currency> is set to a hashref of options (with the keys as
183 option_CURRENCY), appropriate FS::part_pkg::currency records will be inserted.
190 warn "FS::part_pkg::insert called on $self with options ".
191 join(', ', map "$_=>$options{$_}", keys %options)
194 local $SIG{HUP} = 'IGNORE';
195 local $SIG{INT} = 'IGNORE';
196 local $SIG{QUIT} = 'IGNORE';
197 local $SIG{TERM} = 'IGNORE';
198 local $SIG{TSTP} = 'IGNORE';
199 local $SIG{PIPE} = 'IGNORE';
201 my $oldAutoCommit = $FS::UID::AutoCommit;
202 local $FS::UID::AutoCommit = 0;
205 warn " inserting part_pkg record" if $DEBUG;
206 my $error = $self->SUPER::insert( $options{options} );
208 $dbh->rollback if $oldAutoCommit;
213 if ( $self->get('family_pkgpart') eq '' ) {
214 $self->set('family_pkgpart' => $self->pkgpart);
215 $error = $self->SUPER::replace;
217 $dbh->rollback if $oldAutoCommit;
222 warn " inserting part_pkg_taxoverride records" if $DEBUG;
223 my %overrides = %{ $options{'tax_overrides'} || {} };
224 foreach my $usage_class ( keys %overrides ) {
226 ( exists($overrides{$usage_class}) && defined($overrides{$usage_class}) )
227 ? $overrides{$usage_class}
229 my @overrides = (grep "$_", split(',', $override) );
230 my $error = $self->process_m2m (
231 'link_table' => 'part_pkg_taxoverride',
232 'target_table' => 'tax_class',
233 'hashref' => { 'usage_class' => $usage_class },
234 'params' => \@overrides,
237 $dbh->rollback if $oldAutoCommit;
242 warn " inserting part_pkg_currency records" if $DEBUG;
243 my %part_pkg_currency = %{ $options{'part_pkg_currency'} || {} };
244 foreach my $key ( keys %part_pkg_currency ) {
245 $key =~ /^(.+)_([A-Z]{3})$/ or next;
246 my( $optionname, $currency ) = ( $1, $2 );
247 if ( $part_pkg_currency{$key} =~ /^\s*$/ ) {
248 if ( $self->option($optionname) == 0 ) {
249 $part_pkg_currency{$key} = '0';
251 $dbh->rollback if $oldAutoCommit;
252 ( my $thing = $optionname ) =~ s/_/ /g;
253 return ucfirst($thing). " $currency is required";
256 my $part_pkg_currency = new FS::part_pkg_currency {
257 'pkgpart' => $self->pkgpart,
258 'optionname' => $optionname,
259 'currency' => $currency,
260 'optionvalue' => $part_pkg_currency{$key},
262 my $error = $part_pkg_currency->insert;
264 $dbh->rollback if $oldAutoCommit;
269 unless ( $skip_pkg_svc_hack ) {
271 warn " inserting pkg_svc records" if $DEBUG;
272 my $pkg_svc = $options{'pkg_svc'} || {};
273 my $hidden_svc = $options{'hidden_svc'} || {};
274 foreach my $part_svc ( qsearch('part_svc', {} ) ) {
275 my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
277 ( $options{'primary_svc'} && $options{'primary_svc'}==$part_svc->svcpart )
281 my $pkg_svc = new FS::pkg_svc( {
282 'pkgpart' => $self->pkgpart,
283 'svcpart' => $part_svc->svcpart,
284 'quantity' => $quantity,
285 'primary_svc' => $primary_svc,
286 'hidden' => $hidden_svc->{$part_svc->svcpart},
288 my $error = $pkg_svc->insert;
290 $dbh->rollback if $oldAutoCommit;
297 if ( $options{'cust_pkg'} ) {
298 warn " updating cust_pkg record " if $DEBUG;
300 ref($options{'cust_pkg'})
301 ? $options{'cust_pkg'}
302 : qsearchs('cust_pkg', { pkgnum => $options{'cust_pkg'} } );
303 ${ $options{'custnum_ref'} } = $old_cust_pkg->custnum
304 if $options{'custnum_ref'};
305 my %hash = $old_cust_pkg->hash;
306 $hash{'pkgpart'} = $self->pkgpart,
307 my $new_cust_pkg = new FS::cust_pkg \%hash;
308 local($FS::cust_pkg::disable_agentcheck) = 1;
309 my $error = $new_cust_pkg->replace($old_cust_pkg);
311 $dbh->rollback if $oldAutoCommit;
312 return "Error modifying cust_pkg record: $error";
316 if ( $options{'part_pkg_vendor'} ) {
317 while ( my ($exportnum, $vendor_pkg_id) =
318 each %{ $options{part_pkg_vendor} }
321 my $ppv = new FS::part_pkg_vendor( {
322 'pkgpart' => $self->pkgpart,
323 'exportnum' => $exportnum,
324 'vendor_pkg_id' => $vendor_pkg_id,
326 my $error = $ppv->insert;
328 $dbh->rollback if $oldAutoCommit;
329 return "Error inserting part_pkg_vendor record: $error";
334 warn " committing transaction" if $DEBUG and $oldAutoCommit;
335 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
342 Currently unimplemented.
347 return "Can't (yet?) delete package definitions.";
348 # check & make sure the pkgpart isn't in cust_pkg or type_pkgs?
351 =item replace OLD_RECORD [ , OPTION => VALUE ... ]
353 Replaces OLD_RECORD with this one in the database. If there is an error,
354 returns the error, otherwise returns false.
356 Currently available options are: I<pkg_svc>, I<hidden_svc>, I<primary_svc>
359 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
360 values, the appropriate FS::pkg_svc records will be replaced. I<hidden_svc>
361 can be set to a hashref of svcparts and flag values ('Y' or '') to set the
362 'hidden' field in these records. I<bulk_skip> can be set to a hashref of
363 svcparts and flag values ('Y' or '') to set the 'bulk_skip' field in those
366 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
367 FS::pkg_svc record will be updated.
369 If I<options> is set to a hashref, the appropriate FS::part_pkg_option records
372 If I<part_pkg_currency> is set to a hashref of options (with the keys as
373 option_CURRENCY), appropriate FS::part_pkg::currency records will be replaced.
380 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
385 ( ref($_[0]) eq 'HASH' )
389 $options->{options} = { $old->options } unless defined($options->{options});
391 warn "FS::part_pkg::replace called on $new to replace $old with options".
392 join(', ', map "$_ => ". $options->{$_}, keys %$options)
395 local $SIG{HUP} = 'IGNORE';
396 local $SIG{INT} = 'IGNORE';
397 local $SIG{QUIT} = 'IGNORE';
398 local $SIG{TERM} = 'IGNORE';
399 local $SIG{TSTP} = 'IGNORE';
400 local $SIG{PIPE} = 'IGNORE';
402 my $oldAutoCommit = $FS::UID::AutoCommit;
403 local $FS::UID::AutoCommit = 0;
406 my $conf = new FS::Conf;
407 if ( $conf->exists('part_pkg-lineage') ) {
408 if ( grep { $options->{options}->{$_} ne $old->option($_, 1) }
409 qw(setup_fee recur_fee) #others? config?
412 warn " superseding package" if $DEBUG;
414 my $error = $new->supersede($old, %$options);
416 $dbh->rollback if $oldAutoCommit;
420 warn " committing transaction" if $DEBUG and $oldAutoCommit;
421 $dbh->commit if $oldAutoCommit;
428 #plandata shit stays in replace for upgrades until after 2.0 (or edit
430 warn " saving legacy plandata" if $DEBUG;
431 my $plandata = $new->get('plandata');
432 $new->set('plandata', '');
434 warn " deleting old part_pkg_option records" if $DEBUG;
435 foreach my $part_pkg_option ( $old->part_pkg_option ) {
436 my $error = $part_pkg_option->delete;
438 $dbh->rollback if $oldAutoCommit;
443 warn " replacing part_pkg record" if $DEBUG;
444 my $error = $new->SUPER::replace($old, $options->{options} );
446 $dbh->rollback if $oldAutoCommit;
450 warn " inserting part_pkg_option records for plandata: $plandata|" if $DEBUG;
451 foreach my $part_pkg_option (
452 map { /^(\w+)=(.*)$/ or do { $dbh->rollback if $oldAutoCommit;
453 return "illegal plandata: $plandata";
455 new FS::part_pkg_option {
456 'pkgpart' => $new->pkgpart,
461 split("\n", $plandata)
463 my $error = $part_pkg_option->insert;
465 $dbh->rollback if $oldAutoCommit;
470 #trivial nit: not the most efficient to delete and reinsert
471 warn " deleting old part_pkg_currency records" if $DEBUG;
472 foreach my $part_pkg_currency ( $old->part_pkg_currency ) {
473 my $error = $part_pkg_currency->delete;
475 $dbh->rollback if $oldAutoCommit;
476 return "error deleting part_pkg_currency record: $error";
480 warn " inserting new part_pkg_currency records" if $DEBUG;
481 my %part_pkg_currency = %{ $options->{'part_pkg_currency'} || {} };
482 foreach my $key ( keys %part_pkg_currency ) {
483 $key =~ /^(.+)_([A-Z]{3})$/ or next;
484 my $part_pkg_currency = new FS::part_pkg_currency {
485 'pkgpart' => $new->pkgpart,
488 'optionvalue' => $part_pkg_currency{$key},
490 my $error = $part_pkg_currency->insert;
492 $dbh->rollback if $oldAutoCommit;
493 return "error inserting part_pkg_currency record: $error";
498 warn " replacing pkg_svc records" if $DEBUG;
499 my $pkg_svc = $options->{'pkg_svc'};
500 my $hidden_svc = $options->{'hidden_svc'} || {};
501 my $bulk_skip = $options->{'bulk_skip'} || {};
502 if ( $pkg_svc ) { # if it wasn't passed, don't change existing pkg_svcs
503 foreach my $part_svc ( qsearch('part_svc', {} ) ) {
504 my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
505 my $hidden = $hidden_svc->{$part_svc->svcpart} || '';
506 my $bulk_skip = $bulk_skip->{$part_svc->svcpart} || '';
508 ( defined($options->{'primary_svc'}) && $options->{'primary_svc'}
509 && $options->{'primary_svc'} == $part_svc->svcpart
514 my $old_pkg_svc = qsearchs('pkg_svc', {
515 'pkgpart' => $old->pkgpart,
516 'svcpart' => $part_svc->svcpart,
519 my $old_quantity = 0;
520 my $old_primary_svc = '';
522 my $old_bulk_skip = '';
523 if ( $old_pkg_svc ) {
524 $old_quantity = $old_pkg_svc->quantity;
525 $old_primary_svc = $old_pkg_svc->primary_svc
526 if $old_pkg_svc->dbdef_table->column('primary_svc'); # is this needed?
527 $old_hidden = $old_pkg_svc->hidden;
528 $old_bulk_skip = $old_pkg_svc->old_bulk_skip;
531 next unless $old_quantity != $quantity
532 || $old_primary_svc ne $primary_svc
533 || $old_hidden ne $hidden
534 || $old_bulk_skip ne $bulk_skip;
536 my $new_pkg_svc = new FS::pkg_svc( {
537 'pkgsvcnum' => ( $old_pkg_svc ? $old_pkg_svc->pkgsvcnum : '' ),
538 'pkgpart' => $new->pkgpart,
539 'svcpart' => $part_svc->svcpart,
540 'quantity' => $quantity,
541 'primary_svc' => $primary_svc,
543 'bulk_skip' => $bulk_skip,
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_textn('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->ut_alphan('agent_pkgpartid')
691 || $self->SUPER::check
693 return $error if $error;
695 return 'Unknown plan '. $self->plan
696 unless exists($plans{$self->plan});
698 my $conf = new FS::Conf;
699 return 'Taxclass is required'
700 if ! $self->taxclass && $conf->exists('require_taxclasses');
705 =item supersede OLD [, OPTION => VALUE ... ]
707 Inserts this package as a successor to the package OLD. All options are as
708 for C<insert>. After inserting, disables OLD and sets the new package as its
714 my ($new, $old, %options) = @_;
717 $new->set('pkgpart' => '');
718 $new->set('family_pkgpart' => $old->family_pkgpart);
719 warn " inserting successor package\n" if $DEBUG;
720 $error = $new->insert(%options);
721 return $error if $error;
723 warn " disabling superseded package\n" if $DEBUG;
724 $old->set('successor' => $new->pkgpart);
725 $old->set('disabled' => 'Y');
726 $error = $old->SUPER::replace; # don't change its options/pkg_svc records
727 return $error if $error;
729 warn " propagating changes to family" if $DEBUG;
730 $new->propagate($old);
735 If any of certain fields have changed from OLD to this package, then,
736 for all packages in the same lineage as this one, sets those fields
737 to their values in this package.
741 my @propagate_fields = (
742 qw( pkg classnum setup_cost recur_cost taxclass
743 setuptax recurtax pay_weight credit_weight
751 map { $_ => $new->get($_) }
752 grep { $new->get($_) ne $old->get($_) }
756 my @part_pkg = qsearch('part_pkg', {
757 'family_pkgpart' => $new->family_pkgpart
760 foreach my $part_pkg ( @part_pkg ) {
761 my $pkgpart = $part_pkg->pkgpart;
762 next if $pkgpart == $new->pkgpart; # don't modify $new
763 warn " propagating to pkgpart $pkgpart\n" if $DEBUG;
764 foreach ( keys %fields ) {
765 $part_pkg->set($_, $fields{$_});
767 # SUPER::replace to avoid changing non-core fields
768 my $error = $part_pkg->SUPER::replace;
769 push @error, "pkgpart $pkgpart: $error"
775 =item pkg_locale LOCALE
777 Returns a customer-viewable string representing this package for the given
778 locale, from the part_pkg_msgcat table. If the given locale is empty or no
779 localized string is found, returns the base pkg field.
784 my( $self, $locale ) = @_;
785 return $self->pkg unless $locale;
786 my $part_pkg_msgcat = $self->part_pkg_msgcat($locale) or return $self->pkg;
787 $part_pkg_msgcat->pkg;
790 =item part_pkg_msgcat LOCALE
792 Like pkg_locale, but returns the FS::part_pkg_msgcat object itself.
796 sub part_pkg_msgcat {
797 my( $self, $locale ) = @_;
798 qsearchs( 'part_pkg_msgcat', {
799 pkgpart => $self->pkgpart,
804 =item pkg_comment [ OPTION => VALUE... ]
806 Returns an (internal) string representing this package. Currently,
807 "pkgpart: pkg - comment", is returned. "pkg - comment" may be returned in the
808 future, omitting pkgpart. The comment will have '(CUSTOM) ' prepended if
811 If the option nopkgpart is true then the "pkgpart: ' is omitted.
819 #$self->pkg. ' - '. $self->comment;
820 #$self->pkg. ' ('. $self->comment. ')';
821 my $pre = $opt{nopkgpart} ? '' : $self->pkgpart. ': ';
822 my $custom_comment = $self->custom_comment(%opt);
823 $pre. $self->pkg. ( $custom_comment ? " - $custom_comment" : '' );
826 #without price info (so without hitting the DB again)
827 sub pkg_comment_only {
831 my $pre = $opt{nopkgpart} ? '' : $self->pkgpart. ': ';
832 my $comment = $self->comment;
833 $pre. $self->pkg. ( $comment ? " - $comment" : '' );
836 sub price_info { # safety, in case a part_pkg hasn't defined price_info
842 my $price_info = $self->price_info(@_);
843 ( $self->custom ? '(CUSTOM) ' : '' ).
845 ( ($self->custom || $self->comment) ? ' - ' : '' ).
846 ($price_info || 'No charge');
851 $self->pkg. ' - '. ($self->price_info || 'No charge');
856 Returns the package class, as an FS::pkg_class object, or the empty string
857 if there is no package class.
859 =item addon_pkg_class
861 Returns the add-on package class, as an FS::pkg_class object, or the empty
862 string if there is no add-on package class.
866 sub addon_pkg_class {
868 if ( $self->addon_classnum ) {
869 qsearchs('pkg_class', { 'classnum' => $self->addon_classnum } );
877 Returns the package category name, or the empty string if there is no package
884 my $pkg_class = $self->pkg_class;
886 ? $pkg_class->categoryname
892 Returns the package class name, or the empty string if there is no package
899 my $pkg_class = $self->pkg_class;
901 ? $pkg_class->classname
905 =item addon_classname
907 Returns the add-on package class name, or the empty string if there is no
908 add-on package class.
912 sub addon_classname {
914 my $pkg_class = $self->addon_pkg_class;
916 ? $pkg_class->classname
922 Returns the associated agent for this event, if any, as an FS::agent object.
924 =item pkg_svc [ HASHREF | OPTION => VALUE ]
926 Returns all FS::pkg_svc objects (see L<FS::pkg_svc>) for this package
927 definition (with non-zero quantity).
929 One option is available, I<disable_linked>. If set true it will return the
930 services for this package definition alone, omitting services from any add-on
937 Returns all FS::type_pkgs objects (see L<FS::type_pkgs>) for this package
945 # #sort { $b->primary cmp $a->primary }
946 # grep { $_->quantity }
947 # qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
949 my $opt = ref($_[0]) ? $_[0] : { @_ };
950 my %pkg_svc = map { $_->svcpart => $_ }
951 grep { $_->quantity }
952 qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
954 unless ( $opt->{disable_linked} ) {
955 foreach my $dst_pkg ( map $_->dst_pkg, $self->svc_part_pkg_link ) {
956 my @pkg_svc = grep { $_->quantity }
957 qsearch( 'pkg_svc', { pkgpart=>$dst_pkg->pkgpart } );
958 foreach my $pkg_svc ( @pkg_svc ) {
959 if ( $pkg_svc{$pkg_svc->svcpart} ) {
960 my $quantity = $pkg_svc{$pkg_svc->svcpart}->quantity;
961 $pkg_svc{$pkg_svc->svcpart}->quantity($quantity + $pkg_svc->quantity);
963 $pkg_svc{$pkg_svc->svcpart} = $pkg_svc;
973 =item svcpart [ SVCDB ]
975 Returns the svcpart of the primary service definition (see L<FS::part_svc>)
976 associated with this package definition (see L<FS::pkg_svc>). Returns
977 false if there not a primary service definition or exactly one service
978 definition with quantity 1, or if SVCDB is specified and does not match the
979 svcdb of the service definition. SVCDB can be specified as a scalar table
980 name, such as 'svc_acct', or as an arrayref of possible table names.
985 my $pkg_svc = shift->_primary_pkg_svc(@_);
986 $pkg_svc ? $pkg_svc->svcpart : '';
989 =item part_svc [ SVCDB ]
991 Like the B<svcpart> method, but returns the FS::part_svc object (see
997 my $pkg_svc = shift->_primary_pkg_svc(@_);
998 $pkg_svc ? $pkg_svc->part_svc : '';
1001 sub _primary_pkg_svc {
1004 my $svcdb = scalar(@_) ? shift : [];
1005 $svcdb = ref($svcdb) ? $svcdb : [ $svcdb ];
1006 my %svcdb = map { $_=>1 } @$svcdb;
1009 grep { !scalar(@$svcdb) || $svcdb{ $_->part_svc->svcdb } }
1012 my @pkg_svc = grep { $_->primary_svc =~ /^Y/i } @svcdb_pkg_svc;
1013 @pkg_svc = grep {$_->quantity == 1 } @svcdb_pkg_svc
1015 return '' if scalar(@pkg_svc) != 1;
1019 =item svcpart_unique_svcdb SVCDB
1021 Returns the svcpart of a service definition (see L<FS::part_svc>) matching
1022 SVCDB associated with this package definition (see L<FS::pkg_svc>). Returns
1023 false if there not a primary service definition for SVCDB or there are multiple
1024 service definitions for SVCDB.
1028 sub svcpart_unique_svcdb {
1029 my( $self, $svcdb ) = @_;
1030 my @svcdb_pkg_svc = grep { ( $svcdb eq $_->part_svc->svcdb ) } $self->pkg_svc;
1031 return '' if scalar(@svcdb_pkg_svc) != 1;
1032 $svcdb_pkg_svc[0]->svcpart;
1037 Returns a list of the acceptable payment types for this package. Eventually
1038 this should come out of a database table and be editable, but currently has the
1039 following logic instead:
1041 If the package is free, the single item B<BILL> is
1042 returned, otherwise, the single item B<CARD> is returned.
1044 (CHEK? LEC? Probably shouldn't accept those by default, prone to abuse)
1050 if ( $self->is_free ) {
1059 Returns true if this package is free.
1065 if ( $self->can('is_free_options') ) {
1066 not grep { $_ !~ /^\s*0*(\.0*)?\s*$/ }
1067 map { $self->option($_) }
1068 $self->is_free_options;
1070 warn "FS::part_pkg::is_free: FS::part_pkg::". $self->plan. " subclass ".
1071 "provides neither is_free_options nor is_free method; returning false";
1076 # whether the plan allows discounts to be applied to this package
1077 sub can_discount { 0; }
1079 # whether the plan allows changing the start date
1080 sub can_start_date { 1; }
1082 # whether the plan supports part_pkg_usageprice add-ons (a specific kind of
1083 # pre-selectable usage pricing, there's others this doesn't refer to)
1084 sub can_usageprice { 0; }
1086 # the delay start date if present
1087 sub delay_start_date {
1090 my $delay = $self->delay_start or return '';
1092 # avoid timelocal silliness
1093 my $dt = DateTime->today(time_zone => 'local');
1094 $dt->add(days => $delay);
1098 sub can_currency_exchange { 0; }
1101 # moved to FS::Misc to make this accessible to other packages
1103 FS::Misc::pkg_freqs();
1108 Returns an english representation of the I<freq> field, such as "monthly",
1109 "weekly", "semi-annually", etc.
1115 my $freq = $self->freq;
1117 #my $freqs_href = $self->freqs_href;
1118 my $freqs_href = freqs_href();
1120 if ( exists($freqs_href->{$freq}) ) {
1121 $freqs_href->{$freq};
1123 my $interval = 'month';
1124 if ( $freq =~ /^(\d+)([hdw])$/ ) {
1125 my %interval = ( 'h' => 'hour', 'd'=>'day', 'w'=>'week' );
1126 $interval = $interval{$2};
1131 "every $freq ${interval}s";
1136 =item add_freq TIMESTAMP [ FREQ ]
1138 Adds a billing period of some frequency to the provided timestamp and
1139 returns the resulting timestamp, or -1 if the frequency could not be
1140 parsed (shouldn't happen). By default, the frequency of this package
1141 will be used; to override this, pass a different frequency as a second
1147 my( $self, $date, $freq ) = @_;
1148 $freq = $self->freq unless $freq;
1150 #change this bit to use Date::Manip? CAREFUL with timezones (see
1151 # mailing list archive)
1152 my ($sec,$min,$hour,$mday,$mon,$year) = (localtime($date) )[0,1,2,3,4,5];
1154 if ( $freq =~ /^\d+$/ ) {
1156 until ( $mon < 12 ) { $mon -= 12; $year++; }
1158 $mday = 28 if $mday > 28 && FS::Conf->new->exists('anniversary-rollback');
1160 } elsif ( $freq =~ /^(\d+)w$/ ) {
1162 $mday += $weeks * 7;
1163 } elsif ( $freq =~ /^(\d+)d$/ ) {
1166 } elsif ( $freq =~ /^(\d+)h$/ ) {
1173 timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year);
1178 For backwards compatibility, returns the plandata field as well as all options
1179 from FS::part_pkg_option.
1185 carp "plandata is deprecated";
1187 $self->SUPER::plandata(@_);
1189 my $plandata = $self->get('plandata');
1190 my %options = $self->options;
1191 $plandata .= join('', map { "$_=$options{$_}\n" } keys %options );
1196 =item part_pkg_vendor
1198 Returns all vendor/external package ids as FS::part_pkg_vendor objects (see
1199 L<FS::part_pkg_vendor>).
1201 =item vendor_pkg_ids
1203 Returns a list of vendor/external package ids by exportnum
1207 sub vendor_pkg_ids {
1209 map { $_->exportnum => $_->vendor_pkg_id } $self->part_pkg_vendor;
1212 =item part_pkg_option
1214 Returns all options as FS::part_pkg_option objects (see
1215 L<FS::part_pkg_option>).
1219 Returns a list of option names and values suitable for assigning to a hash.
1225 map { $_->optionname => $_->optionvalue } $self->part_pkg_option;
1228 =item option OPTIONNAME [ QUIET ]
1230 Returns the option value for the given name, or the empty string. If a true
1231 value is passed as the second argument, warnings about missing the option
1237 my( $self, $opt, $ornull ) = @_;
1238 cluck "$self -> option: searching for $opt"
1240 my $part_pkg_option =
1241 qsearchs('part_pkg_option', {
1242 pkgpart => $self->pkgpart,
1245 return $part_pkg_option->optionvalue if $part_pkg_option;
1246 my %plandata = map { /^(\w+)=(.*)$/; ( $1 => $2 ); }
1247 split("\n", $self->get('plandata') );
1248 return $plandata{$opt} if exists $plandata{$opt};
1249 cluck "WARNING: (pkgpart ". $self->pkgpart. ") Package def option $opt ".
1250 "not found in options or plandata!\n"
1255 =item part_pkg_currency [ CURRENCY ]
1257 Returns all currency options as FS::part_pkg_currency objects (see
1258 L<FS::part_pkg_currency>), or, if a currency is specified, only return the
1259 objects for that currency.
1263 sub part_pkg_currency {
1265 my %hash = ( 'pkgpart' => $self->pkgpart );
1266 $hash{'currency'} = shift if @_;
1267 qsearch('part_pkg_currency', \%hash );
1270 =item part_pkg_currency_options CURRENCY
1272 Returns a list of option names and values from FS::part_pkg_currency for the
1277 sub part_pkg_currency_options {
1279 map { $_->optionname => $_->optionvalue } $self->part_pkg_currency(shift);
1282 =item part_pkg_currency_option CURRENCY OPTIONNAME
1284 Returns the option value for the given name and currency.
1288 sub part_pkg_currency_option {
1289 my( $self, $currency, $optionname ) = @_;
1290 my $part_pkg_currency =
1291 qsearchs('part_pkg_currency', { 'pkgpart' => $self->pkgpart,
1292 'currency' => $currency,
1293 'optionname' => $optionname,
1296 #fatal if not found? that works for our use cases from
1297 #part_pkg/currency_fixed, but isn't how we would typically/expect the method
1298 #to behave. have to catch it there if we change it here...
1299 or die "Unknown price for ". $self->pkg_comment. " in $currency\n";
1301 $part_pkg_currency->optionvalue;
1304 =item bill_part_pkg_link
1306 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
1310 sub bill_part_pkg_link {
1311 shift->_part_pkg_link('bill', @_);
1314 =item svc_part_pkg_link
1316 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
1320 sub svc_part_pkg_link {
1321 shift->_part_pkg_link('svc', @_);
1324 =item supp_part_pkg_link
1326 Returns the associated part_pkg_link records of type 'supp' (supplemental
1331 sub supp_part_pkg_link {
1332 shift->_part_pkg_link('supp', @_);
1335 sub _part_pkg_link {
1336 my( $self, $type ) = @_;
1337 qsearch({ table => 'part_pkg_link',
1338 hashref => { 'src_pkgpart' => $self->pkgpart,
1339 'link_type' => $type,
1340 #protection against infinite recursive links
1341 'dst_pkgpart' => { op=>'!=', value=> $self->pkgpart },
1343 order_by => "ORDER BY hidden",
1347 sub self_and_bill_linked {
1348 shift->_self_and_linked('bill', @_);
1351 sub self_and_svc_linked {
1352 shift->_self_and_linked('svc', @_);
1355 sub _self_and_linked {
1356 my( $self, $type, $hidden ) = @_;
1360 foreach ( ( $self, map { $_->dst_pkg->_self_and_linked($type, $_->hidden) }
1361 $self->_part_pkg_link($type) ) )
1363 $_->hidden($hidden) if $hidden;
1370 =item part_pkg_taxoverride [ CLASS ]
1372 Returns all associated FS::part_pkg_taxoverride objects (see
1373 L<FS::part_pkg_taxoverride>). Limits the returned set to those
1374 of class CLASS if defined. Class may be one of 'setup', 'recur',
1375 the empty string (default), or a usage class number (see L<FS::usage_class>).
1376 When a class is specified, the empty string class (default) is returned
1377 if no more specific values exist.
1381 sub part_pkg_taxoverride {
1385 my $hashref = { 'pkgpart' => $self->pkgpart };
1386 $hashref->{'usage_class'} = $class if defined($class);
1387 my @overrides = qsearch('part_pkg_taxoverride', $hashref );
1389 unless ( scalar(@overrides) || !defined($class) || !$class ){
1390 $hashref->{'usage_class'} = '';
1391 @overrides = qsearch('part_pkg_taxoverride', $hashref );
1397 =item has_taxproduct
1399 Returns true if this package has any taxproduct associated with it.
1403 sub has_taxproduct {
1406 $self->taxproductnum ||
1407 scalar( grep { $_ =~/^usage_taxproductnum_/ && $self->option($_) }
1408 keys %{ {$self->options} }
1414 =item taxproduct [ CLASS ]
1416 Returns the associated tax product for this package definition (see
1417 L<FS::part_pkg_taxproduct>). CLASS may be one of 'setup', 'recur' or
1418 the usage classnum (see L<FS::usage_class>). Returns the default
1419 tax product for this record if the more specific CLASS value does
1428 my $part_pkg_taxproduct;
1430 my $taxproductnum = $self->taxproductnum;
1432 my $class_taxproductnum = $self->option("usage_taxproductnum_$class", 1);
1433 $taxproductnum = $class_taxproductnum
1434 if $class_taxproductnum
1437 $part_pkg_taxproduct =
1438 qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
1440 unless ($part_pkg_taxproduct || $taxproductnum eq $self->taxproductnum ) {
1441 $taxproductnum = $self->taxproductnum;
1442 $part_pkg_taxproduct =
1443 qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
1446 $part_pkg_taxproduct;
1449 =item taxproduct_description [ CLASS ]
1451 Returns the description of the associated tax product for this package
1452 definition (see L<FS::part_pkg_taxproduct>).
1456 sub taxproduct_description {
1458 my $part_pkg_taxproduct = $self->taxproduct(@_);
1459 $part_pkg_taxproduct ? $part_pkg_taxproduct->description : '';
1463 =item tax_rates DATA_PROVIDER, GEOCODE, [ CLASS ]
1465 Returns the tax table entries (L<FS::tax_rate> objects) that apply to this
1466 package in the location specified by GEOCODE, for usage class CLASS (one of
1467 'setup', 'recur', null, or a C<usage_class> number).
1473 my ($vendor, $geocode, $class) = @_;
1474 my @taxclassnums = map { $_->taxclassnum }
1475 $self->part_pkg_taxoverride($class);
1476 if (!@taxclassnums) {
1477 my $part_pkg_taxproduct = $self->taxproduct($class);
1478 # If this isn't defined, then the class has no taxproduct designation,
1479 # so return no tax rates.
1480 return () if !$part_pkg_taxproduct;
1482 # convert the taxproduct to the tax classes that might apply to it in
1484 @taxclassnums = map { $_->taxclassnum }
1485 grep { $_->taxable eq 'Y' } # why do we need this?
1486 $part_pkg_taxproduct->part_pkg_taxrate($geocode);
1488 return unless @taxclassnums;
1490 # then look up the actual tax_rate entries
1491 warn "Found taxclassnum values of ". join(',', @taxclassnums) ."\n"
1493 my $extra_sql = "AND taxclassnum IN (". join(',', @taxclassnums) . ")";
1494 my @taxes = qsearch({ 'table' => 'tax_rate',
1495 'hashref' => { 'geocode' => $geocode,
1496 'data_vendor' => $vendor },
1497 'extra_sql' => $extra_sql,
1499 warn "Found taxes ". join(',', map {$_->taxnum} @taxes) ."\n"
1505 =item part_pkg_discount
1507 Returns the package to discount m2m records (see L<FS::part_pkg_discount>)
1510 =item part_pkg_usage
1512 Returns the voice usage pools (see L<FS::part_pkg_usage>) defined for
1517 Reblesses the object into the FS::part_pkg::PLAN class (if available), where
1518 PLAN is the object's I<plan> field. There should be better docs
1519 on how to create new price plans, but until then, see L</NEW PLAN CLASSES>.
1525 my $plan = $self->plan;
1527 cluck "no price plan found for pkgpart ". $self->pkgpart. "\n"
1531 return $self if ref($self) =~ /::$plan$/; #already blessed into plan subclass
1532 my $class = ref($self). "::$plan";
1533 warn "reblessing $self into $class" if $DEBUG > 1;
1536 bless($self, $class) unless $@;
1541 sub calc_setup { die 'no calc_setup for '. shift->plan. "\n"; }
1542 sub calc_recur { die 'no calc_recur for '. shift->plan. "\n"; }
1544 #fallback that return 0 for old legacy packages with no plan
1545 sub calc_remain { 0; }
1546 sub calc_units { 0; }
1548 #fallback for everything not based on flat.pm
1549 sub recur_temporality { 'upcoming'; }
1550 sub calc_cancel { 0; }
1552 #fallback for everything except bulk.pm
1553 sub hide_svc_detail { 0; }
1555 #fallback for packages that can't/won't summarize usage
1556 sub sum_usage { 0; }
1558 =item recur_cost_permonth CUST_PKG
1560 recur_cost divided by freq (only supported for monthly and longer frequencies)
1564 sub recur_cost_permonth {
1565 my($self, $cust_pkg) = @_;
1566 return 0 unless $self->freq =~ /^\d+$/ && $self->freq > 0;
1567 sprintf('%.2f', $self->recur_cost / $self->freq );
1570 =item cust_bill_pkg_recur CUST_PKG
1572 Actual recurring charge for the specified customer package from customer's most
1577 sub cust_bill_pkg_recur {
1578 my($self, $cust_pkg) = @_;
1579 my $cust_bill_pkg = qsearchs({
1580 'table' => 'cust_bill_pkg',
1581 'addl_from' => 'LEFT JOIN cust_bill USING ( invnum )',
1582 'hashref' => { 'pkgnum' => $cust_pkg->pkgnum,
1583 'recur' => { op=>'>', value=>'0' },
1585 'order_by' => 'ORDER BY cust_bill._date DESC,
1586 cust_bill_pkg.sdate DESC
1589 }) or return 0; #die "use cust_bill_pkg_recur credits with once_perinv condition";
1590 $cust_bill_pkg->recur;
1593 =item unit_setup CUST_PKG
1595 Returns the setup fee for one unit of the package.
1600 my ($self, $cust_pkg) = @_;
1601 $self->option('setup_fee') || 0;
1606 unit_setup minus setup_cost
1612 $self->unit_setup(@_) - $self->setup_cost;
1615 =item recur_margin_permonth
1617 base_recur_permonth minus recur_cost_permonth
1621 sub recur_margin_permonth {
1623 $self->base_recur_permonth(@_) - $self->recur_cost_permonth(@_);
1626 =item format OPTION DATA
1628 Returns data formatted according to the function 'format' described
1629 in the plan info. Returns DATA if no such function exists.
1634 my ($self, $option, $data) = (shift, shift, shift);
1635 if (exists($plans{$self->plan}->{fields}->{$option}{format})) {
1636 &{$plans{$self->plan}->{fields}->{$option}{format}}($data);
1642 =item parse OPTION DATA
1644 Returns data parsed according to the function 'parse' described
1645 in the plan info. Returns DATA if no such function exists.
1650 my ($self, $option, $data) = (shift, shift, shift);
1651 if (exists($plans{$self->plan}->{fields}->{$option}{parse})) {
1652 &{$plans{$self->plan}->{fields}->{$option}{parse}}($data);
1662 =head1 CLASS METHODS
1670 # Used by FS::Upgrade to migrate to a new database.
1672 sub _upgrade_data { # class method
1673 my($class, %opts) = @_;
1675 warn "[FS::part_pkg] upgrading $class\n" if $DEBUG;
1677 my @part_pkg = qsearch({
1678 'table' => 'part_pkg',
1679 'extra_sql' => "WHERE ". join(' OR ',
1680 'plan IS NULL', "plan = '' ",
1684 foreach my $part_pkg (@part_pkg) {
1686 unless ( $part_pkg->plan ) {
1687 $part_pkg->plan('flat');
1693 # the rest can be done asynchronously
1696 sub queueable_upgrade {
1697 # now upgrade to the explicit custom flag
1699 my $search = FS::Cursor->new({
1700 'table' => 'part_pkg',
1701 'hashref' => { disabled => 'Y', custom => '' },
1702 'extra_sql' => "AND comment LIKE '(CUSTOM) %'",
1706 while (my $part_pkg = $search->fetch) {
1707 my $new = new FS::part_pkg { $part_pkg->hash };
1709 my $comment = $part_pkg->comment;
1710 $comment =~ s/^\(CUSTOM\) //;
1711 $comment = '(none)' unless $comment =~ /\S/;
1712 $new->comment($comment);
1714 my $pkg_svc = { map { $_->svcpart => $_->quantity } $part_pkg->pkg_svc };
1715 my $primary = $part_pkg->svcpart;
1716 my $options = { $part_pkg->options };
1718 my $error = $new->replace( $part_pkg,
1719 'pkg_svc' => $pkg_svc,
1720 'primary_svc' => $primary,
1721 'options' => $options,
1724 warn "pkgpart#".$part_pkg->pkgpart.": $error\n";
1731 # set family_pkgpart on any packages that don't have it
1732 $search = FS::Cursor->new('part_pkg', { 'family_pkgpart' => '' });
1733 while (my $part_pkg = $search->fetch) {
1734 $part_pkg->set('family_pkgpart' => $part_pkg->pkgpart);
1735 my $error = $part_pkg->SUPER::replace;
1737 warn "pkgpart#".$part_pkg->pkgpart.": $error\n";
1744 my @part_pkg_option = qsearch('part_pkg_option',
1745 { 'optionname' => 'unused_credit',
1748 foreach my $old_opt (@part_pkg_option) {
1749 my $pkgpart = $old_opt->pkgpart;
1750 my $error = $old_opt->delete;
1751 die $error if $error;
1753 foreach (qw(unused_credit_cancel unused_credit_change)) {
1754 my $new_opt = new FS::part_pkg_option {
1755 'pkgpart' => $pkgpart,
1759 $error = $new_opt->insert;
1760 die $error if $error;
1764 # migrate use_disposition_taqua and use_disposition to disposition_in
1765 @part_pkg_option = qsearch('part_pkg_option',
1766 { 'optionname' => { op => 'LIKE',
1767 value => 'use_disposition%',
1771 my %newopts = map { $_->pkgpart => $_ }
1772 qsearch('part_pkg_option', { 'optionname' => 'disposition_in', } );
1773 foreach my $old_opt (@part_pkg_option) {
1774 my $pkgpart = $old_opt->pkgpart;
1775 my $newval = $old_opt->optionname eq 'use_disposition_taqua' ? '100'
1777 my $error = $old_opt->delete;
1778 die $error if $error;
1780 if ( exists($newopts{$pkgpart}) ) {
1781 my $opt = $newopts{$pkgpart};
1782 $opt->optionvalue($opt->optionvalue.",$newval");
1783 $error = $opt->replace;
1784 die $error if $error;
1786 my $new_opt = new FS::part_pkg_option {
1787 'pkgpart' => $pkgpart,
1788 'optionname' => 'disposition_in',
1789 'optionvalue' => $newval,
1791 $error = $new_opt->insert;
1792 die $error if $error;
1793 $newopts{$pkgpart} = $new_opt;
1797 # set any package with FCC voice lines to the "VoIP with broadband" category
1798 # for backward compatibility
1800 # recover from a bad upgrade bug
1801 my $upgrade = 'part_pkg_fcc_voip_class_FIX';
1802 if (!FS::upgrade_journal->is_done($upgrade)) {
1803 my $bad_upgrade = qsearchs('upgrade_journal',
1804 { upgrade => 'part_pkg_fcc_voip_class' }
1806 if ( $bad_upgrade ) {
1807 my $where = 'WHERE history_date <= '.$bad_upgrade->_date.
1808 ' AND history_date > '.($bad_upgrade->_date - 3600);
1809 my @h_part_pkg_option = map { FS::part_pkg_option->new($_->hashref) }
1812 'table' => 'h_part_pkg_option',
1814 'extra_sql' => "$where AND history_action = 'delete'",
1815 'order_by' => 'ORDER BY history_date ASC',
1817 my @h_pkg_svc = map { FS::pkg_svc->new($_->hashref) }
1820 'table' => 'h_pkg_svc',
1822 'extra_sql' => "$where AND history_action = 'replace_old'",
1823 'order_by' => 'ORDER BY history_date ASC',
1826 foreach my $deleted (@h_part_pkg_option, @h_pkg_svc) {
1827 my $pkgpart ||= $deleted->pkgpart;
1828 $opt{$pkgpart} ||= {
1834 if ( $deleted->isa('FS::part_pkg_option') ) {
1835 $opt{$pkgpart}{options}{ $deleted->optionname } = $deleted->optionvalue;
1837 my $svcpart = $deleted->svcpart;
1838 $opt{$pkgpart}{pkg_svc}{$svcpart} = $deleted->quantity;
1839 $opt{$pkgpart}{hidden_svc}{$svcpart} ||= $deleted->hidden;
1840 $opt{$pkgpart}{primary_svc} = $svcpart if $deleted->primary_svc;
1843 foreach my $pkgpart (keys %opt) {
1844 my $part_pkg = FS::part_pkg->by_key($pkgpart);
1845 my $error = $part_pkg->replace( $part_pkg->replace_old, $opt{$pkgpart} );
1847 die "error recovering damaged pkgpart $pkgpart:\n$error\n";
1850 } # $bad_upgrade exists
1851 else { # do the original upgrade, but correctly this time
1852 my @part_pkg = qsearch('part_pkg', {
1853 fcc_ds0s => { op => '>', value => 0 },
1854 fcc_voip_class => ''
1856 foreach my $part_pkg (@part_pkg) {
1857 $part_pkg->set(fcc_voip_class => 2);
1858 my @pkg_svc = $part_pkg->pkg_svc;
1859 my %quantity = map {$_->svcpart, $_->quantity} @pkg_svc;
1860 my %hidden = map {$_->svcpart, $_->hidden } @pkg_svc;
1861 my $error = $part_pkg->replace(
1862 $part_pkg->replace_old,
1863 options => { $part_pkg->options },
1864 pkg_svc => \%quantity,
1865 hidden_svc => \%hidden,
1866 primary_svc => ($part_pkg->svcpart || ''),
1868 die $error if $error;
1871 FS::upgrade_journal->set_done($upgrade);
1876 =item curuser_pkgs_sql
1878 Returns an SQL fragment for searching for packages the current user can
1879 use, either via part_pkg.agentnum directly, or via agent type (see
1884 sub curuser_pkgs_sql {
1887 $class->_pkgs_sql( $FS::CurrentUser::CurrentUser->agentnums );
1891 =item agent_pkgs_sql AGENT | AGENTNUM, ...
1893 Returns an SQL fragment for searching for packages the provided agent or agents
1894 can use, either via part_pkg.agentnum directly, or via agent type (see
1899 sub agent_pkgs_sql {
1900 my $class = shift; #i'm a class method, not a sub (the question is... why??)
1901 my @agentnums = map { ref($_) ? $_->agentnum : $_ } @_;
1903 $class->_pkgs_sql(@agentnums); #is this why
1908 my( $class, @agentnums ) = @_;
1909 my $agentnums = join(',', @agentnums);
1913 ( agentnum IS NOT NULL AND agentnum IN ($agentnums) )
1914 OR ( agentnum IS NULL
1915 AND EXISTS ( SELECT 1
1917 LEFT JOIN agent_type USING ( typenum )
1918 LEFT JOIN agent AS typeagent USING ( typenum )
1919 WHERE type_pkgs.pkgpart = part_pkg.pkgpart
1920 AND typeagent.agentnum IN ($agentnums)
1938 #false laziness w/part_export & cdr
1940 foreach my $INC ( @INC ) {
1941 warn "globbing $INC/FS/part_pkg/*.pm\n" if $DEBUG;
1942 foreach my $file ( glob("$INC/FS/part_pkg/*.pm") ) {
1943 warn "attempting to load plan info from $file\n" if $DEBUG;
1944 $file =~ /\/(\w+)\.pm$/ or do {
1945 warn "unrecognized file in $INC/FS/part_pkg/: $file\n";
1949 my $info = eval "use FS::part_pkg::$mod; ".
1950 "\\%FS::part_pkg::$mod\::info;";
1952 die "error using FS::part_pkg::$mod (skipping): $@\n" if $@;
1955 unless ( keys %$info ) {
1956 warn "no %info hash found in FS::part_pkg::$mod, skipping\n";
1959 warn "got plan info from FS::part_pkg::$mod: $info\n" if $DEBUG;
1960 #if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
1961 # warn "skipping disabled plan FS::part_pkg::$mod" if $DEBUG;
1964 $info{$mod} = $info;
1965 $info->{'weight'} ||= 0; # quiet warnings
1969 # copy one level deep to allow replacement of fields and fieldorder
1970 tie %plans, 'Tie::IxHash',
1971 map { my %infohash = %{ $info{$_} };
1973 sort { $info{$a}->{'weight'} <=> $info{$b}->{'weight'} }
1976 # inheritance of plan options
1977 foreach my $name (keys(%info)) {
1978 if (exists($info{$name}->{'disabled'}) and $info{$name}->{'disabled'}) {
1979 warn "skipping disabled plan FS::part_pkg::$name" if $DEBUG;
1980 delete $plans{$name};
1983 my $parents = $info{$name}->{'inherit_fields'} || [];
1984 my (%fields, %field_exists, @fieldorder);
1985 foreach my $parent ($name, @$parents) {
1986 if ( !exists($info{$parent}) ) {
1987 warn "$name tried to inherit from nonexistent '$parent'\n";
1990 %fields = ( # avoid replacing existing fields
1991 %{ $info{$parent}->{'fields'} || {} },
1994 foreach (@{ $info{$parent}->{'fieldorder'} || [] }) {
1996 next if $field_exists{$_};
1997 $field_exists{$_} = 1;
1998 # allow inheritors to remove inherited fields from the fieldorder
1999 push @fieldorder, $_ if !exists($fields{$_}) or
2000 !exists($fields{$_}->{'disabled'});
2003 $plans{$name}->{'fields'} = \%fields;
2004 $plans{$name}->{'fieldorder'} = \@fieldorder;
2014 =head1 NEW PLAN CLASSES
2016 A module should be added in FS/FS/part_pkg/ Eventually, an example may be
2017 found in eg/plan_template.pm. Until then, it is suggested that you use the
2018 other modules in FS/FS/part_pkg/ as a guide.
2022 The delete method is unimplemented.
2024 setup and recur semantics are not yet defined (and are implemented in
2025 FS::cust_bill. hmm.). now they're deprecated and need to go.
2029 part_pkg_taxrate is Pg specific
2031 replace should be smarter about managing the related tables (options, pkg_svc)
2035 L<FS::Record>, L<FS::cust_pkg>, L<FS::type_pkgs>, L<FS::pkg_svc>, L<Safe>.
2036 schema.html from the base documentation.