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