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