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 );
18 use FS::part_pkg_option;
19 use FS::part_pkg_msgcat;
20 use FS::part_pkg_taxrate;
21 use FS::part_pkg_taxoverride;
22 use FS::part_pkg_taxproduct;
23 use FS::part_pkg_link;
24 use FS::part_pkg_discount;
25 use FS::part_pkg_vendor;
26 use FS::part_pkg_currency;
30 $skip_pkg_svc_hack = 0;
34 FS::part_pkg - Object methods for part_pkg objects
40 $record = new FS::part_pkg \%hash
41 $record = new FS::part_pkg { 'column' => 'value' };
43 $custom_record = $template_record->clone;
45 $error = $record->insert;
47 $error = $new_record->replace($old_record);
49 $error = $record->delete;
51 $error = $record->check;
53 @pkg_svc = $record->pkg_svc;
55 $svcnum = $record->svcpart;
56 $svcnum = $record->svcpart( 'svc_acct' );
60 An FS::part_pkg object represents a package definition. FS::part_pkg
61 inherits from FS::Record. The following fields are currently supported:
65 =item pkgpart - primary key (assigned automatically for new package definitions)
67 =item pkg - Text name of this package definition (customer-viewable)
69 =item comment - Text name of this package definition (non-customer-viewable)
71 =item classnum - Optional package class (see L<FS::pkg_class>)
73 =item promo_code - Promotional code
75 =item setup - Setup fee expression (deprecated)
77 =item freq - Frequency of recurring fee
79 =item recur - Recurring fee expression (deprecated)
81 =item setuptax - Setup fee tax exempt flag, empty or `Y'
83 =item recurtax - Recurring fee tax exempt flag, empty or `Y'
85 =item taxclass - Tax class
87 =item plan - Price plan
89 =item plandata - Price plan data (deprecated - see L<FS::part_pkg_option> instead)
91 =item disabled - Disabled flag, empty or `Y'
93 =item custom - Custom flag, empty or `Y'
95 =item setup_cost - for cost tracking
97 =item recur_cost - for cost tracking
99 =item pay_weight - Weight (relative to credit_weight and other package definitions) that controls payment application to specific line items.
101 =item credit_weight - Weight (relative to other package definitions) that controls credit application to specific line items.
103 =item agentnum - Optional agentnum (see L<FS::agent>)
105 =item fcc_ds0s - Optional DS0 equivalency number for FCC form 477
107 =item fcc_voip_class - Which column of FCC form 477 part II.B this package
110 =item successor - Foreign key for the part_pkg that replaced this record.
111 If this record is not obsolete, will be null.
113 =item family_pkgpart - Foreign key for the part_pkg that was the earliest
114 ancestor of this record. If this record is not a successor to another
115 part_pkg, will be equal to pkgpart.
117 =item delay_start - Number of days to delay package start, by default
127 Creates a new package definition. To add the package definition to
128 the database, see L<"insert">.
132 sub table { 'part_pkg'; }
136 An alternate constructor. Creates a new package definition by duplicating
137 an existing definition. A new pkgpart is assigned and the custom flag is
138 set to Y. To add the package definition to the database, see L<"insert">.
144 my $class = ref($self);
145 my %hash = $self->hash;
146 $hash{'pkgpart'} = '';
147 $hash{'custom'} = 'Y';
148 #new FS::part_pkg ( \%hash ); # ?
149 new $class ( \%hash ); # ?
152 =item insert [ , OPTION => VALUE ... ]
154 Adds this package definition to the database. If there is an error,
155 returns the error, otherwise returns false.
157 Currently available options are: I<pkg_svc>, I<primary_svc>, I<cust_pkg>,
158 I<custnum_ref> and I<options>.
160 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
161 values, appropriate FS::pkg_svc records will be inserted. I<hidden_svc> can
162 be set to a hashref of svcparts and flag values ('Y' or '') to set the
163 'hidden' field in these records.
165 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
166 FS::pkg_svc record will be updated.
168 If I<cust_pkg> is set to a pkgnum of a FS::cust_pkg record (or the FS::cust_pkg
169 record itself), the object will be updated to point to this package definition.
171 In conjunction with I<cust_pkg>, if I<custnum_ref> is set to a scalar reference,
172 the scalar will be updated with the custnum value from the cust_pkg record.
174 If I<tax_overrides> is set to a hashref with usage classes as keys and comma
175 separated tax class numbers as values, appropriate FS::part_pkg_taxoverride
176 records will be inserted.
178 If I<options> is set to a hashref of options, appropriate FS::part_pkg_option
179 records will be inserted.
181 If I<part_pkg_currency> is set to a hashref of options (with the keys as
182 option_CURRENCY), appropriate FS::part_pkg::currency records will be inserted.
189 warn "FS::part_pkg::insert called on $self with options ".
190 join(', ', map "$_=>$options{$_}", keys %options)
193 local $SIG{HUP} = 'IGNORE';
194 local $SIG{INT} = 'IGNORE';
195 local $SIG{QUIT} = 'IGNORE';
196 local $SIG{TERM} = 'IGNORE';
197 local $SIG{TSTP} = 'IGNORE';
198 local $SIG{PIPE} = 'IGNORE';
200 my $oldAutoCommit = $FS::UID::AutoCommit;
201 local $FS::UID::AutoCommit = 0;
204 warn " inserting part_pkg record" if $DEBUG;
205 my $error = $self->SUPER::insert( $options{options} );
207 $dbh->rollback if $oldAutoCommit;
212 if ( $self->get('family_pkgpart') eq '' ) {
213 $self->set('family_pkgpart' => $self->pkgpart);
214 $error = $self->SUPER::replace;
216 $dbh->rollback if $oldAutoCommit;
221 my $conf = new FS::Conf;
222 if ( $conf->exists('agent_defaultpkg') ) {
223 warn " agent_defaultpkg set; allowing all agents to purchase package"
225 foreach my $agent_type ( qsearch('agent_type', {} ) ) {
226 my $type_pkgs = new FS::type_pkgs({
227 'typenum' => $agent_type->typenum,
228 'pkgpart' => $self->pkgpart,
230 my $error = $type_pkgs->insert;
232 $dbh->rollback if $oldAutoCommit;
238 warn " inserting part_pkg_taxoverride records" if $DEBUG;
239 my %overrides = %{ $options{'tax_overrides'} || {} };
240 foreach my $usage_class ( keys %overrides ) {
242 ( exists($overrides{$usage_class}) && defined($overrides{$usage_class}) )
243 ? $overrides{$usage_class}
245 my @overrides = (grep "$_", split(',', $override) );
246 my $error = $self->process_m2m (
247 'link_table' => 'part_pkg_taxoverride',
248 'target_table' => 'tax_class',
249 'hashref' => { 'usage_class' => $usage_class },
250 'params' => \@overrides,
253 $dbh->rollback if $oldAutoCommit;
258 warn " inserting part_pkg_currency records" if $DEBUG;
259 my %part_pkg_currency = %{ $options{'part_pkg_currency'} || {} };
260 foreach my $key ( keys %part_pkg_currency ) {
261 $key =~ /^(.+)_([A-Z]{3})$/ or next;
262 my( $optionname, $currency ) = ( $1, $2 );
263 if ( $part_pkg_currency{$key} =~ /^\s*$/ ) {
264 if ( $self->option($optionname) == 0 ) {
265 $part_pkg_currency{$key} = '0';
267 $dbh->rollback if $oldAutoCommit;
268 ( my $thing = $optionname ) =~ s/_/ /g;
269 return ucfirst($thing). " $currency is required";
272 my $part_pkg_currency = new FS::part_pkg_currency {
273 'pkgpart' => $self->pkgpart,
274 'optionname' => $optionname,
275 'currency' => $currency,
276 'optionvalue' => $part_pkg_currency{$key},
278 my $error = $part_pkg_currency->insert;
280 $dbh->rollback if $oldAutoCommit;
285 unless ( $skip_pkg_svc_hack ) {
287 warn " inserting pkg_svc records" if $DEBUG;
288 my $pkg_svc = $options{'pkg_svc'} || {};
289 my $hidden_svc = $options{'hidden_svc'} || {};
290 foreach my $part_svc ( qsearch('part_svc', {} ) ) {
291 my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
293 ( $options{'primary_svc'} && $options{'primary_svc'}==$part_svc->svcpart )
297 my $pkg_svc = new FS::pkg_svc( {
298 'pkgpart' => $self->pkgpart,
299 'svcpart' => $part_svc->svcpart,
300 'quantity' => $quantity,
301 'primary_svc' => $primary_svc,
302 'hidden' => $hidden_svc->{$part_svc->svcpart},
304 my $error = $pkg_svc->insert;
306 $dbh->rollback if $oldAutoCommit;
313 if ( $options{'cust_pkg'} ) {
314 warn " updating cust_pkg record " if $DEBUG;
316 ref($options{'cust_pkg'})
317 ? $options{'cust_pkg'}
318 : qsearchs('cust_pkg', { pkgnum => $options{'cust_pkg'} } );
319 ${ $options{'custnum_ref'} } = $old_cust_pkg->custnum
320 if $options{'custnum_ref'};
321 my %hash = $old_cust_pkg->hash;
322 $hash{'pkgpart'} = $self->pkgpart,
323 my $new_cust_pkg = new FS::cust_pkg \%hash;
324 local($FS::cust_pkg::disable_agentcheck) = 1;
325 my $error = $new_cust_pkg->replace($old_cust_pkg);
327 $dbh->rollback if $oldAutoCommit;
328 return "Error modifying cust_pkg record: $error";
332 if ( $options{'part_pkg_vendor'} ) {
333 while ( my ($exportnum, $vendor_pkg_id) =
334 each %{ $options{part_pkg_vendor} }
337 my $ppv = new FS::part_pkg_vendor( {
338 'pkgpart' => $self->pkgpart,
339 'exportnum' => $exportnum,
340 'vendor_pkg_id' => $vendor_pkg_id,
342 my $error = $ppv->insert;
344 $dbh->rollback if $oldAutoCommit;
345 return "Error inserting part_pkg_vendor record: $error";
350 warn " committing transaction" if $DEBUG and $oldAutoCommit;
351 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
358 Currently unimplemented.
363 return "Can't (yet?) delete package definitions.";
364 # check & make sure the pkgpart isn't in cust_pkg or type_pkgs?
367 =item replace OLD_RECORD [ , OPTION => VALUE ... ]
369 Replaces OLD_RECORD with this one in the database. If there is an error,
370 returns the error, otherwise returns false.
372 Currently available options are: I<pkg_svc>, I<hidden_svc>, I<primary_svc>
375 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
376 values, the appropriate FS::pkg_svc records will be replaced. I<hidden_svc>
377 can be set to a hashref of svcparts and flag values ('Y' or '') to set the
378 'hidden' field in these records. I<bulk_skip> can be set to a hashref of
379 svcparts and flag values ('Y' or '') to set the 'bulk_skip' field in those
382 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
383 FS::pkg_svc record will be updated.
385 If I<options> is set to a hashref, the appropriate FS::part_pkg_option records
388 If I<part_pkg_currency> is set to a hashref of options (with the keys as
389 option_CURRENCY), appropriate FS::part_pkg::currency records will be replaced.
396 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
401 ( ref($_[0]) eq 'HASH' )
405 $options->{options} = { $old->options } unless defined($options->{options});
407 warn "FS::part_pkg::replace called on $new to replace $old with options".
408 join(', ', map "$_ => ". $options->{$_}, keys %$options)
411 local $SIG{HUP} = 'IGNORE';
412 local $SIG{INT} = 'IGNORE';
413 local $SIG{QUIT} = 'IGNORE';
414 local $SIG{TERM} = 'IGNORE';
415 local $SIG{TSTP} = 'IGNORE';
416 local $SIG{PIPE} = 'IGNORE';
418 my $oldAutoCommit = $FS::UID::AutoCommit;
419 local $FS::UID::AutoCommit = 0;
422 my $conf = new FS::Conf;
423 if ( $conf->exists('part_pkg-lineage') ) {
424 if ( grep { $options->{options}->{$_} ne $old->option($_, 1) }
425 qw(setup_fee recur_fee) #others? config?
428 warn " superseding package" if $DEBUG;
430 my $error = $new->supersede($old, %$options);
432 $dbh->rollback if $oldAutoCommit;
436 warn " committing transaction" if $DEBUG and $oldAutoCommit;
437 $dbh->commit if $oldAutoCommit;
444 #plandata shit stays in replace for upgrades until after 2.0 (or edit
446 warn " saving legacy plandata" if $DEBUG;
447 my $plandata = $new->get('plandata');
448 $new->set('plandata', '');
450 warn " deleting old part_pkg_option records" if $DEBUG;
451 foreach my $part_pkg_option ( $old->part_pkg_option ) {
452 my $error = $part_pkg_option->delete;
454 $dbh->rollback if $oldAutoCommit;
459 warn " replacing part_pkg record" if $DEBUG;
460 my $error = $new->SUPER::replace($old, $options->{options} );
462 $dbh->rollback if $oldAutoCommit;
466 warn " inserting part_pkg_option records for plandata: $plandata|" if $DEBUG;
467 foreach my $part_pkg_option (
468 map { /^(\w+)=(.*)$/ or do { $dbh->rollback if $oldAutoCommit;
469 return "illegal plandata: $plandata";
471 new FS::part_pkg_option {
472 'pkgpart' => $new->pkgpart,
477 split("\n", $plandata)
479 my $error = $part_pkg_option->insert;
481 $dbh->rollback if $oldAutoCommit;
486 #trivial nit: not the most efficient to delete and reinsert
487 warn " deleting old part_pkg_currency records" if $DEBUG;
488 foreach my $part_pkg_currency ( $old->part_pkg_currency ) {
489 my $error = $part_pkg_currency->delete;
491 $dbh->rollback if $oldAutoCommit;
492 return "error deleting part_pkg_currency record: $error";
496 warn " inserting new part_pkg_currency records" if $DEBUG;
497 my %part_pkg_currency = %{ $options->{'part_pkg_currency'} || {} };
498 foreach my $key ( keys %part_pkg_currency ) {
499 $key =~ /^(.+)_([A-Z]{3})$/ or next;
500 my $part_pkg_currency = new FS::part_pkg_currency {
501 'pkgpart' => $new->pkgpart,
504 'optionvalue' => $part_pkg_currency{$key},
506 my $error = $part_pkg_currency->insert;
508 $dbh->rollback if $oldAutoCommit;
509 return "error inserting part_pkg_currency record: $error";
514 warn " replacing pkg_svc records" if $DEBUG;
515 my $pkg_svc = $options->{'pkg_svc'};
516 my $hidden_svc = $options->{'hidden_svc'} || {};
517 my $bulk_skip = $options->{'bulk_skip'} || {};
518 if ( $pkg_svc ) { # if it wasn't passed, don't change existing pkg_svcs
519 foreach my $part_svc ( qsearch('part_svc', {} ) ) {
520 my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
521 my $hidden = $hidden_svc->{$part_svc->svcpart} || '';
522 my $bulk_skip = $bulk_skip->{$part_svc->svcpart} || '';
524 ( defined($options->{'primary_svc'}) && $options->{'primary_svc'}
525 && $options->{'primary_svc'} == $part_svc->svcpart
530 my $old_pkg_svc = qsearchs('pkg_svc', {
531 'pkgpart' => $old->pkgpart,
532 'svcpart' => $part_svc->svcpart,
535 my $old_quantity = 0;
536 my $old_primary_svc = '';
538 my $old_bulk_skip = '';
539 if ( $old_pkg_svc ) {
540 $old_quantity = $old_pkg_svc->quantity;
541 $old_primary_svc = $old_pkg_svc->primary_svc
542 if $old_pkg_svc->dbdef_table->column('primary_svc'); # is this needed?
543 $old_hidden = $old_pkg_svc->hidden;
544 $old_bulk_skip = $old_pkg_svc->old_bulk_skip;
547 next unless $old_quantity != $quantity
548 || $old_primary_svc ne $primary_svc
549 || $old_hidden ne $hidden
550 || $old_bulk_skip ne $bulk_skip;
552 my $new_pkg_svc = new FS::pkg_svc( {
553 'pkgsvcnum' => ( $old_pkg_svc ? $old_pkg_svc->pkgsvcnum : '' ),
554 'pkgpart' => $new->pkgpart,
555 'svcpart' => $part_svc->svcpart,
556 'quantity' => $quantity,
557 'primary_svc' => $primary_svc,
559 'bulk_skip' => $bulk_skip,
561 my $error = $old_pkg_svc
562 ? $new_pkg_svc->replace($old_pkg_svc)
563 : $new_pkg_svc->insert;
565 $dbh->rollback if $oldAutoCommit;
569 } #if $options->{pkg_svc}
571 my @part_pkg_vendor = $old->part_pkg_vendor;
572 my @current_exportnum = ();
573 if ( $options->{'part_pkg_vendor'} ) {
574 my($exportnum,$vendor_pkg_id);
575 while ( ($exportnum,$vendor_pkg_id)
576 = each %{$options->{'part_pkg_vendor'}} ) {
578 foreach my $part_pkg_vendor ( @part_pkg_vendor ) {
579 if($exportnum == $part_pkg_vendor->exportnum
580 && $vendor_pkg_id ne $part_pkg_vendor->vendor_pkg_id) {
581 $part_pkg_vendor->vendor_pkg_id($vendor_pkg_id);
582 my $error = $part_pkg_vendor->replace;
584 $dbh->rollback if $oldAutoCommit;
585 return "Error replacing part_pkg_vendor record: $error";
590 elsif($exportnum == $part_pkg_vendor->exportnum
591 && $vendor_pkg_id eq $part_pkg_vendor->vendor_pkg_id) {
596 unless ( $noinsert ) {
597 my $ppv = new FS::part_pkg_vendor( {
598 'pkgpart' => $new->pkgpart,
599 'exportnum' => $exportnum,
600 'vendor_pkg_id' => $vendor_pkg_id,
602 my $error = $ppv->insert;
604 $dbh->rollback if $oldAutoCommit;
605 return "Error inserting part_pkg_vendor record: $error";
608 push @current_exportnum, $exportnum;
611 foreach my $part_pkg_vendor ( @part_pkg_vendor ) {
612 unless ( grep($_ eq $part_pkg_vendor->exportnum, @current_exportnum) ) {
613 my $error = $part_pkg_vendor->delete;
615 $dbh->rollback if $oldAutoCommit;
616 return "Error deleting part_pkg_vendor record: $error";
621 # propagate changes to certain core fields
622 if ( $conf->exists('part_pkg-lineage') ) {
623 warn " propagating changes to family" if $DEBUG;
624 my $error = $new->propagate($old);
626 $dbh->rollback if $oldAutoCommit;
631 warn " committing transaction" if $DEBUG and $oldAutoCommit;
632 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
638 Checks all fields to make sure this is a valid package definition. If
639 there is an error, returns the error, otherwise returns false. Called by the
640 insert and replace methods.
646 warn "FS::part_pkg::check called on $self" if $DEBUG;
648 for (qw(setup recur plandata)) {
649 #$self->set($_=>0) if $self->get($_) =~ /^\s*$/; }
650 return "Use of $_ field is deprecated; set a plan and options: ".
652 if length($self->get($_));
656 if ( $self->dbdef_table->column('freq')->type =~ /(int)/i ) {
657 my $error = $self->ut_number('freq');
658 return $error if $error;
660 $self->freq =~ /^(\d+[hdw]?)$/
661 or return "Illegal or empty freq: ". $self->freq;
665 my @null_agentnum_right = ( 'Edit global package definitions' );
666 push @null_agentnum_right, 'One-time charge'
667 if $self->freq =~ /^0/;
668 push @null_agentnum_right, 'Customize customer package'
669 if $self->disabled eq 'Y'; #good enough
671 my $error = $self->ut_numbern('pkgpart')
672 || $self->ut_text('pkg')
673 || $self->ut_textn('comment')
674 || $self->ut_textn('promo_code')
675 || $self->ut_alphan('plan')
676 || $self->ut_enum('setuptax', [ '', 'Y' ] )
677 || $self->ut_enum('recurtax', [ '', 'Y' ] )
678 || $self->ut_textn('taxclass')
679 || $self->ut_enum('disabled', [ '', 'Y' ] )
680 || $self->ut_enum('custom', [ '', 'Y' ] )
681 || $self->ut_enum('no_auto', [ '', 'Y' ])
682 || $self->ut_enum('recur_show_zero', [ '', 'Y' ])
683 || $self->ut_enum('setup_show_zero', [ '', 'Y' ])
684 #|| $self->ut_moneyn('setup_cost')
685 #|| $self->ut_moneyn('recur_cost')
686 || $self->ut_floatn('setup_cost')
687 || $self->ut_floatn('recur_cost')
688 || $self->ut_floatn('pay_weight')
689 || $self->ut_floatn('credit_weight')
690 || $self->ut_numbern('taxproductnum')
691 || $self->ut_foreign_keyn('classnum', 'pkg_class', 'classnum')
692 || $self->ut_foreign_keyn('addon_classnum', 'pkg_class', 'classnum')
693 || $self->ut_foreign_keyn('taxproductnum',
694 'part_pkg_taxproduct',
698 ? $self->ut_foreign_keyn('agentnum', 'agent', 'agentnum' )
699 : $self->ut_agentnum_acl('agentnum', \@null_agentnum_right)
701 || $self->ut_numbern('fcc_ds0s')
702 || $self->ut_numbern('fcc_voip_class')
703 || $self->ut_numbern('delay_start')
704 || $self->ut_foreign_keyn('successor', 'part_pkg', 'pkgpart')
705 || $self->ut_foreign_keyn('family_pkgpart', 'part_pkg', 'pkgpart')
706 || $self->SUPER::check
708 return $error if $error;
710 return 'Unknown plan '. $self->plan
711 unless exists($plans{$self->plan});
713 my $conf = new FS::Conf;
714 return 'Taxclass is required'
715 if ! $self->taxclass && $conf->exists('require_taxclasses');
720 =item supersede OLD [, OPTION => VALUE ... ]
722 Inserts this package as a successor to the package OLD. All options are as
723 for C<insert>. After inserting, disables OLD and sets the new package as its
729 my ($new, $old, %options) = @_;
732 $new->set('pkgpart' => '');
733 $new->set('family_pkgpart' => $old->family_pkgpart);
734 warn " inserting successor package\n" if $DEBUG;
735 $error = $new->insert(%options);
736 return $error if $error;
738 warn " disabling superseded package\n" if $DEBUG;
739 $old->set('successor' => $new->pkgpart);
740 $old->set('disabled' => 'Y');
741 $error = $old->SUPER::replace; # don't change its options/pkg_svc records
742 return $error if $error;
744 warn " propagating changes to family" if $DEBUG;
745 $new->propagate($old);
750 If any of certain fields have changed from OLD to this package, then,
751 for all packages in the same lineage as this one, sets those fields
752 to their values in this package.
756 my @propagate_fields = (
757 qw( pkg classnum setup_cost recur_cost taxclass
758 setuptax recurtax pay_weight credit_weight
766 map { $_ => $new->get($_) }
767 grep { $new->get($_) ne $old->get($_) }
771 my @part_pkg = qsearch('part_pkg', {
772 'family_pkgpart' => $new->family_pkgpart
775 foreach my $part_pkg ( @part_pkg ) {
776 my $pkgpart = $part_pkg->pkgpart;
777 next if $pkgpart == $new->pkgpart; # don't modify $new
778 warn " propagating to pkgpart $pkgpart\n" if $DEBUG;
779 foreach ( keys %fields ) {
780 $part_pkg->set($_, $fields{$_});
782 # SUPER::replace to avoid changing non-core fields
783 my $error = $part_pkg->SUPER::replace;
784 push @error, "pkgpart $pkgpart: $error"
790 =item pkg_locale LOCALE
792 Returns a customer-viewable string representing this package for the given
793 locale, from the part_pkg_msgcat table. If the given locale is empty or no
794 localized string is found, returns the base pkg field.
799 my( $self, $locale ) = @_;
800 return $self->pkg unless $locale;
801 my $part_pkg_msgcat = $self->part_pkg_msgcat($locale) or return $self->pkg;
802 $part_pkg_msgcat->pkg;
805 =item part_pkg_msgcat LOCALE
807 Like pkg_locale, but returns the FS::part_pkg_msgcat object itself.
811 sub part_pkg_msgcat {
812 my( $self, $locale ) = @_;
813 qsearchs( 'part_pkg_msgcat', {
814 pkgpart => $self->pkgpart,
819 =item pkg_comment [ OPTION => VALUE... ]
821 Returns an (internal) string representing this package. Currently,
822 "pkgpart: pkg - comment", is returned. "pkg - comment" may be returned in the
823 future, omitting pkgpart. The comment will have '(CUSTOM) ' prepended if
826 If the option nopkgpart is true then the "pkgpart: ' is omitted.
834 #$self->pkg. ' - '. $self->comment;
835 #$self->pkg. ' ('. $self->comment. ')';
836 my $pre = $opt{nopkgpart} ? '' : $self->pkgpart. ': ';
837 my $custom_comment = $self->custom_comment(%opt);
838 $pre. $self->pkg. ( $custom_comment ? " - $custom_comment" : '' );
841 sub price_info { # safety, in case a part_pkg hasn't defined price_info
847 my $price_info = $self->price_info(@_);
848 ( $self->custom ? '(CUSTOM) ' : '' ).
850 ( ($self->custom || $self->comment) ? ' - ' : '' ).
851 ($price_info || 'No charge');
856 $self->pkg. ' - '. ($self->price_info || 'No charge');
861 Returns the package class, as an FS::pkg_class object, or the empty string
862 if there is no package class.
864 =item addon_pkg_class
866 Returns the add-on package class, as an FS::pkg_class object, or the empty
867 string if there is no add-on package class.
871 sub addon_pkg_class {
873 if ( $self->addon_classnum ) {
874 qsearchs('pkg_class', { 'classnum' => $self->addon_classnum } );
882 Returns the package category name, or the empty string if there is no package
889 my $pkg_class = $self->pkg_class;
891 ? $pkg_class->categoryname
897 Returns the package class name, or the empty string if there is no package
904 my $pkg_class = $self->pkg_class;
906 ? $pkg_class->classname
910 =item addon_classname
912 Returns the add-on package class name, or the empty string if there is no
913 add-on package class.
917 sub addon_classname {
919 my $pkg_class = $self->addon_pkg_class;
921 ? $pkg_class->classname
927 Returns the associated agent for this event, if any, as an FS::agent object.
929 =item pkg_svc [ HASHREF | OPTION => VALUE ]
931 Returns all FS::pkg_svc objects (see L<FS::pkg_svc>) for this package
932 definition (with non-zero quantity).
934 One option is available, I<disable_linked>. If set true it will return the
935 services for this package definition alone, omitting services from any add-on
942 Returns all FS::type_pkgs objects (see L<FS::type_pkgs>) for this package
950 # #sort { $b->primary cmp $a->primary }
951 # grep { $_->quantity }
952 # qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
954 my $opt = ref($_[0]) ? $_[0] : { @_ };
955 my %pkg_svc = map { $_->svcpart => $_ }
956 grep { $_->quantity }
957 qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
959 unless ( $opt->{disable_linked} ) {
960 foreach my $dst_pkg ( map $_->dst_pkg, $self->svc_part_pkg_link ) {
961 my @pkg_svc = grep { $_->quantity }
962 qsearch( 'pkg_svc', { pkgpart=>$dst_pkg->pkgpart } );
963 foreach my $pkg_svc ( @pkg_svc ) {
964 if ( $pkg_svc{$pkg_svc->svcpart} ) {
965 my $quantity = $pkg_svc{$pkg_svc->svcpart}->quantity;
966 $pkg_svc{$pkg_svc->svcpart}->quantity($quantity + $pkg_svc->quantity);
968 $pkg_svc{$pkg_svc->svcpart} = $pkg_svc;
978 =item svcpart [ SVCDB ]
980 Returns the svcpart of the primary service definition (see L<FS::part_svc>)
981 associated with this package definition (see L<FS::pkg_svc>). Returns
982 false if there not a primary service definition or exactly one service
983 definition with quantity 1, or if SVCDB is specified and does not match the
984 svcdb of the service definition. SVCDB can be specified as a scalar table
985 name, such as 'svc_acct', or as an arrayref of possible table names.
990 my $pkg_svc = shift->_primary_pkg_svc(@_);
991 $pkg_svc ? $pkg_svc->svcpart : '';
994 =item part_svc [ SVCDB ]
996 Like the B<svcpart> method, but returns the FS::part_svc object (see
1002 my $pkg_svc = shift->_primary_pkg_svc(@_);
1003 $pkg_svc ? $pkg_svc->part_svc : '';
1006 sub _primary_pkg_svc {
1009 my $svcdb = scalar(@_) ? shift : [];
1010 $svcdb = ref($svcdb) ? $svcdb : [ $svcdb ];
1011 my %svcdb = map { $_=>1 } @$svcdb;
1014 grep { !scalar(@$svcdb) || $svcdb{ $_->part_svc->svcdb } }
1017 my @pkg_svc = grep { $_->primary_svc =~ /^Y/i } @svcdb_pkg_svc;
1018 @pkg_svc = grep {$_->quantity == 1 } @svcdb_pkg_svc
1020 return '' if scalar(@pkg_svc) != 1;
1024 =item svcpart_unique_svcdb SVCDB
1026 Returns the svcpart of a service definition (see L<FS::part_svc>) matching
1027 SVCDB associated with this package definition (see L<FS::pkg_svc>). Returns
1028 false if there not a primary service definition for SVCDB or there are multiple
1029 service definitions for SVCDB.
1033 sub svcpart_unique_svcdb {
1034 my( $self, $svcdb ) = @_;
1035 my @svcdb_pkg_svc = grep { ( $svcdb eq $_->part_svc->svcdb ) } $self->pkg_svc;
1036 return '' if scalar(@svcdb_pkg_svc) != 1;
1037 $svcdb_pkg_svc[0]->svcpart;
1042 Returns a list of the acceptable payment types for this package. Eventually
1043 this should come out of a database table and be editable, but currently has the
1044 following logic instead:
1046 If the package is free, the single item B<BILL> is
1047 returned, otherwise, the single item B<CARD> is returned.
1049 (CHEK? LEC? Probably shouldn't accept those by default, prone to abuse)
1055 if ( $self->is_free ) {
1064 Returns true if this package is free.
1070 if ( $self->can('is_free_options') ) {
1071 not grep { $_ !~ /^\s*0*(\.0*)?\s*$/ }
1072 map { $self->option($_) }
1073 $self->is_free_options;
1075 warn "FS::part_pkg::is_free: FS::part_pkg::". $self->plan. " subclass ".
1076 "provides neither is_free_options nor is_free method; returning false";
1081 # whether the plan allows discounts to be applied to this package
1082 sub can_discount { 0; }
1084 # whether the plan allows changing the start date
1085 sub can_start_date { 1; }
1087 # whether the plan supports part_pkg_usageprice add-ons (a specific kind of
1088 # pre-selectable usage pricing, there's others this doesn't refer to)
1089 sub can_usageprice { 0; }
1091 # the delay start date if present
1092 sub delay_start_date {
1095 my $delay = $self->delay_start or return '';
1097 # avoid timelocal silliness
1098 my $dt = DateTime->today(time_zone => 'local');
1099 $dt->add(days => $delay);
1103 sub can_currency_exchange { 0; }
1106 # moved to FS::Misc to make this accessible to other packages
1108 FS::Misc::pkg_freqs();
1113 Returns an english representation of the I<freq> field, such as "monthly",
1114 "weekly", "semi-annually", etc.
1120 my $freq = $self->freq;
1122 #my $freqs_href = $self->freqs_href;
1123 my $freqs_href = freqs_href();
1125 if ( exists($freqs_href->{$freq}) ) {
1126 $freqs_href->{$freq};
1128 my $interval = 'month';
1129 if ( $freq =~ /^(\d+)([hdw])$/ ) {
1130 my %interval = ( 'h' => 'hour', 'd'=>'day', 'w'=>'week' );
1131 $interval = $interval{$2};
1136 "every $freq ${interval}s";
1141 =item add_freq TIMESTAMP [ FREQ ]
1143 Adds a billing period of some frequency to the provided timestamp and
1144 returns the resulting timestamp, or -1 if the frequency could not be
1145 parsed (shouldn't happen). By default, the frequency of this package
1146 will be used; to override this, pass a different frequency as a second
1152 my( $self, $date, $freq ) = @_;
1153 $freq = $self->freq unless $freq;
1155 #change this bit to use Date::Manip? CAREFUL with timezones (see
1156 # mailing list archive)
1157 my ($sec,$min,$hour,$mday,$mon,$year) = (localtime($date) )[0,1,2,3,4,5];
1159 if ( $freq =~ /^\d+$/ ) {
1161 until ( $mon < 12 ) { $mon -= 12; $year++; }
1163 $mday = 28 if $mday > 28 && FS::Conf->new->exists('anniversary-rollback');
1165 } elsif ( $freq =~ /^(\d+)w$/ ) {
1167 $mday += $weeks * 7;
1168 } elsif ( $freq =~ /^(\d+)d$/ ) {
1171 } elsif ( $freq =~ /^(\d+)h$/ ) {
1178 timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year);
1183 For backwards compatibility, returns the plandata field as well as all options
1184 from FS::part_pkg_option.
1190 carp "plandata is deprecated";
1192 $self->SUPER::plandata(@_);
1194 my $plandata = $self->get('plandata');
1195 my %options = $self->options;
1196 $plandata .= join('', map { "$_=$options{$_}\n" } keys %options );
1201 =item part_pkg_vendor
1203 Returns all vendor/external package ids as FS::part_pkg_vendor objects (see
1204 L<FS::part_pkg_vendor>).
1206 =item vendor_pkg_ids
1208 Returns a list of vendor/external package ids by exportnum
1212 sub vendor_pkg_ids {
1214 map { $_->exportnum => $_->vendor_pkg_id } $self->part_pkg_vendor;
1217 =item part_pkg_option
1219 Returns all options as FS::part_pkg_option objects (see
1220 L<FS::part_pkg_option>).
1224 Returns a list of option names and values suitable for assigning to a hash.
1230 map { $_->optionname => $_->optionvalue } $self->part_pkg_option;
1233 =item option OPTIONNAME [ QUIET ]
1235 Returns the option value for the given name, or the empty string. If a true
1236 value is passed as the second argument, warnings about missing the option
1242 my( $self, $opt, $ornull ) = @_;
1243 my $part_pkg_option =
1244 qsearchs('part_pkg_option', {
1245 pkgpart => $self->pkgpart,
1248 return $part_pkg_option->optionvalue if $part_pkg_option;
1249 my %plandata = map { /^(\w+)=(.*)$/; ( $1 => $2 ); }
1250 split("\n", $self->get('plandata') );
1251 return $plandata{$opt} if exists $plandata{$opt};
1252 cluck "WARNING: (pkgpart ". $self->pkgpart. ") Package def option $opt ".
1253 "not found in options or plandata!\n"
1258 =item part_pkg_currency [ CURRENCY ]
1260 Returns all currency options as FS::part_pkg_currency objects (see
1261 L<FS::part_pkg_currency>), or, if a currency is specified, only return the
1262 objects for that currency.
1266 sub part_pkg_currency {
1268 my %hash = ( 'pkgpart' => $self->pkgpart );
1269 $hash{'currency'} = shift if @_;
1270 qsearch('part_pkg_currency', \%hash );
1273 =item part_pkg_currency_options CURRENCY
1275 Returns a list of option names and values from FS::part_pkg_currency for the
1280 sub part_pkg_currency_options {
1282 map { $_->optionname => $_->optionvalue } $self->part_pkg_currency(shift);
1285 =item part_pkg_currency_option CURRENCY OPTIONNAME
1287 Returns the option value for the given name and currency.
1291 sub part_pkg_currency_option {
1292 my( $self, $currency, $optionname ) = @_;
1293 my $part_pkg_currency =
1294 qsearchs('part_pkg_currency', { 'pkgpart' => $self->pkgpart,
1295 'currency' => $currency,
1296 'optionname' => $optionname,
1299 #fatal if not found? that works for our use cases from
1300 #part_pkg/currency_fixed, but isn't how we would typically/expect the method
1301 #to behave. have to catch it there if we change it here...
1302 or die "Unknown price for ". $self->pkg_comment. " in $currency\n";
1304 $part_pkg_currency->optionvalue;
1307 =item bill_part_pkg_link
1309 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
1313 sub bill_part_pkg_link {
1314 shift->_part_pkg_link('bill', @_);
1317 =item svc_part_pkg_link
1319 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
1323 sub svc_part_pkg_link {
1324 shift->_part_pkg_link('svc', @_);
1327 =item supp_part_pkg_link
1329 Returns the associated part_pkg_link records of type 'supp' (supplemental
1334 sub supp_part_pkg_link {
1335 shift->_part_pkg_link('supp', @_);
1338 sub _part_pkg_link {
1339 my( $self, $type ) = @_;
1340 qsearch({ table => 'part_pkg_link',
1341 hashref => { 'src_pkgpart' => $self->pkgpart,
1342 'link_type' => $type,
1343 #protection against infinite recursive links
1344 'dst_pkgpart' => { op=>'!=', value=> $self->pkgpart },
1346 order_by => "ORDER BY hidden",
1350 sub self_and_bill_linked {
1351 shift->_self_and_linked('bill', @_);
1354 sub self_and_svc_linked {
1355 shift->_self_and_linked('svc', @_);
1358 sub _self_and_linked {
1359 my( $self, $type, $hidden ) = @_;
1363 foreach ( ( $self, map { $_->dst_pkg->_self_and_linked($type, $_->hidden) }
1364 $self->_part_pkg_link($type) ) )
1366 $_->hidden($hidden) if $hidden;
1373 =item part_pkg_taxoverride [ CLASS ]
1375 Returns all associated FS::part_pkg_taxoverride objects (see
1376 L<FS::part_pkg_taxoverride>). Limits the returned set to those
1377 of class CLASS if defined. Class may be one of 'setup', 'recur',
1378 the empty string (default), or a usage class number (see L<FS::usage_class>).
1379 When a class is specified, the empty string class (default) is returned
1380 if no more specific values exist.
1384 sub part_pkg_taxoverride {
1388 my $hashref = { 'pkgpart' => $self->pkgpart };
1389 $hashref->{'usage_class'} = $class if defined($class);
1390 my @overrides = qsearch('part_pkg_taxoverride', $hashref );
1392 unless ( scalar(@overrides) || !defined($class) || !$class ){
1393 $hashref->{'usage_class'} = '';
1394 @overrides = qsearch('part_pkg_taxoverride', $hashref );
1400 =item has_taxproduct
1402 Returns true if this package has any taxproduct associated with it.
1406 sub has_taxproduct {
1409 $self->taxproductnum ||
1410 scalar( grep { $_ =~/^usage_taxproductnum_/ && $self->option($_) }
1411 keys %{ {$self->options} }
1417 =item taxproduct [ CLASS ]
1419 Returns the associated tax product for this package definition (see
1420 L<FS::part_pkg_taxproduct>). CLASS may be one of 'setup', 'recur' or
1421 the usage classnum (see L<FS::usage_class>). Returns the default
1422 tax product for this record if the more specific CLASS value does
1431 my $part_pkg_taxproduct;
1433 my $taxproductnum = $self->taxproductnum;
1435 my $class_taxproductnum = $self->option("usage_taxproductnum_$class", 1);
1436 $taxproductnum = $class_taxproductnum
1437 if $class_taxproductnum
1440 $part_pkg_taxproduct =
1441 qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
1443 unless ($part_pkg_taxproduct || $taxproductnum eq $self->taxproductnum ) {
1444 $taxproductnum = $self->taxproductnum;
1445 $part_pkg_taxproduct =
1446 qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
1449 $part_pkg_taxproduct;
1452 =item taxproduct_description [ CLASS ]
1454 Returns the description of the associated tax product for this package
1455 definition (see L<FS::part_pkg_taxproduct>).
1459 sub taxproduct_description {
1461 my $part_pkg_taxproduct = $self->taxproduct(@_);
1462 $part_pkg_taxproduct ? $part_pkg_taxproduct->description : '';
1465 =item part_pkg_taxrate DATA_PROVIDER, GEOCODE, [ CLASS ]
1467 Returns the package to taxrate m2m records for this package in the location
1468 specified by GEOCODE (see L<FS::part_pkg_taxrate>) and usage class CLASS.
1469 CLASS may be one of 'setup', 'recur', or one of the usage classes numbers
1470 (see L<FS::usage_class>).
1474 sub _expand_cch_taxproductnum {
1477 my $part_pkg_taxproduct = $self->taxproduct($class);
1479 my ($a,$b,$c,$d) = ( $part_pkg_taxproduct
1480 ? ( split ':', $part_pkg_taxproduct->taxproduct )
1483 $a = '' unless $a; $b = '' unless $b; $c = '' unless $c; $d = '' unless $d;
1484 my $extra_sql = "AND ( taxproduct = '$a:$b:$c:$d'
1485 OR taxproduct = '$a:$b:$c:'
1486 OR taxproduct = '$a:$b:".":$d'
1487 OR taxproduct = '$a:$b:".":' )";
1488 map { $_->taxproductnum } qsearch( { 'table' => 'part_pkg_taxproduct',
1489 'hashref' => { 'data_vendor'=>'cch' },
1490 'extra_sql' => $extra_sql,
1495 sub part_pkg_taxrate {
1497 my ($data_vendor, $geocode, $class) = @_;
1500 my $extra_sql = 'WHERE part_pkg_taxproduct.data_vendor = '.
1501 dbh->quote($data_vendor);
1503 # CCH oddness in m2m
1504 $extra_sql .= ' AND ('.
1505 join(' OR ', map{ 'geocode = '. $dbh->quote(substr($geocode, 0, $_)) }
1509 # much more CCH oddness in m2m -- this is kludgy
1510 my @tpnums = $self->_expand_cch_taxproductnum($class);
1511 if (scalar(@tpnums)) {
1512 $extra_sql .= ' AND ('.
1513 join(' OR ', map{ "taxproductnum = $_" } @tpnums ).
1516 $extra_sql .= ' AND ( 0 = 1 )';
1519 my $addl_from = 'LEFT JOIN part_pkg_taxproduct USING ( taxproductnum )';
1520 my $order_by = 'ORDER BY taxclassnum, length(geocode) desc, length(taxproduct) desc';
1521 my $select = 'DISTINCT ON(taxclassnum) *, taxproduct';
1523 # should qsearch preface columns with the table to facilitate joins?
1524 qsearch( { 'table' => 'part_pkg_taxrate',
1525 'select' => $select,
1526 'hashref' => { # 'data_vendor' => $data_vendor,
1527 # 'taxproductnum' => $self->taxproductnum,
1529 'addl_from' => $addl_from,
1530 'extra_sql' => $extra_sql,
1531 'order_by' => $order_by,
1535 =item part_pkg_discount
1537 Returns the package to discount m2m records (see L<FS::part_pkg_discount>)
1540 =item part_pkg_usage
1542 Returns the voice usage pools (see L<FS::part_pkg_usage>) defined for
1547 Reblesses the object into the FS::part_pkg::PLAN class (if available), where
1548 PLAN is the object's I<plan> field. There should be better docs
1549 on how to create new price plans, but until then, see L</NEW PLAN CLASSES>.
1555 my $plan = $self->plan;
1557 cluck "no price plan found for pkgpart ". $self->pkgpart. "\n"
1561 return $self if ref($self) =~ /::$plan$/; #already blessed into plan subclass
1562 my $class = ref($self). "::$plan";
1563 warn "reblessing $self into $class" if $DEBUG > 1;
1566 bless($self, $class) unless $@;
1571 sub calc_setup { die 'no calc_setup for '. shift->plan. "\n"; }
1572 sub calc_recur { die 'no calc_recur for '. shift->plan. "\n"; }
1574 #fallback that return 0 for old legacy packages with no plan
1575 sub calc_remain { 0; }
1576 sub calc_units { 0; }
1578 #fallback for everything not based on flat.pm
1579 sub recur_temporality { 'upcoming'; }
1580 sub calc_cancel { 0; }
1582 #fallback for everything except bulk.pm
1583 sub hide_svc_detail { 0; }
1585 #fallback for packages that can't/won't summarize usage
1586 sub sum_usage { 0; }
1588 =item recur_cost_permonth CUST_PKG
1590 recur_cost divided by freq (only supported for monthly and longer frequencies)
1594 sub recur_cost_permonth {
1595 my($self, $cust_pkg) = @_;
1596 return 0 unless $self->freq =~ /^\d+$/ && $self->freq > 0;
1597 sprintf('%.2f', $self->recur_cost / $self->freq );
1600 =item cust_bill_pkg_recur CUST_PKG
1602 Actual recurring charge for the specified customer package from customer's most
1607 sub cust_bill_pkg_recur {
1608 my($self, $cust_pkg) = @_;
1609 my $cust_bill_pkg = qsearchs({
1610 'table' => 'cust_bill_pkg',
1611 'addl_from' => 'LEFT JOIN cust_bill USING ( invnum )',
1612 'hashref' => { 'pkgnum' => $cust_pkg->pkgnum,
1613 'recur' => { op=>'>', value=>'0' },
1615 'order_by' => 'ORDER BY cust_bill._date DESC,
1616 cust_bill_pkg.sdate DESC
1619 }) or return 0; #die "use cust_bill_pkg_recur credits with once_perinv condition";
1620 $cust_bill_pkg->recur;
1623 =item unit_setup CUST_PKG
1625 Returns the setup fee for one unit of the package.
1630 my ($self, $cust_pkg) = @_;
1631 $self->option('setup_fee') || 0;
1634 =item format OPTION DATA
1636 Returns data formatted according to the function 'format' described
1637 in the plan info. Returns DATA if no such function exists.
1642 my ($self, $option, $data) = (shift, shift, shift);
1643 if (exists($plans{$self->plan}->{fields}->{$option}{format})) {
1644 &{$plans{$self->plan}->{fields}->{$option}{format}}($data);
1650 =item parse OPTION DATA
1652 Returns data parsed according to the function 'parse' described
1653 in the plan info. Returns DATA if no such function exists.
1658 my ($self, $option, $data) = (shift, shift, shift);
1659 if (exists($plans{$self->plan}->{fields}->{$option}{parse})) {
1660 &{$plans{$self->plan}->{fields}->{$option}{parse}}($data);
1670 =head1 CLASS METHODS
1678 # Used by FS::Upgrade to migrate to a new database.
1680 sub _upgrade_data { # class method
1681 my($class, %opts) = @_;
1683 warn "[FS::part_pkg] upgrading $class\n" if $DEBUG;
1685 my @part_pkg = qsearch({
1686 'table' => 'part_pkg',
1687 'extra_sql' => "WHERE ". join(' OR ',
1688 'plan IS NULL', "plan = '' ",
1692 foreach my $part_pkg (@part_pkg) {
1694 unless ( $part_pkg->plan ) {
1695 $part_pkg->plan('flat');
1702 # now upgrade to the explicit custom flag
1704 @part_pkg = qsearch({
1705 'table' => 'part_pkg',
1706 'hashref' => { disabled => 'Y', custom => '' },
1707 'extra_sql' => "AND comment LIKE '(CUSTOM) %'",
1710 foreach my $part_pkg (@part_pkg) {
1711 my $new = new FS::part_pkg { $part_pkg->hash };
1713 my $comment = $part_pkg->comment;
1714 $comment =~ s/^\(CUSTOM\) //;
1715 $comment = '(none)' unless $comment =~ /\S/;
1716 $new->comment($comment);
1718 my $pkg_svc = { map { $_->svcpart => $_->quantity } $part_pkg->pkg_svc };
1719 my $primary = $part_pkg->svcpart;
1720 my $options = { $part_pkg->options };
1722 my $error = $new->replace( $part_pkg,
1723 'pkg_svc' => $pkg_svc,
1724 'primary_svc' => $primary,
1725 'options' => $options,
1727 die $error if $error;
1730 # set family_pkgpart on any packages that don't have it
1731 @part_pkg = qsearch('part_pkg', { 'family_pkgpart' => '' });
1732 foreach my $part_pkg (@part_pkg) {
1733 $part_pkg->set('family_pkgpart' => $part_pkg->pkgpart);
1734 my $error = $part_pkg->SUPER::replace;
1735 die $error if $error;
1738 my @part_pkg_option = qsearch('part_pkg_option',
1739 { 'optionname' => 'unused_credit',
1742 foreach my $old_opt (@part_pkg_option) {
1743 my $pkgpart = $old_opt->pkgpart;
1744 my $error = $old_opt->delete;
1745 die $error if $error;
1747 foreach (qw(unused_credit_cancel unused_credit_change)) {
1748 my $new_opt = new FS::part_pkg_option {
1749 'pkgpart' => $pkgpart,
1753 $error = $new_opt->insert;
1754 die $error if $error;
1758 # migrate use_disposition_taqua and use_disposition to disposition_in
1759 @part_pkg_option = qsearch('part_pkg_option',
1760 { 'optionname' => { op => 'LIKE',
1761 value => 'use_disposition%',
1765 my %newopts = map { $_->pkgpart => $_ }
1766 qsearch('part_pkg_option', { 'optionname' => 'disposition_in', } );
1767 foreach my $old_opt (@part_pkg_option) {
1768 my $pkgpart = $old_opt->pkgpart;
1769 my $newval = $old_opt->optionname eq 'use_disposition_taqua' ? '100'
1771 my $error = $old_opt->delete;
1772 die $error if $error;
1774 if ( exists($newopts{$pkgpart}) ) {
1775 my $opt = $newopts{$pkgpart};
1776 $opt->optionvalue($opt->optionvalue.",$newval");
1777 $error = $opt->replace;
1778 die $error if $error;
1780 my $new_opt = new FS::part_pkg_option {
1781 'pkgpart' => $pkgpart,
1782 'optionname' => 'disposition_in',
1783 'optionvalue' => $newval,
1785 $error = $new_opt->insert;
1786 die $error if $error;
1787 $newopts{$pkgpart} = $new_opt;
1791 # set any package with FCC voice lines to the "VoIP with broadband" category
1792 # for backward compatibility
1794 # recover from a bad upgrade bug
1795 my $upgrade = 'part_pkg_fcc_voip_class_FIX';
1796 if (!FS::upgrade_journal->is_done($upgrade)) {
1797 my $bad_upgrade = qsearchs('upgrade_journal',
1798 { upgrade => 'part_pkg_fcc_voip_class' }
1800 if ( $bad_upgrade ) {
1801 my $where = 'WHERE history_date <= '.$bad_upgrade->_date.
1802 ' AND history_date > '.($bad_upgrade->_date - 3600);
1803 my @h_part_pkg_option = map { FS::part_pkg_option->new($_->hashref) }
1806 'table' => 'h_part_pkg_option',
1808 'extra_sql' => "$where AND history_action = 'delete'",
1809 'order_by' => 'ORDER BY history_date ASC',
1811 my @h_pkg_svc = map { FS::pkg_svc->new($_->hashref) }
1814 'table' => 'h_pkg_svc',
1816 'extra_sql' => "$where AND history_action = 'replace_old'",
1817 'order_by' => 'ORDER BY history_date ASC',
1820 foreach my $deleted (@h_part_pkg_option, @h_pkg_svc) {
1821 my $pkgpart ||= $deleted->pkgpart;
1822 $opt{$pkgpart} ||= {
1828 if ( $deleted->isa('FS::part_pkg_option') ) {
1829 $opt{$pkgpart}{options}{ $deleted->optionname } = $deleted->optionvalue;
1831 my $svcpart = $deleted->svcpart;
1832 $opt{$pkgpart}{pkg_svc}{$svcpart} = $deleted->quantity;
1833 $opt{$pkgpart}{hidden_svc}{$svcpart} ||= $deleted->hidden;
1834 $opt{$pkgpart}{primary_svc} = $svcpart if $deleted->primary_svc;
1837 foreach my $pkgpart (keys %opt) {
1838 my $part_pkg = FS::part_pkg->by_key($pkgpart);
1839 my $error = $part_pkg->replace( $part_pkg->replace_old, $opt{$pkgpart} );
1841 die "error recovering damaged pkgpart $pkgpart:\n$error\n";
1844 } # $bad_upgrade exists
1845 else { # do the original upgrade, but correctly this time
1846 @part_pkg = qsearch('part_pkg', {
1847 fcc_ds0s => { op => '>', value => 0 },
1848 fcc_voip_class => ''
1850 foreach my $part_pkg (@part_pkg) {
1851 $part_pkg->set(fcc_voip_class => 2);
1852 my @pkg_svc = $part_pkg->pkg_svc;
1853 my %quantity = map {$_->svcpart, $_->quantity} @pkg_svc;
1854 my %hidden = map {$_->svcpart, $_->hidden } @pkg_svc;
1855 my $error = $part_pkg->replace(
1856 $part_pkg->replace_old,
1857 options => { $part_pkg->options },
1858 pkg_svc => \%quantity,
1859 hidden_svc => \%hidden,
1860 primary_svc => ($part_pkg->svcpart || ''),
1862 die $error if $error;
1865 FS::upgrade_journal->set_done($upgrade);
1870 =item curuser_pkgs_sql
1872 Returns an SQL fragment for searching for packages the current user can
1873 use, either via part_pkg.agentnum directly, or via agent type (see
1878 sub curuser_pkgs_sql {
1881 $class->_pkgs_sql( $FS::CurrentUser::CurrentUser->agentnums );
1885 =item agent_pkgs_sql AGENT | AGENTNUM, ...
1887 Returns an SQL fragment for searching for packages the provided agent or agents
1888 can use, either via part_pkg.agentnum directly, or via agent type (see
1893 sub agent_pkgs_sql {
1894 my $class = shift; #i'm a class method, not a sub (the question is... why??)
1895 my @agentnums = map { ref($_) ? $_->agentnum : $_ } @_;
1897 $class->_pkgs_sql(@agentnums); #is this why
1902 my( $class, @agentnums ) = @_;
1903 my $agentnums = join(',', @agentnums);
1907 ( agentnum IS NOT NULL AND agentnum IN ($agentnums) )
1908 OR ( agentnum IS NULL
1909 AND EXISTS ( SELECT 1
1911 LEFT JOIN agent_type USING ( typenum )
1912 LEFT JOIN agent AS typeagent USING ( typenum )
1913 WHERE type_pkgs.pkgpart = part_pkg.pkgpart
1914 AND typeagent.agentnum IN ($agentnums)
1932 #false laziness w/part_export & cdr
1934 foreach my $INC ( @INC ) {
1935 warn "globbing $INC/FS/part_pkg/*.pm\n" if $DEBUG;
1936 foreach my $file ( glob("$INC/FS/part_pkg/*.pm") ) {
1937 warn "attempting to load plan info from $file\n" if $DEBUG;
1938 $file =~ /\/(\w+)\.pm$/ or do {
1939 warn "unrecognized file in $INC/FS/part_pkg/: $file\n";
1943 my $info = eval "use FS::part_pkg::$mod; ".
1944 "\\%FS::part_pkg::$mod\::info;";
1946 die "error using FS::part_pkg::$mod (skipping): $@\n" if $@;
1949 unless ( keys %$info ) {
1950 warn "no %info hash found in FS::part_pkg::$mod, skipping\n";
1953 warn "got plan info from FS::part_pkg::$mod: $info\n" if $DEBUG;
1954 #if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
1955 # warn "skipping disabled plan FS::part_pkg::$mod" if $DEBUG;
1958 $info{$mod} = $info;
1959 $info->{'weight'} ||= 0; # quiet warnings
1963 # copy one level deep to allow replacement of fields and fieldorder
1964 tie %plans, 'Tie::IxHash',
1965 map { my %infohash = %{ $info{$_} };
1967 sort { $info{$a}->{'weight'} <=> $info{$b}->{'weight'} }
1970 # inheritance of plan options
1971 foreach my $name (keys(%info)) {
1972 if (exists($info{$name}->{'disabled'}) and $info{$name}->{'disabled'}) {
1973 warn "skipping disabled plan FS::part_pkg::$name" if $DEBUG;
1974 delete $plans{$name};
1977 my $parents = $info{$name}->{'inherit_fields'} || [];
1978 my (%fields, %field_exists, @fieldorder);
1979 foreach my $parent ($name, @$parents) {
1980 if ( !exists($info{$parent}) ) {
1981 warn "$name tried to inherit from nonexistent '$parent'\n";
1984 %fields = ( # avoid replacing existing fields
1985 %{ $info{$parent}->{'fields'} || {} },
1988 foreach (@{ $info{$parent}->{'fieldorder'} || [] }) {
1990 next if $field_exists{$_};
1991 $field_exists{$_} = 1;
1992 # allow inheritors to remove inherited fields from the fieldorder
1993 push @fieldorder, $_ if !exists($fields{$_}) or
1994 !exists($fields{$_}->{'disabled'});
1997 $plans{$name}->{'fields'} = \%fields;
1998 $plans{$name}->{'fieldorder'} = \@fieldorder;
2008 =head1 NEW PLAN CLASSES
2010 A module should be added in FS/FS/part_pkg/ Eventually, an example may be
2011 found in eg/plan_template.pm. Until then, it is suggested that you use the
2012 other modules in FS/FS/part_pkg/ as a guide.
2016 The delete method is unimplemented.
2018 setup and recur semantics are not yet defined (and are implemented in
2019 FS::cust_bill. hmm.). now they're deprecated and need to go.
2023 part_pkg_taxrate is Pg specific
2025 replace should be smarter about managing the related tables (options, pkg_svc)
2029 L<FS::Record>, L<FS::cust_pkg>, L<FS::type_pkgs>, L<FS::pkg_svc>, L<Safe>.
2030 schema.html from the base documentation.