fix duplication of Washington sales taxes, #73185, fallout from #71501
[freeside.git] / FS / FS / quotation_pkg.pm
1 package FS::quotation_pkg;
2 use base qw( FS::TemplateItem_Mixin FS::Record );
3
4 use strict;
5 use FS::Record qw( qsearchs qsearch dbh );
6 use FS::part_pkg;
7 use FS::quotation_pkg_discount; #so its loaded when TemplateItem_Mixin needs it
8 use FS::quotation_pkg_detail;
9 use List::Util qw(sum);
10
11 =head1 NAME
12
13 FS::quotation_pkg - Object methods for quotation_pkg records
14
15 =head1 SYNOPSIS
16
17   use FS::quotation_pkg;
18
19   $record = new FS::quotation_pkg \%hash;
20   $record = new FS::quotation_pkg { 'column' => 'value' };
21
22   $error = $record->insert;
23
24   $error = $new_record->replace($old_record);
25
26   $error = $record->delete;
27
28   $error = $record->check;
29
30 =head1 DESCRIPTION
31
32 An FS::quotation_pkg object represents a quotation package.
33 FS::quotation_pkg inherits from FS::Record.  The following fields are currently
34 supported:
35
36 =over 4
37
38 =item quotationpkgnum
39
40 primary key
41
42 =item pkgpart
43
44 pkgpart (L<FS::part_pkg>) of the package
45
46 =item locationnum
47
48 locationnum (L<FS::cust_location>) where the package will be in service
49
50 =item start_date
51
52 expected start date for the package, as a timestamp
53
54 =item contract_end
55
56 contract end date
57
58 =item quantity
59
60 quantity
61
62 =item waive_setup
63
64 'Y' to waive the setup fee
65
66 =item unitsetup
67
68 The amount per package that will be charged in setup/one-time fees.
69
70 =item unitrecur
71
72 The amount per package that will be charged per billing cycle.
73
74 =item freq
75
76 The length of the billing cycle. If zero it's a one-time charge; if any 
77 other number it's that many months; other values are in L<FS::Misc::pkg_freqs>.
78
79 =back
80
81 =head1 METHODS
82
83 =over 4
84
85 =item new HASHREF
86
87 Creates a new quotation package.  To add the quotation package to the database,
88 see L<"insert">.
89
90 Note that this stores the hash reference, not a distinct copy of the hash it
91 points to.  You can ask the object for a copy with the I<hash> method.
92
93 =cut
94
95 sub table { 'quotation_pkg'; }
96
97 sub display_table         { 'quotation_pkg'; }
98
99 #forget it, just overriding cust_bill_pkg_display entirely
100 #sub display_table_orderby { 'quotationpkgnum'; } # something else?
101 #                                                 #  (for invoice display order)
102
103 sub discount_table        { 'quotation_pkg_discount'; }
104 sub detail_table          { 'quotation_pkg_detail'; }
105
106 =item insert
107
108 Adds this record to the database.  If there is an error, returns the error,
109 otherwise returns false.  Accepts the following options:
110
111 quotation_details - optional arrayref of detail strings to add (creates quotation_pkg_detail records)
112
113 copy_on_order - value for this field when creating quotation_pkg_detail records (same for all details)
114
115 =cut
116
117 sub insert {
118   my ($self, %options) = @_;
119
120   my $dbh = dbh;
121   my $oldAutoCommit = $FS::UID::AutoCommit;
122   local $FS::UID::AutoCommit = 0;
123
124   my $error = $self->SUPER::insert;
125
126   if ( !$error and ($self->setup_discountnum || $self->recur_discountnum) ) {
127       #warn "inserting discount\n";
128     $error = $self->insert_discount;
129     $error .= ' (setting discount)' if $error;
130   }
131
132   if ( $error ) {
133     $dbh->rollback if $oldAutoCommit;
134     return $error;
135   }
136
137   if ($options{'quotation_details'}) {
138     $error = $self->set_details(
139                 details => $options{'quotation_details'},
140                 copy_on_order => $options{'copy_on_order'} ? 'Y' : '',
141              );
142     if ( $error ) {
143       $error .= ' (setting details)';
144       $dbh->rollback if $oldAutoCommit;
145       return $error;
146     }
147   }
148
149   $dbh->commit if $oldAutoCommit;
150   return '';
151 }
152
153 =item delete
154
155 Delete this record from the database.
156
157 =cut
158
159 sub delete {
160   my $self = shift;
161
162   my $dbh = dbh;
163   my $oldAutoCommit = $FS::UID::AutoCommit;
164   local $FS::UID::AutoCommit = 0;
165
166   my $error = $self->delete_details;
167   if ( $error ) {
168     $dbh->rollback if $oldAutoCommit;
169     return $error;
170   }
171
172   foreach ($self->quotation_pkg_discount, $self->quotation_pkg_tax) {
173     $error = $_->delete;
174     if ( $error ) {
175       $dbh->rollback if $oldAutoCommit;
176       return $error . ' (deleting discount)';
177     }
178   }
179
180   $error = $self->SUPER::delete;
181   if ( $error ) {
182     $dbh->rollback if $oldAutoCommit;
183     return $error;
184   } else {
185     $dbh->commit if $oldAutoCommit;
186   }
187   
188   $self->quotation->estimate;
189 }
190
191 =item replace OLD_RECORD
192
193 Replaces the OLD_RECORD with this one in the database.  If there is an error,
194 returns the error, otherwise returns false.
195
196 =item check
197
198 Checks all fields to make sure this is a valid quotation package.  If there is
199 an error, returns the error, otherwise returns false.  Called by the insert
200 and replace methods.
201
202 =cut
203
204 sub check {
205   my $self = shift;
206
207   my @freqs = ('', keys (%{ FS::Misc->pkg_freqs }));
208
209   my $error = 
210     $self->ut_numbern('quotationpkgnum')
211     || $self->ut_foreign_key(  'quotationnum', 'quotation',    'quotationnum' )
212     || $self->ut_foreign_key(  'pkgpart',      'part_pkg',     'pkgpart'      )
213     || $self->ut_foreign_keyn( 'locationnum', 'cust_location', 'locationnum'  )
214     || $self->ut_numbern('start_date')
215     || $self->ut_numbern('contract_end')
216     || $self->ut_numbern('quantity')
217     || $self->ut_moneyn('unitsetup')
218     || $self->ut_moneyn('unitrecur')
219     || $self->ut_enum('freq', \@freqs)
220     || $self->ut_enum('waive_setup', [ '', 'Y'] )
221   ;
222
223   if ($self->locationnum eq '') {
224     # use the customer default
225     my $quotation = $self->quotation;
226     if ($quotation->custnum) {
227       $self->set('locationnum', $quotation->cust_main->ship_locationnum);
228     } elsif ($quotation->prospectnum) {
229       # use the first non-disabled location for that prospect
230       my $cust_location = qsearchs('cust_location',
231         { prospectnum => $quotation->prospectnum,
232           disabled => '' });
233       $self->set('locationnum', $cust_location->locationnum) if $cust_location;
234     } # else the quotation is invalid
235   }
236
237   return $error if $error;
238
239   $self->SUPER::check;
240 }
241
242 #it looks redundant with a v4.x+ auto-generated method, but need to override
243 # FS::TemplateItem_Mixin's version
244 sub part_pkg {
245   my $self = shift;
246   qsearchs('part_pkg', { 'pkgpart' => $self->pkgpart } );
247 }
248
249 sub desc {
250   my $self = shift;
251   $self->part_pkg->pkg;
252 }
253
254 =cut
255
256 =item insert_discount
257
258 Associates this package with a discount (see L<FS::cust_pkg_discount>,
259 possibly inserting a new discount on the fly (see L<FS::discount>). Properties
260 of the discount will be taken from this object.
261
262 =cut
263
264 sub insert_discount {
265   #my ($self, %options) = @_;
266   my $self = shift;
267
268   foreach my $x (qw(setup recur)) {
269     if ( my $discountnum = $self->get("${x}_discountnum") ) {
270       my $cust_pkg_discount = FS::quotation_pkg_discount->new( { 
271         'quotationpkgnum' => $self->quotationpkgnum,
272         'discountnum' => $discountnum,
273         'setuprecur'  => $x,
274         #for the create a new discount case
275         'amount'      => $self->get("${x}_discountnum_amount"),
276         'percent'     => $self->get("${x}_discountnum_percent"),
277         'months'      => $self->get("${x}_discountnum_months"),
278       } );
279       if ( $x eq 'setup' ) {
280         $cust_pkg_discount->setup('Y');
281         $cust_pkg_discount->months('');
282       } 
283       my $error = $cust_pkg_discount->insert;
284       return $error if $error;
285     } 
286   } 
287 }
288
289 sub _item_discount {
290   my $self = shift;
291   my %options = @_;
292   my $setuprecur = $options{'setuprecur'};
293   # a little different from cust_bill_pkg::_item_discount, in that this one
294   # is asked specifically whether to show setup or recur discounts (because
295   # on the quotation they're separate sections entirely)
296
297   my @pkg_discounts = grep { $_->setuprecur eq $setuprecur }
298                         $self->pkg_discount;
299   return if @pkg_discounts == 0;
300   
301   my @ext;
302   my $d = {
303     _is_discount    => 1,
304     description     => $self->mt('Discount'),
305     amount          => 0,
306     ext_description => \@ext,
307     # maybe should show quantity/unit discount?
308   };
309   foreach my $pkg_discount (@pkg_discounts) {
310     push @ext, $pkg_discount->description;
311     my $amount = $pkg_discount->get('amount');
312     $d->{amount} -= $amount;
313   }
314   $d->{amount} = sprintf('%.2f', $d->{amount} * $self->quantity);
315   
316   return $d;
317 }
318
319 sub setup {
320   my $self = shift;
321   return '0.00' if $self->waive_setup eq 'Y';;
322   my $discount_amount = sum(0, map { $_->amount }
323                                grep { $_->setuprecur eq 'setup' }
324                                $self->pkg_discount
325                            );
326   ($self->unitsetup - $discount_amount) * ($self->quantity || 1);
327
328 }
329
330 sub setup_show_zero {
331   my $self = shift;
332   return $self->part_pkg->setup_show_zero;
333 }
334
335 sub setup_tax {
336   my $self = shift;
337   sum(0, map { $_->setup_amount } $self->quotation_pkg_tax);
338 }
339
340 sub recur {
341   my $self = shift;
342   my $discount_amount = sum(0, map { $_->amount }
343                                grep { $_->setuprecur eq 'recur' }
344                                $self->pkg_discount
345                            );
346   ($self->unitrecur - $discount_amount) * ($self->quantity || 1);
347
348 }
349
350 sub recur_show_zero {
351   my $self = shift;
352   return $self->part_pkg->recur_show_zero;
353 }
354
355 sub recur_tax {
356   my $self = shift;
357   sum(0, map { $_->recur_amount } $self->quotation_pkg_tax);
358 }
359
360 =item part_pkg_currency_option OPTIONNAME
361
362 Returns a two item list consisting of the currency of this quotation's customer
363 or prospect, if any, and a value for the provided option.  If the customer or
364 prospect has a currency, the value is the option value the given name and the
365 currency (see L<FS::part_pkg_currency>).  Otherwise, if the customer or
366 prospect has no currency, is the regular option value for the given name (see
367 L<FS::part_pkg_option>).
368
369 =cut
370
371 #false laziness w/cust_pkg->part_pkg_currency_option
372 sub part_pkg_currency_option {
373   my( $self, $optionname ) = @_;
374   my $part_pkg = $self->part_pkg;
375   my $prospect_or_customer = $self->cust_main || $self->prospect_main;
376   if ( my $currency = $prospect_or_customer->currency ) {
377     ($currency, $part_pkg->part_pkg_currency_option($currency, $optionname) );
378   } else {
379     ('', $part_pkg->option($optionname) );
380   }
381 }
382
383 =item delete_details
384
385 Deletes all quotation_pkgs_details associated with this pkg (see L<FS::quotation_pkg_detail>).
386
387 =cut
388
389 sub delete_details {
390   my $self = shift;
391
392   my $oldAutoCommit = $FS::UID::AutoCommit;
393   local $FS::UID::AutoCommit = 0;
394   my $dbh = dbh;
395
396   foreach my $detail ( qsearch('quotation_pkg_detail',{ 'quotationpkgnum' => $self->quotationpkgnum }) ) {
397     my $error = $detail->delete;
398     if ( $error ) {
399       $dbh->rollback if $oldAutoCommit;
400       return "error removing old detail: $error";
401     }
402   }
403
404   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
405   '';
406
407 }
408
409 =item set_details PARAM
410
411 Sets new quotation details for this package (see L<FS::quotation_pkg_detail>),
412 removing existing details.
413
414 Recognizes the following parameters:
415
416 details - arrayref of strings, one for each new detail
417
418 copy_on_order - if true, sets copy_on_order flag on new details
419
420 If there is an error, returns the error, otherwise returns false.
421
422 =cut
423
424 sub set_details {
425   my $self = shift;
426   my %opt = @_;
427
428   $opt{'details'} ||= [];
429   my @details = @{$opt{'details'}};
430
431   my $oldAutoCommit = $FS::UID::AutoCommit;
432   local $FS::UID::AutoCommit = 0;
433   my $dbh = dbh;
434
435   my $error = $self->delete_details;
436   if ( $error ) {
437     $dbh->rollback if $oldAutoCommit;
438     return $error;
439   }
440
441   foreach my $detail ( @details ) {
442     my $quotation_pkg_detail = new FS::quotation_pkg_detail {
443       'quotationpkgnum' => $self->quotationpkgnum,
444       'detail' => $detail,
445       'copy_on_order' => $opt{'copy_on_order'} ? 'Y' : '',
446     };
447     $error = $quotation_pkg_detail->insert;
448     if ( $error ) {
449       $dbh->rollback if $oldAutoCommit;
450       return "error adding new detail: $error";
451     }
452   }
453
454   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
455   '';
456
457 }
458
459 sub details_header {
460   return ();
461 }
462
463 =item cust_bill_pkg_display [ type => TYPE ]
464
465 =cut
466
467 sub cust_bill_pkg_display {
468   my ( $self, %opt ) = @_;
469
470   my $type = $opt{type} if exists $opt{type};
471   return () if $type eq 'U'; #quotations don't have usage
472
473   if ( $self->get('display') ) {
474     return ( grep { defined($type) ? ($type eq $_->type) : 1 }
475                @{ $self->get('display') }
476            );
477   } else {
478
479     #??
480     my $setup = $self->new($self->hashref);
481     $setup->{'_NO_RECUR_KLUDGE'} = 1;
482     $setup->{'type'} = 'S';
483     my $recur = $self->new($self->hashref);
484     $recur->{'_NO_SETUP_KLUDGE'} = 1;
485     $recur->{'type'} = 'R';
486
487     if ( $type eq 'S' ) {
488       return ($setup);
489     } elsif ( $type eq 'R' ) {
490       return ($recur);
491     } else {
492       #return ($setup, $recur);
493       return ($self);
494     }
495
496   }
497
498 }
499
500 =item cust_main
501
502 Returns the customer (L<FS::cust_main> object).
503
504 =cut
505
506 sub cust_main {
507   my $self = shift;
508   my $quotation = $self->quotation or return '';
509   $quotation->cust_main;
510 }
511
512 =item prospect_main
513
514 Returns the prospect (L<FS::prospect_main> object).
515
516 =cut
517
518 sub prospect_main {
519   my $self = shift;
520   my $quotation = $self->quotation or return '';
521   $quotation->prospect_main;
522 }
523
524 sub tax_locationnum {
525   my $self = shift;
526   $self->locationnum;
527 }
528
529 sub _upgrade_data {
530   my $class = shift;
531   my @quotation_pkg_without_location =
532     qsearch( 'quotation_pkg', { locationnum => '' } );
533   if (@quotation_pkg_without_location) {
534     warn "setting default location on quotation_pkg records\n";
535     foreach my $quotation_pkg (@quotation_pkg_without_location) {
536       # check() will fix this
537       my $error = $quotation_pkg->replace;
538       if ($error) {
539         die "quotation #".$quotation_pkg->quotationnum.": $error\n";
540       }
541     }
542   }
543   '';
544 }
545
546 =back
547
548 =head1 BUGS
549
550 Doesn't support fees, or add-on packages.
551
552 =head1 SEE ALSO
553
554 L<FS::Record>, schema.html from the base documentation.
555
556 =cut
557
558 1;
559